code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
' This is comment line 1
' This is comment line 2
' This is comment line 3
Imports System
Imports System.Collections.Generic
Imports System.Text
Namespace SampleNamespace
''' <summary>
''' This is a sample class definition.
''' </summary>
Public Class SampleClass
End Class
End Namespace
|
adgistics/Adgistics.Build
|
NArrange/src/NArrange.Tests.VisualBasic/TestSourceFiles/ClassDefinition.vb
|
Visual Basic
|
apache-2.0
| 295
|
' Licensed to the .NET Foundation under one or more 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.[Text]
Imports System.Collections.Generic
Imports System.Linq
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class SimpleFlowTests
Inherits FlowTestBase
<Fact>
Public Sub TestUninitializedIntegerLocal()
Dim program = <compilation name="TestUninitializedIntegerLocal">
<file name="a.b">
Module Module1
Sub Goo(z As Integer)
Dim x As Integer
If z = 2 Then
Dim y As Integer = x : x = y ' ok to use unassigned integer local
Else
dim y as integer = x : x = y ' no diagnostic in unreachable code
End If
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<Fact>
Public Sub TestUnusedIntegerLocal()
Dim program = <compilation name="TestUnusedIntegerLocal">
<file name="a.b">
Module Module1
Public Sub SubWithByRef(ByRef i As Integer)
End Sub
Sub TestInitialized1()
Dim x as integer = 1 ' No warning for a variable assigned a value but not used
Dim i1 As Integer
Dim i2 As Integer
i2 = i1 ' OK to use an uninitialized integer. Spec says all variables are initialized
Dim i3 As Integer
SubWithByRef(i3) ' Ok to pass an uninitialized integer byref
Dim i4 As Integer ' Warning - unused local
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
<expected>
BC42024: Unused local variable: 'i4'.
Dim i4 As Integer ' Warning - unused local
~~
</expected>)
End Sub
<Fact>
Public Sub TestStructure1()
Dim program = <compilation name="TestStructure1">
<file name="a.b">
Module Module1
Structure s1
Dim i As Integer
Dim o As Object
End Structure
Public Sub SubWithByRef(ByRef i As s1, j as integer)
End Sub
Sub TestInitialized1()
Dim i1 As s1
Dim i2 As s1
i2 = i1 ' Warning- use of uninitialized variable
Dim i3 As s1
SubWithByRef(j := 1, i := i3) ' Warning- use of uninitialized variable
Dim i4 As s1 ' Warning - unused local
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
BC42109: Variable 'i1' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
i2 = i1 ' Warning- use of uninitialized variable
~~
BC42108: Variable 'i3' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
SubWithByRef(j := 1, i := i3) ' Warning- use of uninitialized variable
~~
BC42024: Unused local variable: 'i4'.
Dim i4 As s1 ' Warning - unused local
~~
</expected>))
End Sub
<Fact>
Public Sub TestObject1()
Dim program = <compilation name="TestObject1">
<file name="a.b">
Module Module1
Class C1
Public i As Integer
Public o As Object
End Class
Public Sub SubWithByRef(ByRef i As C1)
End Sub
Sub TestInitialized1()
Dim i1 As C1
Dim i2 As C1
i2 = i1 ' Warning- use of uninitialized variable
Dim i3 As MyClass
SubWithByRef(i3) ' Warning- use of uninitialized variable
Dim i4 As C1 ' Warning - unused local
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
BC42104: Variable 'i1' is used before it has been assigned a value. A null reference exception could result at runtime.
i2 = i1 ' Warning- use of uninitialized variable
~~
BC42104: Variable 'i3' is used before it has been assigned a value. A null reference exception could result at runtime.
SubWithByRef(i3) ' Warning- use of uninitialized variable
~~
BC42024: Unused local variable: 'i4'.
Dim i4 As C1 ' Warning - unused local
~~
</expected>))
End Sub
<Fact()>
Public Sub LambdaInUnimplementedPartial_1()
Dim program = <compilation name="LambdaInUnimplementedPartial_1">
<file name="a.b">
Imports System
Partial Class C
Partial Private Shared Sub Goo(a As action)
End Sub
Public Shared Sub Main()
Goo(DirectCast(Sub()
Dim x As Integer
Dim y As Integer = x
End Sub, Action))
End Sub
End Class
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs, (<errors></errors>))
End Sub
<Fact()>
Public Sub LambdaInUnimplementedPartial_2()
Dim program = <compilation name="LambdaInUnimplementedPartial_2">
<file name="a.b">
Imports System
Partial Class C
Partial Private Shared Sub Goo(a As action)
End Sub
Public Shared Sub Main()
Goo(DirectCast(Sub()
Dim x As Integer
End Sub, Action))
End Sub
End Class
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<errors>
BC42024: Unused local variable: 'x'.
Dim x As Integer
~
</errors>))
End Sub
<WorkItem(722619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722619")>
<Fact()>
Public Sub Bug_722619()
Dim program =
<compilation>
<file name="a.b">
Imports System
Friend Module SubMod
Sub Main()
Dim x As Exception
Try
Throw New DivideByZeroException
L1:
'COMPILEWARNING: BC42104, "x"
Console.WriteLine(x.Message)
Catch ex As DivideByZeroException
GoTo L1
Finally
x = New Exception("finally")
End Try
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(comp,
<errors>
BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.WriteLine(x.Message)
~
</errors>)
End Sub
<WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")>
<Fact()>
Public Sub Bug_722575a()
Dim program =
<compilation>
<file name="a.b">
Imports System
Friend Module TestNone
Structure Str1(Of T)
Dim x As T
Sub goo()
Dim o As Object
Dim s1 As Str1(Of T)
o = s1
Dim s2 As Str1(Of T)
o = s2.x
Dim s3 As Str1(Of T)
s3.x = Nothing
o = s3.x
Dim s4 As Str1(Of T)
s4.x = Nothing
o = s4
End Sub
End Structure
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")>
<Fact()>
Public Sub Bug_722575b()
Dim program =
<compilation>
<file name="a.b">
Imports System
Friend Module TestStruct
Structure Str1(Of T As Structure)
Dim x As T
Sub goo()
Dim o As Object
Dim s1 As Str1(Of T)
o = s1
Dim s2 As Str1(Of T)
o = s2.x
Dim s3 As Str1(Of T)
s3.x = Nothing
o = s3.x
Dim s4 As Str1(Of T)
s4.x = Nothing
o = s4
End Sub
End Structure
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")>
<Fact()>
Public Sub Bug_722575c()
Dim program =
<compilation>
<file name="a.b">
Imports System
Friend Module TestClass
Structure Str1(Of T As Class)
Dim x As T
Sub goo()
Dim o As Object
Dim s1 As Str1(Of T)
o = s1
Dim s2 As Str1(Of T)
o = s2.x
Dim s3 As Str1(Of T)
s3.x = Nothing
o = s3.x
Dim s4 As Str1(Of T)
s4.x = Nothing
o = s4
End Sub
End Structure
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(comp,
<errors>
BC42109: Variable 's1' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
o = s1
~~
BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime.
o = s2.x
~~~~
</errors>)
End Sub
<WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")>
<Fact()>
Public Sub Bug_722575d()
Dim program =
<compilation>
<file name="a.b">
Imports System
Friend Module TestNewAndDisposable
Structure Str1(Of T As {IDisposable, New})
Dim x As T
Sub goo()
Dim o As Object
Dim s1 As Str1(Of T)
o = s1
Dim s2 As Str1(Of T)
o = s2.x
Dim s3 As Str1(Of T)
s3.x = Nothing
o = s3.x
Dim s4 As Str1(Of T)
s4.x = Nothing
o = s4
End Sub
End Structure
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")>
<Fact()>
Public Sub Bug_722575e()
Dim program =
<compilation>
<file name="a.b">
Imports System
Friend Class TestNone(Of T)
Structure Str1
Dim x As T
Sub goo()
Dim o As Object
Dim s1 As Str1
o = s1
Dim s2 As Str1
o = s2.x
Dim s3 As Str1
s3.x = Nothing
o = s3.x
Dim s4 As Str1
s4.x = Nothing
o = s4
End Sub
End Structure
End Class
Friend Class TestStruct(Of T As Structure)
Structure Str1
Dim x As T
Sub goo()
Dim o As Object
Dim s1 As Str1
o = s1
Dim s2 As Str1
o = s2.x
Dim s3 As Str1
s3.x = Nothing
o = s3.x
Dim s4 As Str1
s4.x = Nothing
o = s4
End Sub
End Structure
End Class
Friend Class TestClass(Of T As Class)
Structure Str1
Dim x As T
Sub goo()
Dim o As Object
Dim s1 As Str1
o = s1
Dim s2 As Str1
o = s2.x
Dim s3 As Str1
s3.x = Nothing
o = s3.x
Dim s4 As Str1
s4.x = Nothing
o = s4
End Sub
End Structure
End Class
Friend Class TestNewAndDisposable(Of T As {IDisposable, New})
Structure Str1
Dim x As T
Sub goo()
Dim o As Object
Dim s1 As Str1
o = s1
Dim s2 As Str1
o = s2.x
Dim s3 As Str1
s3.x = Nothing
o = s3.x
Dim s4 As Str1
s4.x = Nothing
o = s4
End Sub
End Structure
End Class
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(comp,
<errors>
BC42109: Variable 's1' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
o = s1
~~
BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime.
o = s2.x
~~~~
</errors>)
End Sub
<WorkItem(617061, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617061")>
<Fact()>
Public Sub Bug_617061()
Dim program =
<compilation>
<file name="a.b">
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim a(100) As MEMORY_BASIC_INFORMATION
Dim b = From x In a Select x.BaseAddress
End Sub
End Module
Structure MEMORY_BASIC_INFORMATION
Dim BaseAddress As UIntPtr
End Structure
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(544072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544072")>
<Fact()>
Public Sub TestBug12221a()
Dim program =
<compilation name="TestBug12221a">
<file name="a.b">
Imports System
Structure SS
Public S As String
End Structure
Module Program222
Sub Main(args As String())
Dim s As SS
Dim dict As New Dictionary(Of String, SS)
If dict.TryGetValue("", s) Then
End If
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
BC42109: Variable 's' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
If dict.TryGetValue("", s) Then
~
</expected>))
End Sub
<WorkItem(544072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544072")>
<Fact()>
Public Sub TestBug12221b()
Dim program =
<compilation name="TestBug12221b">
<file name="a.b">
Imports System
Structure SS
Public S As Integer
End Structure
Module Program222
Sub Main(args As String())
Dim s As SS
Dim dict As New Dictionary(Of String, SS)
If dict.TryGetValue("", s) Then
End If
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
</expected>))
End Sub
<WorkItem(544072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544072")>
<Fact()>
Public Sub TestBug12221c()
Dim program =
<compilation name="TestBug12221c">
<file name="a.b">
Module Program222
Interface I
End Interface
Sub Main(Of T As I)(args As String())
Dim s As T
Dim dict As New Dictionary(Of String, T)
If dict.TryGetValue("", s) Then
End If
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
</expected>))
End Sub
<WorkItem(544072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544072")>
<Fact()>
Public Sub TestBug12221d()
Dim program =
<compilation name="TestBug12221d">
<file name="a.b">
Module Program222
Sub Main(Of T As Class)(args As String())
Dim s As T
Dim dict As New Dictionary(Of String, T)
If dict.TryGetValue("", s) Then
End If
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
BC42104: Variable 's' is used before it has been assigned a value. A null reference exception could result at runtime.
If dict.TryGetValue("", s) Then
~
</expected>))
End Sub
<Fact()>
Public Sub TestReachable1()
Dim program = <compilation name="TestReachable1">
<file name="a.b">
Imports System
Module Module1
Sub TestUnreachable1()
Dim i As Integer ' Dev10 Warning - unused local
Return
Dim j As Integer ' Dev10 No warning because this is unreachable
Console.WriteLine(i, j)
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
</expected>))
End Sub
<Fact>
Public Sub TestReachable2()
Dim program = <compilation name="TestReachable2">
<file name="a.b">
Imports System
Module Module1
Sub TestUnreachable1()
Dim i As Integer ' Dev10 Warning - unused local
Return
Dim j As Integer = 1 ' Dev10 No warning because this is unreachable
Console.WriteLine(i, j)
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
</expected>))
End Sub
<Fact>
Public Sub TestGoto1()
Dim program = <compilation name="TestGoto1">
<file name="a.b">
Imports System
Module Module1
Sub TestGoto1()
Dim o1, o2 As Object
GoTo l1
l2:
o1 = o2
return
l1:
If false Then
o2 = "a"
end if
GoTo l2
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
BC42104: Variable 'o2' is used before it has been assigned a value. A null reference exception could result at runtime.
o1 = o2
~~
</expected>))
End Sub
<Fact>
Public Sub LambdaEntryPointIsReachable1()
Dim program = <compilation name="LambdaEntryPointIsReachable1">
<file name="a.b">
Imports System
Public Module Program
Public Sub Main(args As String())
Dim i As Integer
Return
Dim x As Integer = i
Dim a As action = DirectCast(Sub()
Dim j As Integer = i + j
End Sub, action)
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
</expected>))
End Sub
<Fact>
Public Sub LambdaEntryPointIsReachable2()
Dim program = <compilation name="LambdaEntryPointIsReachable2">
<file name="a.b">
Imports System
Public Module Program
Public Sub Main(args As String())
Dim i As Integer
Return
Dim a As action = DirectCast(Sub()
Dim j As Integer = i + j
End Sub, action)
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
</expected>))
End Sub
<Fact>
Public Sub LambdaEntryPointIsReachable3()
Dim program = <compilation name="LambdaEntryPointIsReachable3">
<file name="a.b">
Imports System
Public Module Program
Public Sub Main(args As String())
Dim i As Integer
Return
Dim a As action = DirectCast(Sub()
Dim j As Integer = i + j
Return
Dim k = j
End Sub, action)
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
</expected>))
End Sub
<Fact>
Public Sub TestDoLoop1()
Dim program = <compilation name="TestDoLoop1">
<file name="a.b">
Imports System
Module Module1
Sub TestGoto1()
Dim o1, o2 As Object
GoTo l1
l2:
o1 = o2
return
l1:
do
exit do
o2 = "a"
loop
GoTo l2
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
BC42104: Variable 'o2' is used before it has been assigned a value. A null reference exception could result at runtime.
o1 = o2
~~
</expected>))
End Sub
<Fact>
Public Sub TestDoLoop2()
Dim program = <compilation name="TestDoLoop2">
<file name="a.b">
Imports System
Module Module1
Sub TestGoto1()
Dim o1, o2 As Object
GoTo l1
l2:
o1 = o2
return
do
l1:
o2 = "a"
exit do
loop
goto l2
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<Fact>
Public Sub TestBlocks()
Dim program = <compilation name="TestDoLoop2">
<file name="a.b">
Imports System
Module Module1
Sub TestGoto1()
do until false
while false
end while
loop
do while true
while true
end while
loop
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<Fact>
Public Sub RefParameter01()
Dim program = <compilation name="RefParameter01">
<file name="a.b">
class Program
public shared Sub Main(args as string())
dim i as string
F(i) ' use of unassigned local variable 'i'
end sub
shared sub F(byref i as string)
end sub
end class</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Assert.NotEmpty(Me.FlowDiagnostics(comp).AsEnumerable().Where(Function(e) e.Severity = DiagnosticSeverity.[Warning]))
End Sub
<Fact>
Public Sub FunctionDoesNotReturnAValue()
Dim program = <compilation name="FunctionDoesNotReturnAValue">
<file name="a.b">
class Program
public function goo() as integer
end function
end class</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<errors>
BC42353: Function 'goo' doesn't return a value on all code paths. Are you missing a 'Return' statement?
end function
~~~~~~~~~~~~
</errors>))
End Sub
<Fact>
Public Sub FunctionReturnsAValue()
Dim program = <compilation name="FunctionDoesNotReturnAValue">
<file name="a.b">
class Program
public function goo() as integer
return 0
end function
public function bar() as integer
bar = 0
end function
end class</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<errors>
</errors>))
End Sub
<WorkItem(540687, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540687")>
<Fact>
Public Sub FunctionDoesNotReturnAnEnumValue()
Dim program = <compilation name="FunctionDoesNotReturnAValue">
<file name="a.b">
Imports System
Imports System.Collections.Generic
Imports System.Linq
Enum e1
a
b
End Enum
Module Program
Function f As e1
End Function
Sub Main(args As String())
Dim x As Func(Of e1) = Function()
End Function
End Sub
End Module</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<errors>
<![CDATA[
BC42353: Function 'f' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function
~~~~~~~~~~~~
BC42353: Function '<anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function
~~~~~~~~~~~~
]]>
</errors>))
End Sub
<WorkItem(541005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541005")>
<Fact>
Public Sub TestLocalsInitializedByAsNew()
Dim program = <compilation name="TestLocalsInitializedByAsNew">
<file name="a.b">
Module Module1
Class C
Public Sub New()
End Class
End Class
Sub Goo()
Dim x, y, z as New C
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<WorkItem(542817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542817")>
<Fact>
Public Sub ConditionalStateInsideQueryLambda()
Dim program = <compilation name="ConditionalStateInsideQueryLambda">
<file name="a.b">
Imports System.Linq
Class PEModuleSymbol
Function IsNoPiaLocalType(i As Integer) As Boolean
End Function
End Class
Class PENamedTypeSymbol
Friend Sub New(
moduleSymbol As PEModuleSymbol,
containingNamespace As PENamespaceSymbol,
typeRid As Integer
)
End Sub
End Class
Class PENamespaceSymbol
Private Sub LazyInitializeTypes(types As IEnumerable(Of IGrouping(Of String, Integer)))
Dim moduleSymbol As PEModuleSymbol = Nothing
Dim children As IEnumerable(Of PENamedTypeSymbol)
children = (From g In types, t In g
Where Not moduleSymbol.IsNoPiaLocalType(t)
Select New PENamedTypeSymbol(moduleSymbol, Me, t))
End Sub
End Class
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim diags = comp.GetDiagnostics()
End Sub
<Fact>
Public Sub TestSelectCase_CaseClauseExpression_NeverConstantExpr()
Dim program = <compilation name="TestUninitializedIntegerLocal">
<file name="a.b">
<![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(number as Integer)
' No unreachable code warning for any case block
Select Case 1
Case 1
Console.WriteLine("Equal to 1")
Case Is < 1
Console.WriteLine("Less than 1")
Case 1 To 5
Console.WriteLine("Between 2 and 5, inclusive")
Case 6, 7, 8
Console.WriteLine("Between 6 and 8, inclusive")
Case 9 To 10
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<Fact>
Public Sub TestSelectCase_NoCaseBlocks_NoUnusedLocalWarning()
Dim program = <compilation name="TestUnusedIntegerLocal">
<file name="a.b">
Imports System
Module M1
Sub Main()
Dim number as Integer = 10
Select Case number ' no unused integer warning even though select statement is optimized away
End Select
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<Fact>
Public Sub TestSelectCase_UninitializedLocalWarning()
Dim program = <compilation name="TestUnusedIntegerLocal">
<file name="a.b">
Imports System
Module M1
Sub Main()
Dim obj as Object
Select Case 1
Case 1 ' Case clause expression are never compile time constants, hence Case Else is reachable.
obj = new Object()
Case Else
End Select
Console.WriteLine(obj) ' Use of uninitialized local warning
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<errors>
BC42104: Variable 'obj' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.WriteLine(obj) ' Use of uninitialized local warning
~~~
</errors>))
End Sub
<Fact>
Public Sub TestSelectCase_NoUninitializedLocalWarning()
Dim program = <compilation name="TestUnusedIntegerLocal">
<file name="a.b">
Imports System
Module M1
Sub Main()
Dim obj as Object
Select Case 1
Case 1
obj = new Object()
Case Is > 1, 2
obj = new Object()
Case 1 To 10
obj = new Object()
Case Else
obj = new Object()
End Select
Console.WriteLine(obj)
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<Fact>
Public Sub TestSelectCase_UninitializedLocalWarning_InvalidRangeClause()
Dim program = <compilation name="TestUnusedIntegerLocal">
<file name="a.b">
Imports System
Module M1
Sub Main()
Dim obj as Object
Select Case 1
Case 10 To 1 ' Invalid range clause
obj = new Object()
End Select
Console.WriteLine(obj) ' Use of uninitialized local warning
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<errors>
BC42104: Variable 'obj' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.WriteLine(obj) ' Use of uninitialized local warning
~~~
</errors>))
End Sub
<Fact>
Public Sub TestSelectCase_NoUninitializedLocalWarning_JumpToAnotherCaseBlock()
Dim program = <compilation name="TestUnusedIntegerLocal">
<file name="a.b">
Imports System
Module M1
Sub Main()
Dim obj as Object
Select Case 1
Case 1 ' Case clause expression are never compile time constants, hence Case Else is reachable.
Label1:
obj = new Object()
Case Else
Goto Label1
End Select
Console.WriteLine(obj) ' Use of uninitialized local warning
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<WorkItem(543095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543095")>
<Fact()>
Public Sub TestSelectCase_Error_MissingCaseStatement()
Dim program = <compilation name="TestSelectCase_Error_MissingCaseStatement">
<file name="a.b">
Imports System
Module Program
Sub Main(args As String())
Dim x As New myclass1
Select x
Ca
End Sub
End Module
Structure myclass1
Implements IDisposable
Public Sub dispose() Implements IDisposable.Dispose
End Sub
End Structure
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<WorkItem(543095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543095")>
<Fact()>
Public Sub TestSelectCase_Error_MissingCaseExpression()
Dim program = <compilation name="TestSelectCase_Error_MissingCaseExpression">
<file name="a.b">
Imports System
Module Program
Sub Main(args As String())
Dim x As New myclass1
Select x
Case
End Select
End Sub
End Module
Structure myclass1
Implements IDisposable
Public Sub dispose() Implements IDisposable.Dispose
End Sub
End Structure
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<Fact>
<WorkItem(100475, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems?_a=edit&id=100475")>
<WorkItem(529405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529405")>
Public Sub TestThrowDoNotReportUnreachable()
Dim program =
<compilation>
<file name="a.b">
Imports System
Class Test
Sub Method1()
Throw New Exception()
Return
End Sub
Function Method2(x As Integer) As Integer
If x < 0 Then
Return -1
Else
Return 1
End If
Throw New System.InvalidOperationException()
End Function
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40(program).VerifyDiagnostics()
End Sub
<WorkItem(531310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531310")>
<Fact()>
Public Sub Bug_17926()
Dim program =
<compilation>
<file name="a.b">
Imports System
Imports System.Collections.Generic
Module Module1
Public Function RemoveTextWriterTraceListener() As Boolean
Try
RemoveTextWriterTraceListener = False
'Return true to indicate that the TextWriterTraceListener was removed
RemoveTextWriterTraceListener = True
Catch e As Exception
Console.WriteLine("")
End Try
Return RemoveTextWriterTraceListener
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program)
CompilationUtils.AssertTheseDiagnostics(compilation, <errors></errors>)
End Sub
<WorkItem(531529, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531529")>
<Fact()>
Public Sub Bug_18255()
Dim program =
<compilation>
<file name="a.b">
Imports System
Public Class TestState
ReadOnly Property IsImmediateWindow As Boolean
Get
Return IsImmediateWindow
End Get
End Property
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
</errors>)
End Sub
<WorkItem(531530, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531530")>
<Fact()>
Public Sub Bug_18256()
Dim program =
<compilation>
<file name="a.b">
Imports System
Structure SSSS1
End Structure
Structure SSSS2
Private s As String
End Structure
Enum e1
a
End Enum
Class CCCCCC
Public ReadOnly Property Prop1 As System.Threading.CancellationToken
Get
End Get
End Property
Public ReadOnly Property Prop2 As SSSS1
Get
End Get
End Property
Public ReadOnly Property Prop3 As SSSS2
Get
End Get
End Property
Public ReadOnly Property Prop4 As e1
Get
End Get
End Property
Public ReadOnly Property Prop5 As String
Get
End Get
End Property
Public ReadOnly Property Prop6 As Integer
Get
End Get
End Property
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC42107: Property 'Prop3' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Get
~~~~~~~
BC42355: Property 'Prop4' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Get
~~~~~~~
BC42107: Property 'Prop5' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Get
~~~~~~~
BC42355: Property 'Prop6' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Get
~~~~~~~
</errors>)
End Sub
<Fact(), WorkItem(531237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531237")>
Public Sub Bug17796()
Dim program = <compilation>
<file name="a.b"><![CDATA[
Imports System, System.Runtime.CompilerServices
Public Module Program
Sub Main()
End Sub
Interface ITextView
Event Closed As EventHandler
End Interface
<Extension()>
Public Sub AddOneTimeCloseHandler(ByVal view As ITextView, ByVal del As Action)
Dim del2 As EventHandler = Sub(notUsed1, notUsed2)
del()
RemoveHandler view.Closed, del2
End Sub
Dim del3 As Object = Function() As Object
del()
return del3
End Function.Invoke()
Dim del4 As EventHandler
del4 = Sub(notUsed1, notUsed2)
del()
RemoveHandler view.Closed, del4
End Sub
Dim del5 As Object
del5 = Function() As Object
del()
return del5
End Function.Invoke()
Dim del6 As EventHandler = DirectCast(TryCast(CType(
Sub(notUsed1, notUsed2)
del()
RemoveHandler view.Closed, del6
End Sub, EventHandler), EventHandler), EventHandler)
Dim del7 As EventHandler = (Sub(notUsed1, notUsed2)
del()
RemoveHandler view.Closed, del7
End Sub)
End Sub
End Module
]]></file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, {SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(comp,
<errors>
BC42104: Variable 'del3' is used before it has been assigned a value. A null reference exception could result at runtime.
return del3
~~~~
BC42104: Variable 'del5' is used before it has been assigned a value. A null reference exception could result at runtime.
return del5
~~~~
</errors>)
End Sub
<Fact(), WorkItem(530465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530465")>
Public Sub SuppressErrorReportingForSynthesizedLocalSymbolWithEmptyName()
Dim program = <compilation>
<file name="a.b"><![CDATA[
Module Module1
Sub Main()
Dim
End Sub
Sub M()
Static
End Sub
End Module
]]></file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program)
CompilationUtils.AssertTheseDiagnostics(comp,
<errors>
BC30203: Identifier expected.
Dim
~
BC30203: Identifier expected.
Static
~
</errors>)
End Sub
<Fact(), WorkItem(2896, "https://github.com/dotnet/roslyn/issues/2896")>
Public Sub Issue2896()
Dim program = <compilation>
<file name="a.b"><![CDATA[
Public Class Test
Private _f1 As Boolean = Not Me.DaysTimesInputEnable
Private _f2 As Boolean = Me.DaysTimesInputEnable
Public ReadOnly Property DaysTimesInputEnable As Boolean
Get
Return True
End Get
End Property
End Class
]]></file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program)
CompilationUtils.AssertTheseDiagnostics(comp)
End Sub
<Fact>
Public Sub LogicalExpressionInErroneousObjectInitializer()
Dim program = <compilation>
<file name="a.b">
Public Class Class1
Sub Test()
Dim x As S1
Dim y As New C1() With {.F1 = x.F1 AndAlso x.F2, .F3 = x.F3}
End Sub
End Class
Public Structure S1
Public F1 As Boolean
Public F2 As Boolean
Public F3 As Object
End Structure
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program, options:=TestOptions.DebugDll)
comp.AssertTheseDiagnostics(
<expected>
BC30002: Type 'C1' is not defined.
Dim y As New C1() With {.F1 = x.F1 AndAlso x.F2, .F3 = x.F3}
~~
BC42104: Variable 'F3' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim y As New C1() With {.F1 = x.F1 AndAlso x.F2, .F3 = x.F3}
~~~~
</expected>
)
End Sub
End Class
End Namespace
|
davkean/roslyn
|
src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/FlowDiagnosticTests.vb
|
Visual Basic
|
apache-2.0
| 58,249
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Globalization
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Display = Microsoft.CodeAnalysis.VisualBasic.SymbolDisplay
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' The base class for all symbols (namespaces, classes, method, parameters, etc.) that are
''' exposed by the compiler.
''' </summary>
<DebuggerDisplay("{GetDebuggerDisplay(), nq}")>
Friend MustInherit Class Symbol
Implements ISymbol, IMessageSerializable
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
' Changes to the public interface of this class should remain synchronized with the C# version of Symbol.
' Do not make any changes to the public interface without making the corresponding change
' to the C# version.
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
''' <summary>
''' Gets the name of this symbol.
''' </summary>
''' <returns>Returns the name of this symbol. Symbols without a name return the empty string;
''' Nothing is never returned.</returns>
Public Overridable ReadOnly Property Name As String
Get
Return String.Empty
End Get
End Property
''' <summary>
''' Gets the name of a symbol as it appears in metadata. Most of the time, this
''' is the same as the Name property, with the following exceptions:
''' 1) The metadata name of generic types includes the "`1", "`2" etc. suffix that
''' indicates the number of type parameters (it does not include, however, names of
''' containing types or namespaces).
''' 2) The metadata name of methods that overload or override methods with the same
''' case-insensitive name but different case-sensitive names are adjusted so that
''' the overrides and overloads always have the same name in a case-sensitive way.
'''
''' It should be noted that Visual Basic merges namespace declaration from source
''' and/or metadata with different casing into a single namespace symbol. Thus, for
''' namespace symbols this property may return incorrect information if multiple declarations
''' with different casing were found.
''' </summary>
Public Overridable ReadOnly Property MetadataName As String Implements ISymbol.MetadataName
Get
Return Name
End Get
End Property
''' <summary>
''' Set the metadata name for this symbol.
''' Called from <see cref="OverloadingHelper.SetMetadataNameForAllOverloads"/> for each symbol of the same name in a type.
''' </summary>
Friend Overridable Sub SetMetadataName(metadataName As String)
' only user defined methods and properties can have their name changed
Throw ExceptionUtilities.Unreachable
End Sub
''' <summary>
''' Gets the kind of this symbol.
''' </summary>
Public MustOverride ReadOnly Property Kind As SymbolKind
''' <summary>
''' Get the symbol that logically contains this symbol.
''' </summary>
Public MustOverride ReadOnly Property ContainingSymbol As Symbol
''' <summary>
''' Gets the nearest enclosing namespace for this namespace or type. For a nested type,
''' returns the namespace that contains its container.
''' </summary>
Public ReadOnly Property ContainingNamespace As NamespaceSymbol
Get
Dim container = Me.ContainingSymbol
While container IsNot Nothing
Dim ns = TryCast(container, NamespaceSymbol)
If ns IsNot Nothing Then
Return ns
End If
container = container.ContainingSymbol
End While
Return Nothing
End Get
End Property
''' <summary>
''' Returns the nearest lexically enclosing type, or Nothing if there is none.
''' </summary>
Public Overridable ReadOnly Property ContainingType As NamedTypeSymbol
Get
Dim container As Symbol = Me.ContainingSymbol
Dim containerAsType As NamedTypeSymbol = TryCast(container, NamedTypeSymbol)
' NOTE: container could be null, so we do not check
' whether containerAsType is not null, but
' instead check if it did not change after
' the cast.
If containerAsType Is container Then
' this should be relatively uncommon
' most symbols that may be contained in a type
' know their containing type and can override ContainingType
' with a more precise implementation
Return containerAsType
End If
' this is recursive, but recursion should be very short
' before we reach symbol that definitely knows its containing type.
Return container.ContainingType
End Get
End Property
''' <summary>
''' Returns the containing type or namespace, if this symbol is immediately contained by it.
''' Otherwise returns Nothing.
''' </summary>
Friend ReadOnly Property ContainingNamespaceOrType As NamespaceOrTypeSymbol
Get
Dim container = Me.ContainingSymbol
If container IsNot Nothing Then
Select Case container.Kind
Case SymbolKind.Namespace
Return DirectCast(ContainingSymbol, NamespaceSymbol)
Case SymbolKind.NamedType
Return DirectCast(ContainingSymbol, NamedTypeSymbol)
End Select
End If
Return Nothing
End Get
End Property
''' <summary>
''' Returns the assembly containing this symbol. If this symbol is shared
''' across multiple assemblies, or doesn't belong to an assembly, returns Nothing.
''' </summary>
Public Overridable ReadOnly Property ContainingAssembly As AssemblySymbol
Get
' Default implementation gets the containers assembly.
Dim container As Symbol = Me.ContainingSymbol
If container IsNot Nothing Then
Return container.ContainingAssembly
Else
Return Nothing
End If
End Get
End Property
''' <summary>
''' For a source assembly, the associated compilation.
''' For any other assembly, null.
''' For a source module, the DeclaringCompilation of the associated source assembly.
''' For any other module, null.
''' For any other symbol, the DeclaringCompilation of the associated module.
''' </summary>
''' <remarks>
''' We're going through the containing module, rather than the containing assembly,
''' because of /addmodule (symbols in such modules should return null).
'''
''' Remarks, not "ContainingCompilation" because it isn't transitive.
''' </remarks>
Friend Overridable ReadOnly Property DeclaringCompilation As VisualBasicCompilation
Get
Select Case Me.Kind
Case SymbolKind.ErrorType
Return Nothing
Case SymbolKind.Assembly
Debug.Assert(Not (TypeOf Me Is SourceAssemblySymbol), "SourceAssemblySymbol must override DeclaringCompilation")
Return Nothing
Case SymbolKind.NetModule
Debug.Assert(Not (TypeOf Me Is SourceModuleSymbol), "SourceModuleSymbol must override DeclaringCompilation")
Return Nothing
End Select
Dim sourceModuleSymbol = TryCast(Me.ContainingModule, SourceModuleSymbol)
Return If(sourceModuleSymbol Is Nothing, Nothing, sourceModuleSymbol.DeclaringCompilation)
End Get
End Property
''' <summary>
''' Returns the module containing this symbol. If this symbol is shared
''' across multiple modules, or doesn't belong to a module, returns Nothing.
''' </summary>
Public Overridable ReadOnly Property ContainingModule As ModuleSymbol
Get
' Default implementation gets the containers module.
Dim container As Symbol = Me.ContainingSymbol
If (container IsNot Nothing) Then
Return container.ContainingModule
Else
Return Nothing
End If
End Get
End Property
''' <summary>
''' Get the original definition of this symbol. If this symbol is derived from another
''' symbol by (say) type substitution, this gets the original symbol, as it was defined
''' in source or metadata.
''' </summary>
Public ReadOnly Property OriginalDefinition As Symbol
Get
Return OriginalSymbolDefinition
End Get
End Property
Protected Overridable ReadOnly Property OriginalSymbolDefinition As Symbol
Get
' Default implements returns Me.
Return Me
End Get
End Property
''' <summary>
''' Returns true if this is the original definition of this symbol.
''' </summary>
Public ReadOnly Property IsDefinition As Boolean
Get
' TODO: Is "Is" or "Equals" correct here?
Return OriginalDefinition Is Me
End Get
End Property
''' <summary>
''' <para>
''' Get a source location key for sorting. For performance, it's important that this
''' be able to be returned from a symbol without doing any additional allocations (even
''' if nothing is cached yet.)
''' </para>
''' <para>
''' Only (original) source symbols and namespaces that can be merged
''' need override this function if they want to do so for efficiency.
''' </para>
''' </summary>
Friend Overridable Function GetLexicalSortKey() As LexicalSortKey
Dim locations = Me.Locations
Dim declaringCompilation = Me.DeclaringCompilation
Debug.Assert(declaringCompilation IsNot Nothing) ' require that it is a source symbol
Return If(locations.Length > 0, New LexicalSortKey(locations(0), declaringCompilation), LexicalSortKey.NotInSource)
End Function
''' <summary>
''' Gets the locations where this symbol was originally defined, either in source
''' or metadata. Some symbols (for example, partial classes) may be defined in more
''' than one location.
''' </summary>
Public MustOverride ReadOnly Property Locations As ImmutableArray(Of Location)
''' <summary>
''' Get the syntax node(s) where this symbol was declared in source. Some symbols (for example,
''' partial classes) may be defined in more than one location. This property should return
''' one or more syntax nodes only if the symbol was declared in source code and also was
''' not implicitly declared (see the IsImplicitlyDeclared property).
'''
''' Note that for namespace symbol, the declaring syntax might be declaring a nested namespace.
''' For example, the declaring syntax node for N1 in "Namespace N1.N2" is the
''' NamespaceDeclarationSyntax for N1.N2. For the project namespace, the declaring syntax will
''' be the CompilationUnitSyntax.
''' </summary>
''' <returns>
''' The syntax node(s) that declared the symbol. If the symbol was declared in metadata
''' or was implicitly declared, returns an empty read-only array.
''' </returns>
''' <remarks>
''' To go the opposite direction (from syntax node to symbol), see <see cref="VBSemanticModel.GetDeclaredSymbol"/>.
''' </remarks>
Public MustOverride ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
''' <summary>
''' Helper for implementing DeclaringSyntaxNodes for derived classes that store a location but not a SyntaxNode or SyntaxReference.
''' </summary>
Friend Shared Function GetDeclaringSyntaxNodeHelper(Of TNode As VisualBasicSyntaxNode)(locations As ImmutableArray(Of Location)) As ImmutableArray(Of VisualBasicSyntaxNode)
If locations.IsEmpty Then
Return ImmutableArray(Of VisualBasicSyntaxNode).Empty
Else
Dim builder As ArrayBuilder(Of VisualBasicSyntaxNode) = ArrayBuilder(Of VisualBasicSyntaxNode).GetInstance()
For Each location In locations
If location.IsInSource AndAlso location.SourceTree IsNot Nothing Then
Dim token = CType(location.SourceTree.GetRoot().FindToken(location.SourceSpan.Start), SyntaxToken)
If token.Kind <> SyntaxKind.None Then
Dim node As VisualBasicSyntaxNode = token.Parent.FirstAncestorOrSelf(Of TNode)()
If node IsNot Nothing Then
builder.Add(node)
End If
End If
End If
Next
Return builder.ToImmutableAndFree()
End If
End Function
''' <summary>
''' Helper for implementing DeclaringSyntaxNodes for derived classes that store a location but not a SyntaxNode or SyntaxReference.
''' </summary>
Friend Shared Function GetDeclaringSyntaxReferenceHelper(Of TNode As VisualBasicSyntaxNode)(locations As ImmutableArray(Of Location)) As ImmutableArray(Of SyntaxReference)
Dim nodes = GetDeclaringSyntaxNodeHelper(Of TNode)(locations)
If nodes.IsEmpty Then
Return ImmutableArray(Of SyntaxReference).Empty
Else
Dim builder As ArrayBuilder(Of SyntaxReference) = ArrayBuilder(Of SyntaxReference).GetInstance()
For Each node In nodes
builder.Add(node.GetReference())
Next
Return builder.ToImmutableAndFree()
End If
End Function
''' <summary>
''' Helper for implementing DeclaringSyntaxNodes for derived classes that store SyntaxReferences.
''' </summary>
Friend Shared Function GetDeclaringSyntaxReferenceHelper(references As ImmutableArray(Of SyntaxReference)) As ImmutableArray(Of SyntaxReference)
' Optimize for the very common case of just one reference
If references.Length = 1 Then
Return GetDeclaringSyntaxReferenceHelper(references(0))
End If
Dim builder As ArrayBuilder(Of SyntaxReference) = ArrayBuilder(Of SyntaxReference).GetInstance()
For Each reference In references
Dim tree = reference.SyntaxTree
If Not tree.IsEmbeddedOrMyTemplateTree() Then
builder.Add(New BeginOfBlockSyntaxReference(reference))
End If
Next
Return builder.ToImmutableAndFree()
End Function
Friend Shared Function GetDeclaringSyntaxReferenceHelper(reference As SyntaxReference) As ImmutableArray(Of SyntaxReference)
If reference IsNot Nothing Then
Dim tree = reference.SyntaxTree
If Not tree.IsEmbeddedOrMyTemplateTree() Then
Return ImmutableArray.Create(Of SyntaxReference)(New BeginOfBlockSyntaxReference(reference))
End If
End If
Return ImmutableArray(Of SyntaxReference).Empty
End Function
''' <summary>
''' Get this accessibility that was declared on this symbol. For symbols that do
''' not have accessibility declared on them, returns NotApplicable.
''' </summary>
Public MustOverride ReadOnly Property DeclaredAccessibility As Accessibility
''' <summary>
''' Returns true if this symbol is "shared"; i.e., declared with the "Shared"
''' modifier or implicitly always shared.
''' </summary>
Public MustOverride ReadOnly Property IsShared As Boolean
''' <summary>
''' Returns true if this member is overridable, has an implementation,
''' and does not override a base class member; i.e., declared with the "Overridable"
''' modifier. Does not return true for members declared as MustOverride or Overrides.
''' </summary>
Public MustOverride ReadOnly Property IsOverridable As Boolean
''' <summary>
''' Returns true if this symbol was declared to override a base class members; i.e., declared
''' with the "Overrides" modifier. Still returns true if the members was declared
''' to override something, but (erroneously) no member to override exists.
''' </summary>
Public MustOverride ReadOnly Property IsOverrides As Boolean
''' <summary>
''' Returns true if this symbol was declared as requiring an override; i.e., declared
''' with the "MustOverride" modifier. Never returns true for types.
''' Also methods, properties and events declared in interface are considered to have MustOverride.
''' </summary>
Public MustOverride ReadOnly Property IsMustOverride As Boolean
''' <summary>
''' Returns true if this symbol was declared to override a base class members and was
''' also restricted from further overriding; i.e., declared with the "NotOverridable"
''' modifier. Never returns true for types.
''' </summary>
Public MustOverride ReadOnly Property IsNotOverridable As Boolean
''' <summary>
''' Returns true if this symbol was automatically created by the compiler, and does not
''' have an explicit corresponding source code declaration.
''' </summary>
''' <remarks>
''' This is intended for symbols that are ordinary symbols in the language sense,
''' and may be used by code, but that are simply declared implicitly rather than
''' with explicit language syntax.
'''
''' Examples include (this list is not exhaustive):
''' the default constructor for a class or struct that is created if one is not provided,
''' the BeginInvoke/Invoke/EndInvoke methods for a delegate,
''' the generated backing field for an auto property or a field-like event,
''' the "this" parameter for non-static methods,
''' the "value" parameter for a property setter,
''' the parameters on indexer accessor methods (not on the indexer itself),
''' methods in anonymous types
''' </remarks>
Public Overridable ReadOnly Property IsImplicitlyDeclared As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' True if this symbol has been marked with the Obsolete attribute.
''' This property returns Unknown if the Obsolete Attribute hasn't been cracked yet.
''' </summary>
Friend ReadOnly Property ObsoleteState As ThreeState
Get
Select Case ObsoleteKind
Case ObsoleteAttributeKind.None, ObsoleteAttributeKind.Experimental
Return ThreeState.False
Case ObsoleteAttributeKind.Uninitialized
Return ThreeState.Unknown
Case Else
Return ThreeState.True
End Select
End Get
End Property
Friend ReadOnly Property ObsoleteKind As ObsoleteAttributeKind
Get
Dim data = Me.ObsoleteAttributeData
Return If(data Is Nothing, ObsoleteAttributeKind.None, data.Kind)
End Get
End Property
''' <summary>
''' Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute.
''' This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet.
''' </summary>
Friend MustOverride ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
''' <summary>
''' Returns the symbol that implicitly defined this symbol, or Nothing if this
''' symbol was declared explicitly. Examples of implicit symbols are property
''' accessors and the backing field for an automatically implemented property.
'''
''' NOTE: there are scenarios in which ImplicitlyDefinedBy is called while bound members
''' are not yet published. This typically happens if ImplicitlyDefinedBy while binding members.
''' In such case, if callee needs to refer to a member of enclosing type it must
''' do that in the context of unpublished members that caller provides
''' (asking encompassing type for members will cause infinite recursion).
'''
''' NOTE: There could be several threads trying to bind and publish members, only one will succeed.
''' Reporting ImplicitlyDefinedBy within the set of members known to the caller guarantees
''' that if particular thread succeeds it will not have information that refers to something
''' built by another thread and discarded.
''' </summary>
Friend Overridable ReadOnly Property ImplicitlyDefinedBy(Optional membersInProgress As Dictionary(Of String, ArrayBuilder(Of Symbol)) = Nothing) As Symbol
Get
Return Nothing
End Get
End Property
''' <summary>
''' Returns true if 'Shadows' is explicitly specified on the declaration if the symbol is from
''' source, or in cases of synthesized symbols, if 'Shadows' is specified on the associated
''' source symbol. (For instance, ShadowsExplicitly will be set on the backing fields and
''' accessors for properties and events based on the value from the property or event.)
''' Returns false in all other cases, in particular, for symbols not from source.
''' </summary>
Friend Overridable ReadOnly Property ShadowsExplicitly As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Returns true if this symbol can be referenced by its name in code. Examples of symbols
''' that cannot be referenced by name are:
''' constructors, operators,
''' accessor methods for properties and events.
''' </summary>
Public ReadOnly Property CanBeReferencedByName As Boolean
Get
Select Case Me.Kind
Case SymbolKind.Local,
SymbolKind.Label,
SymbolKind.Alias
' Can't be imported, but might have syntax errors in which case we use an empty name:
Return Me.Name.Length > 0
Case SymbolKind.Namespace,
SymbolKind.Field,
SymbolKind.RangeVariable,
SymbolKind.Property,
SymbolKind.Event,
SymbolKind.Parameter,
SymbolKind.TypeParameter,
SymbolKind.ErrorType
Exit Select
Case SymbolKind.NamedType
If DirectCast(Me, NamedTypeSymbol).IsSubmissionClass Then
Return False
End If
Exit Select
Case SymbolKind.Method
Select Case DirectCast(Me, MethodSymbol).MethodKind
Case MethodKind.Ordinary, MethodKind.DeclareMethod, MethodKind.ReducedExtension
Exit Select
Case MethodKind.DelegateInvoke, MethodKind.UserDefinedOperator, MethodKind.Conversion
Return True
Case Else
Return False
End Select
Case SymbolKind.Assembly, SymbolKind.NetModule, SymbolKind.ArrayType
Return False
Case Else
Throw ExceptionUtilities.UnexpectedValue(Me.Kind)
End Select
' If we are from source, only need to check the first character, because all special
' names we create in source have a bad first character.
' NOTE: usually, the distinction we want to make is between the "current" compilation and another
' compilation, rather than between source and non-source. In this case, however, it suffices
' to know that the symbol came from any compilation because we are just optimizing based on whether
' or not previous validation occurred.
If Me.Dangerous_IsFromSomeCompilationIncludingRetargeting Then
Return Not String.IsNullOrEmpty(Me.Name) AndAlso SyntaxFacts.IsIdentifierStartCharacter(Me.Name(0))
Else
Return SyntaxFacts.IsValidIdentifier(Me.Name)
End If
End Get
End Property
''' <summary>
''' As an optimization, viability checking in the lookup code should use this property instead
''' of CanBeReferencedByName.
''' </summary>
''' <remarks>
''' This property exists purely for performance reasons.
''' </remarks>
Friend ReadOnly Property CanBeReferencedByNameIgnoringIllegalCharacters As Boolean
Get
If Me.Kind = SymbolKind.Method Then
Select Case (DirectCast(Me, MethodSymbol)).MethodKind
Case MethodKind.Ordinary, MethodKind.DeclareMethod, MethodKind.ReducedExtension, MethodKind.DelegateInvoke, MethodKind.UserDefinedOperator, MethodKind.Conversion
Return True
Case Else
Return False
End Select
End If
Return True
End Get
End Property
''' <summary>
''' Is this a symbol that is generated by the compiler and
''' automatically added to the compilation? Note that
''' only source symbols may be embedded symbols.
'''
''' Namespace symbol is considered to be an embedded symbol
''' if at least one of its declarations are embedded symbols.
''' </summary>
Friend ReadOnly Property IsEmbedded As Boolean
Get
Return EmbeddedSymbolKind <> VisualBasic.Symbols.EmbeddedSymbolKind.None
End Get
End Property
Friend Overridable ReadOnly Property EmbeddedSymbolKind As EmbeddedSymbolKind
Get
Return EmbeddedSymbolKind.None
End Get
End Property
''' <summary>
''' <see cref="CharSet"/> effective for this symbol (type or DllImport method).
''' Nothing if <see cref="DefaultCharSetAttribute"/> isn't applied on the containing module or it doesn't apply on this symbol.
''' </summary>
''' <remarks>
''' Determined based upon value specified via <see cref="DefaultCharSetAttribute"/> applied on the containing module.
''' Symbols that are embedded are not affected by <see cref="DefaultCharSetAttribute"/> (see DevDiv bug #16434).
''' </remarks>
Friend ReadOnly Property EffectiveDefaultMarshallingCharSet As CharSet?
Get
Return If(IsEmbedded, Nothing, Me.ContainingModule.DefaultMarshallingCharSet)
End Get
End Property
Friend Function IsFromCompilation(compilation As VisualBasicCompilation) As Boolean
Debug.Assert(compilation IsNot Nothing)
Return compilation Is Me.DeclaringCompilation
End Function
''' <summary>
''' Always prefer IsFromCompilation.
''' </summary>
''' <remarks>
''' This property is actually a triple workaround:
'''
''' 1) Unfortunately, when determining overriding/hiding/implementation relationships, we don't
''' have the "current" compilation available. We could, but that would clutter up the API
''' without providing much benefit. As a compromise, we consider all compilations "current".
'''
''' 2) TypeSymbol.Interfaces doesn't roundtrip in the presence of implicit interface implementation.
''' In particular, the metadata symbol may declare fewer interfaces than the source symbol so
''' that runtime implicit interface implementation will find the right symbol. Thus, we need to
''' know what kind of symbol we are dealing with to be able to interpret the Interfaces property
''' properly. Since a retargeting TypeSymbol will reflect the behavior of the underlying source
''' TypeSymbol, we need this property to match as well. (C# does not have this problem.)
'''
''' 3) The Dev12 VB compiler avoided loading private fields of structs from metadata, even though
''' they're supposed to affect definite assignment analysis. For compatibility
''' we therefore ignore these fields when doing DA analysis. (C# has a similar issue.)
''' </remarks>
Friend ReadOnly Property Dangerous_IsFromSomeCompilationIncludingRetargeting As Boolean
Get
If Me.DeclaringCompilation IsNot Nothing Then
Return True
End If
If Me.Kind = SymbolKind.Assembly Then
Dim retargetingAssembly = TryCast(Me, Retargeting.RetargetingAssemblySymbol)
Return retargetingAssembly IsNot Nothing AndAlso retargetingAssembly.UnderlyingAssembly.DeclaringCompilation IsNot Nothing
End If
Dim [module] = If(Me.Kind = SymbolKind.NetModule, Me, Me.ContainingModule)
Dim retargetingModule = TryCast([module], Retargeting.RetargetingModuleSymbol)
Return retargetingModule IsNot Nothing AndAlso retargetingModule.UnderlyingModule.DeclaringCompilation IsNot Nothing
End Get
End Property
''' <summary>
''' Equivalent to MethodKind = MethodKind.LambdaMethod, but can be called on a symbol directly.
''' </summary>
Friend Overridable ReadOnly Property IsLambdaMethod As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Is this an auto-generated property of a group class?
''' </summary>
Friend Overridable ReadOnly Property IsMyGroupCollectionProperty As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Is this lambda method a query lambda?
''' If it is, IsLambdaMethod == True as well.
''' </summary>
Friend Overridable ReadOnly Property IsQueryLambdaMethod As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Returns true and a <see cref="String"/> from the first <see cref="GuidAttribute"/> on the symbol,
''' the string might be null or an invalid guid representation. False,
''' if there is no <see cref="GuidAttribute"/> with string argument.
''' </summary>
Friend Function GetGuidStringDefaultImplementation(<Out> ByRef guidString As String) As Boolean
For Each attrData In GetAttributes()
If attrData.IsTargetAttribute(Me, AttributeDescription.GuidAttribute) Then
If attrData.TryGetGuidAttributeValue(guidString) Then
Return True
End If
End If
Next
guidString = Nothing
Return False
End Function
''' <summary>
''' Returns the Documentation Comment ID for the symbol, or Nothing if the symbol
''' doesn't support documentation comments.
''' </summary>
Public Overridable Function GetDocumentationCommentId() As String Implements ISymbol.GetDocumentationCommentId
Dim pool = PooledStringBuilder.GetInstance()
DocumentationCommentIdVisitor.Instance.Visit(Me, pool.Builder)
Dim result = pool.ToStringAndFree()
Return If(result.Length = 0, Nothing, result)
End Function
''' <summary>
''' Fetches the documentation comment for this element with a cancellation token.
''' </summary>
''' <param name="preferredCulture">Optionally, retrieve the comments formatted for a particular culture. No impact on source documentation comments.</param>
''' <param name="expandIncludes">Optionally, expand <![CDATA[<include>]]> elements. No impact on non-source documentation comments.</param>
''' <param name="cancellationToken">Optionally, allow cancellation of documentation comment retrieval.</param>
''' <returns>The XML that would be written to the documentation file for the symbol.</returns>
Public Overridable Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Implements ISymbol.GetDocumentationCommentXml
Return ""
End Function
''' <summary>
''' Compare two symbol objects to see if they refer to the same symbol. You should always use
''' = and <> or the Equals method, to compare two symbols for equality.
''' </summary>
Public Shared Operator =(left As Symbol, right As Symbol) As Boolean
'PERF: this Function() Is often called with
' 1) left referencing same object as the right
' 2) right being null
' The code attempts to check for these conditions before
' resorting to .Equals
If (right Is Nothing) Then
Return left Is Nothing
End If
Return left Is right OrElse right.Equals(left)
End Operator
''' <summary>
''' Compare two symbol objects to see if they refer to the same symbol. You should always use
''' = and <>, or the Equals method, to compare two symbols for equality.
''' </summary>
Public Shared Operator <>(left As Symbol, right As Symbol) As Boolean
'PERF: this Function() Is often called with
' 1) left referencing same object as the right
' 2) right being null
' The code attempts to check for these conditions before
' resorting to .Equals
If (right Is Nothing) Then
Return left IsNot Nothing
End If
Return left IsNot right AndAlso Not right.Equals(left)
End Operator
' By default, we do reference equality. This can be overridden.
Public Overrides Function [Equals](obj As Object) As Boolean
Return Me Is obj
End Function
Public Overloads Function [Equals](other As ISymbol) As Boolean Implements IEquatable(Of ISymbol).Equals
Return Me.[Equals](CObj(other))
End Function
' By default, we do reference equality. This can be overridden.
Public Overrides Function GetHashCode() As Integer
Return MyBase.GetHashCode()
End Function
Public NotOverridable Overrides Function ToString() As String
Return ToDisplayString(SymbolDisplayFormat.VisualBasicErrorMessageFormat)
End Function
Public Function ToDisplayString(Optional format As SymbolDisplayFormat = Nothing) As String
Return Display.ToDisplayString(Me, format)
End Function
Public Function ToDisplayParts(Optional format As SymbolDisplayFormat = Nothing) As ImmutableArray(Of SymbolDisplayPart)
Return Display.ToDisplayParts(Me, format)
End Function
Public Function ToMinimalDisplayString(semanticModel As SemanticModel, position As Integer, Optional format As SymbolDisplayFormat = Nothing) As String
Return Display.ToMinimalDisplayString(Me, semanticModel, position, format)
End Function
Public Function ToMinimalDisplayParts(semanticModel As SemanticModel, position As Integer, Optional format As SymbolDisplayFormat = Nothing) As ImmutableArray(Of SymbolDisplayPart)
Return Display.ToMinimalDisplayParts(Me, semanticModel, position, format)
End Function
Private Function GetDebuggerDisplay() As String
Return String.Format("{0} {1}", Me.Kind, Me.ToDisplayString(SymbolDisplayFormat.TestFormat))
End Function
' ---- End of Public Definition ---
' Below here can be Friend members that are useful to the compiler, but we don't
' want to expose publicly. However, using a class derived from SymbolVisitor can be
' a way to add the equivalent of a virtual method, but without having to put it directly
' in the Symbol class.
' ---- End of Public Definition ---
Friend MustOverride Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult
' Prevent anyone else from deriving from this class.
Friend Sub New()
End Sub
' Returns true if some or all of the symbol is defined in the given source tree.
Friend Overridable Function IsDefinedInSourceTree(tree As SyntaxTree, definedWithinSpan As TextSpan?, Optional cancellationToken As CancellationToken = Nothing) As Boolean
Dim declaringReferences = Me.DeclaringSyntaxReferences
If Me.IsImplicitlyDeclared AndAlso declaringReferences.Length = 0 Then
Return Me.ContainingSymbol.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken)
End If
' Default implementation: go through all locations and check for the definition.
' This is overridden for certain special cases (e.g., the implicit default constructor).
For Each syntaxRef In declaringReferences
cancellationToken.ThrowIfCancellationRequested()
If syntaxRef.SyntaxTree Is tree AndAlso
(Not definedWithinSpan.HasValue OrElse syntaxRef.Span.IntersectsWith(definedWithinSpan.Value)) Then
Return True
End If
Next
Return False
End Function
Friend Shared Function IsDefinedInSourceTree(syntaxNode As SyntaxNode, tree As SyntaxTree, definedWithinSpan As TextSpan?, Optional cancellationToken As CancellationToken = Nothing) As Boolean
Return syntaxNode IsNot Nothing AndAlso
syntaxNode.SyntaxTree Is tree AndAlso
(Not definedWithinSpan.HasValue OrElse definedWithinSpan.Value.IntersectsWith(syntaxNode.FullSpan))
End Function
''' <summary>
''' Force all declaration diagnostics to be generated for the symbol.
''' </summary>
Friend Overridable Sub GenerateDeclarationErrors(cancellationToken As CancellationToken)
End Sub
#Region "Use-Site Diagnostic"
''' <summary>
''' Returns error info for an error, if any, that should be reported at the use site of the symbol.
''' </summary>
Friend Overridable Function GetUseSiteErrorInfo() As DiagnosticInfo
Return Nothing
End Function
''' <summary>
''' Indicates that this symbol uses metadata that cannot be supported by the language.
'''
''' Examples include:
''' - Pointer types in VB
''' - ByRef return type
''' - Required custom modifiers
'''
''' This is distinguished from, for example, references to metadata symbols defined in assemblies that weren't referenced.
''' Symbols where this returns true can never be used successfully, and thus should never appear in any IDE feature.
'''
''' This is set for metadata symbols, as follows:
''' Type - if a type is unsupported (e.g., a pointer type, etc.)
''' Method - parameter or return type is unsupported
''' Field - type is unsupported
''' Event - type is unsupported
''' Property - type is unsupported
''' Parameter - type is unsupported
''' </summary>
Public Overridable ReadOnly Property HasUnsupportedMetadata As Boolean Implements ISymbol.HasUnsupportedMetadata
Get
Return False
End Get
End Property
''' <summary>
''' Derive error info from a type symbol.
''' </summary>
Friend Function DeriveUseSiteErrorInfoFromType(type As TypeSymbol) As DiagnosticInfo
Dim errorInfo As DiagnosticInfo = type.GetUseSiteErrorInfo()
If errorInfo IsNot Nothing Then
Select Case errorInfo.Code
Case ERRID.ERR_UnsupportedType1
Select Case Me.Kind
Case SymbolKind.Field
errorInfo = ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedField1, CustomSymbolDisplayFormatter.ShortErrorName(Me))
Case SymbolKind.Method
errorInfo = ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedMethod1, CustomSymbolDisplayFormatter.ShortErrorName(Me))
Case SymbolKind.Property
errorInfo = ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedProperty1, CustomSymbolDisplayFormatter.ShortErrorName(Me))
End Select
Case Else
' Nothing to do, simply use the same error info.
End Select
End If
Return errorInfo
End Function
''' <summary>
''' Return error code that has highest priority while calculating use site error for this symbol.
''' </summary>
Protected Overridable ReadOnly Property HighestPriorityUseSiteError As Integer ' Supposed to be ERRID, but it causes inconsistent accessibility error.
Get
Return Integer.MaxValue
End Get
End Property
Friend Function MergeUseSiteErrorInfo(first As DiagnosticInfo, second As DiagnosticInfo) As DiagnosticInfo
If first Is Nothing Then
Return second
End If
If second Is Nothing OrElse second.Code <> HighestPriorityUseSiteError Then
Return first
End If
Return second
End Function
Friend Function DeriveUseSiteErrorInfoFromParameter(param As ParameterSymbol, highestPriorityUseSiteError As Integer) As DiagnosticInfo
Dim errorInfo As DiagnosticInfo = DeriveUseSiteErrorInfoFromType(param.Type)
If errorInfo IsNot Nothing AndAlso errorInfo.Code = highestPriorityUseSiteError Then
Return errorInfo
End If
Dim refModifiersErrorInfo As DiagnosticInfo = DeriveUseSiteErrorInfoFromCustomModifiers(param.RefCustomModifiers)
If refModifiersErrorInfo IsNot Nothing AndAlso refModifiersErrorInfo.Code = highestPriorityUseSiteError Then
Return refModifiersErrorInfo
End If
Dim modifiersErrorInfo As DiagnosticInfo = DeriveUseSiteErrorInfoFromCustomModifiers(param.CustomModifiers)
If modifiersErrorInfo IsNot Nothing AndAlso modifiersErrorInfo.Code = highestPriorityUseSiteError Then
Return modifiersErrorInfo
End If
Return If(errorInfo, If(refModifiersErrorInfo, modifiersErrorInfo))
End Function
Friend Function DeriveUseSiteErrorInfoFromParameters(parameters As ImmutableArray(Of ParameterSymbol)) As DiagnosticInfo
Dim paramsErrorInfo As DiagnosticInfo = Nothing
Dim highestPriorityUseSiteError As Integer = Me.HighestPriorityUseSiteError
For Each param As ParameterSymbol In parameters
Dim errorInfo As DiagnosticInfo = DeriveUseSiteErrorInfoFromParameter(param, highestPriorityUseSiteError)
If errorInfo IsNot Nothing Then
If errorInfo.Code = highestPriorityUseSiteError Then
Return errorInfo
End If
If paramsErrorInfo Is Nothing Then
paramsErrorInfo = errorInfo
End If
End If
Next
Return paramsErrorInfo
End Function
Friend Function DeriveUseSiteErrorInfoFromCustomModifiers(
customModifiers As ImmutableArray(Of CustomModifier)
) As DiagnosticInfo
Dim modifiersErrorInfo As DiagnosticInfo = Nothing
Dim highestPriorityUseSiteError As Integer = Me.HighestPriorityUseSiteError
For Each modifier As CustomModifier In customModifiers
Dim errorInfo As DiagnosticInfo = DeriveUseSiteErrorInfoFromType(DirectCast(modifier.Modifier, TypeSymbol))
If errorInfo IsNot Nothing Then
If errorInfo.Code = highestPriorityUseSiteError Then
Return errorInfo
End If
If modifiersErrorInfo Is Nothing Then
modifiersErrorInfo = errorInfo
End If
End If
Next
Return modifiersErrorInfo
End Function
Friend Overloads Shared Function GetUnificationUseSiteDiagnosticRecursive(Of T As TypeSymbol)(types As ImmutableArray(Of T), owner As Symbol, ByRef checkedTypes As HashSet(Of TypeSymbol)) As DiagnosticInfo
For Each t In types
Dim info = t.GetUnificationUseSiteDiagnosticRecursive(owner, checkedTypes)
If info IsNot Nothing Then
Return info
End If
Next
Return Nothing
End Function
Friend Overloads Shared Function GetUnificationUseSiteDiagnosticRecursive(modifiers As ImmutableArray(Of CustomModifier), owner As Symbol, ByRef checkedTypes As HashSet(Of TypeSymbol)) As DiagnosticInfo
For Each modifier In modifiers
Dim info = DirectCast(modifier.Modifier, TypeSymbol).GetUnificationUseSiteDiagnosticRecursive(owner, checkedTypes)
If info IsNot Nothing Then
Return info
End If
Next
Return Nothing
End Function
Friend Overloads Shared Function GetUnificationUseSiteDiagnosticRecursive(parameters As ImmutableArray(Of ParameterSymbol), owner As Symbol, ByRef checkedTypes As HashSet(Of TypeSymbol)) As DiagnosticInfo
For Each parameter In parameters
Dim info = If(parameter.Type.GetUnificationUseSiteDiagnosticRecursive(owner, checkedTypes),
If(GetUnificationUseSiteDiagnosticRecursive(parameter.RefCustomModifiers, owner, checkedTypes),
GetUnificationUseSiteDiagnosticRecursive(parameter.CustomModifiers, owner, checkedTypes)))
If info IsNot Nothing Then
Return info
End If
Next
Return Nothing
End Function
Friend Overloads Shared Function GetUnificationUseSiteDiagnosticRecursive(typeParameters As ImmutableArray(Of TypeParameterSymbol), owner As Symbol, ByRef checkedTypes As HashSet(Of TypeSymbol)) As DiagnosticInfo
For Each typeParameter In typeParameters
Dim info = GetUnificationUseSiteDiagnosticRecursive(typeParameter.ConstraintTypesNoUseSiteDiagnostics, owner, checkedTypes)
If info IsNot Nothing Then
Return info
End If
Next
Return Nothing
End Function
#End Region
#Region "ISymbol"
Public MustOverride Sub Accept(visitor As SymbolVisitor) Implements ISymbol.Accept
Public MustOverride Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult Implements ISymbol.Accept
Public MustOverride Sub Accept(visitor As VisualBasicSymbolVisitor)
Public MustOverride Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult
Private ReadOnly Property ISymbol_ContainingAssembly As IAssemblySymbol Implements ISymbol.ContainingAssembly
Get
Return Me.ContainingAssembly
End Get
End Property
Private ReadOnly Property ISymbol_ContainingModule As IModuleSymbol Implements ISymbol.ContainingModule
Get
Return Me.ContainingModule
End Get
End Property
Private ReadOnly Property ISymbol_ContainingNamespace As INamespaceSymbol Implements ISymbol.ContainingNamespace
Get
Return Me.ContainingNamespace
End Get
End Property
Private ReadOnly Property ISymbol_ContainingSymbol As ISymbol Implements ISymbol.ContainingSymbol
Get
Return Me.ContainingSymbol
End Get
End Property
Private ReadOnly Property ISymbol_ContainingType As INamedTypeSymbol Implements ISymbol.ContainingType
Get
Return Me.ContainingType
End Get
End Property
Private ReadOnly Property ISymbol_DeclaredAccessibility As Accessibility Implements ISymbol.DeclaredAccessibility
Get
Return Me.DeclaredAccessibility
End Get
End Property
Protected Overridable ReadOnly Property ISymbol_IsAbstract As Boolean Implements ISymbol.IsAbstract
Get
Return Me.IsMustOverride
End Get
End Property
Private ReadOnly Property ISymbol_IsDefinition As Boolean Implements ISymbol.IsDefinition
Get
Return Me.IsDefinition
End Get
End Property
Private ReadOnly Property ISymbol_IsOverride As Boolean Implements ISymbol.IsOverride
Get
Return Me.IsOverrides
End Get
End Property
Protected Overridable ReadOnly Property ISymbol_IsSealed As Boolean Implements ISymbol.IsSealed
Get
Return Me.IsNotOverridable
End Get
End Property
Protected Overridable ReadOnly Property ISymbol_IsStatic As Boolean Implements ISymbol.IsStatic
Get
Return Me.IsShared
End Get
End Property
Private ReadOnly Property ISymbol_IsImplicitlyDeclared As Boolean Implements ISymbol.IsImplicitlyDeclared
Get
Return Me.IsImplicitlyDeclared
End Get
End Property
Private ReadOnly Property ISymbol_IsVirtual As Boolean Implements ISymbol.IsVirtual
Get
Return Me.IsOverridable
End Get
End Property
Private ReadOnly Property ISymbol_CanBeReferencedByName As Boolean Implements ISymbol.CanBeReferencedByName
Get
Return Me.CanBeReferencedByName
End Get
End Property
Public ReadOnly Property Language As String Implements ISymbol.Language
Get
Return LanguageNames.VisualBasic
End Get
End Property
Private ReadOnly Property ISymbol_Locations As ImmutableArray(Of Location) Implements ISymbol.Locations
Get
Return Me.Locations
End Get
End Property
Private ReadOnly Property ISymbol_DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Implements ISymbol.DeclaringSyntaxReferences
Get
Return Me.DeclaringSyntaxReferences
End Get
End Property
Private ReadOnly Property ISymbol_Name As String Implements ISymbol.Name
Get
Return Me.Name
End Get
End Property
Private ReadOnly Property ISymbol_OriginalDefinition As ISymbol Implements ISymbol.OriginalDefinition
Get
Return Me.OriginalDefinition
End Get
End Property
Private ReadOnly Property ISymbol_Kind As SymbolKind Implements ISymbol.Kind
Get
Return Me.Kind
End Get
End Property
Private Function ISymbol_ToDisplayString(Optional format As SymbolDisplayFormat = Nothing) As String Implements ISymbol.ToDisplayString
Return Display.ToDisplayString(Me, format)
End Function
Private Function ISymbol_ToDisplayParts(Optional format As SymbolDisplayFormat = Nothing) As ImmutableArray(Of SymbolDisplayPart) Implements ISymbol.ToDisplayParts
Return Display.ToDisplayParts(Me, format)
End Function
Private Function ISymbol_ToMinimalDisplayString(semanticModel As SemanticModel, position As Integer, Optional format As SymbolDisplayFormat = Nothing) As String Implements ISymbol.ToMinimalDisplayString
Return Display.ToMinimalDisplayString(Me, semanticModel, position, format)
End Function
Private Function ISymbol_ToMinimalDisplayParts(semanticModel As SemanticModel, position As Integer, Optional format As SymbolDisplayFormat = Nothing) As ImmutableArray(Of SymbolDisplayPart) Implements ISymbol.ToMinimalDisplayParts
Return Display.ToMinimalDisplayParts(Me, semanticModel, position, format)
End Function
Private ReadOnly Property ISymbol_IsExtern As Boolean Implements ISymbol.IsExtern
Get
Return False
End Get
End Property
Private Function ISymbol_GetAttributes() As ImmutableArray(Of AttributeData) Implements ISymbol.GetAttributes
Return StaticCast(Of AttributeData).From(Me.GetAttributes())
End Function
#End Region
End Class
End Namespace
|
amcasey/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/Symbol.vb
|
Visual Basic
|
apache-2.0
| 55,806
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Composition
Imports System.Runtime.Analyzers
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace System.Runtime.VisualBasic.Analyzers
''' <summary>
''' CA2242: Test for NaN correctly
''' </summary>
<ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]>
Public NotInheritable Class BasicTestForNaNCorrectlyFixer
Inherits TestForNaNCorrectlyFixer
Protected Overrides Function GetBinaryExpression(node As SyntaxNode) As SyntaxNode
Dim argumentSyntax = TryCast(node, ArgumentSyntax)
Return If(argumentSyntax IsNot Nothing, argumentSyntax.GetExpression(), node)
End Function
Protected Overrides Function IsEqualsOperator(node As SyntaxNode) As Boolean
return node.IsKind(SyntaxKind.EqualsExpression)
End Function
Protected Overrides Function IsNotEqualsOperator(node As SyntaxNode) As Boolean
return node.IsKind(SyntaxKind.NotEqualsExpression)
End Function
Protected Overrides Function GetLeftOperand(binaryExpressionSyntax As SyntaxNode) As SyntaxNode
Return DirectCast(binaryExpressionSyntax, BinaryExpressionSyntax).Left
End Function
Protected Overrides Function GetRightOperand(binaryExpressionSyntax As SyntaxNode) As SyntaxNode
Return DirectCast(binaryExpressionSyntax, BinaryExpressionSyntax).Right
End Function
End Class
End Namespace
|
qinxgit/roslyn-analyzers
|
src/System.Runtime.Analyzers/VisualBasic/BasicTestForNaNCorrectly.Fixer.vb
|
Visual Basic
|
apache-2.0
| 1,733
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Globalization
Imports System.Text
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols
Imports Roslyn.Test.Utilities
Imports System.Collections.Immutable
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class ContainerTests
Inherits BasicTestBase
' Check that "basRootNS" is actually a bad root namespace
Private Sub BadDefaultNS(badRootNS As String)
AssertTheseDiagnostics(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace(badRootNS).Errors,
<expected>
BC2014: the value '<%= badRootNS %>' is invalid for option 'RootNamespace'
</expected>)
End Sub
<Fact>
Public Sub SimpleAssembly()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Banana">
<file name="b.vb">
Namespace NS
Public Class Goo
End Class
End Namespace
</file>
</compilation>)
Dim sym = compilation.Assembly
Assert.Equal("Banana", sym.Name)
Assert.Equal("Banana, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", sym.ToTestDisplayString())
Assert.Equal(String.Empty, sym.GlobalNamespace.Name)
Assert.Equal(SymbolKind.Assembly, sym.Kind)
Assert.Equal(Accessibility.NotApplicable, sym.DeclaredAccessibility)
Assert.False(sym.IsShared)
Assert.False(sym.IsOverridable)
Assert.False(sym.IsOverrides)
Assert.False(sym.IsMustOverride)
Assert.False(sym.IsNotOverridable)
Assert.Null(sym.ContainingAssembly)
Assert.Null(sym.ContainingSymbol)
End Sub
<WorkItem(537302, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537302")>
<Fact>
Public Sub SourceModule()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Banana">
<file name="m.vb">
Namespace NS
Public Class Goo
End Class
End Namespace
</file>
</compilation>)
Dim sym = compilation.SourceModule
Assert.Equal("Banana.dll", sym.Name)
Assert.Equal(String.Empty, sym.GlobalNamespace.Name)
Assert.Equal(SymbolKind.NetModule, sym.Kind)
Assert.Equal(Accessibility.NotApplicable, sym.DeclaredAccessibility)
Assert.False(sym.IsShared)
Assert.False(sym.IsOverridable)
Assert.False(sym.IsOverrides)
Assert.False(sym.IsMustOverride)
Assert.False(sym.IsNotOverridable)
Assert.Equal("Banana", sym.ContainingAssembly.Name)
Assert.Equal("Banana", sym.ContainingSymbol.Name)
End Sub
<WorkItem(537421, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537421")>
<Fact>
Public Sub StandardModule()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Banana">
<file name="m.vb">
Namespace NS
Module MGoo
Dim A As Integer
Sub MySub()
End Sub
Function Func(x As Long) As Long
Return x
End Function
End Module
End Namespace
</file>
</compilation>)
Dim ns As NamespaceSymbol = DirectCast(compilation.SourceModule.GlobalNamespace.GetMembers("NS").Single(), NamespaceSymbol)
Dim sym1 = ns.GetMembers("MGoo").Single()
Assert.Equal("MGoo", sym1.Name)
Assert.Equal("NS.MGoo", sym1.ToTestDisplayString())
Assert.Equal(SymbolKind.NamedType, sym1.Kind)
' default - Friend
Assert.Equal(Accessibility.Friend, sym1.DeclaredAccessibility)
Assert.False(sym1.IsShared)
Assert.False(sym1.IsOverridable)
Assert.False(sym1.IsOverrides)
Assert.False(sym1.IsMustOverride)
Assert.False(sym1.IsNotOverridable)
Assert.Equal("Banana", sym1.ContainingAssembly.Name)
Assert.Equal("NS", sym1.ContainingSymbol.Name)
' module member
Dim smod = DirectCast(sym1, NamedTypeSymbol)
Dim sym2 = DirectCast(smod.GetMembers("A").Single(), FieldSymbol)
' default - Private
Assert.Equal(Accessibility.Private, sym2.DeclaredAccessibility)
Assert.True(sym2.IsShared)
Dim sym3 = DirectCast(smod.GetMembers("MySub").Single(), MethodSymbol)
Dim sym4 = DirectCast(smod.GetMembers("Func").Single(), MethodSymbol)
' default - Public
Assert.Equal(Accessibility.Public, sym3.DeclaredAccessibility)
Assert.Equal(Accessibility.Public, sym4.DeclaredAccessibility)
Assert.True(sym3.IsShared)
Assert.True(sym4.IsShared)
' shared cctor
'sym4 = DirectCast(smod.GetMembers(WellKnownMemberNames.StaticConstructorName).Single(), MethodSymbol)
End Sub
' Check that we disallow certain kids of bad root namespaces
<Fact>
Public Sub BadDefaultNSTest()
BadDefaultNS("Goo.7")
BadDefaultNS("Goo..Bar")
BadDefaultNS(".X")
BadDefaultNS("$")
End Sub
' Check that parse errors are reported
<Fact>
Public Sub NamespaceParseErrors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Banana">
<file name="a.vb">
Imports System.7
</file>
<file name="b.vb">
Namespace Goo
End Class
</file>
</compilation>)
Dim expectedErrors = <errors>
BC30205: End of statement expected.
Imports System.7
~~
BC30626: 'Namespace' statement must end with a matching 'End Namespace'.
Namespace Goo
~~~~~~~~~~~~~
BC30460: 'End Class' must be preceded by a matching 'Class'.
End Class
~~~~~~~~~
</errors>
CompilationUtils.AssertTheseParseDiagnostics(compilation, expectedErrors)
End Sub
' Check namespace symbols
<Fact>
Public Sub NSSym()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="C">
<file name="a.vb">
Namespace A
End Namespace
Namespace C
End Namespace
</file>
<file name="b.vb">
Namespace A.B
End Namespace
Namespace a.B
End Namespace
Namespace e
End Namespace
</file>
<file name="c.vb">
Namespace A.b.D
End Namespace
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Assert.Equal("", globalNS.Name)
Assert.Equal(SymbolKind.Namespace, globalNS.Kind)
Assert.Equal(3, globalNS.GetMembers().Length())
Dim members = globalNS.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name, IdentifierComparison.Comparer).ToArray()
Dim membersA = globalNS.GetMembers("a")
Dim membersC = globalNS.GetMembers("c")
Dim membersE = globalNS.GetMembers("E")
Assert.Equal(3, members.Length)
Assert.Equal(1, membersA.Length)
Assert.Equal(1, membersC.Length)
Assert.Equal(1, membersE.Length)
Assert.True(members.SequenceEqual(membersA.Concat(membersC).Concat(membersE).AsEnumerable()))
Assert.Equal("a", membersA.First().Name, IdentifierComparison.Comparer)
Assert.Equal("C", membersC.First().Name, IdentifierComparison.Comparer)
Assert.Equal("E", membersE.First().Name, IdentifierComparison.Comparer)
Dim nsA As NamespaceSymbol = DirectCast(membersA.First(), NamespaceSymbol)
Assert.Equal("A", nsA.Name, IdentifierComparison.Comparer)
Assert.Equal(SymbolKind.Namespace, nsA.Kind)
Assert.Equal(1, nsA.GetMembers().Length())
Dim nsB As NamespaceSymbol = DirectCast(nsA.GetMembers().First(), NamespaceSymbol)
Assert.Equal("B", nsB.Name, IdentifierComparison.Comparer)
Assert.Equal(SymbolKind.Namespace, nsB.Kind)
Assert.Equal(1, nsB.GetMembers().Length())
Dim nsD As NamespaceSymbol = DirectCast(nsB.GetMembers().First(), NamespaceSymbol)
Assert.Equal("D", nsD.Name)
Assert.Equal(SymbolKind.Namespace, nsD.Kind)
Assert.Equal(0, nsD.GetMembers().Length())
AssertTheseDeclarationDiagnostics(compilation,
<expected>
BC40055: Casing of namespace name 'a' does not match casing of namespace name 'A' in 'a.vb'.
Namespace a.B
~
BC40055: Casing of namespace name 'b' does not match casing of namespace name 'B' in 'b.vb'.
Namespace A.b.D
~
</expected>)
End Sub
' Check namespace symbols in the presence of a root namespace
<Fact>
Public Sub NSSymWithRootNamespace()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="C">
<file name="a.vb">
Namespace A
End Namespace
Namespace E
End Namespace
</file>
<file name="b.vb">
Namespace A.B
End Namespace
Namespace C
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithRootNamespace("Goo.Bar"))
Dim globalNS = compilation.SourceModule.GlobalNamespace
Assert.Equal("", globalNS.Name)
Assert.Equal(SymbolKind.Namespace, globalNS.Kind)
Assert.Equal(1, globalNS.GetMembers().Length())
Dim members = globalNS.GetMembers()
Dim nsGoo As NamespaceSymbol = DirectCast(members.First(), NamespaceSymbol)
Assert.Equal("Goo", nsGoo.Name, IdentifierComparison.Comparer)
Assert.Equal(SymbolKind.Namespace, nsGoo.Kind)
Assert.Equal(1, nsGoo.GetMembers().Length())
Dim membersGoo = nsGoo.GetMembers()
Dim nsBar As NamespaceSymbol = DirectCast(membersGoo.First(), NamespaceSymbol)
Assert.Equal("Bar", nsBar.Name, IdentifierComparison.Comparer)
Assert.Equal(SymbolKind.Namespace, nsBar.Kind)
Assert.Equal(3, nsBar.GetMembers().Length())
Dim membersBar = nsBar.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name, IdentifierComparison.Comparer).ToArray()
Dim membersA = nsBar.GetMembers("a")
Dim membersC = nsBar.GetMembers("c")
Dim membersE = nsBar.GetMembers("E")
Assert.Equal(3, membersBar.Length)
Assert.Equal(1, membersA.Length)
Assert.Equal(1, membersC.Length)
Assert.Equal(1, membersE.Length)
Assert.True(membersBar.SequenceEqual(membersA.Concat(membersC).Concat(membersE).AsEnumerable()))
Assert.Equal("a", membersA.First().Name, IdentifierComparison.Comparer)
Assert.Equal("C", membersC.First().Name, IdentifierComparison.Comparer)
Assert.Equal("E", membersE.First().Name, IdentifierComparison.Comparer)
Dim nsA As NamespaceSymbol = DirectCast(membersA.First(), NamespaceSymbol)
Assert.Equal("A", nsA.Name, IdentifierComparison.Comparer)
Assert.Equal(SymbolKind.Namespace, nsA.Kind)
Assert.Equal(1, nsA.GetMembers().Length())
Dim nsB As NamespaceSymbol = DirectCast(nsA.GetMembers().First(), NamespaceSymbol)
Assert.Equal("B", nsB.Name, IdentifierComparison.Comparer)
Assert.Equal(SymbolKind.Namespace, nsB.Kind)
Assert.Equal(0, nsB.GetMembers().Length())
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
' Check namespace symbol containers in the presence of a root namespace
<Fact>
Public Sub NSContainersWithRootNamespace()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="C">
<file name="a.vb">
Class Type1
End Class
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithRootNamespace("Goo.Bar"))
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim members = globalNS.GetMembers()
Dim nsGoo As NamespaceSymbol = DirectCast(members.First(), NamespaceSymbol)
Dim membersGoo = nsGoo.GetMembers()
Dim nsBar As NamespaceSymbol = DirectCast(membersGoo.First(), NamespaceSymbol)
Dim type1Sym = nsBar.GetMembers("Type1").Single()
Assert.Same(nsBar, type1Sym.ContainingSymbol)
Assert.Same(nsGoo, nsBar.ContainingSymbol)
Assert.Same(globalNS, nsGoo.ContainingSymbol)
Assert.Same(compilation.SourceModule, globalNS.ContainingSymbol)
End Sub
' Check namespace symbol containers in the presence of a root namespace
<Fact>
Public Sub NSContainersWithoutRootNamespace()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="C">
<file name="a.vb">
Class Type1
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim type1Sym = globalNS.GetMembers("Type1").Single()
Assert.Same(globalNS, type1Sym.ContainingSymbol)
Assert.Same(compilation.SourceModule, globalNS.ContainingSymbol)
End Sub
<Fact>
Public Sub ImportsAlias01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Test">
<file name="a.vb">
Imports ALS = N1.N2
Namespace N1
Namespace N2
Public Class A
Sub S()
End Sub
End Class
End Namespace
End Namespace
Namespace N3
Public Class B
Inherits ALS.A
End Class
End Namespace
</file>
<file name="b.vb">
Imports ANO = N3
Namespace N1.N2
Class C
Inherits ANO.B
End Class
End Namespace
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim n3 = DirectCast(globalNS.GetMembers("N3").Single(), NamespaceSymbol)
Dim mem1 = DirectCast(n3.GetTypeMembers("B").Single(), NamedTypeSymbol)
Assert.Equal("A", mem1.BaseType.Name)
Assert.Equal("N1.N2.A", mem1.BaseType.ToTestDisplayString())
Dim n1 = DirectCast(globalNS.GetMembers("N1").Single(), NamespaceSymbol)
Dim n2 = DirectCast(n1.GetMembers("N2").Single(), NamespaceSymbol)
Dim mem2 = DirectCast(n2.GetTypeMembers("C").Single(), NamedTypeSymbol)
Assert.Equal("B", mem2.BaseType.Name)
Assert.Equal("N3.B", mem2.BaseType.ToTestDisplayString())
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact, WorkItem(544009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544009")>
Public Sub MultiModulesNamespace()
Dim text3 = <![CDATA[
Namespace N1
Structure SGoo
End Structure
End Namespace
]]>.Value
Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Test1">
<file name="a.vb">
Namespace N1
Class CGoo
End Class
End Namespace
</file>
</compilation>)
Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Test2">
<file name="b.vb">
Namespace N1
Interface IGoo
End Interface
End Namespace
</file>
</compilation>)
Dim compRef1 = New VisualBasicCompilationReference(comp1)
Dim compRef2 = New VisualBasicCompilationReference(comp2)
Dim comp = VisualBasicCompilation.Create("Test3", {VisualBasicSyntaxTree.ParseText(text3)}, {MscorlibRef, compRef1, compRef2})
Dim globalNS = comp.GlobalNamespace
Dim ns = DirectCast(globalNS.GetMembers("N1").Single(), NamespaceSymbol)
Assert.Equal(3, ns.GetTypeMembers().Length())
Dim ext = ns.Extent
Assert.Equal(NamespaceKind.Compilation, ext.Kind)
Assert.Equal("Compilation: " & GetType(VisualBasicCompilation).FullName, ext.ToString())
Dim constituents = ns.ConstituentNamespaces
Assert.Equal(3, constituents.Length)
Assert.True(constituents.Contains(TryCast(comp.SourceAssembly.GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol)))
Assert.True(constituents.Contains(TryCast(comp.GetReferencedAssemblySymbol(compRef1).GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol)))
Assert.True(constituents.Contains(TryCast(comp.GetReferencedAssemblySymbol(compRef2).GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol)))
For Each constituentNs In constituents
Assert.Equal(NamespaceKind.Module, constituentNs.Extent.Kind)
Assert.Equal(ns.ToTestDisplayString(), constituentNs.ToTestDisplayString())
Next
End Sub
<WorkItem(537310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537310")>
<Fact>
Public Sub MultiModulesNamespaceCorLibraries()
Dim text1 = <![CDATA[
Namespace N1
Class CGoo
End Class
End Namespace
]]>.Value
Dim text2 = <![CDATA[
Namespace N1
Interface IGoo
End Interface
End Namespace
]]>.Value
Dim text3 = <![CDATA[
Namespace N1
Structure SGoo
End Structure
End Namespace
]]>.Value
Dim comp1 = VisualBasicCompilation.Create("Test1", syntaxTrees:={VisualBasicSyntaxTree.ParseText(text1)})
Dim comp2 = VisualBasicCompilation.Create("Test2", syntaxTrees:={VisualBasicSyntaxTree.ParseText(text2)})
Dim compRef1 = New VisualBasicCompilationReference(comp1)
Dim compRef2 = New VisualBasicCompilationReference(comp2)
Dim comp = VisualBasicCompilation.Create("Test3", {VisualBasicSyntaxTree.ParseText(text3)}, {compRef1, compRef2})
Dim globalNS = comp.GlobalNamespace
Dim ns = DirectCast(globalNS.GetMembers("N1").Single(), NamespaceSymbol)
Assert.Equal(3, ns.GetTypeMembers().Length())
Assert.Equal(NamespaceKind.Compilation, ns.Extent.Kind)
Dim constituents = ns.ConstituentNamespaces
Assert.Equal(3, constituents.Length)
Assert.True(constituents.Contains(TryCast(comp.SourceAssembly.GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol)))
Assert.True(constituents.Contains(TryCast(comp.GetReferencedAssemblySymbol(compRef1).GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol)))
Assert.True(constituents.Contains(TryCast(comp.GetReferencedAssemblySymbol(compRef2).GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol)))
For Each constituentNs In constituents
Assert.Equal(NamespaceKind.Module, constituentNs.Extent.Kind)
Assert.Equal(ns.ToTestDisplayString(), constituentNs.ToTestDisplayString())
Next
End Sub
<WorkItem(690871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/690871")>
<Fact>
Public Sub SpecialTypesAndAliases()
Dim source =
<compilation name="C">
<file>
Public Class C
End Class
</file>
</compilation>
Dim aliasedCorlib = TestReferences.NetFx.v4_0_30319.mscorlib.WithAliases(ImmutableArray.Create("Goo"))
Dim comp = CreateCompilationWithReferences(source, {aliasedCorlib})
' NOTE: this doesn't compile in dev11 - it reports that it cannot find System.Object.
' However, we've already changed how special type lookup works, so this is not a major issue.
comp.AssertNoDiagnostics()
Dim objectType = comp.GetSpecialType(SpecialType.System_Object)
Assert.Equal(TypeKind.Class, objectType.TypeKind)
Assert.Equal("System.Object", objectType.ToTestDisplayString())
Assert.Equal(objectType, comp.Assembly.GetSpecialType(SpecialType.System_Object))
Assert.Equal(objectType, comp.Assembly.CorLibrary.GetSpecialType(SpecialType.System_Object))
End Sub
<WorkItem(690871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/690871")>
<Fact>
Public Sub WellKnownTypesAndAliases()
Dim [lib] =
<compilation name="lib">
<file>
Namespace System.Threading.Tasks
Public Class Task
Public Status As Integer
End Class
End Namespace
</file>
</compilation>
Dim source =
<compilation name="test">
<file>
Imports System.Threading.Tasks
Public Class App
Public T as Task
End Class
</file>
</compilation>
Dim libComp = CreateCompilationWithReferences([lib], {MscorlibRef_v4_0_30316_17626})
Dim libRef = libComp.EmitToImageReference(aliases:=ImmutableArray.Create("myTask"))
Dim comp = CreateCompilationWithReferences(source, {libRef, MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929})
' NOTE: Unlike in C#, aliases on metadata references are ignored, so the
' reference to System.Threading.Tasks is ambiguous.
comp.AssertTheseDiagnostics(
<expected>
BC30560: 'Task' is ambiguous in the namespace 'System.Threading.Tasks'.
Public T as Task
~~~~
</expected>)
End Sub
End Class
End Namespace
|
mmitche/roslyn
|
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AssemblyAndNamespaceTests.vb
|
Visual Basic
|
apache-2.0
| 21,928
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.Classification
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Classification.Classifiers
Friend Class NameSyntaxClassifier
Inherits AbstractSyntaxClassifier
Public Overrides ReadOnly Property SyntaxNodeTypes As IEnumerable(Of Type)
Get
Return {GetType(NameSyntax), GetType(ModifiedIdentifierSyntax)}
End Get
End Property
Public Overrides Function ClassifyNode(
syntax As SyntaxNode,
semanticModel As SemanticModel,
cancellationToken As CancellationToken) As IEnumerable(Of ClassifiedSpan)
Dim nameSyntax = TryCast(syntax, NameSyntax)
If nameSyntax IsNot Nothing Then
Return ClassifyNameSyntax(
nameSyntax,
DirectCast(semanticModel, SemanticModel),
cancellationToken)
End If
Dim modifiedIdentifier = TryCast(syntax, ModifiedIdentifierSyntax)
If modifiedIdentifier IsNot Nothing Then
Return ClassifyModifiedIdentifier(
modifiedIdentifier,
DirectCast(semanticModel, SemanticModel),
cancellationToken)
End If
Return SpecializedCollections.EmptyEnumerable(Of ClassifiedSpan)()
End Function
Private Function ClassifyNameSyntax(
node As NameSyntax,
semanticModel As SemanticModel,
cancellationToken As CancellationToken) As IEnumerable(Of ClassifiedSpan)
Dim symbolInfo = semanticModel.GetSymbolInfo(node, cancellationToken)
Dim symbol = symbolInfo.Symbol
If symbol Is Nothing AndAlso symbolInfo.CandidateSymbols.Length > 0 Then
Dim firstSymbol = symbolInfo.CandidateSymbols(0)
Select Case symbolInfo.CandidateReason
Case CandidateReason.NotCreatable
' Not creatable types are still classified as types.
If firstSymbol.IsConstructor() OrElse TypeOf firstSymbol Is ITypeSymbol Then
symbol = firstSymbol
End If
Case CandidateReason.OverloadResolutionFailure
' If we couldn't bind to a constructor, still classify the type.
If firstSymbol.IsConstructor() Then
symbol = firstSymbol
End If
Case CandidateReason.Inaccessible
' If we couldn't bind to a constructor, still classify the type if its accessble
If firstSymbol.IsConstructor() AndAlso SemanticModel.IsAccessible(node.SpanStart, firstSymbol.ContainingType) Then
symbol = firstSymbol
End If
End Select
End If
If symbol IsNot Nothing Then
If symbol.Kind = SymbolKind.Method Then
Dim method = DirectCast(symbol, IMethodSymbol)
If method.MethodKind = MethodKind.Constructor Then
' If node is member access or qualified name with explicit New on the right side, we should classify New as a keyword.
If node.IsNewOnRightSideOfDotOrBang() Then
Dim token = GetNameToken(node)
Return SpecializedCollections.SingletonEnumerable(
New ClassifiedSpan(token.Span, ClassificationTypeNames.Keyword))
End If
symbol = method.ContainingType
End If
End If
Dim type = TryCast(symbol, ITypeSymbol)
If type IsNot Nothing Then
Dim classification = GetClassificationForType(type)
If classification IsNot Nothing Then
Dim token = GetNameToken(node)
Return SpecializedCollections.SingletonEnumerable(New ClassifiedSpan(token.Span, classification))
End If
End If
If symbol.IsMyNamespace(semanticModel.Compilation) Then
Return SpecializedCollections.SingletonEnumerable(
New ClassifiedSpan(GetNameToken(node).Span, ClassificationTypeNames.Keyword))
End If
Else
' Okay, it doesn't bind to anything.
Dim identifierName = TryCast(node, IdentifierNameSyntax)
If identifierName IsNot Nothing Then
Dim token = identifierName.Identifier
If token.HasMatchingText(SyntaxKind.FromKeyword) AndAlso
semanticModel.SyntaxTree.IsExpressionContext(token.SpanStart, cancellationToken, semanticModel) Then
' Optimistically classify "From" as a keyword in expression contexts
Return SpecializedCollections.SingletonEnumerable(
New ClassifiedSpan(token.Span, ClassificationTypeNames.Keyword))
ElseIf token.HasMatchingText(SyntaxKind.AsyncKeyword) OrElse
token.HasMatchingText(SyntaxKind.IteratorKeyword) Then
' Optimistically classify "Async" or "Iterator" as a keyword in expression contexts
If semanticModel.SyntaxTree.IsExpressionContext(token.SpanStart, cancellationToken, semanticModel) Then
Return SpecializedCollections.SingletonEnumerable(
New ClassifiedSpan(token.Span, ClassificationTypeNames.Keyword))
End If
End If
End If
End If
Return Nothing
End Function
Private Function ClassifyModifiedIdentifier(
modifiedIdentifier As ModifiedIdentifierSyntax,
semanticModel As SemanticModel,
cancellationToken As CancellationToken
) As IEnumerable(Of ClassifiedSpan)
If modifiedIdentifier.ArrayBounds IsNot Nothing OrElse
modifiedIdentifier.ArrayRankSpecifiers.Count > 0 OrElse
modifiedIdentifier.Nullable.Kind <> SyntaxKind.None Then
Return SpecializedCollections.EmptyEnumerable(Of ClassifiedSpan)()
End If
If modifiedIdentifier.IsParentKind(SyntaxKind.VariableDeclarator) AndAlso
modifiedIdentifier.Parent.IsParentKind(SyntaxKind.FieldDeclaration) Then
If DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).AsClause Is Nothing AndAlso
DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).Initializer Is Nothing Then
Dim token = modifiedIdentifier.Identifier
If token.HasMatchingText(SyntaxKind.AsyncKeyword) OrElse
token.HasMatchingText(SyntaxKind.IteratorKeyword) Then
' Optimistically classify "Async" or "Iterator" as a keyword
Return SpecializedCollections.SingletonEnumerable(
New ClassifiedSpan(token.Span, ClassificationTypeNames.Keyword))
End If
End If
End If
Return SpecializedCollections.EmptyEnumerable(Of ClassifiedSpan)()
End Function
Private Function GetNameToken(node As NameSyntax) As SyntaxToken
Select Case node.Kind
Case SyntaxKind.IdentifierName
Return DirectCast(node, IdentifierNameSyntax).Identifier
Case SyntaxKind.GenericName
Return DirectCast(node, GenericNameSyntax).Identifier
Case SyntaxKind.QualifiedName
Return DirectCast(node, QualifiedNameSyntax).Right.Identifier
Case Else
Throw New NotSupportedException()
End Select
End Function
End Class
End Namespace
|
jgglg/roslyn
|
src/Workspaces/VisualBasic/Portable/Classification/Classifiers/NameSyntaxClassifier.vb
|
Visual Basic
|
apache-2.0
| 8,553
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Partial Public Class FlowAnalysisTests
Inherits FlowTestBase
#Region "Try-Catch-Finally"
<Fact()>
Public Sub TestTryCatchWithGoto01()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchWithGoto01">
<file name="try.vb"><![CDATA[
Imports System
Public Class Test
Sub Test()
Dim x As SByte, y As SByte = 3
L1:
[|
Try
x = y * y
y = x - 1
If x < 222 Then
GoTo L1
End If
Catch e As Exception When e.Message.Contains("ABC")
x = x - 100
GoTo L2
Finally
y = -y
End Try
|]
L2:
End Sub
End Class
]]></file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Equal(0, controlFlowAnalysis.EntryPoints.Count())
Assert.Equal(2, controlFlowAnalysis.ExitPoints.Count())
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.True(controlFlowAnalysis.EndPointIsReachable)
Assert.Equal("e", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("x, y, e", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("x, y, e", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("Me, y", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchWithGotoMix()
Dim analysis = CompileAndAnalyzeControlFlow(
<compilation name="TestTryCatchWithGotoMix">
<file name="try.vb">
Imports System
Public Class Test
Shared Sub Test()
Try
[|
GoTo lInTry
lInTry:
Dim a As Integer
|]
Catch ex As InvalidOperationException
GoTo lInTry
GoTo lInCatch1
lInCatch1:
Catch ex As Exception
GoTo lInTry
GoTo lInCatch2
lInCatch2:
Finally
GoTo lInFinally
lInFinally:
End Try
End Sub
End Class
</file>
</compilation>)
Assert.Equal(1, analysis.EntryPoints.Count())
Assert.Equal(0, analysis.ExitPoints.Count())
Assert.True(analysis.StartPointIsReachable)
Assert.True(analysis.EndPointIsReachable)
End Sub
<Fact()>
Public Sub TestTryCatchWithGoto02()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchWithGoto02">
<file name="try.vb">
Imports System
Public Class Test
Shared Sub Test()
Dim x As Byte, y as byte = 1
Try [|
L1: x = y + 123
Exit Sub
|]
Catch e As Exception
x = x - 100
If x = -1 Then
GoTo L1
End If
Finally
x = x - 1
End Try
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Equal(1, controlFlowAnalysis.EntryPoints.Count())
Assert.Equal(1, controlFlowAnalysis.ExitPoints.Count())
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.False(controlFlowAnalysis.EndPointIsReachable)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("x, y, e", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchWithGoto03()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchWithGoto03">
<file name="try.vb"><![CDATA[
Imports System
Public Class Test
Shared Function Test(p As String) As String
Dim x As UShort, s As String = "abc"
L1:
Try
x = s.Length
s = p + p
Catch e1 As ArgumentException
[|
Try
s = p
If x < 123 Then
GoTo L1
End If
Catch e2 As NullReferenceException
Return "Y"
End Try
|]
End Try
Return s
End Function
End Class
]]></file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Empty(controlFlowAnalysis.EntryPoints)
Assert.Equal(2, controlFlowAnalysis.ExitPoints.Count())
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.True(controlFlowAnalysis.EndPointIsReachable)
Assert.Equal("e2", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("p, x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("p, x", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("p, s", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("s, e2", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("p, x, s, e1", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchWithLoop01()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchInWhile01">
<file name="a.b">
Imports System
Public Class Test
Function Test() As Integer
Dim x As Short = 100
While x > 0
[|
Try
x = x - 3
Continue While
Catch e As Exception
x = -111
Exit While
End Try
|]
End While
Return x
End Function
End Class
</file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Empty(controlFlowAnalysis.EntryPoints)
Assert.Equal(2, controlFlowAnalysis.ExitPoints.Count())
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.False(controlFlowAnalysis.EndPointIsReachable)
Assert.Equal("e", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("x, e", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchWithLoop02()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchInLoop02">
<file name="a.b">
Imports System
Public Class Test
Sub TrySub()
Dim x As SByte = 111
Do Until x = 0
x = x - 3
[|
Try
If x Mod 7 = 0 Then
Continue Do
ElseIf x Mod 11 = 0 Then
Exit Try
End If
Catch ex As ArgumentException
Exit Do
Finally
Try
While x >= 100
x = x - 5
Exit Try
End While
Catch ex As Exception
End Try
End Try
|]
Loop
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Empty(controlFlowAnalysis.EntryPoints)
Assert.Equal(2, controlFlowAnalysis.ExitPoints.Count())
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.True(controlFlowAnalysis.EndPointIsReachable)
Assert.Equal("ex, ex", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("x, ex, ex", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchWithLoop03()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchInLoop03">
<file name="a.b">
Imports System
Public Class Test
Shared Sub TrySub()
Dim x As SByte = 111
Do Until x = 0
x = x - 3
Try
If x Mod 7 = 0 Then
Continue Do
ElseIf x Mod 11 = 0 Then
Exit Try
End If
Catch ex As ArgumentException
[|
Exit Do
|]
Finally
' Start3
Try
While x >= 100
x = x - 5
Exit Try
End While
Catch ex As Exception
End Try
' End3
End Try
Loop
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Empty(controlFlowAnalysis.EntryPoints)
Assert.Equal(1, controlFlowAnalysis.ExitPoints.Count())
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.False(controlFlowAnalysis.EndPointIsReachable)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("x, ex, ex", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchWithLoop04()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchInLoop04">
<file name="a.b">
Imports System
Public Class Test
Sub TrySub()
Dim x As SByte = 111
Do Until x = 0
x = x - 3
Try
If x Mod 7 = 0 Then
Continue Do
ElseIf x Mod 11 = 0 Then
Exit Try
End If
Catch ex As ArgumentException
Exit Do
Finally
[|
Try
While x >= 100
x = x - 5
Exit Try
End While
Catch ex As Exception
End Try
|]
End Try
Loop
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Empty(controlFlowAnalysis.EntryPoints)
Assert.Equal(0, controlFlowAnalysis.ExitPoints.Count())
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.True(controlFlowAnalysis.EndPointIsReachable)
Assert.Equal("ex", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("x, ex", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("Me, x, ex", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchWithReturnExit01()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchWithReturnExit01">
<file name="a.b">
Imports System
Public Class Test
Function TryFunction() As UInteger
Dim x As UInteger = 123
[|
Try
' Start1
If x Mod 7 = 0 Then
Exit Function
ElseIf x Mod 11 = 0 Then
Exit Try
End If
' End1
Catch ex As ArgumentException
' Start2
Try
x = x - 5
Return x
Finally
' Start3
Exit Function 'BC30101
' End3
End Try
' End2
End Try
|]
Return x
End Function
End Class
</file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Empty(controlFlowAnalysis.EntryPoints)
Assert.Equal(3, controlFlowAnalysis.ExitPoints.Count())
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.True(controlFlowAnalysis.EndPointIsReachable)
'Assert.Equal("ex", GetSymbolNamesSortedAndJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
'Assert.Equal("x", GetSymbolNamesSortedAndJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("x, ex", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchWithReturnExit02()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchWithReturnExit02">
<file name="a.b">
Imports System
Public Class Test
Shared Function TryFunction() As UInteger
Dim x As UInteger = 123
Try
' Start1
If x Mod 7 = 0 Then
Exit Function
ElseIf x Mod 11 = 0 Then
Exit Try
End If
' End1
Catch ex As ArgumentException
[|
Try
x = x + ex.Message.Length
Return x
Finally
' Start3
Exit Function 'BC30101
' End3
End Try
|]
End Try
Return x
End Function
End Class
</file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Empty(controlFlowAnalysis.EntryPoints)
Assert.Equal(2, controlFlowAnalysis.ExitPoints.Count())
'Assert.True(controlFlowAnalysis.StartPointIsReachable)
'Assert.True(controlFlowAnalysis.EndPointIsReachable)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("x, ex", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
'Assert.Equal("x", GetSymbolNamesSortedAndJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("x, ex", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("x, ex", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchWithThrow01()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchWithThrow01">
<file name="a.b">
Imports System
Public Class Test
Shared Sub Test(ByRef x As Short)
Try
[| Try
x = x - 11
Throw New ArgumentException()
Catch e As ArgumentException When x = 77
Console.WriteLine("E1")
Catch e As ArgumentException When x = 88
Console.WriteLine(e)
Throw
End Try
|]
Catch When x = 88
Console.WriteLine("E3")
Finally
x = x + 11
Console.WriteLine("F")
End Try
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Empty(controlFlowAnalysis.EntryPoints)
Assert.Empty(controlFlowAnalysis.ExitPoints)
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.True(controlFlowAnalysis.EndPointIsReachable)
Assert.Equal("e, e", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
' first 'e' because the end points of other two branch 'try' and 2nd 'catch' are unreachable
Assert.Equal("e", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("x, e", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("x, e, e", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchWithAssignment01()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchWithAssignment">
<file name="a.b">
Imports System
Public Class Test
Sub F(x as Long, ByRef s as String)
Dim local as Long
[| Try
Dim y as Integer = 11
x = y*y - x
Catch ex As Exception
Dim y as String = s
x = -1
Finally
local = - x
End Try
|]
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Empty(controlFlowAnalysis.EntryPoints)
Assert.Empty(controlFlowAnalysis.ExitPoints)
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.True(controlFlowAnalysis.EndPointIsReachable)
'
Assert.Equal("y, ex, y", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal("x, local", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("x, s", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("x, s, y", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("x, local, y, ex, y", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("Me, x, s", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchWithAssignment02()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchWithAssignment02">
<file name="a.b">
Imports System
Public Class Test
Function F() As Short
Dim sb, sb1 As SByte
[|
Try
sb = 0
Catch ax As ArgumentException
throw
Catch ex As Exception
sb = -128
Finally
if true then
sb1 = -1
End If
End Try
|]
Return sb + sb1
End Function
End Class
</file>
</compilation>)
Dim dataFlowAnalysis = analysisResults.Item2
'
Assert.Equal("ax, ex", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal("sb, sb1", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
'
Assert.Equal("sb, sb1", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("sb, sb1, ax, ex", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("sb, sb1", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("Me", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchWithAssignment03()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchWithAssignment03">
<file name="a.b"><![CDATA[
Imports System
Public Class Test
Function F() As Short
Dim sb As Sbyte, ss As SByte = 0
[|
Try
sb = 0
Catch ax As ArgumentException
if ss <> 0 Then
sb = ss
End If
Catch ex As Exception
sb = -128
Finally
Do While False
ss = -1
Loop
End Try
|]
F = sb + ss
End Function
End Class
]]></file>
</compilation>)
Dim dataFlowAnalysis = analysisResults.Item2
'
Assert.Equal("ax, ex", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("ss", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
Assert.Equal("sb, ss", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("ss", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("sb, ss, ax, ex", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("sb, ss", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("F, Me, ss", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchWithDataFlows01()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchWithDataFlows01">
<file name="a.b">
Imports System
Public Class Test
Sub TryMethod(p As Long)
Dim x As Long = 0, y As Long = 1
Dim z As Long
[|
Try
If (p > 0) Then
z = x
End If
Catch e As Exception
Throw
z = y
Finally
If False Then
x = y * y
End If
End Try
|]
x = z * y
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Empty(controlFlowAnalysis.EntryPoints)
Assert.Empty(controlFlowAnalysis.ExitPoints)
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.True(controlFlowAnalysis.EndPointIsReachable)
'
Assert.Equal("e", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("p, x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
'
Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("p, x, y", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("x, z, e", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("Me, p, x, y", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchWithDataFlows02()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchWithDataFlows02">
<file name="a.b">
Imports System
Public Class Test
Sub TryMethod(p As Long)
Dim x As Long = 0, y As Long = 1
Dim z As Long
[|
Try
x = p
Catch ax As ArgumentException
Finally
z = x
End Try
|]
p = x * y
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Empty(controlFlowAnalysis.EntryPoints)
Assert.Empty(controlFlowAnalysis.ExitPoints)
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.True(controlFlowAnalysis.EndPointIsReachable)
Assert.Equal("ax", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("p, x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
'
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("p, x", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("x, z, ax", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("Me, p, x, y", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchWithDataFlows03()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchWithDataFlows03">
<file name="a.b">
Imports System
Public Class Test
Sub TryMethod(ByRef p As Long)
Dim x As Long = 0, y, z As Long
[|
Try
Try
z = p
Catch ex As Exception
z = p + p
End Try
Catch e As Exception
Throw
y = x
Finally
z = z * p
End Try
|]
x = z * y
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Empty(controlFlowAnalysis.EntryPoints)
Assert.Empty(controlFlowAnalysis.ExitPoints)
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.True(controlFlowAnalysis.EndPointIsReachable)
'
Assert.Equal("ex, e", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("p, z", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("p, x, z", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("y, z, ex, e", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("p, y, z", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("Me, p, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchWithDataFlows04()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchWithDataFlows04">
<file name="a.b">
Imports System
Public Class Test
Sub TryMethod(ByRef p As Long)
Dim x As Long = 0, y, z As Long
[|
Try
L1:
z = x + x
GoTo L1
Catch ax As ArgumentException
p = y + p
Finally
p = p - y
End Try
|]
p = z
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Empty(controlFlowAnalysis.EntryPoints)
Assert.Empty(controlFlowAnalysis.ExitPoints)
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.True(controlFlowAnalysis.EndPointIsReachable)
'
Assert.Equal("ax", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal("p, ax", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("p, x, y", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
Assert.Equal("p, z", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("p, x, y", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("p, z", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("p, z, ax", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("Me, p, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestDataFlowsOutWithException()
Dim analysisResults = CompileAndAnalyzeDataFlow(
<compilation name="TestDataFlowsOutWithException">
<file name="a.b">
Imports System
Public Class Test
Sub TryMethod(ByRef p As Long)
Try
[| p = 1 |]
p = 2
Finally
End Try
End Sub
End Class
</file>
</compilation>)
Assert.Equal("p", GetSymbolNamesJoined(analysisResults.DataFlowsOut))
End Sub
<Fact()>
Public Sub TestTryCatchWithVarDecl01()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchWithVarDecl01">
<file name="a.b">
Imports System
Public Class Test
Sub TryMethod(ByRef p As Long)
Dim x As Byte = 111, y As Byte = 222
[|
Try
Try
If False Then
Dim s As String = "A"
End If
L: Catch ax As ArgumentException
' start1
Console.Write(ax)
GoTo L
Dim s As UShort = x
' end1
End Try
' start2
Catch ex As Exception
Console.Write(ex)
Dim s As Byte = y
Throw
' end2
Finally
Dim s As Char = "a"c
End Try
|]
'p = s 'BC30451
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Empty(controlFlowAnalysis.EntryPoints)
Assert.Empty(controlFlowAnalysis.ExitPoints)
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.True(controlFlowAnalysis.EndPointIsReachable)
Assert.Equal("s, ax, s, ex, s, s", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("x, y, ax, ex", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("s, ax, s, ex, s, s", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("Me, p, x, y", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchWithVarDecl02()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchWithVarDecl02">
<file name="a.b">
Imports System
Public Class Test
Shared Sub TryMethod(ByRef p As Long)
Dim x As Byte = 111, y As Byte = 222
Try
Try
If False Then
Dim s As String = "A"
End If
L: Catch ax As ArgumentException
[|
Console.Write(ax)
GoTo L
Dim s As UShort = x
|]
End Try
' start2
Catch ex As Exception
Console.Write(ex)
Dim s As Byte = y
Throw
' end2
Finally
Dim s As Char = "a"c
End Try
'p = s 'BC30451
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Empty(controlFlowAnalysis.EntryPoints)
'
Assert.Equal(1, controlFlowAnalysis.ExitPoints.Count)
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.False(controlFlowAnalysis.EndPointIsReachable)
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("ax", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("x, ax", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("p, y, ex", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("p, x, y, s, ax, ex, s, s", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchWithVarDecl03()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchWithVarDecl03">
<file name="a.b"><![CDATA[
Imports System
Public Class Test
Function F(x As ULong) As ULong
[|
Try
Dim y As UShort = 11
x = y * y - x
Catch e As Exception When x < 88
Console.WriteLine(x)
Catch e As Exception When x >= 88
Console.WriteLine(e)
x = 200
Finally
x = x - 1
End Try
|]
F = x
End Function
End Class
]]></file>
</compilation>)
Dim dataFlowAnalysis = analysisResults.Item2
'
Assert.Equal("y, e, e", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("x, y, e", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("x, y, e, e", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("F, Me, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchUseLocalInCatch01()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchUseLocalInCatch01">
<file name="a.b">
Imports System
Public Class Test
Sub Test(ByRef x As UInteger)
Dim local As Exception = Nothing
[|
Try
Dim y As UShort = 11
x = y * y - x
Catch local When Filter(x)
'If TypeOf local Is ArgumentException Then
If local.ToString().Contains("ArgumentException") Then
x = 0
End If
Finally
End Try
|]
If local IsNot Nothing Then
End If
End Sub
Function Filter(z As ULong) As Boolean
Return z = 0
End Function
End Class
</file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Empty(controlFlowAnalysis.EntryPoints)
Assert.Empty(controlFlowAnalysis.ExitPoints)
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.True(controlFlowAnalysis.EndPointIsReachable)
Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("Me, x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
'
Assert.Equal("x, local", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("Me, x, local, y", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("x, local", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("x, local, y", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("Me, x, local", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchParameterInCatch()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchParameterInCatch">
<file name="a.b">
Imports System
Public Class Test
Shared Sub Test01(s As String, ByRef pex As ArgumentException)
[|
Try
If String.IsNullOrWhiteSpace(s) Then
Throw New ArgumentException() ' NYI
End If
Catch pex When s Is Nothing
Console.WriteLine("Nothing Ex={0}", pex)
Catch pex When s.Trim() Is String.Empty
Console.WriteLine("Empty")
End Try
|]
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Empty(controlFlowAnalysis.EntryPoints)
Assert.Empty(controlFlowAnalysis.ExitPoints)
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.True(controlFlowAnalysis.EndPointIsReachable)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
Assert.Equal("pex", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("s, pex", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("pex", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("pex", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("s, pex", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchUseLocalParamInCatch01()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchUseLocalParamInCatch01">
<file name="a.b">
Imports System
Public Class Test
Function Filter(s As String) As Boolean
Return String.IsNullOrWhiteSpace(s)
End Function
Function TryFunc(s As String, ByRef pex As Exception) As Integer
Dim lex As ArgumentException
[|
Try
TryFunc = s.Length
Catch lex When s Is Nothing
Console.Write("ArgEx={0}", lex)
Catch pex
Console.Write("OtherEx={0}", pex)
Finally
Try
Dim y As UShort
y = TryFunc + 1
Catch lex
Console.Write("X")
Catch pex When Filter(s)
TryFunc = -1
End Try
End Try
|]
End Function
End Class
</file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Empty(controlFlowAnalysis.EntryPoints)
Assert.Empty(controlFlowAnalysis.ExitPoints)
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.True(controlFlowAnalysis.EndPointIsReachable)
Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("TryFunc, Me, s", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
Assert.Equal("pex", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("TryFunc, Me, s, pex, lex", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("TryFunc, pex, lex, y", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("pex", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("Me, s, pex", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryCatchUseLocalParamInCatch02()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchUseLocalParamInCatch02">
<file name="a.b">
Imports System
Public Class Test
Function Filter(s As String) As Boolean
Return String.IsNullOrWhiteSpace(s)
End Function
Function TryFunc(s As String, ByRef pex As Exception) As Integer
Dim lex As ArgumentException
Try
TryFunc = s.Length
Catch lex When s Is Nothing
Console.Write("ArgEx={0}", lex)
Catch pex
Console.Write("OtherEx={0}", pex)
Finally
[|
Try
Dim y As UShort
y = TryFunc + 1
Catch lex
Console.Write("X")
Catch pex When Filter(s)
TryFunc = -1
End Try
|]
End Try
End Function
End Class
</file>
</compilation>)
Dim controlFlowAnalysis = analysisResults.Item1
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Empty(controlFlowAnalysis.EntryPoints)
Assert.Empty(controlFlowAnalysis.ExitPoints)
Assert.True(controlFlowAnalysis.StartPointIsReachable)
Assert.True(controlFlowAnalysis.EndPointIsReachable)
Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("TryFunc, Me, s", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
Assert.Equal("pex", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("TryFunc, Me, s", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("TryFunc, pex, lex, y", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("s, pex, lex", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("TryFunc, Me, s, pex, lex", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact, WorkItem(8781, "DevDiv_Projects/Roslyn")>
Public Sub TestTryCatchUseFuncAsLocalInCatch()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryCatchUseFuncLocalInCatch">
<file name="a.b"><![CDATA[
Imports System
Public Class Test
Function TryFunc(ByRef x As UInteger) As Exception
TryFunc = Nothing
[|
Try
Dim y As UShort = 11
x = y * y - x
Catch TryFunc When x < 88
x = 100
Console.WriteLine(x)
Catch TryFunc When x >= 88
Console.WriteLine(TryFunc)
x = 200
Finally
End Try
|]
End Function
End Class ]]>
</file>
</compilation>)
Dim dataFlowAnalysis = analysisResults.Item2
Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut))
Assert.Equal("TryFunc, x, y", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside))
Assert.Equal("TryFunc, x, y", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside))
Assert.Equal("TryFunc, Me, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryWithLambda01()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryWithLambda01">
<file name="a.b">
Imports System
Public Class TryCatchFinally
Delegate Function D01(dp As Long) As Long
Shared Function M(ByRef refp As Long) As Long
M = 12345
[|
Try
refp = refp + 11
M = refp + 1
Catch e As Exception
Dim d As D01 = Function(ap)
e = New ArgumentException(ap.ToString())
Return e.Message.Length
End Function
M = d(refp)
End Try
|]
End Function
End Class
</file>
</compilation>)
Dim controlFlowAnalysisResults = analysisResults.Item1
Dim dataFlowAnalysisResults = analysisResults.Item2
Assert.True(controlFlowAnalysisResults.Succeeded)
Assert.True(dataFlowAnalysisResults.Succeeded)
Assert.True(controlFlowAnalysisResults.StartPointIsReachable)
Assert.True(controlFlowAnalysisResults.EndPointIsReachable)
Assert.Equal("e, d, ap", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal("M", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("e", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
Assert.Equal("refp", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal("refp", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("refp, e, d, ap", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("M, refp, e, d, ap", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("refp", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("M, refp", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryWithLambda02()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryWithLambda02">
<file name="a.b">
Imports System
Public Class TryCatchFinally
Delegate Function D01(dp As Long) As Long
Function M(ByRef refp As Long) As Long
M = 12345
Try
M = refp + 1
Catch e As Exception
[|
Dim d As D01 = Function(ap)
e = New ArgumentException(ap.ToString())
Return e.Message.Length
End Function
M = d(refp)
|]
End Try
End Function
End Class
</file>
</compilation>)
Dim controlFlowAnalysisResults = analysisResults.Item1
Dim dataFlowAnalysisResults = analysisResults.Item2
Assert.True(controlFlowAnalysisResults.Succeeded)
Assert.True(dataFlowAnalysisResults.Succeeded)
Assert.True(controlFlowAnalysisResults.StartPointIsReachable)
Assert.True(controlFlowAnalysisResults.EndPointIsReachable)
Assert.Equal("d, ap", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal("M, d", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("e", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
Assert.Equal("refp", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
' Bug#8781 - By Design
Assert.Empty(dataFlowAnalysisResults.DataFlowsOut)
Assert.Equal("refp, e, d, ap", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("M, e, d, ap", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("refp", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("M, Me, refp, e", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryWithLambda03()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryWithLambda03">
<file name="a.b">
Imports System
Public Class TryCatchFinally
Delegate Function D02(dp As Byte) As String
Function M(p As UShort) As String
Dim local As Byte = DirectCast((p Mod Byte.MaxValue), Byte)
[| Try
If local = p Then
Return Nothing
End If
Return local.ToString()
Catch e As Exception
Dim d As D02 = Function(ap As Byte)
Return (ap + local + p).ToString() + e.Message
End Function
Return d(local)
End Try |]
End Function
End Class
</file>
</compilation>)
Dim controlFlowAnalysisResults = analysisResults.Item1
Dim dataFlowAnalysisResults = analysisResults.Item2
Assert.True(controlFlowAnalysisResults.Succeeded)
Assert.True(dataFlowAnalysisResults.Succeeded)
Assert.True(controlFlowAnalysisResults.StartPointIsReachable)
Assert.False(controlFlowAnalysisResults.EndPointIsReachable)
Assert.Equal("e, d, ap", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned)
Assert.Equal("p, local, e", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
Assert.Equal("p, local", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Empty(dataFlowAnalysisResults.DataFlowsOut)
Assert.Equal("p, local, e, d, ap", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("local, e, d, ap", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("Me, p, local", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
End Sub
<Fact()>
Public Sub TestTryWithLambda04()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryWithLambda04">
<file name="a.b">
Imports System
Public Class TryCatchFinally
Delegate Function D02(dp As Byte) As String
Shared Function M(p As UShort) As String
Dim local As Byte = DirectCast((p Mod Byte.MaxValue), Byte)
Try
If local = p Then
Return Nothing
End If
Return local.ToString()
Catch e As Exception
[| Dim d As D02 = Function(ap As Byte)
Return (ap + local + p).ToString() + e.Message
End Function
Return d(local)
|]
End Try
End Function
End Class
</file>
</compilation>)
Dim controlFlowAnalysisResults = analysisResults.Item1
Dim dataFlowAnalysisResults = analysisResults.Item2
Assert.True(controlFlowAnalysisResults.Succeeded)
Assert.True(dataFlowAnalysisResults.Succeeded)
Assert.True(controlFlowAnalysisResults.StartPointIsReachable)
Assert.False(controlFlowAnalysisResults.EndPointIsReachable)
Assert.Equal("d, ap", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal("d", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("p, local, e", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
Assert.Equal("p, local, e", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Empty(dataFlowAnalysisResults.DataFlowsOut)
Assert.Equal("p, local, e, d, ap", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("d, ap", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("p, local", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("p, local, e", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
End Sub
<Fact, WorkItem(541892, "DevDiv")>
Public Sub TestTryWithLambda05()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation name="TestTryWithLambda05">
<file name="a.b">
Imports System
Friend Module TryCatchFinally
Delegate Function D02(dp As Byte) As String
Sub M(p As Byte)
Dim local As Byte = p + 1
[| Try
If local = p Then
Exit Sub
End If
Return
Catch e As Exception When (Function(ap As Byte) As String
Return (ap + local + p).ToString() + e.Message
End Function)(1).Length > 0
End Try |]
End Sub
End Module
</file>
</compilation>)
Dim controlFlowAnalysisResults = analysisResults.Item1
Dim dataFlowAnalysisResults = analysisResults.Item2
Assert.True(controlFlowAnalysisResults.Succeeded)
Assert.True(dataFlowAnalysisResults.Succeeded)
Assert.True(controlFlowAnalysisResults.StartPointIsReachable)
Assert.True(controlFlowAnalysisResults.EndPointIsReachable)
'
Assert.Equal("e, ap", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned)
Assert.Equal("p, local, e", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
Assert.Equal("p, local", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Empty(dataFlowAnalysisResults.DataFlowsOut)
'
Assert.Equal("p, local, e, ap", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("e, ap", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("p, local", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
End Sub
<Fact, WorkItem(541892, "DevDiv"), WorkItem(528622, "DevDiv")>
Public Sub TestTryWithLambda06()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation name="TestTryWithLambda06">
<file name="a.b">
Imports System
Class C
Sub M(p() As String)
Try
If p Is Nothing Then
Exit Sub
End If
Catch e As Exception When e.Message.Contains( [| (Function(ByRef ap As String) As String
Return ap + e.Message
End Function)(p(0)) |] )
End Try
End Sub
End Class
</file>
</compilation>)
Assert.Equal("ap", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
' 8794 (Won't fix)
Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned)
Assert.Equal("e", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
Assert.Equal("p, e", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal("ap", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("p, e, ap", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
' Bug#8789 (fixed)
Assert.Equal("ap", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("p, e", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("Me, p, e", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
End Sub
<WorkItem(543597, "DevDiv")>
<Fact()>
Public Sub TryStatement()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="Test">
<file name="a.b">
Module Program
Sub Main(args As String())
Try
Catch ex As Exception
Finally
End Try
End Sub
End Module
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim tryBlock = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.TryBlock).AsNode(), TryBlockSyntax)
Dim statement As StatementSyntax = tryBlock.TryStatement
Assert.False(model.AnalyzeControlFlow(statement, statement).Succeeded)
Assert.False(model.AnalyzeDataFlow(statement, statement).Succeeded)
statement = tryBlock.CatchBlocks(0).CatchStatement
Assert.False(model.AnalyzeControlFlow(statement, statement).Succeeded)
Assert.False(model.AnalyzeDataFlow(statement, statement).Succeeded)
statement = tryBlock.FinallyBlock.FinallyStatement
Assert.False(model.AnalyzeControlFlow(statement, statement).Succeeded)
Assert.False(model.AnalyzeDataFlow(statement, statement).Succeeded)
End Sub
<WorkItem(543597, "DevDiv")>
<Fact()>
Public Sub CatchStatement()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="Test">
<file name="a.b">
Module Program
Sub Main(args As String())
Try
Catch ex As Exception
Finally
End Try
End Sub
End Module
</file>
</compilation>)
Dim index = compilation.SyntaxTrees.First().GetCompilationUnitRoot().ToFullString().IndexOf("Catch ex As Exception", StringComparison.Ordinal)
Dim statement = DirectCast(compilation.SyntaxTrees.First().GetCompilationUnitRoot().FindToken(index).Parent, StatementSyntax)
Dim binding = compilation.GetSemanticModel(compilation.SyntaxTrees.First())
Dim controlFlowAnalysisResults = binding.AnalyzeControlFlow(statement, statement)
Dim dataFlowAnalysisResults = binding.AnalyzeDataFlow(statement, statement)
Assert.False(controlFlowAnalysisResults.Succeeded)
Assert.False(dataFlowAnalysisResults.Succeeded)
End Sub
<WorkItem(543597, "DevDiv")>
<Fact()>
Public Sub FinallyStatement()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="Test">
<file name="a.b">
Module Program
Sub Main(args As String())
Try
Catch ex As Exception
Finally
End Try
End Sub
End Module
</file>
</compilation>)
Dim index = compilation.SyntaxTrees.First().GetCompilationUnitRoot().ToFullString().IndexOf("Finally", StringComparison.Ordinal)
Dim statement = DirectCast(compilation.SyntaxTrees.First().GetCompilationUnitRoot().FindToken(index).Parent, StatementSyntax)
Dim binding = compilation.GetSemanticModel(compilation.SyntaxTrees.First())
Dim controlFlowAnalysisResults = binding.AnalyzeControlFlow(statement, statement)
Dim dataFlowAnalysisResults = binding.AnalyzeDataFlow(statement, statement)
Assert.False(controlFlowAnalysisResults.Succeeded)
Assert.False(dataFlowAnalysisResults.Succeeded)
End Sub
#End Region
#Region "SyncLock"
<Fact()>
Public Sub SimpleSyncLockBlock()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Class C1
Public Shared Sub Main()
Dim x as String = "Inside Using."
dim lock = new C1()
[|
SyncLock lock
Console.WriteLine(x)
End SyncLock
|]
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysisResults = analysisResults.Item1
Dim dataFlowAnalysisResults = analysisResults.Item2
Assert.True(controlFlowAnalysisResults.Succeeded)
Assert.Equal(0, dataFlowAnalysisResults.AlwaysAssigned.Count)
Assert.Equal(0, dataFlowAnalysisResults.Captured.Count)
Assert.Equal(2, dataFlowAnalysisResults.DataFlowsIn.Count)
Assert.Equal("x", dataFlowAnalysisResults.DataFlowsIn(0).ToDisplayString)
Assert.Equal("lock", dataFlowAnalysisResults.DataFlowsIn(1).ToDisplayString)
Assert.Equal(0, dataFlowAnalysisResults.DataFlowsOut.Count)
Assert.Equal(2, dataFlowAnalysisResults.ReadInside.Count)
Assert.Equal("x", dataFlowAnalysisResults.ReadInside(0).ToDisplayString)
Assert.Equal("lock", dataFlowAnalysisResults.ReadInside(1).ToDisplayString)
Assert.Equal(0, dataFlowAnalysisResults.ReadOutside.Count)
Assert.Equal(0, dataFlowAnalysisResults.VariablesDeclared.Count)
Assert.Equal(0, dataFlowAnalysisResults.WrittenInside.Count)
Assert.Equal(2, dataFlowAnalysisResults.WrittenOutside.Count)
Assert.Equal("x", dataFlowAnalysisResults.WrittenOutside(0).ToDisplayString)
Assert.Equal("lock", dataFlowAnalysisResults.WrittenOutside(1).ToDisplayString)
End Sub
<Fact()>
Public Sub SimpleSyncLockInside()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Class C1
Public Shared Sub Main()
Dim x as String = "Inside Using."
dim lock as Integer = 23
SyncLock lock
[|
Console.WriteLine(x)
|]
End SyncLock
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysisResults = analysisResults.Item1
Dim dataFlowAnalysisResults = analysisResults.Item2
Assert.True(controlFlowAnalysisResults.Succeeded)
Assert.Equal(0, dataFlowAnalysisResults.AlwaysAssigned.Count)
Assert.Equal(0, dataFlowAnalysisResults.Captured.Count)
Assert.Equal(1, dataFlowAnalysisResults.DataFlowsIn.Count)
Assert.Equal("x", dataFlowAnalysisResults.DataFlowsIn(0).ToDisplayString)
Assert.Equal(0, dataFlowAnalysisResults.DataFlowsOut.Count)
Assert.Equal(1, dataFlowAnalysisResults.ReadInside.Count)
Assert.Equal("x", dataFlowAnalysisResults.ReadInside(0).ToDisplayString)
Assert.Equal(1, dataFlowAnalysisResults.ReadOutside.Count)
Assert.Equal("lock", dataFlowAnalysisResults.ReadOutside(0).ToDisplayString)
Assert.Equal(0, dataFlowAnalysisResults.VariablesDeclared.Count)
Assert.Equal(0, dataFlowAnalysisResults.WrittenInside.Count)
Assert.Equal(2, dataFlowAnalysisResults.WrittenOutside.Count)
Assert.Equal("x", dataFlowAnalysisResults.WrittenOutside(0).ToDisplayString)
Assert.Equal("lock", dataFlowAnalysisResults.WrittenOutside(1).ToDisplayString)
End Sub
<Fact()>
Public Sub SimpleSyncLockErrorValueType()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Class C1
Public Shared Sub Main()
Dim x as String = "Inside Using."
dim lock = new C1()
[|
SyncLock lock
Console.WriteLine(x)
End SyncLock
|]
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysisResults = analysisResults.Item1
Dim dataFlowAnalysisResults = analysisResults.Item2
Assert.True(controlFlowAnalysisResults.Succeeded)
Assert.Equal(0, dataFlowAnalysisResults.AlwaysAssigned.Count)
Assert.Equal(0, dataFlowAnalysisResults.Captured.Count)
Assert.Equal(2, dataFlowAnalysisResults.DataFlowsIn.Count)
Assert.Equal("x", dataFlowAnalysisResults.DataFlowsIn(0).ToDisplayString)
Assert.Equal("lock", dataFlowAnalysisResults.DataFlowsIn(1).ToDisplayString)
Assert.Equal(0, dataFlowAnalysisResults.DataFlowsOut.Count)
Assert.Equal(2, dataFlowAnalysisResults.ReadInside.Count)
Assert.Equal("x", dataFlowAnalysisResults.ReadInside(0).ToDisplayString)
Assert.Equal("lock", dataFlowAnalysisResults.ReadInside(1).ToDisplayString)
Assert.Equal(0, dataFlowAnalysisResults.ReadOutside.Count)
Assert.Equal(0, dataFlowAnalysisResults.VariablesDeclared.Count)
Assert.Equal(0, dataFlowAnalysisResults.WrittenInside.Count)
Assert.Equal(2, dataFlowAnalysisResults.WrittenOutside.Count)
Assert.Equal("x", dataFlowAnalysisResults.WrittenOutside(0).ToDisplayString)
Assert.Equal("lock", dataFlowAnalysisResults.WrittenOutside(1).ToDisplayString)
End Sub
#End Region
#Region "Using"
<Fact()>
Public Sub UsingAroundCatch()
Dim analysis = CompileAndAnalyzeDataFlow(
<compilation name="UsingAroundCatch">
<file name="a.vb">
Class Test
Public Shared Sub Main()
Dim y As New MyManagedClass()
Using y
[|Try
System.Console.WriteLine("Try")
Finally
y = Nothing
System.Console.WriteLine("Catch")
End Try|]
End Using
End Sub
End Class
Public Class MyManagedClass
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
System.Console.WriteLine("Res1.Dispose()")
End Sub
End Class
</file>
</compilation>)
Assert.Empty(analysis.VariablesDeclared)
Assert.Equal("y", GetSymbolNamesJoined(analysis.AlwaysAssigned))
Assert.Empty(analysis.DataFlowsIn)
Assert.Empty(analysis.DataFlowsOut)
Assert.Empty(analysis.ReadInside)
Assert.Equal("y", GetSymbolNamesJoined(analysis.ReadOutside))
Assert.Equal("y", GetSymbolNamesJoined(analysis.WrittenInside))
Assert.Equal("y", GetSymbolNamesJoined(analysis.WrittenOutside))
End Sub
<Fact()>
Public Sub MultipleResourceWithDifferentType()
Dim analysis = CompileAndAnalyzeDataFlow(
<compilation name="MultipleResourceWithDifferentType">
<file name="a.vb">
Option Infer On
Imports System
Class Program
Shared Sub Main()
[|Using x = New MyManagedClass(), y = New MyManagedClass1()
End Using|]
End Sub
End Class
Class MyManagedClass
Implements System.IDisposable
Sub Dispose() Implements System.IDisposable.Dispose
System.Console.WriteLine("Dispose")
End Sub
End Class
Structure MyManagedClass1
Implements System.IDisposable
Sub Dispose() Implements System.IDisposable.Dispose
System.Console.WriteLine("Dispose1")
End Sub
End Structure
</file>
</compilation>)
Assert.Equal("x, y", GetSymbolNamesJoined(analysis.VariablesDeclared))
Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned))
Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside))
Assert.Empty(analysis.ReadOutside)
Assert.Equal("x, y", GetSymbolNamesJoined(analysis.WrittenInside))
Assert.Empty(analysis.WrittenOutside)
Assert.Empty(analysis.DataFlowsIn)
Assert.Empty(analysis.DataFlowsOut)
End Sub
<Fact()>
Public Sub MultipleResourceWithDifferentType_1()
Dim analysis = CompileAndAnalyzeDataFlow(
<compilation name="MultipleResourceWithDifferentType">
<file name="a.vb">
Option Infer On
Imports System
Class Program
Shared Sub Main()
[|Using x = New MyManagedClass(), y = New MyManagedClass1()
End Using|]
End Sub
End Class
Class MyManagedClass
Implements System.IDisposable
Sub Dispose() Implements System.IDisposable.Dispose
System.Console.WriteLine("Dispose")
End Sub
End Class
Structure MyManagedClass1
Implements System.IDisposable
Dim Name As String
Sub Dispose() Implements System.IDisposable.Dispose
System.Console.WriteLine("Dispose1")
End Sub
End Structure
</file>
</compilation>)
Assert.Equal("x, y", GetSymbolNamesJoined(analysis.VariablesDeclared))
Assert.Equal("x, y", GetSymbolNamesJoined(analysis.AlwaysAssigned))
Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside))
Assert.Empty(analysis.ReadOutside)
Assert.Equal("x, y", GetSymbolNamesJoined(analysis.WrittenInside))
Assert.Empty(analysis.WrittenOutside)
Assert.Empty(analysis.DataFlowsIn)
Assert.Empty(analysis.DataFlowsOut)
End Sub
<Fact()>
Public Sub MultipleResource()
Dim analysis = CompileAndAnalyzeDataFlow(
<compilation name="MultipleResource">
<file name="a.vb">
Option Infer On
Imports System
Class Program
Shared Sub Main()
[|Using x, y As New MyManagedClass()
End Using|]
End Sub
End Class
Class MyManagedClass
Implements System.IDisposable
Sub Dispose() Implements System.IDisposable.Dispose
System.Console.WriteLine("Dispose")
End Sub
End Class
</file>
</compilation>)
Assert.Equal("x, y", GetSymbolNamesJoined(analysis.VariablesDeclared))
Assert.Equal("x, y", GetSymbolNamesJoined(analysis.AlwaysAssigned))
Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside))
Assert.Empty(analysis.ReadOutside)
Assert.Equal("x, y", GetSymbolNamesJoined(analysis.WrittenInside))
Assert.Empty(analysis.WrittenOutside)
Assert.Empty(analysis.DataFlowsIn)
Assert.Empty(analysis.DataFlowsOut)
End Sub
<Fact()>
Public Sub MultipleResource_1()
Dim analysis = CompileAndAnalyzeDataFlow(
<compilation name="MultipleResource">
<file name="a.vb">
Option Infer On
Imports System
Class Program
Shared Sub Main()
Dim x = 1
Dim y = 1
[|Using foo, foo2 As New MyManagedClass(x), foo3, foo4 As New MyManagedClass(y)
End Using|]
End Sub
End Class
Class MyManagedClass
Implements System.IDisposable
Sub New(x As Integer)
End Sub
Sub Dispose() Implements System.IDisposable.Dispose
System.Console.WriteLine("Dispose")
End Sub
End Class
</file>
</compilation>)
Assert.Equal("foo, foo2, foo3, foo4", GetSymbolNamesJoined(analysis.VariablesDeclared))
Assert.Equal("foo, foo2, foo3, foo4", GetSymbolNamesJoined(analysis.AlwaysAssigned))
Assert.Equal("x, y, foo, foo2, foo3, foo4", GetSymbolNamesJoined(analysis.ReadInside))
Assert.Empty(analysis.ReadOutside)
Assert.Equal("foo, foo2, foo3, foo4", GetSymbolNamesJoined(analysis.WrittenInside))
Assert.Equal("x, y", GetSymbolNamesJoined(analysis.WrittenOutside))
Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn))
Assert.Empty(analysis.DataFlowsOut)
End Sub
<Fact()>
Public Sub QueryInUsing()
Dim analysis = CompileAndAnalyzeDataFlow(
<compilation name="QueryInUsing">
<file name="a.vb">
Option Infer On
Option Strict On
Imports System
Imports System.Linq
Class Program
Shared Sub Main()
Dim objs = GetList()
[|Using x As MyManagedClass = (From y In objs Select y).First
End Using|]
End Sub
Shared Function GetList() As List(Of MyManagedClass)
Return Nothing
End Function
End Class
Public Class MyManagedClass
Implements System.IDisposable
Public Sub Dispose() Implements System.IDisposable.Dispose
Console.Write("Dispose")
End Sub
End Class
</file>
</compilation>)
Assert.Equal("x, y, y", GetSymbolNamesJoined(analysis.VariablesDeclared))
Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned))
Assert.Equal("objs, x, y", GetSymbolNamesJoined(analysis.ReadInside))
Assert.Empty(analysis.ReadOutside)
Assert.Equal("x, y, y", GetSymbolNamesJoined(analysis.WrittenInside))
Assert.Equal("objs", GetSymbolNamesJoined(analysis.WrittenOutside))
Assert.Equal("objs", GetSymbolNamesJoined(analysis.DataFlowsIn))
Assert.Empty(analysis.DataFlowsOut)
End Sub
<Fact()>
Public Sub JumpOutFromUsing()
Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation name="JumpOutFromUsing">
<file name="a.vb">
Option Infer On
Imports System
Class Program
Shared Sub Main()
[|Using x = New MyManagedClass()
GoTo label1
End Using|]
label1:
End Sub
End Class
Class MyManagedClass
Implements System.IDisposable
Sub Dispose() Implements System.IDisposable.Dispose
System.Console.WriteLine("Dispose")
End Sub
End Class
</file>
</compilation>)
Dim controlflowAnalysis = analysis.Item1
Dim dataflowAnalysis = analysis.Item2
Assert.Equal("x", GetSymbolNamesJoined(dataflowAnalysis.VariablesDeclared))
Assert.Equal("x", GetSymbolNamesJoined(dataflowAnalysis.AlwaysAssigned))
Assert.Equal("x", GetSymbolNamesJoined(dataflowAnalysis.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataflowAnalysis.ReadOutside))
Assert.Equal("x", GetSymbolNamesJoined(dataflowAnalysis.WrittenInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataflowAnalysis.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataflowAnalysis.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataflowAnalysis.DataFlowsOut))
Assert.Equal(0, controlflowAnalysis.EntryPoints.Count)
Assert.Equal(1, controlflowAnalysis.ExitPoints.Count)
End Sub
<Fact()>
Public Sub JumpOutFromUsing_1()
Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation name="JumpOutFromUsing">
<file name="a.vb">
Option Infer On
Imports System
Class Program
Shared Sub Main(args As String())
Dim Obj1 = New MyManagedClass()
Try
[|Using Obj1
Dim i As Integer = i \ i
Exit Try
End Using|]
Catch ex As Exception
End Try
End Sub
End Class
Class MyManagedClass
Implements System.IDisposable
Sub Dispose() Implements System.IDisposable.Dispose
System.Console.WriteLine("Dispose")
End Sub
End Class
</file>
</compilation>)
Dim controlflowAnalysis = analysis.Item1
Dim dataflowAnalysis = analysis.Item2
Assert.Equal("i", GetSymbolNamesJoined(dataflowAnalysis.VariablesDeclared))
Assert.Equal("i", GetSymbolNamesJoined(dataflowAnalysis.AlwaysAssigned))
Assert.Equal("Obj1, i", GetSymbolNamesJoined(dataflowAnalysis.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataflowAnalysis.ReadOutside))
Assert.Equal("i", GetSymbolNamesJoined(dataflowAnalysis.WrittenInside))
Assert.Equal("args, Obj1, ex", GetSymbolNamesJoined(dataflowAnalysis.WrittenOutside))
Assert.Equal("Obj1", GetSymbolNamesJoined(dataflowAnalysis.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataflowAnalysis.DataFlowsOut))
Assert.Equal(0, controlflowAnalysis.EntryPoints.Count)
Assert.Equal(1, controlflowAnalysis.ExitPoints.Count)
End Sub
<Fact()>
Public Sub UsingWithVariableDeclarations()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Class MyDisposable
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Class C1
Public Shared Sub Main()
Dim x as String = "Inside Using."
[|
Using foo1 As New MyDisposable(), foo2 As New MyDisposable()
Console.WriteLine(x)
End Using
|]
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysisResults = analysisResults.Item1
Dim dataFlowAnalysisResults = analysisResults.Item2
Assert.True(controlFlowAnalysisResults.Succeeded)
Assert.Equal(2, dataFlowAnalysisResults.AlwaysAssigned.Count)
Assert.Equal("foo1", dataFlowAnalysisResults.AlwaysAssigned(0).ToDisplayString)
Assert.Equal("foo2", dataFlowAnalysisResults.AlwaysAssigned(1).ToDisplayString)
Assert.Equal(0, dataFlowAnalysisResults.Captured.Count)
Assert.Equal(1, dataFlowAnalysisResults.DataFlowsIn.Count)
Assert.Equal("x", dataFlowAnalysisResults.DataFlowsIn(0).ToDisplayString)
Assert.Equal(0, dataFlowAnalysisResults.DataFlowsOut.Count)
Assert.Equal(3, dataFlowAnalysisResults.ReadInside.Count)
Assert.Equal("x", dataFlowAnalysisResults.ReadInside(0).ToDisplayString)
Assert.Equal("foo1", dataFlowAnalysisResults.ReadInside(1).ToDisplayString)
Assert.Equal("foo2", dataFlowAnalysisResults.ReadInside(2).ToDisplayString)
Assert.Equal(0, dataFlowAnalysisResults.ReadOutside.Count)
Assert.Equal(2, dataFlowAnalysisResults.VariablesDeclared.Count)
Assert.Equal("foo1", dataFlowAnalysisResults.VariablesDeclared(0).ToDisplayString)
Assert.Equal("foo2", dataFlowAnalysisResults.VariablesDeclared(1).ToDisplayString)
Assert.Equal(2, dataFlowAnalysisResults.WrittenInside.Count)
Assert.Equal("foo1", dataFlowAnalysisResults.WrittenInside(0).ToDisplayString)
Assert.Equal("foo2", dataFlowAnalysisResults.WrittenInside(1).ToDisplayString)
Assert.Equal(1, dataFlowAnalysisResults.WrittenOutside.Count)
Assert.Equal("x", dataFlowAnalysisResults.WrittenOutside(0).ToDisplayString)
End Sub
<Fact()>
Public Sub UsingWithExpression()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Class MyDisposable
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Public Sub New(name as String)
End Sub
End Class
Class C1
Public Shared Sub Main()
Dim x as String = "Inside Using."
[|
Using New MyDisposable(x)
Console.WriteLine(x)
End Using
|]
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysisResults = analysisResults.Item1
Dim dataFlowAnalysisResults = analysisResults.Item2
Assert.True(controlFlowAnalysisResults.Succeeded)
Assert.Equal(0, dataFlowAnalysisResults.AlwaysAssigned.Count)
Assert.Equal(0, dataFlowAnalysisResults.Captured.Count)
Assert.Equal(1, dataFlowAnalysisResults.DataFlowsIn.Count)
Assert.Equal("x", dataFlowAnalysisResults.DataFlowsIn(0).ToDisplayString)
Assert.Equal(0, dataFlowAnalysisResults.DataFlowsOut.Count)
Assert.Equal(1, dataFlowAnalysisResults.ReadInside.Count)
Assert.Equal("x", dataFlowAnalysisResults.ReadInside(0).ToDisplayString)
Assert.Equal(0, dataFlowAnalysisResults.ReadOutside.Count)
Assert.Equal(0, dataFlowAnalysisResults.VariablesDeclared.Count)
Assert.Equal(0, dataFlowAnalysisResults.WrittenInside.Count)
Assert.Equal(1, dataFlowAnalysisResults.WrittenOutside.Count)
Assert.Equal("x", dataFlowAnalysisResults.WrittenOutside(0).ToDisplayString)
End Sub
<Fact()>
Public Sub UsingInsideUsing()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Class MyDisposable
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Public Sub New(name as String)
End Sub
End Class
Class C1
Public Shared Sub Main()
Dim x as String = "Inside Using."
Using foo1 As New MyDisposable(x)
[|
Console.WriteLine(x)
|]
End Using
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysisResults = analysisResults.Item1
Dim dataFlowAnalysisResults = analysisResults.Item2
Assert.True(controlFlowAnalysisResults.Succeeded)
Assert.Equal(0, dataFlowAnalysisResults.AlwaysAssigned.Count)
Assert.Equal(0, dataFlowAnalysisResults.Captured.Count)
Assert.Equal(1, dataFlowAnalysisResults.DataFlowsIn.Count)
Assert.Equal("x", dataFlowAnalysisResults.DataFlowsIn(0).ToDisplayString)
Assert.Equal(0, dataFlowAnalysisResults.DataFlowsOut.Count)
Assert.Equal(1, dataFlowAnalysisResults.ReadInside.Count)
Assert.Equal("x", dataFlowAnalysisResults.ReadInside(0).ToDisplayString)
Assert.Equal(2, dataFlowAnalysisResults.ReadOutside.Count)
Assert.Equal("x", dataFlowAnalysisResults.WrittenOutside(0).ToDisplayString)
Assert.Equal("foo1", dataFlowAnalysisResults.WrittenOutside(1).ToDisplayString)
Assert.Equal(0, dataFlowAnalysisResults.VariablesDeclared.Count)
Assert.Equal(0, dataFlowAnalysisResults.WrittenInside.Count)
Assert.Equal(2, dataFlowAnalysisResults.WrittenOutside.Count)
Assert.Equal("x", dataFlowAnalysisResults.WrittenOutside(0).ToDisplayString)
Assert.Equal("foo1", dataFlowAnalysisResults.WrittenOutside(1).ToDisplayString)
End Sub
<Fact()>
Public Sub UsingEmptyStructTypeErrorCase()
Dim analysisResults = CompileAndAnalyzeControlAndDataFlow(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Structure MyDisposableStructure
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Class C1
Public Shared Sub Main()
Dim x as String = "Inside Using."
[|
Using foo1 As New MyDisposableStructure(), foo2 As New MyDisposableStructure()
Console.WriteLine(x)
End Using
|]
End Sub
End Class
</file>
</compilation>)
Dim controlFlowAnalysisResults = analysisResults.Item1
Dim dataFlowAnalysisResults = analysisResults.Item2
Assert.True(controlFlowAnalysisResults.Succeeded)
Assert.Equal(0, dataFlowAnalysisResults.AlwaysAssigned.Count)
Assert.Equal(0, dataFlowAnalysisResults.Captured.Count)
Assert.Equal(1, dataFlowAnalysisResults.DataFlowsIn.Count)
Assert.Equal("x", dataFlowAnalysisResults.DataFlowsIn(0).ToDisplayString)
Assert.Equal(0, dataFlowAnalysisResults.DataFlowsOut.Count)
Assert.Equal(3, dataFlowAnalysisResults.ReadInside.Count)
Assert.Equal("x", dataFlowAnalysisResults.ReadInside(0).ToDisplayString)
Assert.Equal("foo1", dataFlowAnalysisResults.ReadInside(1).ToDisplayString)
Assert.Equal("foo2", dataFlowAnalysisResults.ReadInside(2).ToDisplayString)
Assert.Equal(0, dataFlowAnalysisResults.ReadOutside.Count)
Assert.Equal(2, dataFlowAnalysisResults.VariablesDeclared.Count)
Assert.Equal("foo1", dataFlowAnalysisResults.VariablesDeclared(0).ToDisplayString)
Assert.Equal("foo2", dataFlowAnalysisResults.VariablesDeclared(1).ToDisplayString)
Assert.Equal(2, dataFlowAnalysisResults.WrittenInside.Count)
Assert.Equal("foo1", dataFlowAnalysisResults.WrittenInside(0).ToDisplayString)
Assert.Equal("foo2", dataFlowAnalysisResults.WrittenInside(1).ToDisplayString)
Assert.Equal(1, dataFlowAnalysisResults.WrittenOutside.Count)
Assert.Equal("x", dataFlowAnalysisResults.WrittenOutside(0).ToDisplayString)
End Sub
#End Region
End Class
End Namespace
|
DanielRosenwasser/roslyn
|
src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/TryLockUsingStatementTests.vb
|
Visual Basic
|
apache-2.0
| 89,215
|
' Copyright (c) Microsoft. All rights reserved.
' Licensed under the MIT license. See LICENSE file in the project root for full license information.
Imports System
Imports System.Diagnostics
Imports System.Linq
Imports System.Linq.Expressions
Imports System.Reflection
Namespace Global.Microsoft.VisualBasic.CompilerServices
<Global.System.Diagnostics.DebuggerNonUserCode()>
<Global.System.ComponentModel.EditorBrowsable(Global.System.ComponentModel.EditorBrowsableState.Never)>
Partial Public Class Utils
Private Sub New()
End Sub
Public Shared Function CopyArray(arySrc As Global.System.Array, aryDest As Global.System.Array) As Global.System.Array
If arySrc Is Nothing Then
Return aryDest
End If
Dim lLength As Integer
lLength = arySrc.Length
If lLength = 0 Then
Return aryDest
End If
If aryDest.Rank() <> arySrc.Rank() Then
Throw New Global.System.InvalidCastException()
End If
Dim iDim As Integer
For iDim = 0 To aryDest.Rank() - 2
If aryDest.GetUpperBound(iDim) <> arySrc.GetUpperBound(iDim) Then
Throw New Global.System.ArrayTypeMismatchException()
End If
Next iDim
If lLength > aryDest.Length Then
lLength = aryDest.Length
End If
If arySrc.Rank > 1 Then
Dim lastRank As Integer = arySrc.Rank
Dim lenSrcLastRank As Integer = arySrc.GetLength(lastRank - 1)
Dim lenDestLastRank As Integer = aryDest.GetLength(lastRank - 1)
If lenDestLastRank = 0 Then
Return aryDest
End If
Dim lenCopy As Integer = If(lenSrcLastRank > lenDestLastRank, lenDestLastRank, lenSrcLastRank)
Dim i As Integer
For i = 0 To (arySrc.Length \ lenSrcLastRank) - 1
Global.System.Array.Copy(arySrc, i * lenSrcLastRank, aryDest, i * lenDestLastRank, lenCopy)
Next i
Else
Global.System.Array.Copy(arySrc, aryDest, lLength)
End If
Return aryDest
End Function
End Class
Friend Module ReflectionExtensions
Public Enum MemberTypes
' The following are the known classes which extend MemberInfo
Constructor = &H1
[Event] = &H2
Field = &H4
Method = &H8
[Property] = &H10
TypeInfo = &H20
Custom = &H40
NestedType = &H80
All = Constructor Or [Event] Or Field Or Method Or [Property] Or TypeInfo Or NestedType
End Enum
<System.Runtime.CompilerServices.ExtensionAttribute()>
Public Function MemberType(ByVal memberInfo As MemberInfo) As MemberTypes
If TypeOf memberInfo Is ConstructorInfo Then
Return MemberTypes.Constructor
ElseIf TypeOf memberInfo Is MethodInfo Then
Return MemberTypes.Method
ElseIf TypeOf memberInfo Is PropertyInfo Then
Return MemberTypes.Property
ElseIf TypeOf memberInfo Is FieldInfo Then
Return MemberTypes.Field
ElseIf TypeOf memberInfo Is EventInfo Then
Return MemberTypes.Event
ElseIf TypeOf memberInfo Is System.Reflection.TypeInfo Then
Return MemberTypes.TypeInfo
Else
Throw New System.ArgumentException
End If
End Function
<System.Runtime.CompilerServices.ExtensionAttribute()>
Public Function GetTypeCode(type As Type) As TypeCode
If type Is Nothing Then
Return TypeCode.Empty
ElseIf GetType(Boolean).Equals(type) Then
Return TypeCode.Boolean
ElseIf GetType(Char).Equals(type) Then
Return TypeCode.Char
ElseIf GetType(SByte).Equals(type) Then
Return TypeCode.SByte
ElseIf GetType(Byte).Equals(type) Then
Return TypeCode.Byte
ElseIf GetType(Short).Equals(type) Then
Return TypeCode.Int16
ElseIf GetType(UShort).Equals(type) Then
Return TypeCode.UInt16
ElseIf GetType(Int32).Equals(type) Then
Return TypeCode.Int32
ElseIf GetType(UInt32).Equals(type) Then
Return TypeCode.UInt32
ElseIf GetType(Long).Equals(type) Then
Return TypeCode.Int64
ElseIf GetType(ULong).Equals(type) Then
Return TypeCode.UInt64
ElseIf GetType(Single).Equals(type) Then
Return TypeCode.Single
ElseIf GetType(Double).Equals(type) Then
Return TypeCode.Double
ElseIf GetType(Decimal).Equals(type) Then
Return TypeCode.Decimal
ElseIf GetType(DateTime).Equals(type) Then
Return TypeCode.DateTime
ElseIf GetType(String).Equals(type) Then
Return TypeCode.String
ElseIf type.GetTypeInfo().IsEnum Then
Return GetTypeCode([Enum].GetUnderlyingType(type))
Else
Return TypeCode.Object
End If
End Function
<System.Runtime.CompilerServices.ExtensionAttribute()>
Public Function IsSubclassOf(source As Type, other As Type) As Boolean
Return source.GetTypeInfo().IsSubclassOf(other)
End Function
Public ReadOnly Property BindingFlagsInvokeMethod As BindingFlags
Get
Return CType(256, BindingFlags) ' BindingFlags.InvokeMethod
End Get
End Property
Public ReadOnly Property BindingFlagsGetProperty As BindingFlags
Get
Return CType(4096, BindingFlags) ' BindingFlags.GetProperty
End Get
End Property
Public ReadOnly Property BindingFlagsSetProperty As BindingFlags
Get
Return CType(8192, BindingFlags) ' BindingFlags.SetProperty
End Get
End Property
Public ReadOnly Property BindingFlagsIgnoreReturn As BindingFlags
Get
Return CType(16777216, BindingFlags) ' BindingFlags.IgnoreReturn
End Get
End Property
<System.Runtime.CompilerServices.ExtensionAttribute()>
Public Function IsEquivalentTo(mi1 As MethodBase, mi2 As MethodBase) As Boolean
If mi1 Is Nothing OrElse mi2 Is Nothing Then
Return mi1 Is Nothing AndAlso mi2 Is Nothing
End If
If mi1.Equals(mi2) Then
Return True
End If
If TypeOf mi1 Is MethodInfo AndAlso TypeOf mi2 Is MethodInfo Then
Dim method1 As MethodInfo = DirectCast(mi1, MethodInfo)
Dim method2 As MethodInfo = DirectCast(mi2, MethodInfo)
If method1.IsGenericMethod <> method2.IsGenericMethod Then
Return False
End If
If method1.IsGenericMethod Then
method1 = method1.GetGenericMethodDefinition()
method2 = method2.GetGenericMethodDefinition()
If method1.GetGenericArguments().Length <> method2.GetGenericArguments().Length Then
Return False ' Methods of different arity are not equivalent.
End If
End If
If Not method1.Equals(method2) AndAlso
method1.Name.Equals(method2.Name) AndAlso
method1.DeclaringType.IsGenericallyEqual(method2.DeclaringType) AndAlso
method1.ReturnType.IsGenericallyEquivalentTo(method2.ReturnType, method1, method2) Then
Dim pis1 As ParameterInfo() = method1.GetParameters()
Dim pis2 As ParameterInfo() = method2.GetParameters()
Return pis1.Length = pis2.Length AndAlso
Enumerable.All(Enumerable.Zip(pis1,
pis2,
Function(pi1, pi2) pi1.IsEquivalentTo(pi2, method1, method2)),
Function(x) x)
End If
Return False
End If
If TypeOf mi1 Is ConstructorInfo AndAlso TypeOf mi2 Is ConstructorInfo Then
Dim ctor1 As ConstructorInfo = DirectCast(mi1, ConstructorInfo)
Dim ctor2 As ConstructorInfo = DirectCast(mi2, ConstructorInfo)
If Not ctor1.Equals(ctor2) AndAlso
ctor1.DeclaringType.IsGenericallyEqual(ctor2.DeclaringType) Then
Dim pis1 As ParameterInfo() = ctor1.GetParameters()
Dim pis2 As ParameterInfo() = ctor2.GetParameters()
Return pis1.Length = pis2.Length AndAlso
Enumerable.All(Enumerable.Zip(pis1,
pis2,
Function(pi1, pi2) pi1.IsEquivalentTo(pi2, ctor1, ctor2)),
Function(x) x)
End If
Return False
End If
Return False
End Function
<System.Runtime.CompilerServices.ExtensionAttribute()>
Private Function IsEquivalentTo(pi1 As ParameterInfo, pi2 As ParameterInfo, method1 As MethodBase, method2 As MethodBase) As Boolean
If pi1 Is Nothing OrElse pi2 Is Nothing Then
Return pi1 Is Nothing AndAlso pi2 Is Nothing
End If
If pi1.Equals(pi2) Then
Return True
End If
Return pi1.ParameterType.IsGenericallyEquivalentTo(pi2.ParameterType, method1, method2)
End Function
<System.Runtime.CompilerServices.ExtensionAttribute()>
Private Function IsGenericallyEqual(t1 As Type, t2 As Type) As Boolean
If t1 Is Nothing OrElse t2 Is Nothing Then
Return t1 Is Nothing AndAlso t2 Is Nothing
End If
If t1.Equals(t2) Then
Return True
End If
If t1.IsConstructedGenericType OrElse t2.IsConstructedGenericType Then
Dim t1def As Type = If(t1.IsConstructedGenericType, t1.GetGenericTypeDefinition(), t1)
Dim t2def As Type = If(t2.IsConstructedGenericType, t2.GetGenericTypeDefinition(), t2)
Return t1def.Equals(t2def)
End If
Return False
End Function
' Compares two types and calls them equivalent if a type parameter equals a type argument.
' i.e if the inputs are (T, int, C(Of T), C(Of Integer)) then this will return true.
<System.Runtime.CompilerServices.ExtensionAttribute()>
Private Function IsGenericallyEquivalentTo(t1 As Type, t2 As Type, member1 As MemberInfo, member2 As MemberInfo) As Boolean
Debug.Assert(Not (TypeOf member1 Is MethodBase) OrElse
Not DirectCast(member1, MethodBase).IsGenericMethod OrElse
(DirectCast(member1, MethodBase).IsGenericMethodDefinition AndAlso DirectCast(member2, MethodBase).IsGenericMethodDefinition))
If t1.Equals(t2) Then
Return True
End If
' If one of them is a type param and then the other is a real type, then get the type argument in the member
' or it's declaring type that corresponds to the type param and compare that to the other type.
If t1.IsGenericParameter Then
If t2.IsGenericParameter Then
' If member's declaring type is not type parameter's declaring type, we assume that it is used as a type argument
If t1.GetTypeInfo().DeclaringMethod Is Nothing AndAlso member1.DeclaringType.Equals(t1.GetTypeInfo().DeclaringType) Then
If Not (t2.GetTypeInfo().DeclaringMethod Is Nothing AndAlso member2.DeclaringType.Equals(t2.GetTypeInfo().DeclaringType)) Then
Return t1.IsTypeParameterEquivalentToTypeInst(t2, member2)
End If
ElseIf t2.GetTypeInfo().DeclaringMethod Is Nothing AndAlso member2.DeclaringType.Equals(t2.GetTypeInfo().DeclaringType) Then
Return t2.IsTypeParameterEquivalentToTypeInst(t1, member1)
End If
' If both of these are type params but didn't compare to be equal then one of them is likely bound to another
' open type. Simply disallow such cases.
Return False
End If
Return t1.IsTypeParameterEquivalentToTypeInst(t2, member2)
ElseIf t2.IsGenericParameter Then
Return t2.IsTypeParameterEquivalentToTypeInst(t1, member1)
End If
' Recurse in for generic types arrays, byref and pointer types.
If t1.GetTypeInfo().IsGenericType AndAlso t2.GetTypeInfo().IsGenericType Then
Dim args1 As Type() = t1.GetGenericArguments()
Dim args2 As Type() = t2.GetGenericArguments()
If args1.Length = args2.Length Then
Return t1.IsGenericallyEqual(t2) AndAlso
Enumerable.All(Enumerable.Zip(args1,
args2,
Function(ta1, ta2) ta1.IsGenericallyEquivalentTo(ta2, member1, member2)),
Function(x) x)
End If
End If
If t1.IsArray AndAlso t2.IsArray Then
Return t1.GetArrayRank() = t2.GetArrayRank() AndAlso
t1.GetElementType().IsGenericallyEquivalentTo(t2.GetElementType(), member1, member2)
End If
If (t1.IsByRef AndAlso t2.IsByRef) OrElse
(t1.IsPointer AndAlso t2.IsPointer) Then
Return t1.GetElementType().IsGenericallyEquivalentTo(t2.GetElementType(), member1, member2)
End If
Return False
End Function
<System.Runtime.CompilerServices.ExtensionAttribute()>
Private Function IsTypeParameterEquivalentToTypeInst(typeParam As Type, typeInst As Type, member As MemberInfo) As Boolean
Debug.Assert(typeParam.IsGenericParameter)
If typeParam.GetTypeInfo().DeclaringMethod IsNot Nothing Then
' The type param is from a generic method. Since only methods can be generic, anything else
' here means they are not equivalent.
If Not (TypeOf member Is MethodBase) Then
Return False
End If
Dim method As MethodBase = DirectCast(member, MethodBase)
Dim position As Integer = typeParam.GetTypeInfo().GenericParameterPosition
Dim args As Type() = If(method.IsGenericMethod, method.GetGenericArguments(), Nothing)
Return args IsNot Nothing AndAlso
args.Length > position AndAlso
args(position).Equals(typeInst)
Else
Return member.DeclaringType.GetGenericArguments()(typeParam.GetTypeInfo().GenericParameterPosition).Equals(typeInst)
End If
End Function
Private ReadOnly s_GetMetadataTokenSentinel As Func(Of MemberInfo, Integer) = Function(mi)
Throw New InvalidOperationException()
End Function
Private s_GetMetadataToken As Func(Of MemberInfo, Integer) = s_GetMetadataTokenSentinel
<System.Runtime.CompilerServices.ExtensionAttribute()>
Public Function HasSameMetadataDefinitionAs(mi1 As MethodBase, mi2 As MethodBase) As Boolean
#If UNSUPPORTEDAPI Then
return (mi1.MetadataToken = mi2.MetadataToken) AndAlso mi1.Module.Equals(mi2.Module)
#Else
If Not mi1.Module.Equals(mi2.Module) Then
Return False
End If
If s_GetMetadataToken Is s_GetMetadataTokenSentinel Then
' See if MetadataToken property Is available.
Dim memberInfo As Type = GetType(MemberInfo)
Dim prop As PropertyInfo = memberInfo.GetProperty("MetadataToken", GetType(Integer), Array.Empty(Of Type)())
If prop Is Nothing OrElse Not prop.CanRead Then
s_GetMetadataToken = Nothing
Else
Dim parameter As ParameterExpression = Expression.Parameter(memberInfo)
s_GetMetadataToken = Expression.Lambda(Of Func(Of MemberInfo, Integer))(Expression.Property(parameter, prop), {parameter}).Compile()
End If
End If
If s_GetMetadataToken IsNot Nothing Then
Return s_GetMetadataToken(mi1) = s_GetMetadataToken(mi2)
End If
Return mi1.IsEquivalentTo(mi2)
#End If
End Function
End Module
End Namespace
|
vs-team/corefx
|
src/Microsoft.VisualBasic/src/Microsoft/VisualBasic/CompilerServices/Utils.vb
|
Visual Basic
|
mit
| 17,590
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
'-----------------------------------------------------------------------------------------------------------
' Defines a base class that is inherited by the writing classes that defines a bunch of utility
' functions for building up names of constructs. Basically anything that we want to shared between different
' output classes is defined here.
'-----------------------------------------------------------------------------------------------------------
Imports System.IO
Imports System.Text
' Utility functions for writing out the parse tree. Basically name generation and various simply utility functions
' that are shared by different writing classes. This is typically inherited by a writing class.
Public MustInherit Class WriteUtils
Protected _parseTree As ParseTree ' the tree to output
#If OLDSTYLE Then
Protected Const NodeKindString = "NodeKind"
Protected Const NodeListString = "NodeList"
Protected Const SeparatedNodeListString = "SeparatedNodeList"
Protected Const NodeFactoryListString = "NodeFactory"
#Else
Protected Const NodeKindString = "SyntaxKind"
Protected Const NodeListString = "SyntaxList"
Protected Const SeparatedNodeListString = "SeparatedSyntaxList"
Protected Const NodeFactoryListString = "Syntax"
#End If
Public Sub New(parseTree As ParseTree)
_parseTree = parseTree
End Sub
' Name generation
' Get the base type name (no namespace) for a node structure.
Protected Function StructureTypeName(nodeStructure As ParseNodeStructure) As String
Return Ident(nodeStructure.Name)
End Function
' Get the base type name (no namespace) for an enumeration.
Protected Function EnumerationName(enumeration As ParseEnumeration) As String
Return Ident(enumeration.Name)
End Function
'Get a factory name from a kind
Protected Function FactoryName(nodeKind As ParseNodeKind) As String
Return nodeKind.Name
End Function
'Get a factory name from a structure
Protected Function FactoryName(nodeStructure As ParseNodeStructure) As String
#If OLDSTYLE Then
Return nodeStructure.Name
#Else
If nodeStructure.Name.EndsWith("Syntax", StringComparison.Ordinal) Then
Return nodeStructure.Name.Substring(0, nodeStructure.Name.Length - 6)
Else
Return nodeStructure.Name
End If
#End If
End Function
Protected Function SyntaxFactName(nodeStructure As ParseNodeStructure) As String
Dim name = FactoryName(nodeStructure)
If name = "Keyword" Then
name = "KeywordKind"
End If
Return name
End Function
' Get the name for a field private variable
Protected Function FieldVarName(nodeField As ParseNodeField) As String
Dim name As String = nodeField.Name
Return "_" + LowerFirstCharacter(name)
End Function
' Get the name for a child private variable
Protected Function ChildVarName(nodeChild As ParseNodeChild) As String
Dim name As String = nodeChild.Name
Return "_" + LowerFirstCharacter(name)
End Function
' Get the name for a child private variable cache (not in the builder, but in the actual node)
Protected Function ChildCacheVarName(nodeChild As ParseNodeChild) As String
Dim name As String = nodeChild.Name
Return "_" + LowerFirstCharacter(name) + "Cache"
End Function
' Get the name for a new child variable is the visitor
Protected Function ChildNewVarName(nodeChild As ParseNodeChild) As String
Dim name As String = nodeChild.Name
Return Ident("new" + UpperFirstCharacter(name))
End Function
#If False Then
' Get the name for a new child variable is the visitor, but for the separators
Protected Function ChildNewVarSeparatorsName(ByVal nodeChild As ParseNodeChild) As String
Dim name As String = ChildSeparatorsName(nodeChild)
Return Ident(LowerFirstCharacter(name) + "New")
End Function
#End If
' Get the name for a field parameter.
' If conflictName is not nothing, make sure the name doesn't conflict with that name.
Protected Function FieldParamName(nodeField As ParseNodeField, Optional conflictName As String = Nothing) As String
Dim name As String = nodeField.Name
If String.Equals(name, conflictName, StringComparison.InvariantCultureIgnoreCase) Then
name += "Parameter"
End If
Return Ident(LowerFirstCharacter(name))
End Function
' Get the name for a child parameter
' If conflictName is not nothing, make sure the name doesn't conflict with that name.
Protected Function ChildParamName(nodeChild As ParseNodeChild, Optional conflictName As String = Nothing) As String
Dim name As String = OptionalChildName(nodeChild)
If String.Equals(name, conflictName, StringComparison.InvariantCultureIgnoreCase) Then
name += "Parameter"
End If
Return Ident(LowerFirstCharacter(name))
End Function
#If False Then
' Get the name for a child separator list parameter
Protected Function ChildSeparatorsParamName(ByVal nodeChild As ParseNodeChild) As String
Return Ident(LowerFirstCharacter(ChildSeparatorsName(nodeChild)))
End Function
#End If
' Get the name for a field property
Protected Function FieldPropertyName(nodeField As ParseNodeField) As String
Return Ident(UnescapedFieldPropertyName(nodeField))
End Function
Protected Function UnescapedFieldPropertyName(nodeField As ParseNodeField) As String
Dim name As String = nodeField.Name
Return UpperFirstCharacter(name)
End Function
' Get the name for a child property
Protected Function ChildWithFunctionName(nodeChild As ParseNodeChild) As String
Return Ident("With" + UpperFirstCharacter(nodeChild.Name))
End Function
' Get the name for a child property
Protected Function ChildPropertyName(nodeChild As ParseNodeChild) As String
Return Ident(UnescapedChildPropertyName(nodeChild))
End Function
Protected Function UnescapedChildPropertyName(nodeChild As ParseNodeChild) As String
Return UpperFirstCharacter(OptionalChildName(nodeChild))
End Function
' Get the name for a child separators property
Protected Function ChildSeparatorsPropertyName(nodeChild As ParseNodeChild) As String
Return Ident(UpperFirstCharacter(ChildSeparatorsName(nodeChild)))
End Function
' If a child is optional and isn't a list, add "Optional" to the name.
Protected Function OptionalChildName(nodeChild As ParseNodeChild) As String
Dim name As String = nodeChild.Name
If nodeChild.IsOptional AndAlso Not nodeChild.IsList Then
#If OLDSTYLE Then
Return "Optional" + UpperFirstCharacter(name)
#Else
Return UpperFirstCharacter(name)
#End If
Else
Return UpperFirstCharacter(name)
End If
End Function
' If a child is a separated list, return the name of the separators.
Protected Function ChildSeparatorsName(nodeChild As ParseNodeChild) As String
If nodeChild.IsList AndAlso nodeChild.IsSeparated Then
If String.IsNullOrEmpty(nodeChild.SeparatorsName) Then
_parseTree.ReportError(nodeChild.Element, "separator-name was not found, but is required for separated lists")
End If
Return UpperFirstCharacter(nodeChild.SeparatorsName)
Else
Throw New ApplicationException("Shouldn't get here")
End If
End Function
' Get the type reference for a field property
Protected Function FieldTypeRef(nodeField As ParseNodeField) As String
Dim fieldType As Object = nodeField.FieldType
If TypeOf fieldType Is SimpleType Then
Return SimpleTypeName(CType(fieldType, SimpleType))
ElseIf TypeOf fieldType Is ParseEnumeration Then
Return EnumerationTypeName(CType(fieldType, ParseEnumeration))
End If
nodeField.ParseTree.ReportError(nodeField.Element, "Bad type for field")
Return "UNKNOWNTYPE"
End Function
' Get the type reference for a child property
Protected Function ChildPropertyTypeRef(nodeStructure As ParseNodeStructure, nodeChild As ParseNodeChild, Optional isGreen As Boolean = False, Optional denyOverride As Boolean = False) As String
Dim isOverride = nodeChild.ContainingStructure IsNot nodeStructure AndAlso Not denyOverride
Dim result As String
If nodeChild.IsList Then
If nodeChild.IsSeparated Then
result = String.Format(If(isGreen, "SeparatedSyntaxList(Of {0})", "SeparatedSyntaxList(Of {0})"), BaseTypeReference(nodeChild))
ElseIf KindTypeStructure(nodeChild.ChildKind).IsToken Then
If isGreen Then
result = String.Format("SyntaxList(Of {0})", BaseTypeReference(nodeChild))
Else
result = "SyntaxTokenList"
End If
Else
result = String.Format("SyntaxList(Of {0})", BaseTypeReference(nodeChild))
End If
Else
If Not isGreen AndAlso KindTypeStructure(nodeChild.ChildKind).IsToken Then
Return String.Format("SyntaxToken")
End If
If Not isGreen AndAlso isOverride Then
Dim childKindStructure As ParseNodeStructure = Nothing
If nodeStructure.NodeKinds.Count = 1 Then
Dim childNodeKind = GetChildNodeKind(nodeStructure.NodeKinds(0), nodeChild)
childKindStructure = KindTypeStructure(childNodeKind)
Else
Dim childKinds As New HashSet(Of ParseNodeKind)()
For Each kind In nodeStructure.NodeKinds
Dim childNodeKind = GetChildNodeKind(kind, nodeChild)
If childNodeKind IsNot Nothing Then
childKinds.Add(GetChildNodeKind(kind, nodeChild))
Else
childKinds = Nothing
Exit For
End If
Next
If childKinds IsNot Nothing Then
If childKinds.Count = 1 Then
childKindStructure = KindTypeStructure(childKinds.First)
Else
childKindStructure = GetCommonStructure(childKinds.ToList())
End If
End If
End If
If childKindStructure IsNot Nothing Then
Return childKindStructure.Name
End If
End If
result = BaseTypeReference(nodeChild)
End If
If isGreen Then
Return String.Format("InternalSyntax.{0}", result)
End If
Return result
End Function
Protected Function ChildFieldTypeRef(nodeChild As ParseNodeChild, Optional isGreen As Boolean = False) As String
If nodeChild.IsList Then
If nodeChild.IsSeparated Then
Return String.Format(If(isGreen, "GreenNode", "SeparatedSyntaxList(Of {0})"), BaseTypeReference(nodeChild))
Else
Return String.Format(If(isGreen, "GreenNode", "SyntaxList(Of {0})"), BaseTypeReference(nodeChild))
End If
Else
Return BaseTypeReference(nodeChild)
End If
End Function
Protected Function ChildPrivateFieldTypeRef(nodeChild As ParseNodeChild) As String
If nodeChild.IsList Then
Return "SyntaxNode"
Else
Return BaseTypeReference(nodeChild)
End If
End Function
' Get the type reference for a child separators property
Protected Function ChildSeparatorsTypeRef(nodeChild As ParseNodeChild) As String
Return String.Format("SyntaxList(Of {0})", SeparatorsBaseTypeReference(nodeChild))
End Function
' Get the type reference for a child constructor
Protected Function ChildConstructorTypeRef(nodeChild As ParseNodeChild, Optional isGreen As Boolean = False) As String
If nodeChild.IsList Then
If isGreen OrElse KindTypeStructure(nodeChild.ChildKind).IsToken Then
Return "GreenNode"
Else
Return "SyntaxNode"
End If
Else
Dim name = BaseTypeReference(nodeChild)
If KindTypeStructure(nodeChild.ChildKind).IsToken Then
Return "InternalSyntax." + name
End If
Return name
End If
End Function
' Get the type reference for a child constructor
Protected Function ChildFactoryTypeRef(nodeStructure As ParseNodeStructure, nodeChild As ParseNodeChild, Optional isGreen As Boolean = False, Optional internalForm As Boolean = False) As String
If nodeChild.IsList Then
If nodeChild.IsSeparated Then
If isGreen Then
Return String.Format("InternalSyntax.SeparatedSyntaxList(of InternalSyntax.{0})", BaseTypeReference(nodeChild))
Else
Return String.Format("SeparatedSyntaxList(Of {0})", BaseTypeReference(nodeChild))
End If
Else
If isGreen Then
Return String.Format("InternalSyntax.SyntaxList(of InternalSyntax.{0})", StructureTypeName(_parseTree.RootStructure))
Else
If KindTypeStructure(nodeChild.ChildKind).IsToken Then
Return String.Format("SyntaxTokenList")
Else
Return String.Format("SyntaxList(of {0})", BaseTypeReference(nodeChild))
End If
End If
End If
Else
If Not internalForm AndAlso KindTypeStructure(nodeChild.ChildKind).IsToken Then
Return String.Format("SyntaxToken", BaseTypeReference(nodeChild))
End If
If Not isGreen Then
Return ChildPropertyTypeRef(nodeStructure, nodeChild, isGreen)
Else
Return BaseTypeReference(nodeChild)
End If
End If
End Function
#If False Then
' Get the type reference for a child separators constructor
Protected Function ChildSeparatorConstructorTypeRef(ByVal nodeChild As ParseNodeChild) As String
If nodeChild.IsList AndAlso nodeChild.IsSeparated Then
Return String.Format("SeparatedNodeList(Of {0})", SeparatorsBaseTypeReference(nodeChild))
Else
Throw New ApplicationException("shouldn't get here")
End If
End Function
#End If
' Is this type reference a list structure kind?
Protected Function IsListStructureType(nodeField As ParseNodeChild) As Boolean
Return nodeField.IsList AndAlso (TypeOf nodeField.ChildKind Is ParseNodeKind OrElse TypeOf nodeField.ChildKind Is List(Of ParseNodeKind))
End Function
' Is this type reference a non-list structure kind?
Protected Function IsNodeStructureType(nodeField As ParseNodeChild) As Boolean
Return Not nodeField.IsList AndAlso (TypeOf nodeField.ChildKind Is ParseNodeKind OrElse TypeOf nodeField.ChildKind Is List(Of ParseNodeKind))
End Function
' Get the type reference for a child private variable, ignoring lists
Protected Function BaseTypeReference(nodeChild As ParseNodeChild) As String
Return KindTypeReference(nodeChild.ChildKind, nodeChild.Element)
End Function
' Get the type reference for separators, ignoring lists
Protected Function SeparatorsBaseTypeReference(nodeChild As ParseNodeChild) As String
Return KindTypeReference(nodeChild.SeparatorsKind, nodeChild.Element)
End Function
' Get the type reference for a kind
Private Function KindTypeReference(kind As Object, element As XNode) As String
If TypeOf kind Is ParseNodeKind Then
Return StructureTypeName(CType(kind, ParseNodeKind).NodeStructure)
ElseIf TypeOf kind Is List(Of ParseNodeKind) Then
Dim commonStructure = GetCommonStructure(CType(kind, List(Of ParseNodeKind)))
If commonStructure Is Nothing Then
Return "Object"
Else
Return StructureTypeName(commonStructure)
End If
End If
_parseTree.ReportError(element, "Invalid kind specified")
Return "UNKNOWNTYPE"
End Function
' Get the type reference for a kind
Protected Function KindTypeStructure(kind As Object) As ParseNodeStructure
If TypeOf kind Is ParseNodeKind Then
Return CType(kind, ParseNodeKind).NodeStructure
ElseIf TypeOf kind Is List(Of ParseNodeKind) Then
Return GetCommonStructure(CType(kind, List(Of ParseNodeKind)))
End If
Return Nothing
End Function
' Get the type name of a simple type
Protected Function SimpleTypeName(simpleType As SimpleType) As String
Select Case simpleType
Case SimpleType.Bool
Return "Boolean"
Case SimpleType.Text
Return "String"
Case SimpleType.Character
Return "Char"
Case SimpleType.Int32
Return "Integer"
Case SimpleType.UInt32
Return "UInteger"
Case SimpleType.Int64
Return "Long"
Case SimpleType.UInt64
Return "ULong"
Case SimpleType.Float32
Return "Single"
Case SimpleType.Float64
Return "Double"
Case SimpleType.Decimal
Return "System.Decimal"
Case SimpleType.DateTime
Return "DateTime"
Case SimpleType.TextSpan
Return "TextSpan"
Case SimpleType.NodeKind
Return NodeKindString
Case Else
Throw New ApplicationException("Unexpected simple type")
End Select
End Function
' Get the type name of an enumeration type
Protected Function EnumerationTypeName(enumType As ParseEnumeration) As String
Return Ident(enumType.Name)
End Function
' The name of the node kind enumeration
Protected Function NodeKindType() As String
Return NodeKindString
End Function
' The name of the visitor method for a structure type
Protected Function VisitorMethodName(nodeStructure As ParseNodeStructure) As String
Dim nodeName = nodeStructure.Name
If nodeName.EndsWith("Syntax", StringComparison.Ordinal) Then nodeName = nodeName.Substring(0, nodeName.Length - 6)
Return "Visit" + nodeName
End Function
' Is this structure the root?
Protected Function IsRoot(nodeStructure As ParseNodeStructure) As Boolean
Return String.IsNullOrEmpty(nodeStructure.ParentStructureId)
End Function
' Given a list of ParseNodeKinds, find the common structure that encapsulates all
' of them, or else return Nothing if there is no common structure.
Protected Function GetCommonStructure(kindList As List(Of ParseNodeKind)) As ParseNodeStructure
Dim structList = kindList.ConvertAll(Function(kind) kind.NodeStructure) ' list of the structures.
' Any candidate ancestor is an ancestor (or same) of the first element
Dim candidate As ParseNodeStructure = structList(0)
Do
If IsAncestorOfAll(candidate, structList) Then
Return candidate
End If
candidate = candidate.ParentStructure
Loop While (candidate IsNot Nothing)
Return Nothing ' no ancestor
End Function
' Is this structure an ancestorOrSame of all
Protected Function IsAncestorOfAll(parent As ParseNodeStructure, children As List(Of ParseNodeStructure)) As Boolean
Return children.TrueForAll(Function(child) _parseTree.IsAncestorOrSame(parent, child))
End Function
' Get all of the fields of a structure, including inherited fields, in the right order.
' TODO: need way to get the ordering right.
Protected Function GetAllFieldsOfStructure(struct As ParseNodeStructure) As List(Of ParseNodeField)
Dim fullList As New List(Of ParseNodeField)
' For now, just put inherited stuff at the beginning, until we design a real ordering solution
Do While struct IsNot Nothing
fullList.InsertRange(0, struct.Fields)
struct = struct.ParentStructure
Loop
Return fullList
End Function
' Get all of the children of a structure, including inherited children, in the right order.
' The ordering is defined first by order attribute, then by declared order (base before derived)
Protected Function GetAllChildrenOfStructure(struct As ParseNodeStructure) As List(Of ParseNodeChild)
Dim fullList As New List(Of Tuple(Of ParseNodeChild, Integer))
' For now, just put inherited stuff at the beginning, until we design a real ordering solution
Dim baseLevel = 0 ' 0 for this structure, 1 for base, 2 for grandbase, ...
Do While struct IsNot Nothing
For i = 0 To struct.Children.Count - 1
' Add each child with an integer giving default sort order.
fullList.Add(New Tuple(Of ParseNodeChild, Integer)(struct.Children(i), i - baseLevel * 100))
Next
struct = struct.ParentStructure
baseLevel += 1
Loop
' Return a new list in order.
Return (From n In fullList Order By n.Item1.Order, n.Item2 Select n.Item1).ToList()
End Function
' Get all of the children of a structure, including inherited children, in the right order.
' that can be passed to the factory method.
' The ordering is defined first by order attribute, then by declared order (base before derived)
Protected Function GetAllFactoryChildrenOfStructure(struct As ParseNodeStructure) As IEnumerable(Of ParseNodeChild)
Return From child In GetAllChildrenOfStructure(struct) Where Not child.NotInFactory Select child
End Function
' String utility functions
' Lowercase the first character o a string
Protected Function LowerFirstCharacter(s As String) As String
If s Is Nothing OrElse s.Length = 0 Then
Return s
Else
Return Char.ToLowerInvariant(s(0)) + s.Substring(1)
End If
End Function
' Uppercase the first character o a string
Protected Function UpperFirstCharacter(s As String) As String
If s Is Nothing OrElse s.Length = 0 Then
Return s
Else
Return Char.ToUpperInvariant(s(0)) + s.Substring(1)
End If
End Function
' Word wrap a string into lines
Protected Function WordWrap(text As String) As List(Of String)
Const LineLength As Integer = 80
Dim lines As New List(Of String)
' Remove newlines, consecutive spaces.
text = text.Replace(vbCr, " ")
text = text.Replace(vbLf, " ")
Do
Dim newText = text.Replace(" ", " ")
If newText = text Then Exit Do
text = newText
Loop
text = text.Trim()
While text.Length >= LineLength
Dim split As Integer = text.Substring(0, LineLength).LastIndexOf(" "c)
If split < 0 Then split = LineLength
Dim line As String = text.Substring(0, split).Trim()
lines.Add(line)
text = text.Substring(split).Trim()
End While
If text.Length > 0 Then
lines.Add(text)
End If
Return lines
End Function
' Create a description XML comment with the given tag, indented the given number of characters
Private Sub GenerateXmlCommentPart(writer As TextWriter, text As String, xmlTag As String, indent As Integer)
If String.IsNullOrWhiteSpace(text) Then Return
text = XmlEscape(text)
Dim lines = WordWrap(text)
lines.Insert(0, "<" & xmlTag & ">")
lines.Add("</" & xmlTag & ">")
Dim prefix = New String(" "c, indent) & "''' "
For Each line In lines
writer.WriteLine(prefix & line)
Next
End Sub
Protected Shared Function XmlEscape(value As String) As String
Return value.Replace("&", "&").Replace("<", "<").Replace(">", ">")
End Function
Protected Shadows Function XmlEscapeAndWrap(value As String) As List(Of String)
Return WordWrap(XmlEscape(value))
End Function
Public Sub GenerateSummaryXmlComment(writer As TextWriter, text As String, Optional indent As Integer = 8)
GenerateXmlCommentPart(writer, text, "summary", indent)
End Sub
Public Sub GenerateParameterXmlComment(writer As TextWriter, parameterName As String, text As String, Optional escapeText As Boolean = False, Optional indent As Integer = 8)
If String.IsNullOrWhiteSpace(text) Then Return
If escapeText Then
text = XmlEscape(text)
Else
' Ensure the text does not require escaping.
Dim filtered = text.Replace("<cref ", "").Replace("/>", "").Replace("&", "").Replace("<", "").Replace(">", "")
Debug.Assert(filtered = XmlEscape(filtered))
End If
Dim prefix = New String(" "c, indent) & "''' "
writer.WriteLine(prefix & "<param name=""{0}"">", parameterName)
For Each line In WordWrap(text)
writer.WriteLine(prefix & line)
Next
writer.WriteLine(prefix & "</param>")
End Sub
Public Sub GenerateTypeParameterXmlComment(writer As TextWriter, typeParameterName As String, text As String, Optional indent As Integer = 4)
If String.IsNullOrWhiteSpace(text) Then Return
text = XmlEscape(text)
Dim prefix = New String(" "c, indent) & "''' "
writer.WriteLine(prefix & "<typeparam name=""{0}"">", typeParameterName)
For Each line In WordWrap(text)
writer.WriteLine(prefix & line)
Next
writer.WriteLine(prefix & "</typeparam>")
End Sub
' Generate and XML comment with the given description and remarks sections. If empty, the sections are omitted.
Protected Sub GenerateXmlComment(writer As TextWriter, descriptionText As String, remarksText As String, indent As Integer)
GenerateXmlCommentPart(writer, descriptionText, "summary", indent)
GenerateXmlCommentPart(writer, remarksText, "remarks", indent)
End Sub
' Generate XML comment for a structure
Protected Sub GenerateXmlComment(writer As TextWriter, struct As ParseNodeStructure, indent As Integer)
Dim descriptionText As String = struct.Description
Dim remarksText As String = Nothing
GenerateXmlComment(writer, descriptionText, remarksText, indent)
End Sub
' Generate XML comment for an child
Protected Sub GenerateXmlComment(writer As TextWriter, child As ParseNodeChild, indent As Integer)
Dim descriptionText As String = child.Description
Dim remarksText As String = Nothing
If child.IsOptional Then
If child.IsList Then
remarksText = "If nothing is present, an empty list is returned."
Else
remarksText = "This child is optional. If it is not present, then Nothing is returned."
End If
End If
GenerateXmlComment(writer, descriptionText, remarksText, indent)
End Sub
' Generate XML comment for an child
Protected Sub GenerateWithXmlComment(writer As TextWriter, child As ParseNodeChild, indent As Integer)
Dim descriptionText As String = "Returns a copy of this with the " + ChildPropertyName(child) + " property changed to the specified value. Returns this instance if the specified value is the same as the current value."
Dim remarksText As String = Nothing
GenerateXmlComment(writer, descriptionText, remarksText, indent)
End Sub
' Generate XML comment for an field
Protected Sub GenerateXmlComment(writer As TextWriter, field As ParseNodeField, indent As Integer)
Dim descriptionText As String = field.Description
Dim remarksText As String = Nothing
GenerateXmlComment(writer, descriptionText, remarksText, indent)
End Sub
' Generate XML comment for an kind
Protected Sub GenerateXmlComment(writer As TextWriter, kind As ParseNodeKind, indent As Integer)
Dim descriptionText As String = kind.Description
Dim remarksText As String = Nothing
GenerateXmlComment(writer, descriptionText, remarksText, indent)
End Sub
' Generate XML comment for an enumeration
Protected Sub GenerateXmlComment(writer As TextWriter, enumerator As ParseEnumeration, indent As Integer)
Dim descriptionText As String = enumerator.Description
Dim remarksText As String = Nothing
GenerateXmlComment(writer, descriptionText, remarksText, indent)
End Sub
' Generate XML comment for an enumerator
Protected Sub GenerateXmlComment(writer As TextWriter, enumerator As ParseEnumerator, indent As Integer)
Dim descriptionText As String = enumerator.Description
Dim remarksText As String = Nothing
GenerateXmlComment(writer, descriptionText, remarksText, indent)
End Sub
Private ReadOnly _VBKeywords As String() = {
"ADDHANDLER",
"ADDRESSOF",
"ALIAS",
"AND",
"ANDALSO",
"AS",
"BOOLEAN",
"BYREF",
"BYTE",
"BYVAL",
"CALL",
"CASE",
"CATCH",
"CBOOL",
"CBYTE",
"CCHAR",
"CDATE",
"CDBL",
"CDEC",
"CHAR",
"CINT",
"CLASS",
"CLNG",
"COBJ",
"CONST",
"CONTINUE",
"CSBYTE",
"CSHORT",
"CSNG",
"CSTR",
"CTYPE",
"CUINT",
"CULNG",
"CUSHORT",
"DATE",
"DECIMAL",
"DECLARE",
"DEFAULT",
"DELEGATE",
"DIM",
"DIRECTCAST",
"DO",
"DOUBLE",
"EACH",
"ELSE",
"ELSEIF",
"END",
"ENDIF",
"ENUM",
"ERASE",
"ERROR",
"EVENT",
"EXIT",
"FALSE",
"FINALLY",
"FOR",
"FRIEND",
"FUNCTION",
"GET",
"GETTYPE",
"GETXMLNAMESPACE",
"GLOBAL",
"GOSUB",
"GOTO",
"HANDLES",
"IF",
"IMPLEMENTS",
"IMPORTS",
"IN",
"INHERITS",
"INTEGER",
"INTERFACE",
"IS",
"ISNOT",
"LET",
"LIB",
"LIKE",
"LONG",
"LOOP",
"ME",
"MOD",
"MODULE",
"MUSTINHERIT",
"MUSTOVERRIDE",
"MYBASE",
"MYCLASS",
"NAMESPACE",
"NARROWING",
"NEW",
"NEXT",
"NOT",
"NOTHING",
"NOTINHERITABLE",
"NOTOVERRIDABLE",
"OBJECT",
"OF",
"ON",
"OPERATOR",
"OPTION",
"OPTIONAL",
"OR",
"ORELSE",
"OVERLOADS",
"OVERRIDABLE",
"OVERRIDES",
"PARAMARRAY",
"PARTIAL",
"PRIVATE",
"PROPERTY",
"PROTECTED",
"PUBLIC",
"RAISEEVENT",
"READONLY",
"REDIM",
"REM",
"REMOVEHANDLER",
"RESUME",
"RETURN",
"SBYTE",
"SELECT",
"SET",
"SHADOWS",
"SHARED",
"SHORT",
"SINGLE",
"STATIC",
"STEP",
"STOP",
"STRING",
"STRUCTURE",
"SUB",
"SYNCLOCK",
"THEN",
"THROW",
"TO",
"TRUE",
"TRY",
"TRYCAST",
"TYPEOF",
"UINTEGER",
"ULONG",
"USHORT",
"USING",
"VARIANT",
"WEND",
"WHEN",
"WHILE",
"WIDENING",
"WITH",
"WITHEVENTS",
"WRITEONLY",
"XOR"}
' If the string is a keyword, escape it. Otherwise just return it.
Protected Function Ident(id As String) As String
If _VBKeywords.Contains(id.ToUpperInvariant()) Then
Return "[" + id + "]"
Else
Return id
End If
End Function
Public Function EscapeQuotes(s As String) As String
If s.IndexOf(""""c) <> -1 Then
Dim sb As New StringBuilder
Dim parts = s.Split(""""c)
Dim last = parts.Length - 1
For i = 0 To last - 1
sb.Append(parts(i))
sb.Append("""""")
Next
sb.Append(parts(last))
s = sb.ToString
End If
Return s
End Function
Public Function GetChildNodeKind(nodeKind As ParseNodeKind, child As ParseNodeChild) As ParseNodeKind
Dim childNodeKind = TryCast(child.ChildKind, ParseNodeKind)
Dim childNodeKinds = TryCast(child.ChildKind, List(Of ParseNodeKind))
If childNodeKinds IsNot Nothing AndAlso nodeKind IsNot Nothing Then
childNodeKind = child.ChildKind(nodeKind.Name)
End If
If childNodeKind Is Nothing AndAlso child.DefaultChildKind IsNot Nothing Then
childNodeKind = child.DefaultChildKind
End If
Return childNodeKind
End Function
Public Function IsAutoCreatableToken(node As ParseNodeStructure, nodeKind As ParseNodeKind, child As ParseNodeChild) As Boolean
Dim childNodeKind = GetChildNodeKind(nodeKind, child)
If childNodeKind IsNot Nothing Then
Dim childNodeStructure = KindTypeStructure(childNodeKind)
If childNodeStructure.IsToken AndAlso childNodeKind.Name <> "IdentifierToken" Then
Return True
End If
End If
Return False
End Function
Public Function IsAutoCreatableNodeOfAutoCreatableTokens(node As ParseNodeStructure, nodeKind As ParseNodeKind, child As ParseNodeChild) As Boolean
Dim childNodeKind = GetChildNodeKind(nodeKind, child)
' Node contains only auto-creatable tokens
If childNodeKind IsNot Nothing Then
Dim childNodeStructure = KindTypeStructure(childNodeKind)
If Not childNodeStructure.IsToken Then
Dim allChildren = GetAllChildrenOfStructure(childNodeStructure)
For Each childNodeChild In allChildren
If Not IsAutoCreatableToken(childNodeStructure, childNodeKind, childNodeChild) Then
Return False
End If
Next
Return True
End If
End If
Return False
End Function
Public Function IsAutoCreatableChild(node As ParseNodeStructure, nodeKind As ParseNodeKind, child As ParseNodeChild) As Boolean
Return IsAutoCreatableToken(node, nodeKind, child) OrElse IsAutoCreatableNodeOfAutoCreatableTokens(node, nodeKind, child)
End Function
End Class
|
droyad/roslyn
|
src/Tools/Source/CompilerGeneratorTools/Source/VisualBasicSyntaxGenerator/Util/WriteUtils.vb
|
Visual Basic
|
apache-2.0
| 35,438
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting
<ExportHighlighter(LanguageNames.VisualBasic)>
Friend Class WhileBlockHighlighter
Inherits AbstractKeywordHighlighter(Of SyntaxNode)
Protected Overloads Overrides Function GetHighlights(node As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of TextSpan)
If node.IsIncorrectContinueStatement(SyntaxKind.ContinueWhileStatement) Then
Return SpecializedCollections.EmptyEnumerable(Of TextSpan)()
End If
If node.IsIncorrectExitStatement(SyntaxKind.ExitWhileStatement) Then
Return SpecializedCollections.EmptyEnumerable(Of TextSpan)()
End If
Dim whileBlock = node.GetAncestor(Of WhileBlockSyntax)()
If whileBlock Is Nothing Then
Return SpecializedCollections.EmptyEnumerable(Of TextSpan)()
End If
Dim highlights As New List(Of TextSpan)
With whileBlock
highlights.Add(.WhileStatement.WhileKeyword.Span)
highlights.AddRange(
whileBlock.GetRelatedStatementHighlights(
blockKind:=SyntaxKind.WhileKeyword))
highlights.Add(.EndWhileStatement.Span)
End With
Return highlights
End Function
End Class
End Namespace
|
bbarry/roslyn
|
src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/WhileBlockHighlighter.vb
|
Visual Basic
|
apache-2.0
| 1,749
|
Imports MySql.Data
Imports MySql.Data.MySqlClient
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Public Class formJual
Dim clasQuery As New publicQuery
Dim clasg As New setDefaultGrid
Dim clasc As New autoComplete
Dim dr As MySqlDataReader
Dim kategori As String = ""
Dim disc As String = "0"
Dim autoNumber As String = ""
Private Sub formTerimaKirimJual_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Panel10.Height = SplitContainer1.Panel2.Height - 285
loadSize()
loadCom()
End Sub
Private Sub loadCom()
Select Case Label2.Text
Case "Sponsor"
For Each a As String In clasc.retComplete("select nama from tb_sponsor")
txnama.AutoCompleteCustomSource.Add(a)
Next
Case "Penjualan Toko"
For Each a As String In clasc.retComplete("select namatoko from tb_stores")
txnama.AutoCompleteCustomSource.Add(a)
Next
End Select
cmbGudang.Items.Clear()
For Each a As String In clasc.retComplete("select warehousename from tb_warehouse")
cmbGudang.Items.Add(a)
Next
End Sub
Private Sub loadSize()
Dim dt As DataTable = clasg.setSize()
dGridSize.DataSource = dt
dGridSize.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
dGridSize.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
DataGridView1.Rows.Insert(0, "", "0", "0", "0", "0", "0", "0", "0", "0")
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
DataGridView1.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
End Sub
Private Sub loadAutoKode()
Select Case Label2.Text
Case "Penjualan Gudang"
dr = clasQuery.retDatareader("select kode from tb_penjualan where kode like'FP%' order by kode desc limit 1")
If dr.Read Then
If Integer.Parse(dr(0).ToString.Substring(10)) >= 9999 Then
txtresi.Text = "FP" & Format(Now(), "MMddyyyy") & customNumber("0", 1, 4)
Else
txtresi.Text = "FP" & Format(Now(), "MMddyyyy") & customNumber("0", Integer.Parse(dr(0).ToString.Substring(10)) + 1, 4)
End If
Else
txtresi.Text = "FP" & Format(Now(), "MMddyyyy") & customNumber("0", 1, 4)
End If
Case "Sponsor"
dr = clasQuery.retDatareader("select kode from tb_penjualan where kode like'FS%' order by kode desc limit 1 ")
If dr.Read Then
If Integer.Parse(dr(0).ToString.Substring(10)) >= 9999 Then
txtresi.Text = "FS" & Format(Now(), "MMddyyyy") & customNumber("0", 1, 4)
Else
txtresi.Text = "FS" & Format(Now(), "MMddyyyy") & customNumber("0", Integer.Parse(dr(0).ToString.Substring(10)) + 1, 4)
End If
Else
txtresi.Text = "FS" & Format(Now(), "MMddyyyy") & customNumber("0", 1, 4)
End If
End Select
End Sub
Private Sub Label2_TextChanged(sender As Object, e As EventArgs) Handles Label2.TextChanged
If Label2.Text = "Penjualan Toko" Then
Me.Text = "Store Sales" & Label2.Text
dGridAll.Columns(14).Visible = True
TextBox7.Text = Environment.NewLine & Environment.NewLine & Environment.NewLine & "Cons."
lblNama.Text = "Store"
ElseIf Label2.Text = "Penjualan Gudang" Then
Me.Text = "Warehouse Sales"
lblNama.Visible = False
txnama.Visible = False
cmbcatjual.Visible = True
lblCatJual.Visible = True
lblAuto.Visible = True
lblAuto.Text = "Bill Number"
txtresi.Visible = True
txtresi.Enabled = False
loadAutoKode()
TextBox8.Text = ""
ElseIf Label2.Text = "Sponsor" Then
Label3.Visible = True
Me.Text = "Sponsor Sales"
lblNama.Text = "Name"
loadAutoKode()
TextBox7.Text = Environment.NewLine & Environment.NewLine & Environment.NewLine & "Cons."
dGridAll.Columns(14).Visible = True
lblAuto.Text = "Bill Number"
lblAuto.Visible = True
txtresi.Visible = True
txtresi.Enabled = False
End If
End Sub
#Region "update grid"
Private Sub loadValuetoGrid()
dr = clasQuery.retDatareader(getQuery(Label2.Text))
If dr.Read Then
If dGridAll.Rows.Count = 0 Then
initGrid(dr)
rowTotalUpdate(dr(4).ToString, "0")
Else
For a As Integer = 0 To dGridAll.Rows.Count - 1
If dGridAll.Rows(a).Cells(0).Value = dr(0).ToString Then
rowTotalUpdate(dr(4).ToString, a)
txtbarkode.Clear()
Return
End If
Next
initGrid(dr)
rowTotalUpdate(dr(4).ToString, dGridAll.Rows.Count - 1)
End If
txtbarkode.Clear()
End If
End Sub
Private Sub initGrid(dr As MySqlDataReader)
Select Case Label2.Text
Case "Penjualan Gudang"
Dim rows As String() = {dr(0).ToString, dr(1).ToString, dr(2).ToString, dr(3).ToString, _
"0", "0", "0", "0", "0", "0", "0", "0", "0", dr(5).ToString, "0", "0"}
dGridAll.Rows.Add(rows)
Case "Penjualan Toko"
Dim rows As String() = {dr(0).ToString, dr(1).ToString, dr(2).ToString, dr(3).ToString, _
"0", "0", "0", "0", "0", "0", "0", "0", "0", dr(5).ToString, disc, "0"}
dGridAll.Rows.Add(rows)
Case "Sponsor"
Dim rows As String() = {dr(0).ToString, dr(1).ToString, dr(2).ToString, dr(3).ToString, _
"0", "0", "0", "0", "0", "0", "0", "0", "0", dr(5).ToString, disc, "0"}
dGridAll.Rows.Add(rows)
dGridAll.Columns(14).Visible = True
End Select
End Sub
Private Function getQuery(input As String) As String
Dim output As String = ""
Select Case input
Case "Penjualan Toko", "Penjualan Gudang", "Sponsor"
output = "select a.kodeItem, a.nama,a.color,a.kodeSize,c.value, a.hargaJual, b.barcode " & _
"from tb_produk a, tb_subproduk b, tb_size c where b.barcode ='" & txtbarkode.Text & "' and " & _
"a.kodeItem=b.kodeitem and a.kodesize=c.kode and b.kodesize=c.value and a.status='Active'"
End Select
Return output
End Function
Private Sub rowTotalUpdate(value As String, row As String)
Select Case Label2.Text
Case "Penjualan Gudang"
Dim subtotal As Integer = 0
dGridAll.Rows(row).Cells(3 + (Integer.Parse(value))).Value = _
(Integer.Parse(dGridAll.Rows(row).Cells(3 + (Integer.Parse(value))).Value) + 1).ToString
For x As Integer = 4 To 11
subtotal += Integer.Parse(dGridAll.Rows(row).Cells(x).Value)
Next
dGridAll.Rows(row).Cells(12).Value = subtotal.ToString
dGridAll.Rows(row).Cells(15).Value = (subtotal * (Integer.Parse(dGridAll.Rows(row).Cells(13).Value)))
Case "Penjualan Toko", "Sponsor"
Dim subtotal As Integer = 0
dGridAll.Rows(row).Cells(3 + (Integer.Parse(value))).Value = _
(Integer.Parse(dGridAll.Rows(row).Cells(3 + (Integer.Parse(value))).Value) + 1).ToString
For x As Integer = 4 To 11
subtotal += Integer.Parse(dGridAll.Rows(row).Cells(x).Value)
Next
dGridAll.Rows(row).Cells(12).Value = subtotal.ToString
dGridAll.Rows(row).Cells(15).Value = (subtotal * (Integer.Parse(dGridAll.Rows(row).Cells(13).Value) - _
(Integer.Parse(dGridAll.Rows(row).Cells(13).Value) * (Integer.Parse(dGridAll.Rows(row).Cells(14).Value) / 100))))
End Select
updateGrand()
End Sub
Private Sub updateGrand()
DataGridView1.Rows.Clear()
DataGridView1.Rows.Insert(0, "", "0", "0", "0", "0", "0", "0", "0", "0")
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
DataGridView1.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
txtotQty.Clear()
txtotPrice.Clear()
txGrandtotal1.Clear()
txGrandtotal2.Clear()
If dGridAll.Rows.Count >= 1 Then
For b As Integer = 1 To 8
Dim gt1 As Double = 0
Dim gt2 As Double = 0
Dim gt3 As Double = 0
For a As Integer = 0 To dGridAll.Rows.Count - 1
gt1 += Double.Parse(dGridAll.Rows(a).Cells(b + 3).Value)
gt2 += Double.Parse(dGridAll.Rows(a).Cells(12).Value)
gt3 += Double.Parse(dGridAll.Rows(a).Cells(15).Value)
Next
DataGridView1.Rows(0).Cells(b).Value = gt1.ToString
txtotQty.Text = gt2.ToString
If Label2.Text = "Sponsor" Or Label2.Text = "Penjualan Toko" Or Label2.Text = "Pengiriman" _
Or (Label2.Text = "Return Barang" And cmbstat.SelectedItem = "Toko") Then
txGrandtotal2.Text = gt3.ToString
Else
txGrandtotal1.Text = gt3.ToString
End If
Next
End If
End Sub
#End Region
#Region "save Query"
Private Sub SimpanjualGudang()
If cmbcatjual.SelectedIndex = -1 Or cmbcatjual.Text = "" Then
MsgBox("Choose Sale Category")
Return
ElseIf Label3.Visible = True Then
clasQuery.insertQuery("insert into tb_penjualan values ('','" & cmbGudang.SelectedIndex + 1 & "','" & txtresi.Text & "','" & _
txnama.Text & "','" & DateTime.Now.ToMySql & "','" & MainForm.txUsername.Text & "','" & _
txtotQty.Text & "','" & txGrandtotal1.Text & "','Gudang','Sponsor',0)")
Else
clasQuery.insertQuery("insert into tb_penjualan values ('','" & cmbGudang.SelectedIndex + 1 & "','" & txtresi.Text & "','" & _
txnama.Text & "','" & DateTime.Now.ToMySql & "','" & MainForm.txUsername.Text & "','" & txtotQty.Text & _
"','" & txGrandtotal1.Text & "','Gudang','" & _
cmbcatjual.SelectedItem & "',0)")
End If
For a As Integer = 0 To dGridAll.Rows.Count - 1
Dim tem As String = ""
For b As Integer = 4 To 11
MainForm.ProgressBar1.Value = ((b * (a + 1)) / (11 * dGridAll.Rows.Count) * 100)
clasQuery.updateQuery("update tb_stokgudangdetail set qty=qty-" & dGridAll.Rows(a).Cells(b).Value & " where kodeitem='" & dGridAll.Rows(a).Cells(0).Value & _
"' and value='" & b - 3 & "' and warehouse='" & cmbGudang.SelectedIndex + 1 & "'")
tem &= "('" & txtresi.Text & "','" & dGridAll.Rows(a).Cells(0).Value _
& "','" & b - 3 & "','" & dGridAll.Rows(a).Cells(b).Value & "','" & _
dGridAll.Rows(a).Cells(14).Value & "','" & dGridAll.Rows(a).Cells(13).Value & "'),"
Next
clasQuery.insertQuery("insert into tb_penjualandetail values " & tem.Substring(0, tem.Length - 1))
clasQuery.updateQuery("update tb_stokgudang set qty=qty-" & dGridAll.Rows(a).Cells(12).Value & _
" where kodeitem='" & dGridAll.Rows(a).Cells(0).Value & "' and warehouse='" & cmbGudang.SelectedIndex + 1 & "'")
Next
MsgBox("Saved")
End Sub
Private Sub simpanSponsor()
clasQuery.insertQuery("insert into tb_penjualan values ('','" & cmbGudang.SelectedIndex + 1 & "','" & txtresi.Text & "','" & txnama.Text & _
"','" & DateTime.Now.ToMySql & "','" & MainForm.txUsername.Text & "','" & txtotQty.Text & "','" & _
txGrandtotal1.Text & "','Gudang','Sponsor',0)")
For a As Integer = 0 To dGridAll.Rows.Count - 1
Dim tem As String = ""
For b As Integer = 4 To 11
MainForm.ProgressBar1.Value = ((b * (a + 1)) / (11 * dGridAll.Rows.Count) * 100)
clasQuery.updateQuery("update tb_stokgudangdetail set qty=qty-" & dGridAll.Rows(a).Cells(b).Value & " where kodeitem='" & dGridAll.Rows(a).Cells(0).Value & _
"' and value='" & b - 3 & "' and warehouse='" & cmbGudang.SelectedIndex + 1 & "'")
tem &= "('" & txtresi.Text & "','" & dGridAll.Rows(a).Cells(0).Value _
& "','" & b - 3 & "','" & dGridAll.Rows(a).Cells(b).Value & "','" & _
dGridAll.Rows(a).Cells(14).Value & "','" & dGridAll.Rows(a).Cells(13).Value & "'),"
Next
clasQuery.insertQuery("insert into tb_penjualandetail values " & tem.Substring(0, tem.Length - 1))
clasQuery.updateQuery("update tb_stokgudang set qty=qty-" & dGridAll.Rows(a).Cells(12).Value & _
" where kodeitem='" & dGridAll.Rows(a).Cells(0).Value & "' and warehouse='" & cmbGudang.SelectedIndex + 1 & "'")
Next
MsgBox("Saved")
End Sub
'auto=kodetrans-nama(sponsor,toko,gudang)-tgl-operator-totalqty-totaljual-statjual-mediajual
Private Sub SimpanjualToko()
Dim pos As String = ""
dr = clasQuery.retDatareader("select auto from tb_penjualan order by auto desc limit 1")
If dr.Read Then
pos = (Integer.Parse(dr(0).ToString) + 1).ToString
clasQuery.insertQuery("insert into tb_penjualan values ('','" & cmbGudang.SelectedIndex + 1 & "','" & pos & "','" & txnama.Text & _
"','" & DateTime.Now.ToMySql & "','" & MainForm.txUsername.Text & "','" & txtotQty.Text & _
"','" & txGrandtotal2.Text & "','Toko','-',0)")
Else
pos = 1
clasQuery.insertQuery("insert into tb_penjualan values ('','" & cmbGudang.SelectedIndex + 1 & "','" & pos & "','" & txnama.Text & _
"','" & DateTime.Now.ToMySql & "','" & MainForm.txUsername.Text & "','" & txtotQty.Text & "','" & _
txGrandtotal2.Text & "','Toko','-',0)")
End If
For a As Integer = 0 To dGridAll.Rows.Count - 1
Dim tem As String = ""
For b As Integer = 4 To 11
MainForm.ProgressBar1.Value = ((b * (a + 1)) / (11 * dGridAll.Rows.Count) * 100)
clasQuery.updateQuery("update tb_stoktokodetail set qty=qty-" & dGridAll.Rows(a).Cells(b).Value & " where kodeitem='" & dGridAll.Rows(a).Cells(0).Value & _
"' and value='" & b - 3 & "' and namaToko='" & txnama.Text & "'")
tem &= "('" & pos & "','" & dGridAll.Rows(a).Cells(0).Value _
& "','" & b - 3 & "','" & dGridAll.Rows(a).Cells(b).Value & "','" & _
dGridAll.Rows(a).Cells(14).Value & "','" & dGridAll.Rows(a).Cells(13).Value & "'),"
Next
clasQuery.insertQuery("insert into tb_penjualandetail values " & tem.Substring(0, tem.Length - 1))
clasQuery.updateQuery("update tb_stoktoko set qty=qty-" & dGridAll.Rows(a).Cells(12).Value & " where kodeitem='" & dGridAll.Rows(a).Cells(0).Value & _
"' and namaToko='" & txnama.Text & "'")
Next
MsgBox("Saved")
End Sub
#End Region
Private Sub txnama_TextChanged(sender As Object, e As EventArgs) Handles txnama.TextChanged
If Label2.Text = "Penjualan Toko" Then
dr = clasQuery.retDatareader("select disc from tb_stores where namatoko='" & txnama.Text & "'")
If dr.Read Then
disc = dr(0).ToString
End If
ElseIf Label2.Text = "Sponsor" Then
dr = clasQuery.retDatareader("select disc from tb_sponsor where nama='" & txnama.Text & "'")
If dr.Read Then
disc = dr(0).ToString
End If
End If
End Sub
Private Sub txtbarkode_TextChanged(sender As Object, e As EventArgs) Handles txtbarkode.TextChanged
loadValuetoGrid()
'gridformat(dGridAll, 13)
gridformat(dGridAll, 15)
End Sub
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
Select Case Label2.Text
Case "Penjualan Toko"
SimpanjualToko()
Case "Penjualan Gudang"
SimpanjualGudang()
Case "Sponsor"
simpanSponsor()
End Select
clearForm()
txtresi.Focus()
End Sub
Private Sub clearForm()
dGridAll.Rows.Clear()
DataGridView1.Rows.Clear()
DataGridView1.Rows.Insert(0, "", "0", "0", "0", "0", "0", "0", "0", "0")
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
DataGridView1.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
txtresi.Clear()
txnama.Clear()
txtotQty.Clear()
txtotPrice.Clear()
txGrandtotal1.Clear()
txGrandtotal2.Clear()
cmbcatjual.SelectedIndex = -1
cmbstat.SelectedIndex = -1
cmbstat.Text = ""
cmbcatjual.Text = ""
loadAutoKode()
End Sub
Private Sub dGridAll_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dGridAll.CellDoubleClick
If e.ColumnIndex >= 0 And e.RowIndex >= 0 Then
Dim x As DialogResult = MessageBox.Show("Delete Row?", "INFO", MessageBoxButtons.YesNo)
If x = Windows.Forms.DialogResult.Yes Then
dGridAll.Rows.RemoveAt(e.RowIndex)
updateGrand()
End If
End If
End Sub
Private Sub dGridAll_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles dGridAll.CellValueChanged
Select Case Label2.Text
Case "Penjualan Toko"
Dim subtotal As Integer = 0
For x As Integer = 4 To 11
subtotal += Integer.Parse(dGridAll.Rows(e.RowIndex).Cells(x).Value)
Next
dGridAll.Rows(e.RowIndex).Cells(12).Value = subtotal.ToString
dGridAll.Rows(e.RowIndex).Cells(15).Value = (subtotal * (Integer.Parse(dGridAll.Rows(e.RowIndex).Cells(13).Value) - _
(Integer.Parse(dGridAll.Rows(e.RowIndex).Cells(13).Value) * (Integer.Parse(dGridAll.Rows(e.RowIndex).Cells(14).Value) / 100))))
End Select
updateGrand()
End Sub
Private Sub dGridAll_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dGridAll.CellClick
Select Case Label2.Text
Case "Penjualan Toko"
If ((e.ColumnIndex >= 4 And e.ColumnIndex <= 11) Or (e.ColumnIndex = 13 Or e.ColumnIndex = 14)) And e.RowIndex >= 0 Then
dGridAll.CurrentCell = dGridAll.Rows(e.RowIndex).Cells(e.ColumnIndex)
dGridAll.BeginEdit(True)
End If
End Select
End Sub
Private Sub cmbstat_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbstat.SelectedIndexChanged
dGridAll.Rows.Clear()
DataGridView1.Rows.Clear()
DataGridView1.Rows.Insert(0, "", "0", "0", "0", "0", "0", "0", "0", "0")
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
DataGridView1.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
txnama.Clear()
txGrandtotal1.Clear()
txGrandtotal2.Clear()
If cmbstat.SelectedItem = "Store" Then
TextBox7.Text = Environment.NewLine & Environment.NewLine & Environment.NewLine & "Cons."
TextBox8.Text = Environment.NewLine & Environment.NewLine & Environment.NewLine & "Total Price"
Else
TextBox7.Text = Environment.NewLine & Environment.NewLine & Environment.NewLine & "Total Price"
TextBox8.Text = ""
End If
loadCom()
End Sub
Private Sub formTerimaKirimJual_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
If dGridAll.Rows.Count >= 1 Then
Dim dr As DialogResult = MessageBox.Show("Data not saved, close anyway?", "INFO", MessageBoxButtons.OKCancel)
If dr = Windows.Forms.DialogResult.Cancel Then
e.Cancel = True
Return
End If
End If
End Sub
Private Sub print()
Dim tgl As String = Now.ToShortDateString
Dim dt As New DataTable
Dim dt2 As New DataTable
Dim rpt As New rpttrans
Dim rpt1 As New rptkirim
Dim rpt2 As New rptukuran
Dim kategori As String = Me.Text
With dt
.Columns.Add("tanggal")
.Columns.Add("bill")
.Columns.Add("nama") 'nama garmen / toko
.Columns.Add("kategori")
.Columns.Add("statretur")
.Columns.Add("kode")
.Columns.Add("produk")
.Columns.Add("warna")
.Columns.Add("size")
.Columns.Add("s1")
.Columns.Add("s2")
.Columns.Add("s3")
.Columns.Add("s4")
.Columns.Add("s5")
.Columns.Add("s6")
.Columns.Add("s7")
.Columns.Add("s8")
.Columns.Add("ttlqty")
.Columns.Add("hrg")
.Columns.Add("cons")
.Columns.Add("total")
.Columns.Add("tot1")
.Columns.Add("tot2")
.Columns.Add("tot3")
.Columns.Add("tot4")
.Columns.Add("tot5")
.Columns.Add("tot6")
.Columns.Add("tot7")
.Columns.Add("tot8")
.Columns.Add("totqty")
.Columns.Add("grand")
End With
With dt2
.Columns.Add("s1")
.Columns.Add("s2")
.Columns.Add("s3")
.Columns.Add("s4")
.Columns.Add("s5")
.Columns.Add("s6")
.Columns.Add("s7")
.Columns.Add("s8")
End With
For Each dr As DataGridViewRow In Me.dGridAll.Rows
dt.Rows.Add(tgl, txtresi.Text, txnama.Text, cmbcatjual.Text, cmbstat, dr.Cells(0).Value, dr.Cells(1).Value, dr.Cells(2).Value, _
dr.Cells(3).Value, dr.Cells(4).Value, dr.Cells(5).Value, dr.Cells(6).Value, dr.Cells(7).Value, dr.Cells(8).Value, dr.Cells(9).Value, _
dr.Cells(10).Value, dr.Cells(11).Value, dr.Cells(12).Value, dr.Cells(13).Value, dr.Cells(14).Value, dr.Cells(15).Value, _
DataGridView1.Rows(0).Cells(1).Value, DataGridView1.Rows(0).Cells(2).Value, DataGridView1.Rows(0).Cells(3).Value, _
DataGridView1.Rows(0).Cells(4).Value, DataGridView1.Rows(0).Cells(5).Value, DataGridView1.Rows(0).Cells(6).Value, _
DataGridView1.Rows(0).Cells(7).Value, DataGridView1.Rows(0).Cells(8).Value, txtotQty.Text, txGrandtotal1.Text)
Next
For Each dr2 As DataGridViewRow In Me.dGridSize.Rows
dt2.Rows.Add(dr2.Cells(1).Value, dr2.Cells(2).Value, dr2.Cells(3).Value, dr2.Cells(4).Value, dr2.Cells(5).Value, _
dr2.Cells(6).Value, dr2.Cells(7).Value, dr2.Cells(8).Value)
Next
If Label2.Text = "Pengiriman" Or Label2.Text = "Penjualan Toko" Then
rpt1.SetDataSource(dt)
'rpt2.SetDataSource(dt2)
rpt1.Subreports("rptukuran.rpt").SetDataSource(dt2)
viewreport.CrystalReportViewer1.ReportSource = rpt1
Else
rpt.SetDataSource(dt)
'rpt2.SetDataSource(dt2)
rpt.Subreports("rptukuran.rpt").SetDataSource(dt2)
viewreport.CrystalReportViewer1.ReportSource = rpt
End If
viewreport.ShowDialog()
End Sub
Private Sub cmbcatjual_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbcatjual.SelectedIndexChanged
End Sub
Private Sub PrintToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PrintToolStripMenuItem.Click
print()
Dim dt3 As DataTable = dGridAll.DataSource
MainForm.ProgressBar1.Value = 0
clearForm()
End Sub
Private Sub cmbGudang_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbGudang.SelectedIndexChanged
cmbGudang.Enabled = False
End Sub
Private Sub NewToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NewToolStripMenuItem.Click
cmbGudang.Enabled = True
End Sub
End Class
|
doters/electrohell
|
stockingElectrohell 02-04-16/stockingElectrohell/stockingElectrohell/forms/formJual.vb
|
Visual Basic
|
mit
| 25,558
|
Imports System.Convert
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text
Imports System.Text.Encoding
Namespace Cryptography
Partial Public Class Cipher
#Region " Phonetic Digits "
Public Const PHONETIC_ZERO As String = "Zero"
Public Const PHONETIC_ONE As String = "One"
Public Const PHONETIC_TWO As String = "Two"
Public Const PHONETIC_THREE As String = "Three"
Public Const PHONETIC_FOUR As String = "Four"
Public Const PHONETIC_FIVE As String = "Five"
Public Const PHONETIC_SIX As String = "Six"
Public Const PHONETIC_SEVEN As String = "Seven"
Public Const PHONETIC_EIGHT As String = "Eight"
Public Const PHONETIC_NINE As String = "Nine"
Public Shared PHONETIC_DIGITS As String() = _
New String() _
{ _
PHONETIC_ZERO, PHONETIC_ONE, PHONETIC_TWO, _
PHONETIC_THREE, PHONETIC_FOUR, PHONETIC_FIVE, _
PHONETIC_SIX, PHONETIC_SEVEN, PHONETIC_EIGHT, PHONETIC_NINE _
}
#End Region
#Region " Phonetic Letters "
Public Const PHONETIC_LOWERCASE_A As String = "Alpha"
Public Const PHONETIC_LOWERCASE_B As String = "Bravo"
Public Const PHONETIC_LOWERCASE_C As String = "Charlie"
Public Const PHONETIC_LOWERCASE_D As String = "Delta"
Public Const PHONETIC_LOWERCASE_E As String = "Echo"
Public Const PHONETIC_LOWERCASE_F As String = "Foxtrot"
Public Const PHONETIC_LOWERCASE_G As String = "Golf"
Public Const PHONETIC_LOWERCASE_H As String = "Hotel"
Public Const PHONETIC_LOWERCASE_I As String = "India"
Public Const PHONETIC_LOWERCASE_J As String = "Juliet"
Public Const PHONETIC_LOWERCASE_K As String = "Kilo"
Public Const PHONETIC_LOWERCASE_L As String = "Lima"
Public Const PHONETIC_LOWERCASE_M As String = "Mike"
Public Const PHONETIC_LOWERCASE_N As String = "November"
Public Const PHONETIC_LOWERCASE_O As String = "Oscar"
Public Const PHONETIC_LOWERCASE_P As String = "Papa"
Public Const PHONETIC_LOWERCASE_Q As String = "Quebec"
Public Const PHONETIC_LOWERCASE_R As String = "Romeo"
Public Const PHONETIC_LOWERCASE_S As String = "Sierra"
Public Const PHONETIC_LOWERCASE_T As String = "Tango"
Public Const PHONETIC_LOWERCASE_U As String = "Uniform"
Public Const PHONETIC_LOWERCASE_V As String = "Victor"
Public Const PHONETIC_LOWERCASE_W As String = "Whiskey"
Public Const PHONETIC_LOWERCASE_X As String = "X-Ray"
Public Const PHONETIC_LOWERCASE_Y As String = "Yankee"
Public Const PHONETIC_LOWERCASE_Z As String = "Zulu"
Public Shared PHONETIC_LOWERCASE_LETTERS As String() = _
New String() _
{ _
PHONETIC_LOWERCASE_A, PHONETIC_LOWERCASE_B, PHONETIC_LOWERCASE_C, _
PHONETIC_LOWERCASE_D, PHONETIC_LOWERCASE_E, PHONETIC_LOWERCASE_F, _
PHONETIC_LOWERCASE_G, PHONETIC_LOWERCASE_H, PHONETIC_LOWERCASE_I, _
PHONETIC_LOWERCASE_J, PHONETIC_LOWERCASE_K, PHONETIC_LOWERCASE_L, _
PHONETIC_LOWERCASE_M, PHONETIC_LOWERCASE_N, PHONETIC_LOWERCASE_O, _
PHONETIC_LOWERCASE_P, PHONETIC_LOWERCASE_Q, PHONETIC_LOWERCASE_R, _
PHONETIC_LOWERCASE_S, PHONETIC_LOWERCASE_T, PHONETIC_LOWERCASE_U, _
PHONETIC_LOWERCASE_V, PHONETIC_LOWERCASE_W, PHONETIC_LOWERCASE_X, _
PHONETIC_LOWERCASE_Y, PHONETIC_LOWERCASE_Z _
}
Public Shared PHONETIC_UPPERCASE_A As String = PHONETIC_LOWERCASE_A.ToUpper
Public Shared PHONETIC_UPPERCASE_B As String = PHONETIC_LOWERCASE_B.ToUpper
Public Shared PHONETIC_UPPERCASE_C As String = PHONETIC_LOWERCASE_C.ToUpper
Public Shared PHONETIC_UPPERCASE_D As String = PHONETIC_LOWERCASE_D.ToUpper
Public Shared PHONETIC_UPPERCASE_E As String = PHONETIC_LOWERCASE_E.ToUpper
Public Shared PHONETIC_UPPERCASE_F As String = PHONETIC_LOWERCASE_F.ToUpper
Public Shared PHONETIC_UPPERCASE_G As String = PHONETIC_LOWERCASE_G.ToUpper
Public Shared PHONETIC_UPPERCASE_H As String = PHONETIC_LOWERCASE_H.ToUpper
Public Shared PHONETIC_UPPERCASE_I As String = PHONETIC_LOWERCASE_I.ToUpper
Public Shared PHONETIC_UPPERCASE_J As String = PHONETIC_LOWERCASE_J.ToUpper
Public Shared PHONETIC_UPPERCASE_K As String = PHONETIC_LOWERCASE_K.ToUpper
Public Shared PHONETIC_UPPERCASE_L As String = PHONETIC_LOWERCASE_L.ToUpper
Public Shared PHONETIC_UPPERCASE_M As String = PHONETIC_LOWERCASE_M.ToUpper
Public Shared PHONETIC_UPPERCASE_N As String = PHONETIC_LOWERCASE_N.ToUpper
Public Shared PHONETIC_UPPERCASE_O As String = PHONETIC_LOWERCASE_O.ToUpper
Public Shared PHONETIC_UPPERCASE_P As String = PHONETIC_LOWERCASE_P.ToUpper
Public Shared PHONETIC_UPPERCASE_Q As String = PHONETIC_LOWERCASE_Q.ToUpper
Public Shared PHONETIC_UPPERCASE_R As String = PHONETIC_LOWERCASE_R.ToUpper
Public Shared PHONETIC_UPPERCASE_S As String = PHONETIC_LOWERCASE_S.ToUpper
Public Shared PHONETIC_UPPERCASE_T As String = PHONETIC_LOWERCASE_T.ToUpper
Public Shared PHONETIC_UPPERCASE_U As String = PHONETIC_LOWERCASE_U.ToUpper
Public Shared PHONETIC_UPPERCASE_V As String = PHONETIC_LOWERCASE_V.ToUpper
Public Shared PHONETIC_UPPERCASE_W As String = PHONETIC_LOWERCASE_W.ToUpper
Public Shared PHONETIC_UPPERCASE_X As String = PHONETIC_LOWERCASE_X.ToUpper
Public Shared PHONETIC_UPPERCASE_Y As String = PHONETIC_LOWERCASE_Y.ToUpper
Public Shared PHONETIC_UPPERCASE_Z As String = PHONETIC_LOWERCASE_Z.ToUpper
Public Shared PHONETIC_UPPERCASE_LETTERS As String() = _
New String() _
{ _
PHONETIC_UPPERCASE_A, PHONETIC_UPPERCASE_B, PHONETIC_UPPERCASE_C, _
PHONETIC_UPPERCASE_D, PHONETIC_UPPERCASE_E, PHONETIC_UPPERCASE_F, _
PHONETIC_UPPERCASE_G, PHONETIC_UPPERCASE_H, PHONETIC_UPPERCASE_I, _
PHONETIC_UPPERCASE_J, PHONETIC_UPPERCASE_K, PHONETIC_UPPERCASE_L, _
PHONETIC_UPPERCASE_M, PHONETIC_UPPERCASE_N, PHONETIC_UPPERCASE_O, _
PHONETIC_UPPERCASE_P, PHONETIC_UPPERCASE_Q, PHONETIC_UPPERCASE_R, _
PHONETIC_UPPERCASE_S, PHONETIC_UPPERCASE_T, PHONETIC_UPPERCASE_U, _
PHONETIC_UPPERCASE_V, PHONETIC_UPPERCASE_W, PHONETIC_UPPERCASE_X, _
PHONETIC_UPPERCASE_Y, PHONETIC_UPPERCASE_Z _
}
#End Region
#Region " Digits "
Public Const DIGIT_ZERO As Char = "0"c
Public Const DIGIT_ONE As Char = "1"c
Public Const DIGIT_TWO As Char = "2"c
Public Const DIGIT_THREE As Char = "3"c
Public Const DIGIT_FOUR As Char = "4"c
Public Const DIGIT_FIVE As Char = "5"c
Public Const DIGIT_SIX As Char = "6"c
Public Const DIGIT_SEVEN As Char = "7"c
Public Const DIGIT_EIGHT As Char = "8"c
Public Const DIGIT_NINE As Char = "9"c
Public Shared DIGITS As Char() = _
New Char() _
{ _
DIGIT_ZERO, _
DIGIT_ONE, _
DIGIT_TWO, _
DIGIT_THREE, _
DIGIT_FOUR, _
DIGIT_FIVE, _
DIGIT_SIX, _
DIGIT_SEVEN, _
DIGIT_EIGHT, _
DIGIT_NINE _
}
#End Region
#Region " Letters "
Public Const LETTER_A As Char = "A"c
Public Const LETTER_B As Char = "B"c
Public Const LETTER_C As Char = "C"c
Public Const LETTER_D As Char = "D"c
Public Const LETTER_E As Char = "E"c
Public Const LETTER_F As Char = "F"c
Public Const LETTER_G As Char = "G"c
Public Const LETTER_H As Char = "H"c
Public Const LETTER_I As Char = "I"c
Public Const LETTER_J As Char = "J"c
Public Const LETTER_K As Char = "K"c
Public Const LETTER_L As Char = "L"c
Public Const LETTER_M As Char = "M"c
Public Const LETTER_N As Char = "N"c
Public Const LETTER_O As Char = "O"c
Public Const LETTER_P As Char = "P"c
Public Const LETTER_Q As Char = "Q"c
Public Const LETTER_R As Char = "R"c
Public Const LETTER_S As Char = "S"c
Public Const LETTER_T As Char = "T"c
Public Const LETTER_U As Char = "U"c
Public Const LETTER_V As Char = "V"c
Public Const LETTER_W As Char = "W"c
Public Const LETTER_X As Char = "X"c
Public Const LETTER_Y As Char = "Y"c
Public Const LETTER_Z As Char = "Z"c
Public Shared UPPERCASE_LETTERS As Char() = _
New Char() _
{ _
LETTER_A, LETTER_B, LETTER_C, LETTER_D, LETTER_E, LETTER_F, LETTER_G, _
LETTER_H, LETTER_I, LETTER_J, LETTER_K, LETTER_L, LETTER_M, LETTER_N, _
LETTER_O, LETTER_P, LETTER_Q, LETTER_R, LETTER_S, LETTER_T, LETTER_U, _
LETTER_V, LETTER_W, LETTER_X, LETTER_Y, LETTER_Z _
}
Public Shared LOWERCASE_LETTERS As Char() = _
New Char() _
{ _
Char.ToLower(LETTER_A), Char.ToLower(LETTER_B), Char.ToLower(LETTER_C), _
Char.ToLower(LETTER_D), Char.ToLower(LETTER_E), Char.ToLower(LETTER_F), _
Char.ToLower(LETTER_G), Char.ToLower(LETTER_H), Char.ToLower(LETTER_I), _
Char.ToLower(LETTER_J), Char.ToLower(LETTER_K), Char.ToLower(LETTER_L), _
Char.ToLower(LETTER_M), Char.ToLower(LETTER_N), Char.ToLower(LETTER_O), _
Char.ToLower(LETTER_P), Char.ToLower(LETTER_Q), Char.ToLower(LETTER_R), _
Char.ToLower(LETTER_S), Char.ToLower(LETTER_T), Char.ToLower(LETTER_U), _
Char.ToLower(LETTER_V), Char.ToLower(LETTER_W), Char.ToLower(LETTER_X), _
Char.ToLower(LETTER_Y), Char.ToLower(LETTER_Z) _
}
#End Region
#Region " Punctuation / Symbols "
Public Const AMPERSAND As Char = "&"c
Public Const ANGLE_BRACKET_END As Char = ">"c
Public Const ANGLE_BRACKET_START As Char = "<"c
Public Const ASTERISK As Char = "*"c
Public Const AT_SIGN As Char = "@"c
Public Const BACK_SLASH As Char = "\"c
Public Const BRACE_END As Char = "}"c
Public Const BRACE_START As Char = "{"c
Public Const BRACKET_END As Char = ")"c
Public Const BRACKET_START As Char = "("c
Public Const COLON As Char = ":"c
Public Const COMMA As Char = ","c
Public Const DOLLAR As Char = "$"c
Public Const EXCLAMATION_MARK As Char = "!"c
Public Const EQUALS_SIGN As Char = "="c
Public Const FORWARD_SLASH As Char = "/"c
Public Const FULL_STOP As Char = "."c
Public Const HASH As Char = "#"c
Public Const HYPHEN As Char = "-"c
Public Const PERCENTAGE_MARK As Char = "%"c
Public Const PIPE As Char = "|"c
Public Const PLUS As Char = "+"c
Public Const QUESTION_MARK As Char = "?"c
Public Const QUOTE_SINGLE As Char = "'"c
Public Const QUOTE_DOUBLE As Char = """"c
Public Const SEMI_COLON As Char = ";"c
Public Const SPACE As Char = " "c
Public Const SQUARE_BRACKET_END As Char = "]"c
Public Const SQUARE_BRACKET_START As Char = "["c
Public Const TILDA As Char = "~"c
Public Const [TAB] As Char = Microsoft.VisualBasic.ChrW(&H9)
Public Const UNDER_SCORE As Char = "_"c
#End Region
#Region " Public Constants "
Public Const SALT_SMALL_MIN_SIZE As Integer = 4 ' Default Small Salt Min Size (if required)
Public Const SALT_SMALL_MAX_SIZE As Integer = 8 ' Default Small Salt Max Size (if required)
Public Const SALT_LARGE_MIN_SIZE As Integer = 8 ' Default Small Salt Min Size (if required)
Public Const SALT_LARGE_MAX_SIZE As Integer = 16 ' Default Small Salt Max Size (if required)
#End Region
#Region " Private Shared Generation Methods "
''' <summary>Generates a hash for the given bytes.</summary>
''' <param name="bytesToHash">Byte Array to Hash</param>
''' <param name="hash_Algorithm">Hash Algorithm to use.</returns>
''' <returns>Array of Hash Bytes</returns>
Private Shared Function Generate_Hash_FromBytes( _
ByVal bytesToHash As Byte(), _
ByVal hash_Algorithm As HashType _
) As Byte()
Select Case hash_Algorithm
Case HashType.SHA1
Return New SHA1Managed().ComputeHash(bytesToHash)
Case HashType.SHA256
Return New SHA256Managed().ComputeHash(bytesToHash)
Case HashType.SHA384
Return New SHA384Managed().ComputeHash(bytesToHash)
Case HashType.SHA512
Return New SHA512Managed().ComputeHash(bytesToHash)
Case HashType.MD5
Return New MD5CryptoServiceProvider().ComputeHash(bytesToHash)
Case Else
Return New MD5CryptoServiceProvider().ComputeHash(bytesToHash)
End Select
End Function
#End Region
#Region " Public Shared Generation Methods "
''' <summary>Generates salt bytes for Crytography</summary>
''' <param name="min_Size">The (inclusive) minimum size for the salt array.</param>
''' <param name="max_Size">The (exclusive) maximum size for the saly array.</param>
''' <returns>An Array of Table Salt</returns>
Public Shared Function Generate_Salt( _
ByVal min_Size As Integer, _
ByVal max_Size As Integer _
) As Byte()
Dim salted_Size As Integer = New Random().Next(min_Size, max_Size)
Dim saltBytes As Byte() = New Byte(salted_Size - 1) {}
' Make a 'cryptographically strong' byte array
Dim rnd_Gen As New RNGCryptoServiceProvider()
rnd_Gen.GetNonZeroBytes(saltBytes)
Return saltBytes
End Function
''' <summary>
''' Generates a hash for the given plain text value and returns a base64-encoded result. Before the hash is computed, a random salt
''' is generated and appended to the plain text. This salt is stored at the end of the hash value, so it can be used later for hash
''' verification.
''' </summary>
''' <param name="plain_Text">Plaintext value to be hashed.</param>
''' <param name="salt_Bytes">Salt bytes. This parameter can be null, in which case a random salt value will be generated.</param>
''' <param name="hash_Algorithm">Hash Algorithm to use (Enum, defaults to MD5 [0]).</param>
''' <returns>Hash value formatted as a base64-encoded string.</returns>
''' <remarks></remarks>
Public Shared Function Generate_Salted_Hash( _
ByVal plain_Text As String, _
ByVal salt_Bytes() As Byte, _
Optional ByVal hash_Algorithm As HashType = HashType.MD5 _
) As String
If String.IsNullOrEmpty(plain_Text) Then Return String.Empty
If salt_Bytes Is Nothing Then salt_Bytes = Generate_Salt(SALT_SMALL_MIN_SIZE, SALT_SMALL_MAX_SIZE) ' Create Salt if required
Dim plainText_Bytes As Byte() = System.Text.Encoding.UTF8.GetBytes(plain_Text) ' Plain Text As Byte Array
Dim saltedPlainText_Bytes() As Byte = New Byte(plainText_Bytes.Length + salt_Bytes.Length - 1) {} ' Array for both Plain Text & Salt
plainText_Bytes.CopyTo(saltedPlainText_Bytes, 0) ' Copy in Plain Text Bytes
salt_Bytes.CopyTo(saltedPlainText_Bytes, plainText_Bytes.Length) ' Then Add in a touch of Salt
Dim hash_Bytes As Byte() = Generate_Hash_FromBytes(saltedPlainText_Bytes, hash_Algorithm) ' Do the Hashing
Dim hashWithSalt_Bytes(hash_Bytes.Length + salt_Bytes.Length - 1) As Byte ' Array for both Hash Bytes & Salt
hash_Bytes.CopyTo(hashWithSalt_Bytes, 0) ' Copy in Hash Bytes
salt_Bytes.CopyTo(hashWithSalt_Bytes, hash_Bytes.Length) ' Then Add in a touch of Salt
Return ToBase64String(hashWithSalt_Bytes)
End Function
''' <summary>Generates an (unsalted) hash for the given string</summary>
''' <param name="stringToHash">String Value to generate hash for</param>
''' <param name="hash_Algorithm">Hash Algorithm to use (Enum, defaults to MD5 [0])</param>
''' <returns>Hash value as an Array of Bytes</returns>
Public Shared Function Generate_Hash( _
ByVal stringToHash As String, _
Optional ByVal hash_Algorithm As HashType = HashType.MD5 _
) As String
Return ToBase64String(Generate_Hash_FromBytes(New UnicodeEncoding().GetBytes(stringToHash), hash_Algorithm))
End Function
''' <summary>Generates a hash for the given file</summary>
''' <param name="file">Path and Name of the File to be Hashed</param>
''' <param name="hashFirstNBytes">Hash first 'N' number of Bytes in the file stream</param>
''' <returns>Hash value formatted as a base64-encoded string</returns>
Public Shared Function Generate_Hash( _
ByVal file As IO.FileInfo, _
Optional ByVal hashFirstNBytes As Long = 0 _
) As String
Dim returnHash As String = Nothing
Dim fileIO As FileStream = Nothing
Try
fileIO = file.Open(FileMode.Open, FileAccess.Read)
Dim fileLength As Long
If hashFirstNBytes = 0 OrElse hashFirstNBytes >= fileIO.Length Then
fileLength = fileIO.Length - 1
Else
fileLength = hashFirstNBytes
End If
Dim fileBytes(CInt(fileLength)) As Byte
fileIO.Read(fileBytes, 0, fileBytes.Length)
Dim hashBytes As Byte() = Generate_Hash_FromBytes(fileBytes, HashType.MD5)
returnHash = ToBase64String(hashBytes)
Catch
Finally
If Not fileIO Is Nothing Then
fileIO.Close()
fileIO = Nothing
End If
End Try
Return returnHash
End Function
#End Region
#Region " Public Shared Verfication Methods "
''' <summary>
''' Compares a hash of the specified plain text value to a given hash value.
''' Plain text is hashed with the same salt value as the original hash.
''' </summary>
''' <param name="plainText">Plain text to be verified against the specified hash. The function
''' does not check whether this parameter is null.</param>
''' <param name="hashValue">Base64-encoded hash value produced by ComputeHash function.
''' This value includes the original salt appended to it.</param>
''' <param name="hash_Algorithm">Hash Algorithm to use (Enum, defaults to MD5 [0]).</returns>
''' <remarks></remarks>
Public Shared Function Verify_Hash( _
ByVal plain_Text As String, _
ByVal hash_Value As String, _
Optional ByVal hash_Algorithm As HashType = HashType.MD5 _
) As Boolean
Return String.Compare(hash_Value, Generate_Hash(plain_Text, hash_Algorithm)) = 0
End Function
''' <summary>
''' Compares a hash of the specified plain text value to a given hash value.
''' Plain text is hashed with the same salt value as the original hash.
''' </summary>
''' <param name="plainText">Plain text to be verified against the specified hash. The function
''' does not check whether this parameter is null.</param>
''' <param name="hashValue">Base64-encoded hash value produced by ComputeHash function.
''' This value includes the original salt appended to it.</param>
''' <param name="hash_Algorithm">Hash Algorithm to use (Enum, defaults to MD5 [0]).</returns>
''' <remarks></remarks>
Public Shared Function Verify_Salted_Hash( _
ByVal plain_Text As String, _
ByVal hash_Value As String, _
Optional ByVal hash_Algorithm As HashType = HashType.MD5 _
) As Boolean
' Convert base64-encoded hash value into a byte array.
Dim hashWithSaltBytes As Byte() = FromBase64String(hash_Value)
' We must know size of hash (without salt).
Dim hashSizeInBits As Integer
Dim hashSizeInBytes As Integer
' Size of hash is based on the specified algorithm.
Select Case hash_Algorithm
Case HashType.SHA1
hashSizeInBits = New SHA1Managed().HashSize
Case HashType.SHA256
hashSizeInBits = New SHA256Managed().HashSize
Case HashType.SHA384
hashSizeInBits = New SHA384Managed().HashSize
Case HashType.SHA512
hashSizeInBits = New SHA512Managed().HashSize
Case HashType.MD5
hashSizeInBits = New MD5CryptoServiceProvider().HashSize
Case Else ' Must be MD5
hashSizeInBits = New MD5CryptoServiceProvider().HashSize
End Select
' Convert size of hash from bits to bytes.
hashSizeInBytes = CInt(hashSizeInBits / 8)
' Make sure that the specified hash value is long enough.
If (hashWithSaltBytes.Length < hashSizeInBytes) Then Return False
' Allocate array to hold original salt bytes retrieved from hash.
Dim saltBytes(hashWithSaltBytes.Length - hashSizeInBytes - 1) As Byte
' Copy salt from the end of the hash to the new array.
Array.Copy(hashWithSaltBytes, hashSizeInBytes, saltBytes, 0, saltBytes.Length)
' Compute a new hash string.
Dim expectedHashString As String = Generate_Salted_Hash(plain_Text, saltBytes, hash_Algorithm)
' If the computed hash matches the specified hash,
' the plain text value must be correct.
Return String.Compare(hash_Value, expectedHashString) = 0
End Function
#End Region
#Region " Public Shared Encryption/Decryption Methods "
''' <summary>Encrypts a Plain Text Value</summary>
''' <param name="plain_Text">The Text to Encrypt.</param>
''' <param name="encryption_Key">The Key to Use.</param>
''' <returns>The Cipher Text</returns>
''' <remarks>The First Byte is salt length + final part of cipher text is salt</remarks>
Public Shared Function Encrypt( _
ByVal plain_Text As String, _
ByVal encryption_Key As String _
) As String
Dim plainText_Bytes As Byte() = Encoding.Unicode.GetBytes(plain_Text)
Dim salt_Bytes As Byte() = Generate_Salt(SALT_LARGE_MIN_SIZE, SALT_LARGE_MAX_SIZE)
Dim secret_Key As New Rfc2898DeriveBytes(encryption_Key, salt_Bytes)
Dim memory_Stream As New MemoryStream()
Dim cryptoStream As New CryptoStream(memory_Stream, _
New RijndaelManaged().CreateEncryptor(secret_Key.GetBytes(32), secret_Key.GetBytes(16)), _
CryptoStreamMode.Write)
cryptoStream.Write(plainText_Bytes, 0, plainText_Bytes.Length)
cryptoStream.FlushFinalBlock()
Dim cipherText_Bytes As Byte() = memory_Stream.ToArray()
memory_Stream.Close()
cryptoStream.Close()
Dim cipherText_Array(cipherText_Bytes.Length + salt_Bytes.Length) As Byte
Array.Copy(cipherText_Bytes, 0, cipherText_Array, 1, cipherText_Bytes.Length)
cipherText_Array(0) = CByte(salt_Bytes.Length)
Array.Copy(salt_Bytes, 0, cipherText_Array, cipherText_Bytes.Length + 1, salt_Bytes.Length)
Return ToBase64String(cipherText_Array)
End Function
''' <summary>Decrypts an Encrypted Value back to Plain Text</summary>
''' <param name="cipher_Text">The Cipher Text</param>
''' <param name="encryption_Key">The Key to Use</param>
''' <returns>The Plain Text</returns>
''' <remarks></remarks>
Public Shared Function Decrypt( _
ByVal cipher_Text As String, _
ByVal encryption_Key As String _
) As String
Dim cipherText_Array As Byte() = FromBase64String(cipher_Text)
Dim salt_Bytes(cipherText_Array(0) - 1) As Byte
Array.Copy(cipherText_Array, cipherText_Array.Length - salt_Bytes.Length, salt_Bytes, 0, salt_Bytes.Length)
Dim cipherTextBytes_Array(cipherText_Array.Length - salt_Bytes.Length - 2) As Byte
Array.Copy(cipherText_Array, 1, cipherTextBytes_Array, 0, cipherTextBytes_Array.Length)
Dim secret_Key As New Rfc2898DeriveBytes(encryption_Key, salt_Bytes)
Dim memory_Stream As New MemoryStream(cipherTextBytes_Array)
Dim cryptoStream As New CryptoStream(memory_Stream, _
New RijndaelManaged().CreateDecryptor(secret_Key.GetBytes(32), secret_Key.GetBytes(16)), _
CryptoStreamMode.Read)
Dim plainTextBytes(cipherTextBytes_Array.Length - 1) As Byte
Dim decryptedCount As Integer = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length)
cryptoStream.Read(cipherTextBytes_Array, 0, cipherTextBytes_Array.Length)
memory_Stream.Close()
cryptoStream.Close()
Return Encoding.Unicode.GetString(plainTextBytes, 0, decryptedCount)
End Function
#End Region
#Region " Public Shared Password Methods "
''' <summary>
''' Method to Generate a Password of a given Length and with a given number of Special/
''' Non-Alpha Numeric Characters.
''' </summary>
''' <param name="length">The Password Length Required.</param>
''' <param name="numberOfNonAlphanumericCharacters">The Number of Characters that cannot
''' be Alpha-Numeric.</param>
''' <returns>The new Password.</returns>
''' <remarks>This generation method is only as secure as the RNGCryptoServiceProvider Random
''' Number generator.</remarks>
Public Shared Function Create_Password( _
ByVal length As Integer, _
ByVal numberOfNonAlphanumericCharacters As Integer _
) As String
' -- Check Input Parameters --
If (length < 1 OrElse length > 128) Then Throw New ArgumentException("Password Length Not Valid")
If (numberOfNonAlphanumericCharacters > length OrElse numberOfNonAlphanumericCharacters < 0) Then _
Throw New ArgumentException("Non-AlphaNumeric Characters Length Not Valid")
' ----------------------------
Do While True
Dim nonAlphanumericCount As Integer = 0
Dim buffer As Byte() = New Byte(length - 1) {}
Dim ary_Password As Char() = New Char(length - 1) {}
Dim ary_AlphaNumeric As Char() = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".ToCharArray()
Dim ary_NonAlphaNumeric As Char() = "!@$%^^*()_-+=[{]};:>|./?~".ToCharArray()
' Make a 'cryptographically strong' byte array
Dim rdn_Gen As New RNGCryptoServiceProvider()
rdn_Gen.GetBytes(buffer)
For i As Integer = 0 To length - 1
' Randon Byte --> Char Conversion
Dim rnd_Char As Integer = (buffer(i) Mod 87)
If rnd_Char < 10 Then
ary_Password(i) = System.Convert.ToChar(System.Convert.ToUInt16(48 + rnd_Char))
ElseIf rnd_Char < 36 Then
ary_Password(i) = System.Convert.ToChar(System.Convert.ToUInt16((65 + rnd_Char) - 10))
ElseIf rnd_Char < 62 Then
ary_Password(i) = System.Convert.ToChar(System.Convert.ToUInt16((97 + rnd_Char) - 36))
Else
ary_Password(i) = ary_NonAlphaNumeric(rnd_Char - 62)
nonAlphanumericCount += 1
End If
Next
If nonAlphanumericCount < numberOfNonAlphanumericCharacters Then
Dim rnd_Number As New Random()
For i As Integer = 0 To (numberOfNonAlphanumericCharacters - nonAlphanumericCount) - 1
Dim passwordPos As Integer
Do
passwordPos = rnd_Number.Next(0, length)
Loop While Not Char.IsLetterOrDigit(ary_Password(passwordPos))
ary_Password(passwordPos) = ary_NonAlphaNumeric(rnd_Number.Next(0, ary_NonAlphaNumeric.Length))
Next
ElseIf nonAlphanumericCount > numberOfNonAlphanumericCharacters Then
Dim rnd_Number As New Random()
For i = 0 To (nonAlphanumericCount - numberOfNonAlphanumericCharacters) - 1
Dim passwordPos As Integer
Do
passwordPos = rnd_Number.Next(0, length)
Loop While Char.IsLetterOrDigit(ary_Password(passwordPos))
ary_Password(passwordPos) = ary_AlphaNumeric(rnd_Number.Next(0, ary_AlphaNumeric.Length))
Next
End If
Return New String(ary_Password)
Loop
Return Nothing
End Function
''' <summary>
''' Method to Create a Phonetic Representation of a Password to help ensure complex
''' Password comprehension.
''' </summary>
''' <param name="password">The Password to create the Phonetic of.</param>
''' <returns>The Phonetic Representation as a String.</returns>
''' <remarks></remarks>
Public Shared Function PhoneticPassword( _
ByVal password As String _
) As String
Dim hashPhonetic As New Hashtable
' Numbers
For i As Integer = 0 To DIGITS.Length - 1
hashPhonetic.Add(DIGITS(i), PHONETIC_DIGITS(i))
Next
' Upper Case Letters
For i As Integer = 0 To UPPERCASE_LETTERS.Length - 1
hashPhonetic.Add(UPPERCASE_LETTERS(i), PHONETIC_UPPERCASE_LETTERS(i))
Next
' Lower Case Letters
For i As Integer = 0 To LOWERCASE_LETTERS.Length - 1
hashPhonetic.Add(LOWERCASE_LETTERS(i), PHONETIC_LOWERCASE_LETTERS(i))
Next
Dim sbBuilder As New System.Text.StringBuilder
sbBuilder.Append(BRACE_START)
For i As Integer = 0 To password.Length - 1
Dim singleCharacter As Char = password.Substring(i, 1).Chars(0)
sbBuilder.Append(SPACE)
If i <> 0 Then
sbBuilder.Append(HYPHEN)
sbBuilder.Append(SPACE)
End If
If hashPhonetic.Contains(singleCharacter) Then
sbBuilder.Append(hashPhonetic(singleCharacter))
Else
sbBuilder.Append(singleCharacter)
End If
Next
sbBuilder.Append(SPACE)
sbBuilder.Append(BRACE_END)
Return sbBuilder.ToString
End Function
#End Region
End Class
End Namespace
|
thiscouldbejd/Hermes
|
_Cryptography/Partials/Cipher.vb
|
Visual Basic
|
mit
| 27,978
|
Imports WeifenLuo.WinFormsUI.Docking
Imports OxyPlot
Imports OxyPlot.Series
Imports MathNet.Numerics
Public Class GraphDockPanel : Inherits DockContent
Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
InitializePlot()
End Sub
Private Sub InitializePlot()
Dim plot = New PlotModel
Dim lseries = New LineSeries
Dim lseries2 = New LineSeries
Dim lseries3 = New LineSeries
plot.Axes.Add(New Axes.LinearAxis With {.Position = Axes.AxisPosition.Left})
plot.Axes.Add(New Axes.LinearAxis With {.Position = Axes.AxisPosition.Bottom})
For i = 0 To 200
Dim ydata = Math.Cos(i * Math.PI / 100)
lseries.Points.Add(New DataPoint(i, ydata))
lseries2.Points.Add(New DataPoint(i + 5, ydata))
lseries3.Points.Add(New DataPoint(i + 10, ydata))
Next
plot.Series.Add(lseries)
plot.Series.Add(lseries2)
plot.Series.Add(lseries3)
Me.mainPlot.Model = plot
End Sub
Public Sub AddSeries(ByVal data As Double(,))
Dim lseries = New LineSeries
For i = 0 To Math.Floor(data.Length / 2) - 1
lseries.Points.Add(New DataPoint(data(0, i), data(1, i)))
Next
Me.mainPlot.Model.Series.Add(lseries)
End Sub
Property Plot
Get
Plot = Me.mainPlot
End Get
Set(value)
End Set
End Property
End Class
|
wboxx1/85-EIS-PUMA
|
puma/future_development/Version 2.0 Content/Forms/GraphDockPanel.vb
|
Visual Basic
|
mit
| 1,551
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.18408
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.Stuxnet_Remover.Form1
End Sub
End Class
End Namespace
|
ParityHF/Stuxnet-Remover
|
Stuxnet Remover/My Project/Application.Designer.vb
|
Visual Basic
|
mit
| 1,481
|
Imports NetOffice
Imports Word = NetOffice.WordApi
Imports NetOffice.WordApi.Enums
Imports Tests.Core
Public Class Test08
Implements ITestPackage
Public ReadOnly Property Description As String Implements Tests.Core.ITestPackage.Description
Get
Return "Using Paragraphes."
End Get
End Property
Public ReadOnly Property Language As String Implements Tests.Core.ITestPackage.Language
Get
Return "VB"
End Get
End Property
Public ReadOnly Property Name As String Implements Tests.Core.ITestPackage.Name
Get
Return "Test08"
End Get
End Property
Public ReadOnly Property OfficeProduct As String Implements Tests.Core.ITestPackage.OfficeProduct
Get
Return "Word"
End Get
End Property
Public Function DoTest() As Tests.Core.TestResult Implements Tests.Core.ITestPackage.DoTest
Dim application As Word.Application = Nothing
Dim startTime As DateTime = DateTime.Now
Try
application = New Word.Application()
Dim document As Word.Document = application.Documents.Add()
application.DisplayAlerts = WdAlertLevel.wdAlertsNone
application.Selection.TypeText("Test with TabIntend VB")
application.Selection.Start = 0
Dim p As Word.Paragraph = document.Application.Selection.Range.Paragraphs(1)
p.IndentCharWidth(10)
p.IndentFirstLineCharWidth(8)
p.Space1()
p.Space15()
p.Space2()
p.TabHangingIndent(5)
p.TabIndent(3)
Return New TestResult(True, DateTime.Now.Subtract(startTime), "", Nothing, "")
Catch ex As Exception
Return New TestResult(False, DateTime.Now.Subtract(startTime), ex.Message, ex, "")
Finally
If Not IsNothing(application) Then
application.Quit(WdSaveOptions.wdDoNotSaveChanges)
application.Dispose()
End If
End Try
End Function
End Class
|
NetOfficeFw/NetOffice
|
Tests/Main Tests/WordTestsVB/Test08.vb
|
Visual Basic
|
mit
| 2,097
|
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.Linq
Imports BVSoftware.Bvc5.Core
Partial Class BVAdmin_Controls_CategoryTreeView
Inherits System.Web.UI.UserControl
Private _allCats As Collection(Of Catalog.Category) = Nothing
#Region " Properties "
Public Property SelectedCategories() As Dictionary(Of String, String)
Get
' make sure that we're getting the most up-to-date info
If Me.CategoryTree.Nodes IsNot Nothing AndAlso Me.CategoryTree.Nodes.Count > 0 Then
ViewState("SelectedCategories") = GetSelectedNodes()
End If
Dim obj As Object = ViewState("SelectedCategories")
If obj IsNot Nothing Then
Return CType(obj, Dictionary(Of String, String))
Else
Return New Dictionary(Of String, String)
End If
End Get
Set(ByVal value As Dictionary(Of String, String))
ViewState("SelectedCategories") = value
End Set
End Property
Public Property HighlightSelectedCategories() As Boolean
Get
Dim obj As Object = ViewState("HighlightSelectedCategories")
If obj IsNot Nothing Then
Return CBool(obj)
Else
Return True
End If
End Get
Set(ByVal value As Boolean)
ViewState("HighlightSelectedCategories") = value
End Set
End Property
Public Property ExpandSelectedCategories() As Boolean
Get
Dim obj As Object = ViewState("ExpandSelectedCategories")
If obj IsNot Nothing Then
Return CBool(obj)
Else
Return False
End If
End Get
Set(ByVal value As Boolean)
ViewState("ExpandSelectedCategories") = value
End Set
End Property
Public Property IncludeHiddenCategories() As Boolean
Get
Dim obj As Object = ViewState("IncludeHiddenCategories")
If obj IsNot Nothing Then
Return CBool(obj)
Else
Return False
End If
End Get
Set(ByVal value As Boolean)
ViewState("IncludeHiddenCategories") = value
End Set
End Property
Private ReadOnly Property allCats As Collection(Of Catalog.Category)
Get
If Me._allCats Is Nothing Then
Me._allCats = Catalog.Category.FindAllLight()
End If
Return Me._allCats
End Get
End Property
#End Region
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
LoadTreeView()
End If
End Sub
Public Sub LoadSelectedCategories(ByVal categories As Collection(Of Catalog.Category))
Me.SelectedCategories = Me.ConvertCollectionToDictionary(categories)
End Sub
Public Sub LoadTreeView()
Me.CategoryTree.Nodes.Clear()
Dim topLevelCats As Collection(Of Catalog.Category) = Catalog.Category.FindChildrenInCollection(allCats, "0", Me.IncludeHiddenCategories)
Dim checkedCats As Dictionary(Of String, String) = Me.SelectedCategories
For Each c As Catalog.Category In topLevelCats
'If c.SourceType = Catalog.CategorySourceType.ByRules OrElse c.SourceType = Catalog.CategorySourceType.Manual Then ' exclude CustomLink and CustomPage categories
Dim node As New TreeNode(c.Name, c.Bvin)
node.SelectAction = TreeNodeSelectAction.None ' prevents node from being a link
node.Checked = checkedCats.ContainsKey(c.Bvin)
Me.CategoryTree.Nodes.Add(node)
If AddChildNodes(node, 1, checkedCats) Then
If Me.HighlightSelectedCategories Then
node.Text = "<b>" + node.Text + "</b>"
End If
If Me.ExpandSelectedCategories Then
node.Expanded = True
End If
End If
'End If
Next
End Sub
Private Function AddChildNodes(ByVal node As TreeNode, ByVal currentDepth As Integer, ByVal checkedCats As Dictionary(Of String, String)) As Boolean
Dim result As Boolean = False
Dim childCats As Collection(Of Catalog.Category) = Catalog.Category.FindChildrenInCollection(allCats, node.Value, Me.IncludeHiddenCategories)
For Each c As Catalog.Category In childCats
'If c.SourceType = Catalog.CategorySourceType.ByRules OrElse c.SourceType = Catalog.CategorySourceType.Manual Then ' exclude CustomLink and CustomPage categories
Dim childNode As New TreeNode(c.Name, c.Bvin)
childNode.SelectAction = TreeNodeSelectAction.None ' prevents node from being a link
childNode.Checked = checkedCats.ContainsKey(c.Bvin)
node.ChildNodes.Add(childNode)
If childNode.Checked Then
result = True
End If
If AddChildNodes(childNode, currentDepth + 1, checkedCats) Then
If Me.HighlightSelectedCategories Then
childNode.Text = "<b>" + node.Text + "</b>"
End If
If Me.ExpandSelectedCategories Then
childNode.Expanded = True
End If
result = True
End If
'End If
Next
Return result
End Function
Private Function GetSelectedNodes() As Dictionary(Of String, String)
Dim result As New Dictionary(Of String, String)
For Each node As TreeNode In Me.CategoryTree.CheckedNodes
If node.Checked Then
result.Add(node.Value, node.Text)
End If
Next
Return result
End Function
#Region " Utilities "
Public Function ConvertDictionaryToCollection(ByVal categories As Dictionary(Of String, String)) As Collection(Of Catalog.Category)
Dim result As New Collection(Of Catalog.Category)
If categories IsNot Nothing Then
For Each item As KeyValuePair(Of String, String) In categories
Dim c As Catalog.Category = Catalog.Category.FindInCollection(allCats, item.Key)
If Not String.IsNullOrEmpty(c.Bvin) Then
result.Add(c)
End If
Next
End If
Return result
End Function
Public Function ConvertCollectionToDictionary(ByVal categories As Collection(Of Catalog.Category)) As Dictionary(Of String, String)
Dim result As New Dictionary(Of String, String)
If categories IsNot Nothing Then
For Each c As Catalog.Category In categories
result.Add(c.Bvin, c.Name)
Next
End If
Return result
End Function
#End Region
End Class
|
ajaydex/Scopelist_2015
|
BVAdmin/Controls/CategoryTreeView.ascx.vb
|
Visual Basic
|
apache-2.0
| 6,927
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Debugging
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Debugging
' TODO: Make this class static when we add that functionality to VB.
Namespace DataTipInfoGetter
Friend Module DataTipInfoGetterModule
Friend Async Function GetInfoAsync(document As Document, position As Integer, cancellationToken As CancellationToken) As Task(Of DebugDataTipInfo)
Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
Dim token = root.FindToken(position)
If token.IsKind(SyntaxKind.CommaToken) Then
' The commas in a separated syntax list consider the list's parent
' to be their parent, which leads to false positives below.
Return Nothing
End If
If token.Parent.IsKind(SyntaxKind.ModifiedIdentifier) Then
Return New DebugDataTipInfo(token.Span, text:=Nothing)
End If
Dim expression = TryCast(token.Parent, ExpressionSyntax)
If expression Is Nothing Then
Return If(token.IsKind(SyntaxKind.IdentifierToken),
New DebugDataTipInfo(token.Span, text:=Nothing),
Nothing)
End If
If expression.IsAnyLiteralExpression() Then
Return Nothing
End If
Dim conditionalAccess As ExpressionSyntax = Nothing
If expression.IsRightSideOfDotOrBang() Then
expression = DirectCast(expression.Parent, ExpressionSyntax)
Dim curr = expression
While True
curr = curr.GetCorrespondingConditionalAccessExpression()
If curr Is Nothing Then
Exit While
End If
conditionalAccess = curr
End While
End If
If expression.Parent.IsKind(SyntaxKind.InvocationExpression) Then
expression = DirectCast(expression.Parent, ExpressionSyntax)
End If
Dim span = expression.Span
If conditionalAccess IsNot Nothing Then
' There may not be an ExpressionSyntax corresponding to the range we want.
' For example, for input a?.$$B?.C we want span [|a?.B|].C.
span = TextSpan.FromBounds(conditionalAccess.SpanStart, span.End)
End If
Return New DebugDataTipInfo(span, text:=Nothing)
End Function
End Module
End Namespace
End Namespace
|
abock/roslyn
|
src/Features/VisualBasic/Portable/Debugging/DataTipInfoGetter.vb
|
Visual Basic
|
mit
| 3,236
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.CodeFixes.GenerateMember
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.GenerateType
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateType
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.GenerateType), [Shared]>
<ExtensionOrder(After:=PredefinedCodeFixProviderNames.GenerateVariable)>
Friend Class GenerateTypeCodeFixProvider
Inherits AbstractGenerateMemberCodeFixProvider
Friend Const BC30002 As String = "BC30002" ' error BC30002: Type 'Test' is not defined.
Friend Const BC30182 As String = "BC30182" ' error BC30182: Type expected.
Friend Const BC30451 As String = "BC30451" ' error BC30451: 'Goo' is not declared. It may be inaccessible due to its protection level.
Friend Const BC30456 As String = "BC30456" ' error BC32043: error BC30456: 'B' is not a member of 'A'.
Friend Const BC32042 As String = "BC32042" ' error BC32042: Too few type arguments to 'AA(Of T)'.
Friend Const BC32043 As String = "BC32043" ' error BC32043: Too many type arguments to 'AA(Of T)'.
Friend Const BC32045 As String = "BC32045" ' error BC32045: 'Goo' has no type parameters and so cannot have type arguments.
Friend Const BC40056 As String = "BC40056" ' error BC40056: Namespace or type specified in the Imports 'A' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
<ImportingConstructor>
Public Sub New()
End Sub
Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String)
Get
Return ImmutableArray.Create(BC30002, IDEDiagnosticIds.UnboundIdentifierId, BC30182, BC30451, BC30456, BC32042, BC32043, BC32045, BC40056)
End Get
End Property
Protected Overrides Function GetCodeActionsAsync(document As Document, node As SyntaxNode, cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of CodeAction))
Dim service = document.GetLanguageService(Of IGenerateTypeService)()
Return service.GenerateTypeAsync(document, node, cancellationToken)
End Function
Protected Overrides Function IsCandidate(node As SyntaxNode, token As SyntaxToken, diagnostic As Diagnostic) As Boolean
Dim qualified = TryCast(node, QualifiedNameSyntax)
If qualified IsNot Nothing Then
Return True
End If
Dim simple = TryCast(node, SimpleNameSyntax)
If simple IsNot Nothing Then
Return Not simple.IsParentKind(SyntaxKind.QualifiedName)
End If
Dim memberAccess = TryCast(node, MemberAccessExpressionSyntax)
If memberAccess IsNot Nothing Then
Return True
End If
Return False
End Function
Protected Overrides Function GetTargetNode(node As SyntaxNode) As SyntaxNode
Return (DirectCast(node, ExpressionSyntax)).GetRightmostName()
End Function
End Class
End Namespace
|
abock/roslyn
|
src/Features/VisualBasic/Portable/CodeFixes/GenerateType/GenerateTypeCodeFixProvider.vb
|
Visual Basic
|
mit
| 3,673
|
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.Windows.Controls
Imports ESRI.ArcGIS.Client
Imports System.Windows.Data
Partial Public Class TimeFeatureLayer
Inherits UserControl
Public Sub New()
InitializeComponent()
End Sub
Private Sub FeatureLayer_Initialized(ByVal sender As Object, ByVal e As EventArgs)
Dim intervals As New List(Of DateTime)()
Dim dt As DateTime = MyTimeSlider.MinimumValue
Do While dt < MyTimeSlider.MaximumValue
intervals.Add(dt)
dt = dt.AddYears(2)
Loop
intervals.Add(MyTimeSlider.MaximumValue)
MyTimeSlider.Intervals = intervals
End Sub
End Class
|
Esri/arcgis-samples-silverlight
|
src/VBNet/ArcGISSilverlightSDK/Time/TimeFeatureLayer.xaml.vb
|
Visual Basic
|
apache-2.0
| 675
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.Implementation.GoToDefinition
Imports Microsoft.CodeAnalysis.Editor.UnitTests.GoToDefinition
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities.GoToHelpers
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.GoToDefinition
Public Class GoToDefinitionApiTests
Private Async Function TestAsync(workspaceDefinition As XElement, expectSuccess As Boolean) As Tasks.Task
Using workspace = Await TestWorkspaceFactory.CreateWorkspaceAsync(workspaceDefinition, exportProvider:=GoToTestHelpers.ExportProvider)
Dim solution = workspace.CurrentSolution
Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue)
Dim cursorPosition = cursorDocument.CursorPosition.Value
Dim document = solution.GetDocument(cursorDocument.Id)
Dim root = Await document.GetSyntaxRootAsync()
Dim semanticModel = Await document.GetSemanticModelAsync()
Dim symbol = root.FindToken(cursorPosition).Parent _
.AncestorsAndSelf() _
.Select(Function(n) semanticModel.GetDeclaredSymbol(n, CancellationToken.None)) _
.FirstOrDefault()
Assert.NotNull(symbol)
Dim symbolId = symbol.GetSymbolKey()
Dim project = document.Project
Dim compilation = Await project.GetCompilationAsync()
Dim symbolInfo = symbolId.Resolve(compilation)
Assert.NotNull(symbolInfo.Symbol)
Dim presenter = New MockNavigableItemsPresenter(Sub() Exit Sub)
WpfTestCase.RequireWpfFact($"{NameOf(GoToDefinitionHelpers)}.{NameOf(GoToDefinitionHelpers.TryGoToDefinition)} assumes it's on the UI thread with a WaitAndGetResult call")
Dim success = GoToDefinitionHelpers.TryGoToDefinition(
symbolInfo.Symbol, document.Project, {New Lazy(Of INavigableItemsPresenter)(Function() presenter)}, thirdPartyNavigationAllowed:=True, throwOnHiddenDefinition:=False, cancellationToken:=CancellationToken.None)
Assert.Equal(expectSuccess, success)
End Using
End Function
Private Function TestSuccessAsync(workspaceDefinition As XElement) As Tasks.Task
Return TestAsync(workspaceDefinition, True)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)>
Public Async Function TestVBOperator() As Tasks.Task
Dim workspaceDefinition =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document>
''' <summary>
''' thin wrapper around a single int to test operators
''' </summary>
Structure IntWrapper
Private Value As Integer
Public Sub New(i As Integer)
Value = i
End Sub
Public Shared Widening Operator CType(i As IntWrapper) As Integer
Return i.Value
End Operator
' Repro operator
$$Public Shared Narrowing Operator CType(i As IntWrapper) As Byte
Return CByte(i.Value)
End Operator
Public Shared Narrowing Operator CType(i As IntWrapper) As String
Return String.Format("{0}", i.Value)
End Operator
End Structure
</Document>
</Project>
</Workspace>
Await TestSuccessAsync(workspaceDefinition)
End Function
End Class
End Namespace
|
HellBrick/roslyn
|
src/VisualStudio/Core/Test/GoToDefinition/GoToDefinitionApiTests.vb
|
Visual Basic
|
apache-2.0
| 3,836
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Reflection
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenTests
Inherits BasicTestBase
<WorkItem(776642, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/776642")>
<Fact()>
Public Sub Bug776642a()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Main(args As String())
M(New Object() {})
End Sub
Sub M(args As Object())
args = New Object() {Nothing}
Console.WriteLine((((DirectCast(args(0), OuterStruct)).z).y).x)
End Sub
End Module
Structure TwoInteger
Public x As Integer
Public y As Integer
End Structure
Structure DoubleAndStruct
Public x As Double
Public y As TwoInteger
End Structure
Structure OuterStruct
Public z As DoubleAndStruct
End Structure
</file>
</compilation>).
VerifyIL("Program.M",
<![CDATA[
{
// Code size 37 (0x25)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: newarr "Object"
IL_0006: starg.s V_0
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: ldelem.ref
IL_000b: unbox "OuterStruct"
IL_0010: ldflda "OuterStruct.z As DoubleAndStruct"
IL_0015: ldflda "DoubleAndStruct.y As TwoInteger"
IL_001a: ldfld "TwoInteger.x As Integer"
IL_001f: call "Sub System.Console.WriteLine(Integer)"
IL_0024: ret
}
]]>)
End Sub
<WorkItem(776642, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/776642")>
<Fact()>
Public Sub Bug776642b()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Main(args As String())
M(New Object() {})
End Sub
Sub M(args As Object())
args = New Object() {Nothing}
Console.WriteLine((((DirectCast(args(0), OuterStruct)).z).y).x)
End Sub
End Module
Structure TwoInteger
Public x As Integer
Public y As Integer
End Structure
Structure DoubleAndStruct
Public x As Double
Public y As TwoInteger
End Structure
Class OuterStruct
Public z As DoubleAndStruct
End Class
</file>
</compilation>).
VerifyIL("Program.M",
<![CDATA[
{
// Code size 37 (0x25)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: newarr "Object"
IL_0006: starg.s V_0
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: ldelem.ref
IL_000b: castclass "OuterStruct"
IL_0010: ldflda "OuterStruct.z As DoubleAndStruct"
IL_0015: ldflda "DoubleAndStruct.y As TwoInteger"
IL_001a: ldfld "TwoInteger.x As Integer"
IL_001f: call "Sub System.Console.WriteLine(Integer)"
IL_0024: ret
}
]]>)
End Sub
<Fact()>
Public Sub Bug776642a_ref()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Main(args As String())
M(New Object() {})
End Sub
Sub M(args As Object())
args = New Object() {new OuterStruct(1)}
Console.WriteLine((((DirectCast(args(0), OuterStruct)).z).y).x)
End Sub
End Module
Structure TwoInteger
Public x As Integer
Public y As Integer
End Structure
Class DoubleAndStruct
Public x As Double
Public y As TwoInteger
End Class
Structure OuterStruct
public sub new(i as integer)
z = new DoubleAndStruct()
end sub
Public z As DoubleAndStruct
End Structure
</file>
</compilation>).
VerifyIL("Program.M",
<![CDATA[
{
// Code size 51 (0x33)
.maxstack 4
IL_0000: ldc.i4.1
IL_0001: newarr "Object"
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4.1
IL_0009: newobj "Sub OuterStruct..ctor(Integer)"
IL_000e: box "OuterStruct"
IL_0013: stelem.ref
IL_0014: starg.s V_0
IL_0016: ldarg.0
IL_0017: ldc.i4.0
IL_0018: ldelem.ref
IL_0019: unbox "OuterStruct"
IL_001e: ldfld "OuterStruct.z As DoubleAndStruct"
IL_0023: ldflda "DoubleAndStruct.y As TwoInteger"
IL_0028: ldfld "TwoInteger.x As Integer"
IL_002d: call "Sub System.Console.WriteLine(Integer)"
IL_0032: ret
}
]]>)
End Sub
<WorkItem(776642, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/776642")>
<Fact()>
Public Sub Bug776642_shared()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Main(args As String())
M(New Object() {})
End Sub
Sub M(args As Object())
Console.WriteLine(((OuterStruct.z).y).x)
End Sub
End Module
Structure TwoInteger
Public x As Integer
Public y As Integer
End Structure
Structure DoubleAndStruct
Public x As Double
Public y As TwoInteger
End Structure
Class OuterStruct
Public Shared z As DoubleAndStruct
End Class
</file>
</compilation>).
VerifyIL("Program.M",
<![CDATA[
{
// Code size 21 (0x15)
.maxstack 1
IL_0000: ldsflda "OuterStruct.z As DoubleAndStruct"
IL_0005: ldflda "DoubleAndStruct.y As TwoInteger"
IL_000a: ldfld "TwoInteger.x As Integer"
IL_000f: call "Sub System.Console.WriteLine(Integer)"
IL_0014: ret
}
]]>)
End Sub
<WorkItem(545724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545724")>
<Fact()>
Public Sub Bug14352()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Console
Module Module1
Sub Main()
Dim o1_1 As New C1(Of Double)(False)
Dim o1_2 As New C1(Of Double)(True)
If o1_1 AndAlso o1_2 Then
WriteLine("Failed - 1")
Else
WriteLine("Passed - 1")
End If
End Sub
Class C1(Of T)
Public m_Value As Boolean
Sub New()
End Sub
Sub New(ByVal Value As Boolean)
m_Value = Value
End Sub
Shared Operator And(ByVal arg1 As C1(Of Double), ByVal arg2 As C1(Of T)) As C1(Of T)
Return New C1(Of T)(arg1.m_Value And arg2.m_Value)
End Operator
Shared Operator IsFalse(ByVal arg1 As C1(Of T)) As Boolean
Return Not arg1.m_Value
End Operator
Shared Operator IsTrue(ByVal arg1 As C1(Of T)) As Boolean
Return arg1.m_Value
End Operator
End Class
End Module
</file>
</compilation>, expectedOutput:="Passed - 1")
End Sub
<WorkItem(578074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578074")>
<WorkItem(32576, "https://github.com/dotnet/roslyn/issues/32576")>
<Fact>
Public Sub PreserveZeroDigitsInDecimal()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Console
Module Form1
Sub Main(args As String())
TST()
Console.Write(" ")
TST2()
End Sub
Sub TST(Optional d As Decimal = 0.0000d)
Console.Write(d.ToString(System.Globalization.CultureInfo.InvariantCulture))
End Sub
Sub TST2(Optional d As Decimal = -0.0000000D)
Console.Write(d.ToString(System.Globalization.CultureInfo.InvariantCulture))
End Sub
End Module
</file>
</compilation>, expectedOutput:="0.0000 0.0000000")
End Sub
<Fact()>
Public Sub TestRedimWithArrayType()
CompileAndVerify(
<compilation>
<file name="a.vb">
Class RedimTest
Public Shared Sub Main()
Dim o As Integer()
ReDim o(3)
o(1) = 234
ReDim Preserve o(5)
System.Console.WriteLine(o(1))
System.Console.WriteLine(o(4))
ReDim o(2), o(3), o(4)
System.Console.WriteLine(o(1))
End Sub
End Class
</file>
</compilation>,
expectedOutput:=<![CDATA[
234
0
0
]]>).
VerifyIL("RedimTest.Main",
<![CDATA[
{
// Code size 73 (0x49)
.maxstack 4
IL_0000: ldc.i4.4
IL_0001: newarr "Integer"
IL_0006: dup
IL_0007: ldc.i4.1
IL_0008: ldc.i4 0xea
IL_000d: stelem.i4
IL_000e: ldc.i4.6
IL_000f: newarr "Integer"
IL_0014: call "Function Microsoft.VisualBasic.CompilerServices.Utils.CopyArray(System.Array, System.Array) As System.Array"
IL_0019: castclass "Integer()"
IL_001e: dup
IL_001f: ldc.i4.1
IL_0020: ldelem.i4
IL_0021: call "Sub System.Console.WriteLine(Integer)"
IL_0026: ldc.i4.4
IL_0027: ldelem.i4
IL_0028: call "Sub System.Console.WriteLine(Integer)"
IL_002d: ldc.i4.3
IL_002e: newarr "Integer"
IL_0033: pop
IL_0034: ldc.i4.4
IL_0035: newarr "Integer"
IL_003a: pop
IL_003b: ldc.i4.5
IL_003c: newarr "Integer"
IL_0041: ldc.i4.1
IL_0042: ldelem.i4
IL_0043: call "Sub System.Console.WriteLine(Integer)"
IL_0048: ret
}
]]>)
End Sub
<Fact()>
Public Sub TestRedimWithParamArrayProperty()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module RedimTest
Sub Main()
ReDim Preserve X(0)
End Sub
Dim s As String()
Property X(ParamArray a As String()) As Integer()
Get
s = a
Return New Integer() {}
End Get
Set(ByVal value As Integer())
Console.WriteLine(s Is a)
End Set
End Property
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[False]]>).
VerifyIL("RedimTest.Main",
<![CDATA[
{
// Code size 39 (0x27)
.maxstack 3
IL_0000: ldc.i4.0
IL_0001: newarr "String"
IL_0006: ldc.i4.0
IL_0007: newarr "String"
IL_000c: call "Function RedimTest.get_X(ParamArray String()) As Integer()"
IL_0011: ldc.i4.1
IL_0012: newarr "Integer"
IL_0017: call "Function Microsoft.VisualBasic.CompilerServices.Utils.CopyArray(System.Array, System.Array) As System.Array"
IL_001c: castclass "Integer()"
IL_0021: call "Sub RedimTest.set_X(ParamArray String(), Integer())"
IL_0026: ret
}
]]>)
End Sub
<WorkItem(546809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546809")>
<Fact()>
Public Sub Bug16872()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Imports System.Linq
Public Enum E
A
B
C
End Enum
Public MustInherit Class Base
Public MustOverride ReadOnly Property Kind As E
End Class
Public Class DerivedA
Inherits Base
Public Overrides ReadOnly Property Kind As E
Get
Return E.A
End Get
End Property
End Class
Public Class DerivedB
Inherits Base
Public Overrides ReadOnly Property Kind As E
Get
Return E.B
End Get
End Property
Public ReadOnly Property IsGood As Boolean
Get
Return True
End Get
End Property
End Class
Module Program
Sub Main(args As String())
Dim o As Base = New DerivedA
Dim b As Boolean = (o.Kind = E.B) AndAlso (DirectCast(o, DerivedB).IsGood)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="").
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (Base V_0) //o
IL_0000: newobj "Sub DerivedA..ctor()"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: callvirt "Function Base.get_Kind() As E"
IL_000c: ldc.i4.1
IL_000d: bne.un.s IL_001c
IL_000f: ldloc.0
IL_0010: castclass "DerivedB"
IL_0015: callvirt "Function DerivedB.get_IsGood() As Boolean"
IL_001a: br.s IL_001d
IL_001c: ldc.i4.0
IL_001d: pop
IL_001e: ret
}
]]>)
End Sub
<WorkItem(529861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529861")>
<Fact()>
Public Sub Bug14632a()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Globalization
Module Program
Sub Main()
Console.WriteLine((0e-28d).ToString(CultureInfo.InvariantCulture)) ' Dev11: 0.0000000000000000000000000000
Console.WriteLine((0e-29d).ToString(CultureInfo.InvariantCulture)) ' Dev11: 0.0000000000000000000000000000
Console.WriteLine((0e-30d).ToString(CultureInfo.InvariantCulture)) ' Dev11: 0
Console.WriteLine((0e-40d).ToString(CultureInfo.InvariantCulture)) ' Dev11: 0
Console.WriteLine((0e-50d).ToString(CultureInfo.InvariantCulture)) ' Dev11: 0
Console.WriteLine((0e-100d).ToString(CultureInfo.InvariantCulture)) ' Dev11: 0
Console.WriteLine((0e-1000d).ToString(CultureInfo.InvariantCulture)) ' Dev11: 0
Console.WriteLine((0e-10000d).ToString(CultureInfo.InvariantCulture)) ' Dev11: 0
Console.WriteLine()
Console.WriteLine((1e-28d).ToString(CultureInfo.InvariantCulture)) ' Dev11: 0.0000000000000000000000000001
Console.WriteLine((1e-29d).ToString(CultureInfo.InvariantCulture)) ' Dev11: 0.0000000000000000000000000000
Console.WriteLine((1e-30d).ToString(CultureInfo.InvariantCulture)) ' Dev11: 0
Console.WriteLine((1e-40d).ToString(CultureInfo.InvariantCulture)) ' Dev11: 0
Console.WriteLine((1e-50d).ToString(CultureInfo.InvariantCulture)) ' Dev11: 0
Console.WriteLine((1e-100d).ToString(CultureInfo.InvariantCulture)) ' Dev11: 0
Console.WriteLine((1e-1000d).ToString(CultureInfo.InvariantCulture)) ' Dev11: 0
Console.WriteLine((1e-10000d).ToString(CultureInfo.InvariantCulture)) ' Dev11: 0
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
0.0000000000000000000000000000
0.0000000000000000000000000000
0.0000000000000000000000000000
0.0000000000000000000000000000
0.0000000000000000000000000000
0.0000000000000000000000000000
0.0000000000000000000000000000
0.0000000000000000000000000000
0.0000000000000000000000000001
0.0000000000000000000000000000
0.0000000000000000000000000000
0.0000000000000000000000000000
0.0000000000000000000000000000
0.0000000000000000000000000000
0.0000000000000000000000000000
0.0000000000000000000000000000
]]>)
End Sub
<WorkItem(529861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529861")>
<WorkItem(568475, "DevDiv")>
<Fact()>
Public Sub Bug14632b()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Main(args As String())
Console.WriteLine(0e28d)
Console.WriteLine()
Console.WriteLine(0.000000e28d)
Console.WriteLine(0.000000e29d)
Console.WriteLine(0.000000e30d)
Console.WriteLine(0.000000e34d)
End Sub
End Module
</file>
</compilation>)
Dim d As Decimal = 0
If (Decimal.TryParse("0E1", Globalization.NumberStyles.AllowExponent, Nothing, d)) Then
compilation.AssertNoErrors()
Else
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC30036: Overflow.
Console.WriteLine(0e28d)
~~~~~
BC30036: Overflow.
Console.WriteLine(0.000000e28d)
~~~~~~~~~~~~
BC30036: Overflow.
Console.WriteLine(0.000000e29d)
~~~~~~~~~~~~
BC30036: Overflow.
Console.WriteLine(0.000000e30d)
~~~~~~~~~~~~
BC30036: Overflow.
Console.WriteLine(0.000000e34d)
~~~~~~~~~~~~
]]></errors>)
End If
End Sub
<WorkItem(529861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529861")>
<Fact()>
Public Sub Bug14632c()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Main(args As String())
Console.WriteLine(0.000001e28d)
Console.WriteLine(0.000001e29d)
Console.WriteLine(0.000001e30d)
Console.WriteLine(0.000001e34d)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
10000000000000000000000
100000000000000000000000
1000000000000000000000000
10000000000000000000000000000
]]>)
End Sub
''' <summary>
''' Breaking change: native compiler considers
''' digits < 1e-49 when rounding.
''' </summary>
<WorkItem(568494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568494")>
<WorkItem(568520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568520")>
<WorkItem(32576, "https://github.com/dotnet/roslyn/issues/32576")>
<WorkItem(375, "https://github.com/dotnet/roslyn/issues/375")>
<ConditionalFact(GetType(DesktopOnly))>
Public Sub DecimalLiteral_BreakingChange()
CompileAndVerify(
<compilation>
<file name="c.vb"><![CDATA[
Imports System
Module M
Dim cul As Globalization.CultureInfo = Globalization.CultureInfo.InvariantCulture
Sub Main()
Console.WriteLine(3.0500000000000000000001e-27d.ToString(cul)) ' 3.05e-27d + 1e-49d [Dev11/Roslyn rounds]
Console.WriteLine(3.05000000000000000000001e-27d.ToString(cul)) ' 3.05e-27d + 1e-50d [Dev11 rounds, Roslyn does not]
Console.WriteLine()
Console.WriteLine(5.00000000000000000001e-29d.ToString(cul)) ' 5.0e-29d + 1e-49d [Dev11/Roslyn rounds]
Console.WriteLine(5.0000000000000000000000000000001e-29d.ToString(cul)) ' 5.0e-29d + 1e-60d [Dev11 rounds, Roslyn does not]
Console.WriteLine()
Console.WriteLine((-5.00000000000000000001e-29d).ToString(cul)) ' -5.0e-29d + 1e-49d [Dev11/Roslyn rounds]
Console.WriteLine((-5.0000000000000000000000000000001e-29d).ToString(cul)) ' -5.0e-29d + 1e-60d [Dev11 rounds, Roslyn does not]
Console.WriteLine()
' 10 20 30 40 50 60 70 80 90 100
Console.WriteLine(.1000000000000000000000000000500000000000000000000000000000000000000000000000000000000000000000000001d.ToString(cul)) ' [Dev11 rounds, Roslyn does not]
End Sub
End Module
]]></file>
</compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[
0.0000000000000000000000000031
0.0000000000000000000000000030
0.0000000000000000000000000001
0.0000000000000000000000000000
-0.0000000000000000000000000001
0.0000000000000000000000000000
0.1000000000000000000000000000
]]>)
End Sub
<Fact()>
Public Sub DecimalZero()
CompileAndVerify(
<compilation>
<file name="c.vb"><![CDATA[
Imports System
Imports System.Linq
Module M
Sub Main()
Dump(0E0D)
Dump(0.0E0D)
Dump(0.00E0D)
Console.WriteLine()
Dump(0E-1D)
Dump(0E-10D)
Dump(-0E-10D)
Dump(0.00E-10D)
Dump(0E-100D) ' differs from Dev11
Console.WriteLine()
Dump(decimal.Negate(0E0D))
Dump(decimal.Negate(0.0E0D))
Dump(decimal.Negate(0.00E0D))
Console.WriteLine()
Dump(decimal.Negate(0E-1D))
Dump(decimal.Negate(0E-10D))
Dump(decimal.Negate(-0E-10D))
Dump(decimal.Negate(0.00E-10D))
Dump(decimal.Negate(0E-100D)) ' differs from Dev11
End Sub
Function ToHexString(d As Decimal)
Return String.Join("", Decimal.GetBits(d).Select(Function(word) String.Format("{0:x8}", word)))
End Function
Sub Dump(d As Decimal)
Console.WriteLine(ToHexString(d))
End Sub
End Module
]]></file>
</compilation>, references:=XmlReferences, expectedOutput:=<![CDATA[
00000000000000000000000000000000
00000000000000000000000000010000
00000000000000000000000000020000
00000000000000000000000000010000
000000000000000000000000000a0000
000000000000000000000000800a0000
000000000000000000000000000c0000
000000000000000000000000001c0000
00000000000000000000000080000000
00000000000000000000000080010000
00000000000000000000000080020000
00000000000000000000000080010000
000000000000000000000000800a0000
000000000000000000000000000a0000
000000000000000000000000800c0000
000000000000000000000000801c0000
]]>)
End Sub
''' <summary>
''' Breaking change: native compiler allows 0eNm where N > 0.
''' (The native compiler ignores sign and scale in 0eNm if N > 0
''' and represents such cases as 0e0m.)
''' </summary>
<WorkItem(568475, "DevDiv")>
<Fact()>
Public Sub DecimalZero_BreakingChange()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Imports System
Module M
Sub Main()
Console.WriteLine(0E1D)
Console.WriteLine(0E10D)
Console.WriteLine(-0E10D)
Console.WriteLine(0.00E10D)
Console.WriteLine(-0.00E10D)
Console.WriteLine(0E100D) ' Dev11: BC30036: Overflow.
End Sub
End Module
]]></file>
</compilation>)
Dim d As Decimal = 0
If (Decimal.TryParse("0E1", Globalization.NumberStyles.AllowExponent, Nothing, d)) Then
compilation.AssertNoErrors
Else
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC30036: Overflow.
Console.WriteLine(0E1D)
~~~~
BC30036: Overflow.
Console.WriteLine(0E10D)
~~~~~
BC30036: Overflow.
Console.WriteLine(-0E10D)
~~~~~
BC30036: Overflow.
Console.WriteLine(0.00E10D)
~~~~~~~~
BC30036: Overflow.
Console.WriteLine(-0.00E10D)
~~~~~~~~
BC30036: Overflow.
Console.WriteLine(0E100D) ' Dev11: BC30036: Overflow.
~~~~~~
]]></errors>)
End If
End Sub
<Fact()>
Public Sub TestChainedReadonlyFieldsAccessWithPropertyGetter()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Structure Array(Of T)
Default Public Property Item(i As Integer) As T
Get
Return Nothing
End Get
Set(value As T)
End Set
End Property
End Structure
Structure Field
Public Property Type As String
End Structure
Structure Descr
Public ReadOnly Fields As Array(Of Field)
End Structure
Class Container
Public ReadOnly D As Descr
End Class
Class Member
Public ReadOnly C As Container
Public ReadOnly Property P As String
Get
Return Me.C.D.Fields(123).Type
End Get
End Property
Shared Sub Main(args() As String)
Console.WriteLine("Done")
End Sub
End Class
</file>
</compilation>,
expectedOutput:=<![CDATA[Done]]>).
VerifyIL("Member.get_P",
<![CDATA[
{
// Code size 35 (0x23)
.maxstack 2
.locals init (Array(Of Field) V_0,
Field V_1)
IL_0000: ldarg.0
IL_0001: ldfld "Member.C As Container"
IL_0006: ldfld "Container.D As Descr"
IL_000b: ldfld "Descr.Fields As Array(Of Field)"
IL_0010: stloc.0
IL_0011: ldloca.s V_0
IL_0013: ldc.i4.s 123
IL_0015: call "Function Array(Of Field).get_Item(Integer) As Field"
IL_001a: stloc.1
IL_001b: ldloca.s V_1
IL_001d: call "Function Field.get_Type() As String"
IL_0022: ret
}
]]>)
End Sub
<WorkItem(545120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545120")>
<Fact()>
Public Sub Bug13399a()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class S
Public X As String
Public Y As Object
End Class
Public Module Program
Public Sub Main(args() As String)
Dim i As Integer = 0
Dim a, b As New S() With {
.Y = Function() As String
With .ToString()
i += 1
Return .ToString & ":" & i
End With
End Function.Invoke(), .X = .Y
}
Console.WriteLine(a.X & "-" & b.X)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="S:1-S:2")
End Sub
<WorkItem(545120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545120")>
<Fact()>
Public Sub Bug13399b()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Imports System.Linq
Structure S
Public X As String
Public Y As Object
End Structure
Public Module Program
Public Sub Main(args() As String)
Dim i As Integer = 0
Dim a, b As New S() With {
.Y = Function() As String
With .ToString()
i += 1
Return .ToString & ":" & i
End With
End Function.Invoke(), .X = .Y
}
Console.WriteLine(a.X & "-" & b.X)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="S:1-S:2")
End Sub
<Fact()>
Public Sub TestRedimWithParamArrayProperty2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module RedimTest
Sub Main()
ReDim Preserve X(Y)(0)
End Sub
Property Y As String
Dim s As String()
Property X(ParamArray a As String()) As Integer()
Get
s = a
Return New Integer() {}
End Get
Set(ByVal value As Integer())
Console.WriteLine(s Is a)
End Set
End Property
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[False]]>).
VerifyIL("RedimTest.Main",
<![CDATA[
{
// Code size 53 (0x35)
.maxstack 5
.locals init (String V_0)
IL_0000: ldc.i4.1
IL_0001: newarr "String"
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: call "Function RedimTest.get_Y() As String"
IL_000d: dup
IL_000e: stloc.0
IL_000f: stelem.ref
IL_0010: ldc.i4.1
IL_0011: newarr "String"
IL_0016: dup
IL_0017: ldc.i4.0
IL_0018: ldloc.0
IL_0019: stelem.ref
IL_001a: call "Function RedimTest.get_X(ParamArray String()) As Integer()"
IL_001f: ldc.i4.1
IL_0020: newarr "Integer"
IL_0025: call "Function Microsoft.VisualBasic.CompilerServices.Utils.CopyArray(System.Array, System.Array) As System.Array"
IL_002a: castclass "Integer()"
IL_002f: call "Sub RedimTest.set_X(ParamArray String(), Integer())"
IL_0034: ret
}
]]>)
End Sub
<Fact()>
Public Sub TestByRefMethodWithParamArrayProperty()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M
Sub Main()
M(X)
End Sub
Sub M(ByRef p As Integer())
p = New Integer(100) {}
End Sub
Dim s As String()
Property X(ParamArray a As String()) As Integer()
Get
s = a
Return New Integer() {}
End Get
Set(ByVal value As Integer())
Console.WriteLine(s Is a)
End Set
End Property
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[False]]>).
VerifyIL("M.Main",
<![CDATA[
{
// Code size 32 (0x20)
.maxstack 2
.locals init (Integer() V_0)
IL_0000: ldc.i4.0
IL_0001: newarr "String"
IL_0006: call "Function M.get_X(ParamArray String()) As Integer()"
IL_000b: stloc.0
IL_000c: ldloca.s V_0
IL_000e: call "Sub M.M(ByRef Integer())"
IL_0013: ldc.i4.0
IL_0014: newarr "String"
IL_0019: ldloc.0
IL_001a: call "Sub M.set_X(ParamArray String(), Integer())"
IL_001f: ret
}
]]>)
End Sub
<WorkItem(545404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545404")>
<Fact()>
Public Sub Bug13798()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections
Class CLS
Implements IEnumerable
Public Shared Sub Main(args() As String)
Dim x = New CLS() From {1, 2, 3}
End Sub
Partial Private Sub Add(i As Integer)
End Sub
Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return Nothing
End Function
End Class
</file>
</compilation>,
expectedOutput:="").
VerifyIL("CLS.Main",
<![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: newobj "Sub CLS..ctor()"
IL_0005: pop
IL_0006: ret
}
]]>)
End Sub
<Fact()>
Public Sub PropertiesWithInconsistentAccessors()
Dim vbSource =
<compilation>
<file name="a.vb">
Imports System
Class D3
Inherits D2
Public Overrides WriteOnly Property P_rw_r_w As Integer
Set(value As Integer)
MyBase.P_rw_r_w = value
End Set
End Property
Public Overrides ReadOnly Property P_rw_rw_r As Integer
Get
Return MyBase.P_rw_rw_r
End Get
End Property
Public Overrides WriteOnly Property P_rw_rw_w As Integer
Set(value As Integer)
MyBase.P_rw_rw_w = value
End Set
End Property
Public Sub Test()
Dim tmp As Integer
tmp = Me.P_rw_r_w
tmp = MyClass.P_rw_r_w
tmp = MyBase.P_rw_r_w
Me.P_rw_r_w = tmp
MyClass.P_rw_r_w = tmp
MyBase.P_rw_r_w = tmp
tmp = Me.P_rw_rw_r
tmp = MyClass.P_rw_rw_r
tmp = MyBase.P_rw_rw_r
Me.P_rw_rw_r = tmp
MyClass.P_rw_rw_r = tmp
MyBase.P_rw_rw_r = tmp
tmp = Me.P_rw_rw_w
tmp = MyClass.P_rw_rw_w
tmp = MyBase.P_rw_rw_w
Me.P_rw_rw_w = tmp
MyClass.P_rw_rw_w = tmp
MyBase.P_rw_rw_w = tmp
End Sub
End Class
</file>
</compilation>
CompileWithCustomILSource(vbSource, ClassesWithReadWriteProperties.Value, TestOptions.ReleaseDll).
VerifyIL("D3.Test",
<![CDATA[
{
// Code size 127 (0x7f)
.maxstack 2
.locals init (Integer V_0) //tmp
IL_0000: ldarg.0
IL_0001: callvirt "Function D1.get_P_rw_r_w() As Integer"
IL_0006: stloc.0
IL_0007: ldarg.0
IL_0008: call "Function D1.get_P_rw_r_w() As Integer"
IL_000d: stloc.0
IL_000e: ldarg.0
IL_000f: call "Function D1.get_P_rw_r_w() As Integer"
IL_0014: stloc.0
IL_0015: ldarg.0
IL_0016: ldloc.0
IL_0017: callvirt "Sub D3.set_P_rw_r_w(Integer)"
IL_001c: ldarg.0
IL_001d: ldloc.0
IL_001e: call "Sub D3.set_P_rw_r_w(Integer)"
IL_0023: ldarg.0
IL_0024: ldloc.0
IL_0025: call "Sub D2.set_P_rw_r_w(Integer)"
IL_002a: ldarg.0
IL_002b: callvirt "Function D3.get_P_rw_rw_r() As Integer"
IL_0030: stloc.0
IL_0031: ldarg.0
IL_0032: call "Function D3.get_P_rw_rw_r() As Integer"
IL_0037: stloc.0
IL_0038: ldarg.0
IL_0039: call "Function D2.get_P_rw_rw_r() As Integer"
IL_003e: stloc.0
IL_003f: ldarg.0
IL_0040: ldloc.0
IL_0041: callvirt "Sub D1.set_P_rw_rw_r(Integer)"
IL_0046: ldarg.0
IL_0047: ldloc.0
IL_0048: call "Sub D1.set_P_rw_rw_r(Integer)"
IL_004d: ldarg.0
IL_004e: ldloc.0
IL_004f: call "Sub D1.set_P_rw_rw_r(Integer)"
IL_0054: ldarg.0
IL_0055: callvirt "Function D1.get_P_rw_rw_w() As Integer"
IL_005a: stloc.0
IL_005b: ldarg.0
IL_005c: call "Function D1.get_P_rw_rw_w() As Integer"
IL_0061: stloc.0
IL_0062: ldarg.0
IL_0063: call "Function D1.get_P_rw_rw_w() As Integer"
IL_0068: stloc.0
IL_0069: ldarg.0
IL_006a: ldloc.0
IL_006b: callvirt "Sub D3.set_P_rw_rw_w(Integer)"
IL_0070: ldarg.0
IL_0071: ldloc.0
IL_0072: call "Sub D3.set_P_rw_rw_w(Integer)"
IL_0077: ldarg.0
IL_0078: ldloc.0
IL_0079: call "Sub D2.set_P_rw_rw_w(Integer)"
IL_007e: ret
}
]]>)
End Sub
Public Shared ReadOnly AttributesWithReadWriteProperties As XCData = <![CDATA[
.class public auto ansi beforefieldinit B
extends [mscorlib]System.Attribute
{
.custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 FF 7F 00 00 00 00 )
.method public hidebysig newslot specialname virtual
instance int32 get_P_rw_r_w() cil managed
{
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldc.i4.1
IL_0001: ret
} // end of method B::get_P_rw_r_w
.method public hidebysig newslot specialname virtual
instance void set_P_rw_r_w(int32 'value') cil managed
{
// Code size 1 (0x1)
.maxstack 8
IL_0000: ret
} // end of method B::set_P_rw_r_w
.method public hidebysig newslot specialname virtual
instance int32 get_P_rw_rw_w() cil managed
{
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldc.i4.1
IL_0001: ret
} // end of method B::get_P_rw_rw_w
.method public hidebysig newslot specialname virtual
instance void set_P_rw_rw_w(int32 'value') cil managed
{
// Code size 1 (0x1)
.maxstack 8
IL_0000: ret
} // end of method B::set_P_rw_rw_w
.method public hidebysig newslot specialname virtual
instance int32 get_P_rw_rw_r() cil managed
{
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldc.i4.1
IL_0001: ret
} // end of method B::get_P_rw_rw_r
.method public hidebysig newslot specialname virtual
instance void set_P_rw_rw_r(int32 'value') cil managed
{
// Code size 1 (0x1)
.maxstack 8
IL_0000: ret
} // end of method B::set_P_rw_rw_r
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Attribute::.ctor()
IL_0006: ret
} // end of method B::.ctor
.property instance int32 P_rw_r_w()
{
.get instance int32 B::get_P_rw_r_w()
.set instance void B::set_P_rw_r_w(int32)
} // end of property B::P_rw_r_w
.property instance int32 P_rw_rw_w()
{
.set instance void B::set_P_rw_rw_w(int32)
.get instance int32 B::get_P_rw_rw_w()
} // end of property B::P_rw_rw_w
.property instance int32 P_rw_rw_r()
{
.get instance int32 B::get_P_rw_rw_r()
.set instance void B::set_P_rw_rw_r(int32)
} // end of property B::P_rw_rw_r
} // end of class B
.class public auto ansi beforefieldinit D1
extends B
{
.method public hidebysig specialname virtual
instance int32 get_P_rw_r_w() cil managed
{
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldc.i4.1
IL_0001: ret
} // end of method D1::get_P_rw_r_w
.method public hidebysig specialname virtual
instance int32 get_P_rw_rw_w() cil managed
{
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldc.i4.1
IL_0001: ret
} // end of method D1::get_P_rw_rw_w
.method public hidebysig specialname virtual
instance void set_P_rw_rw_w(int32 'value') cil managed
{
// Code size 1 (0x1)
.maxstack 8
IL_0000: ret
} // end of method D1::set_P_rw_rw_w
.method public hidebysig specialname virtual
instance int32 get_P_rw_rw_r() cil managed
{
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldc.i4.1
IL_0001: ret
} // end of method D1::get_P_rw_rw_r
.method public hidebysig specialname virtual
instance void set_P_rw_rw_r(int32 'value') cil managed
{
// Code size 1 (0x1)
.maxstack 8
IL_0000: ret
} // end of method D1::set_P_rw_rw_r
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void B::.ctor()
IL_0006: ret
} // end of method D1::.ctor
.property instance int32 P_rw_r_w()
{
.get instance int32 D1::get_P_rw_r_w()
} // end of property D1::P_rw_r_w
.property instance int32 P_rw_rw_w()
{
.get instance int32 D1::get_P_rw_rw_w()
.set instance void D1::set_P_rw_rw_w(int32)
} // end of property D1::P_rw_rw_w
.property instance int32 P_rw_rw_r()
{
.get instance int32 D1::get_P_rw_rw_r()
.set instance void D1::set_P_rw_rw_r(int32)
} // end of property D1::P_rw_rw_r
} // end of class D1
.class public auto ansi beforefieldinit D2
extends D1
{
.method public hidebysig specialname virtual
instance void set_P_rw_r_w(int32 'value') cil managed
{
// Code size 1 (0x1)
.maxstack 8
IL_0000: ret
} // end of method D2::set_P_rw_r_w
.method public hidebysig specialname virtual
instance void set_P_rw_rw_w(int32 'value') cil managed
{
// Code size 1 (0x1)
.maxstack 8
IL_0000: ret
} // end of method D2::set_P_rw_rw_w
.method public hidebysig specialname virtual
instance int32 get_P_rw_rw_r() cil managed
{
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldc.i4.1
IL_0001: ret
} // end of method D2::get_P_rw_rw_r
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void D1::.ctor()
IL_0006: ret
} // end of method D2::.ctor
.property instance int32 P_rw_r_w()
{
.set instance void D2::set_P_rw_r_w(int32)
} // end of property D2::P_rw_r_w
.property instance int32 P_rw_rw_w()
{
.set instance void D2::set_P_rw_rw_w(int32)
} // end of property D2::P_rw_rw_w
.property instance int32 P_rw_rw_r()
{
.get instance int32 D2::get_P_rw_rw_r()
} // end of property D2::P_rw_rw_r
} // end of class D2
.class public auto ansi beforefieldinit XXX
extends [mscorlib]System.Object
{
.custom instance void D2::.ctor() = ( 01 00 03 00 54 08 08 50 5F 72 77 5F 72 5F 77 01 // ....T..P_rw_r_w.
00 00 00 54 08 09 50 5F 72 77 5F 72 77 5F 77 02 // ...T..P_rw_rw_w.
00 00 00 54 08 09 50 5F 72 77 5F 72 77 5F 72 03 // ...T..P_rw_rw_r.
00 00 00 )
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method XXX::.ctor
} // end of class XXX
]]>
<Fact()>
Public Sub AttributesWithInconsistentPropertiesAccessors()
Dim vbSource =
<compilation>
<file name="a.vb">
Imports System
Imports System.Reflection
Imports System.Collections.Generic
<D2(P_rw_r_w:=1, P_rw_rw_w:=2)>
Class AttrTest
End Class
Module M
Sub Main()
PrintAttributeData(New AttrTest().GetType().GetCustomAttributesData())
PrintAttributeData(New XXX().GetType().GetCustomAttributesData())
End Sub
Sub PrintAttributeData(a As IList(Of CustomAttributeData))
For Each ad In a
Console.WriteLine(ad.Constructor.ToString() & "(.." & ad.ConstructorArguments.Count.ToString() & "..)")
For Each na In ad.NamedArguments
Console.WriteLine(na.MemberInfo.ToString() & ":=" & na.TypedValue.ToString())
Next
Next
End Sub
End Module
</file>
</compilation>
CompileWithCustomILSource(vbSource, AttributesWithReadWriteProperties.Value,
options:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
expectedOutput:=<![CDATA[
Void .ctor()(..0..)
Int32 P_rw_r_w:=(Int32)1
Int32 P_rw_rw_w:=(Int32)2
Void .ctor()(..0..)
Int32 P_rw_r_w:=(Int32)1
Int32 P_rw_rw_w:=(Int32)2
Int32 P_rw_rw_r:=(Int32)3
]]>.Value.Replace(vbLf, Environment.NewLine))
End Sub
<Fact()>
Public Sub TestByRefMethodWithParamArrayProperty2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M
Sub Main()
M(X(New String(1) {}))
End Sub
Sub M(ByRef p As Integer())
p = New Integer(100) {}
End Sub
Dim s As String()
Property X(ParamArray a As String()) As Integer()
Get
s = a
Return New Integer() {}
End Get
Set(ByVal value As Integer())
Console.WriteLine(s Is a)
End Set
End Property
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[True]]>).
VerifyIL("M.Main",
<![CDATA[
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (Integer() V_0)
IL_0000: ldc.i4.2
IL_0001: newarr "String"
IL_0006: dup
IL_0007: call "Function M.get_X(ParamArray String()) As Integer()"
IL_000c: stloc.0
IL_000d: ldloca.s V_0
IL_000f: call "Sub M.M(ByRef Integer())"
IL_0014: ldloc.0
IL_0015: call "Sub M.set_X(ParamArray String(), Integer())"
IL_001a: ret
}
]]>)
End Sub
<Fact()>
Public Sub TestByRefMethodWithByRefParamArrayProperty()
Dim ilSource = <![CDATA[
.class public auto ansi sealed TestModule
extends [mscorlib]System.Object
{
.field private static string[] s
.method public specialname static int32[]
get_X(string[]& a) cil managed
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 )
// Code size 18 (0x12)
.maxstack 1
.locals init ([0] int32[] X)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stsfld string[] TestModule::s
IL_0007: ldc.i4.0
IL_0008: newarr [mscorlib]System.Int32
IL_000d: stloc.0
IL_000e: br.s IL_0010
IL_0010: ldloc.0
IL_0011: ret
} // end of method RedimTest::get_X
.method public specialname static void
set_X(string[]& a,
int32[] 'value') cil managed
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 )
// Code size 17 (0x11)
.maxstack 8
IL_0000: nop
IL_0001: ldsfld string[] TestModule::s
IL_0006: ldarg.0
IL_0007: ceq
IL_0009: call void [mscorlib]System.Console::WriteLine(bool)
IL_000e: nop
IL_000f: nop
IL_0010: ret
} // end of method RedimTest::set_X
.property int32[] X(string[]&)
{
.set void TestModule::set_X(string[]&,
int32[])
.get int32[] TestModule::get_X(string[]&)
} // end of property RedimTest::X
} // end of class ClassLibrary1.RedimTest
]]>
Dim vbSource =
<compilation>
<file name="a.vb">
Imports System
Module M
Sub Main()
M(TestModule.X)
End Sub
Sub M(ByRef p As Integer())
p = New Integer(100) {}
End Sub
End Module
</file>
</compilation>
CompileWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDll).
VerifyIL("M.Main",
<![CDATA[
{
// Code size 38 (0x26)
.maxstack 2
.locals init (Integer() V_0,
String() V_1)
IL_0000: ldc.i4.0
IL_0001: newarr "String"
IL_0006: stloc.1
IL_0007: ldloca.s V_1
IL_0009: call "Function TestModule.get_X(ByRef ParamArray String()) As Integer()"
IL_000e: stloc.0
IL_000f: ldloca.s V_0
IL_0011: call "Sub M.M(ByRef Integer())"
IL_0016: ldc.i4.0
IL_0017: newarr "String"
IL_001c: stloc.1
IL_001d: ldloca.s V_1
IL_001f: ldloc.0
IL_0020: call "Sub TestModule.set_X(ByRef ParamArray String(), Integer())"
IL_0025: ret
}
]]>)
End Sub
<WorkItem(546853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546853")>
<Fact()>
Public Sub CallingVirtualFinalMethod()
Dim ilSource = <![CDATA[
.class public auto ansi beforefieldinit B
extends [mscorlib]System.Object
{
.method public hidebysig newslot specialname virtual instance bool get_M1() cil managed
{
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}
.method public hidebysig newslot specialname virtual final instance bool get_M2() cil managed
{
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
.property instance bool M1()
{
.get instance bool B::get_M1()
}
.property instance bool M2()
{
.get instance bool B::get_M2()
}
}
]]>
Dim vbSource =
<compilation>
<file name="a.vb">
Imports System
Module C
Sub S()
Dim b As Boolean = (New B()).M1 AndAlso (New B()).M2
End Sub
End Module
</file>
</compilation>
CompileWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDll).
VerifyIL("C.S",
<![CDATA[
{
// Code size 27 (0x1b)
.maxstack 1
IL_0000: newobj "Sub B..ctor()"
IL_0005: callvirt "Function B.get_M1() As Boolean"
IL_000a: brfalse.s IL_0018
IL_000c: newobj "Sub B..ctor()"
IL_0011: call "Function B.get_M2() As Boolean"
IL_0016: br.s IL_0019
IL_0018: ldc.i4.0
IL_0019: pop
IL_001a: ret
}
]]>)
End Sub
<Fact()>
Public Sub TestToStringOnStruct()
Dim ilSource = <![CDATA[
.class sequential ansi sealed public Struct1
extends [mscorlib]System.ValueType
{
.method public hidebysig virtual instance string
ToString() cil managed
{
// Code size 11 (0xb)
.maxstack 1
.locals init (string V_0)
IL_0000: nop
IL_0001: ldstr "Struct1 "
IL_0006: stloc.0
IL_0007: br.s IL_0009
IL_0009: ldloc.0
IL_000a: ret
}
}
.class sequential ansi sealed public Struct2
extends [mscorlib]System.ValueType
{
.method public strict virtual instance string
ToString() cil managed
{
// Code size 11 (0xb)
.maxstack 1
.locals init (string V_0)
IL_0000: nop
IL_0001: ldstr "Struct2 "
IL_0006: stloc.0
IL_0007: br.s IL_0009
IL_0009: ldloc.0
IL_000a: ret
}
}
]]>
Dim vbSource =
<compilation>
<file name="a.vb">
Imports System
Module M
Sub Main()
Dim s1 As New Struct1()
Console.Write(s1.ToString())
Dim s2 As New Struct2()
Console.Write(s2.ToString())
End Sub
End Module
</file>
</compilation>
CompileWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDll).
VerifyIL("M.Main",
<![CDATA[
{
// Code size 53 (0x35)
.maxstack 1
.locals init (Struct1 V_0, //s1
Struct2 V_1) //s2
IL_0000: ldloca.s V_0
IL_0002: initobj "Struct1"
IL_0008: ldloca.s V_0
IL_000a: constrained. "Struct1"
IL_0010: callvirt "Function Object.ToString() As String"
IL_0015: call "Sub System.Console.Write(String)"
IL_001a: ldloca.s V_1
IL_001c: initobj "Struct2"
IL_0022: ldloca.s V_1
IL_0024: constrained. "Struct2"
IL_002a: callvirt "Function Object.ToString() As String"
IL_002f: call "Sub System.Console.Write(String)"
IL_0034: ret
}
]]>)
End Sub
<Fact()>
Public Sub TestRedimWithObjectAndProperty()
CompileAndVerify(
<compilation>
<file name="a.vb">
Class RedimTest
Public Shared Sub Main()
ReDim Func.Prop()(2)
DirectCast(Func.Prop, Object())(1) = "stored value"
ReDim Preserve Func.Prop()(5)
System.Console.WriteLine(DirectCast(Func.Prop, Object())(1))
End Sub
Public Shared Function Func() As RedimTest
Return instance
End Function
Private Shared instance As RedimTest = New RedimTest()
Public _Prop As Object
Public Property Prop As Object
Get
System.Console.WriteLine("Reading")
Return _Prop
End Get
Set(value As Object)
System.Console.WriteLine("Writing")
_Prop = value
End Set
End Property
End Class
</file>
</compilation>,
expectedOutput:=<![CDATA[
Writing
Reading
Reading
Writing
Reading
stored value
]]>).
VerifyIL("RedimTest.Main",
<![CDATA[
{
// Code size 100 (0x64)
.maxstack 3
.locals init (RedimTest V_0)
IL_0000: call "Function RedimTest.Func() As RedimTest"
IL_0005: ldc.i4.3
IL_0006: newarr "Object"
IL_000b: callvirt "Sub RedimTest.set_Prop(Object)"
IL_0010: call "Function RedimTest.Func() As RedimTest"
IL_0015: callvirt "Function RedimTest.get_Prop() As Object"
IL_001a: castclass "Object()"
IL_001f: ldc.i4.1
IL_0020: ldstr "stored value"
IL_0025: stelem.ref
IL_0026: call "Function RedimTest.Func() As RedimTest"
IL_002b: dup
IL_002c: stloc.0
IL_002d: ldloc.0
IL_002e: callvirt "Function RedimTest.get_Prop() As Object"
IL_0033: castclass "System.Array"
IL_0038: ldc.i4.6
IL_0039: newarr "Object"
IL_003e: call "Function Microsoft.VisualBasic.CompilerServices.Utils.CopyArray(System.Array, System.Array) As System.Array"
IL_0043: callvirt "Sub RedimTest.set_Prop(Object)"
IL_0048: call "Function RedimTest.Func() As RedimTest"
IL_004d: callvirt "Function RedimTest.get_Prop() As Object"
IL_0052: castclass "Object()"
IL_0057: ldc.i4.1
IL_0058: ldelem.ref
IL_0059: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_005e: call "Sub System.Console.WriteLine(Object)"
IL_0063: ret
}
]]>)
End Sub
<WorkItem(529442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529442")>
<Fact>
Public Sub ExplicitStandardModuleAttribute()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
<Global.Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute()>
Public Module Module1
Public Sub Main()
Console.WriteLine(
Attribute.GetCustomAttributes(
GetType(Module1),
GetType(Global.Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute)
).Length
)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="2")
End Sub
<Fact()>
Public Sub EmitObjectGetTypeCallOnStruct()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Public Structure S1
End Structure
Class MainClass
Public Shared Sub Main()
System.Console.WriteLine((New S1()).GetType())
End Sub
End Class
</file>
</compilation>,
expectedOutput:=<![CDATA[
S1
]]>).
VerifyIL("MainClass.Main",
<![CDATA[
{
// Code size 25 (0x19)
.maxstack 1
.locals init (S1 V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj "S1"
IL_0008: ldloc.0
IL_0009: box "S1"
IL_000e: call "Function Object.GetType() As System.Type"
IL_0013: call "Sub System.Console.WriteLine(Object)"
IL_0018: ret
}
]]>)
End Sub
<Fact()>
Public Sub EmitCallToOverriddenToStringOnStruct()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Public Structure S1
Public Overrides Function ToString() As String
Return "123"
End Function
End Structure
Class MainClass
Public Shared Sub Main()
Dim s As S1 = New S1()
System.Console.WriteLine(s.ToString())
End Sub
End Class
</file>
</compilation>,
expectedOutput:=<![CDATA[
123
]]>).
VerifyIL("MainClass.Main",
<![CDATA[
{
// Code size 27 (0x1b)
.maxstack 1
.locals init (S1 V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj "S1"
IL_0008: ldloca.s V_0
IL_000a: constrained. "S1"
IL_0010: callvirt "Function Object.ToString() As String"
IL_0015: call "Sub System.Console.WriteLine(String)"
IL_001a: ret
}
]]>)
End Sub
<Fact()>
Public Sub EmitInterfaceMethodOnStruct()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Interface I
Sub M()
End Interface
Public Structure S1
Implements I
Public Sub M() Implements I.M
System.Console.WriteLine("S1:M")
End Sub
End Structure
Class MainClass
Public Shared Sub Main()
Dim s As S1 = New S1()
s.M()
DirectCast(s, I).M()
End Sub
End Class
</file>
</compilation>,
expectedOutput:=<![CDATA[
S1:M
S1:M
]]>).
VerifyIL("MainClass.Main",
<![CDATA[
{
// Code size 32 (0x20)
.maxstack 1
.locals init (S1 V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj "S1"
IL_0008: ldloca.s V_0
IL_000a: call "Sub S1.M()"
IL_000f: ldloc.0
IL_0010: box "S1"
IL_0015: castclass "I"
IL_001a: callvirt "Sub I.M()"
IL_001f: ret
}
]]>)
End Sub
<WorkItem(531085, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531085")>
<Fact()>
Public Sub EmitMyBaseCall()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class Base1
Protected memberee As Integer = 0
Protected Property xyz As Integer
Default Protected Property this(num As Integer) As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
End Class
Class Derived : Inherits Base1
Public Sub inc()
MyBase.memberee += 1
MyBase.xyz += 1
MyBase.this(0) += 1
End Sub
End Class
Module Program
Sub Main(args As String())
End Sub
End Module
</file>
</compilation>,
expectedOutput:="").
VerifyIL("Derived.inc",
<![CDATA[
{
// Code size 44 (0x2c)
.maxstack 4
.locals init (Integer& V_0)
IL_0000: ldarg.0
IL_0001: ldflda "Base1.memberee As Integer"
IL_0006: dup
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldind.i4
IL_000a: ldc.i4.1
IL_000b: add.ovf
IL_000c: stind.i4
IL_000d: ldarg.0
IL_000e: ldarg.0
IL_000f: call "Function Base1.get_xyz() As Integer"
IL_0014: ldc.i4.1
IL_0015: add.ovf
IL_0016: call "Sub Base1.set_xyz(Integer)"
IL_001b: ldarg.0
IL_001c: ldc.i4.0
IL_001d: ldarg.0
IL_001e: ldc.i4.0
IL_001f: call "Function Base1.get_this(Integer) As Integer"
IL_0024: ldc.i4.1
IL_0025: add.ovf
IL_0026: call "Sub Base1.set_this(Integer, Integer)"
IL_002b: ret
}
]]>)
End Sub
<Fact()>
Public Sub EmitObjectToStringOnSimpleType()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class MainClass
Public Shared Sub Main()
Dim x as Integer = 123
Console.WriteLine(x.ToString())
End Sub
End Class
</file>
</compilation>,
expectedOutput:=<![CDATA[123]]>).
VerifyIL("MainClass.Main",
<![CDATA[
{
// Code size 16 (0x10)
.maxstack 1
.locals init (Integer V_0) //x
IL_0000: ldc.i4.s 123
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: call "Function Integer.ToString() As String"
IL_000a: call "Sub System.Console.WriteLine(String)"
IL_000f: ret
}
]]>)
End Sub
<Fact()>
Public Sub EmitObjectMethodOnSpecialByRefType()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class MainClass
Public Shared Sub Main()
End Sub
Sub M(tr As System.TypedReference)
Dim i As Integer = tr.GetHashCode()
End Sub
End Class
</file>
</compilation>).
VerifyIL("MainClass.M",
<![CDATA[
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: ldarga.s V_1
IL_0002: call "Function System.TypedReference.GetHashCode() As Integer"
IL_0007: pop
IL_0008: ret
}
]]>)
End Sub
<Fact()>
Public Sub EmitNonVirtualInstanceEnumMethodCallOnEnum()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Public Enum Shade
White
Gray
Black
End Enum
Class MainClass
Public Shared Sub Main()
Dim v As Shade = Shade.Gray
System.Console.WriteLine(v.GetType())
System.Console.WriteLine(v.HasFlag(Shade.Black))
System.Console.WriteLine(v.ToString("G"))
End Sub
End Class
</file>
</compilation>,
expectedOutput:=<![CDATA[
Shade
False
Gray
]]>).
VerifyIL("MainClass.Main",
<![CDATA[
{
// Code size 62 (0x3e)
.maxstack 2
.locals init (Shade V_0) //v
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: box "Shade"
IL_0008: call "Function Object.GetType() As System.Type"
IL_000d: call "Sub System.Console.WriteLine(Object)"
IL_0012: ldloc.0
IL_0013: box "Shade"
IL_0018: ldc.i4.2
IL_0019: box "Shade"
IL_001e: call "Function System.Enum.HasFlag(System.Enum) As Boolean"
IL_0023: call "Sub System.Console.WriteLine(Boolean)"
IL_0028: ldloc.0
IL_0029: box "Shade"
IL_002e: ldstr "G"
IL_0033: call "Function System.Enum.ToString(String) As String"
IL_0038: call "Sub System.Console.WriteLine(String)"
IL_003d: ret
}
]]>)
End Sub
<Fact()>
Public Sub TestTernaryConditionalOperatorInterfaceRegression()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Public Interface IA
End Interface
Public Interface IB
Function f() As Integer
End Interface
Public Class AB1
Implements IA, IB
Public Function f() As Integer Implements IB.f
Return 42
End Function
End Class
Public Class AB2
Implements IA, IB
Public Function f() As Integer Implements IB.f
Return 1
End Function
End Class
Class MainClass
Public Shared Function g(p As Boolean) As Integer
Return (If(p, DirectCast(New AB1(), IB), DirectCast(New AB2(), IB))).f()
End Function
Public Shared Sub Main()
System.Console.WriteLine(g(True))
System.Console.WriteLine(g(False))
End Sub
End Class
</file>
</compilation>,
expectedOutput:=<![CDATA[
42
1
]]>).
VerifyIL("MainClass.g",
<![CDATA[
{
// Code size 23 (0x17)
.maxstack 1
.locals init (IB V_0)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000a
IL_0003: newobj "Sub AB2..ctor()"
IL_0008: br.s IL_0011
IL_000a: newobj "Sub AB1..ctor()"
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: callvirt "Function IB.f() As Integer"
IL_0016: ret
}
]]>)
End Sub
<WorkItem(546809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546809")>
<Fact()>
Public Sub TestBinaryConditionalOperator_16872a()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Interface I
End Interface
Class C1
Implements I
End Class
Class C2
Implements I
End Class
Module Program
Sub Main(args As String())
Console.WriteLine(F().ToString())
End Sub
Public Function F() As I
Dim i As I = F1()
Return If(i, F2())
End Function
Public Function F1() As C1
Return New C1()
End Function
Public Function F2() As C2
Return New C2()
End Function
End Module
</file>
</compilation>,
expectedOutput:="C1").
VerifyIL("Program.F",
<![CDATA[
{
// Code size 17 (0x11)
.maxstack 2
.locals init (I V_0)
IL_0000: call "Function Program.F1() As C1"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: dup
IL_0008: brtrue.s IL_0010
IL_000a: pop
IL_000b: call "Function Program.F2() As C2"
IL_0010: ret
}
]]>)
End Sub
<WorkItem(634407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634407")>
<Fact()>
Public Sub TestTernary_Null()
CompileAndVerify(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Security
<Assembly: SecurityTransparent()>
Class Program
Private Shared Function C() As Boolean
Return True
End Function
Public Shared Sub Main()
Dim f1 As Exception() = Nothing
Dim oo = If(C(), f1, TryCast(Nothing, IEnumerable(Of Object)))
Console.WriteLine(oo)
Dim oo1 = If(C(), DirectCast(DirectCast(Nothing, IEnumerable(Of Object)), IEnumerable(Of Object)), f1)
Console.WriteLine(oo1)
End Sub
End Class
]]>
</file>
</compilation>, expectedOutput:="").
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 35 (0x23)
.maxstack 1
.locals init (System.Exception() V_0) //f1
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: call "Function Program.C() As Boolean"
IL_0007: brtrue.s IL_000c
IL_0009: ldnull
IL_000a: br.s IL_000d
IL_000c: ldloc.0
IL_000d: call "Sub System.Console.WriteLine(Object)"
IL_0012: call "Function Program.C() As Boolean"
IL_0017: brtrue.s IL_001c
IL_0019: ldloc.0
IL_001a: br.s IL_001d
IL_001c: ldnull
IL_001d: call "Sub System.Console.WriteLine(Object)"
IL_0022: ret
}
]]>)
End Sub
<WorkItem(546809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546809")>
<Fact()>
Public Sub TestBinaryConditionalOperator_16872b()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Interface I
End Interface
Class C1
Implements I
End Class
Class C2
Implements I
End Class
Module Program
Sub Main(args As String())
Console.WriteLine(F().ToString())
End Sub
Public Function F() As I
Dim i As I = F1()
Return If(i Is Nothing, F2(), i)
End Function
Public Function F1() As C1
Return New C1()
End Function
Public Function F2() As C2
Return New C2()
End Function
End Module
</file>
</compilation>,
expectedOutput:="C1").
VerifyIL("Program.F",
<![CDATA[
{
// Code size 17 (0x11)
.maxstack 1
.locals init (I V_0) //i
IL_0000: call "Function Program.F1() As C1"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: brfalse.s IL_000b
IL_0009: ldloc.0
IL_000a: ret
IL_000b: call "Function Program.F2() As C2"
IL_0010: ret
}
]]>)
End Sub
<Fact()>
Public Sub TestBinaryConditionalOperatorInterfaceRegression()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Public Interface IA
End Interface
Public Interface IB
Function f() As Integer
End Interface
Public Class AB1
Implements IA, IB
Public Function f() As Integer Implements IB.f
Return 42
End Function
End Class
Public Class AB2
Implements IA, IB
Public Function f() As Integer Implements IB.f
Return 1
End Function
End Class
Class MainClass
Public Shared Function g() As Integer
Return (If(DirectCast(New AB1(), IB), DirectCast(New AB2(), IB))).f()
End Function
Public Shared Sub Main()
System.Console.WriteLine(g())
End Sub
End Class
</file>
</compilation>,
expectedOutput:=<![CDATA[
42
]]>).
VerifyIL("MainClass.g",
<![CDATA[
{
// Code size 22 (0x16)
.maxstack 2
.locals init (IB V_0)
IL_0000: newobj "Sub AB1..ctor()"
IL_0005: dup
IL_0006: brtrue.s IL_0010
IL_0008: pop
IL_0009: newobj "Sub AB2..ctor()"
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: callvirt "Function IB.f() As Integer"
IL_0015: ret
}
]]>)
End Sub
<Fact()>
Public Sub TestTernaryConditionalExpression()
CompileAndVerify(
<compilation>
<file name="a.vb">Imports System
Imports System.Globalization
Class EmitTest
Shared Function GetCultureInvariantString(val As Object) As String
If val Is Nothing Then
Return Nothing
End If
Dim vType = val.GetType()
Dim valStr = val.ToString()
If vType Is GetType(DateTime) Then
valStr = DirectCast(val, DateTime).ToString("M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture)
ElseIf vType Is GetType(Single) Then
valStr = DirectCast(val, Single).ToString(CultureInfo.InvariantCulture)
ElseIf vType Is GetType(Double) Then
valStr = DirectCast(val, Double).ToString(CultureInfo.InvariantCulture)
ElseIf vType Is GetType(Decimal) Then
valStr = DirectCast(val, Decimal).ToString(CultureInfo.InvariantCulture)
End If
Return valStr
End Function
Public Shared Sub Main()
WriteResult("Test01", Test01(New EmitTest))
WriteResult("Test02", Test02(New EmitTest))
WriteResult("Test03", Test03(False))
WriteResult("Test04", Test04)
WriteResult("Test05", Test05)
WriteResult("Test06", Test06)
WriteResult("Test07", Test07("s"))
End Sub
Public Shared Sub WriteResult(name As String, result As Object)
Dim val = GetCultureInvariantString(result)
Console.WriteLine("{0}: {1}", name.PadLeft(10),
If(result Is Nothing, "<Nothing>", String.Format("{0}||{1}", val, result.GetType.FullName)))
End Sub
Public Property ObjProp As Object
Public Property StrProp As String
Public Shared Function Test01(a As EmitTest) As Object
Return If(0, a.ObjProp, a.StrProp)
End Function
Public Shared Function Test02(a As EmitTest) As Object
Return If(True, #1/1/1#, a.StrProp)
End Function
Public Shared Function Test03(b As Boolean) As Object
Dim ch As Char() = Nothing
Return If(b, ch, "if-false")
End Function
Public Shared Function Test04() As Object
Return If(True, Nothing, #1/1/2000#)
End Function
Public Shared Function Test05() As Object
Return If(False, 1, Nothing)
End Function
Public Shared Function Test06() As Object
Return If(1.55, 1 / 0, 1)
End Function
Public Shared Function Test07(s As String) As Object
Return If(true, s + "tr", Nothing)
End Function
Interface I1
End Interface
Class CLS
Implements I1
End Class
End Class
</file>
</compilation>,
expectedOutput:=<![CDATA[
Test01: <Nothing>
Test02: 1/1/0001 12:00:00 AM||System.DateTime
Test03: if-false||System.String
Test04: 1/1/0001 12:00:00 AM||System.DateTime
Test05: 0||System.Int32
Test06: Infinity||System.Double
Test07: str||System.String
]]>).
VerifyIL("EmitTest.Test07",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldstr "tr"
IL_0006: call "Function String.Concat(String, String) As String"
IL_000b: ret
}
]]>).
VerifyIL("EmitTest.Test06",
<![CDATA[
{
// Code size 15 (0xf)
.maxstack 1
IL_0000: ldc.r8 Infinity
IL_0009: box "Double"
IL_000e: ret
}
]]>).
VerifyIL("EmitTest.Test05",
<![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: box "Integer"
IL_0006: ret
}
]]>).
VerifyIL("EmitTest.Test04",
<![CDATA[
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldsfld "Date.MinValue As Date"
IL_0005: box "Date"
IL_000a: ret
}
]]>).
VerifyIL("EmitTest.Test03",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 1
.locals init (Char() V_0) //ch
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldarg.0
IL_0003: brtrue.s IL_000b
IL_0005: ldstr "if-false"
IL_000a: ret
IL_000b: ldloc.0
IL_000c: newobj "Sub String..ctor(Char())"
IL_0011: ret
}
]]>).
VerifyIL("EmitTest.Test02",
<![CDATA[
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldsfld "Date.MinValue As Date"
IL_0005: box "Date"
IL_000a: ret
}
]]>).
VerifyIL("EmitTest.Test01",
<![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: callvirt "Function EmitTest.get_StrProp() As String"
IL_0006: ret
}
]]>)
End Sub
<Fact()>
Public Sub TestBinaryConditionalExpression()
CompileAndVerify(
<compilation>
<file name="a.vb">
Class EmitTest
Public Shared Sub Main()
WriteResult("Test01", Test01)
WriteResult("Test02", Test02)
WriteResult("Test03", Test03)
WriteResult("Test04", Test04("z"))
WriteResult("Test05", Test05)
WriteResult("Test06", Test06("xyz"))
WriteResult("Test07", Test07(New EmitTest))
WriteResult("Test08", Test08(New EmitTest))
WriteResult("Test09", Test09(New EmitTest))
WriteResult("Test10", Test10)
WriteResult("Test11", Test11)
WriteResult("Test12", Test12(New EmitTest, "a"))
WriteResult("Test13", Test13(New EmitTest, "a"))
WriteResult("Test14", Test14(Nothing))
WriteResult("Test15", Test15)
WriteResult("Test16", Test16)
End Sub
Shared cul = System.Globalization.CultureInfo.InvariantCulture
Public Shared Sub WriteResult(name As String, result As Object)
If result IsNot Nothing AndAlso result.GetType() Is GetType(System.DateTime) Then
System.Console.WriteLine("{0}: {1}", name.PadLeft(10), String.Format("{0}||{1}",
CType(result, System.DateTime).ToString("M/d/yyyy h:mm:ss tt", cul), result.GetType.FullName))
Else
System.Console.WriteLine("{0}: {1}", name.PadLeft(10),
If(result Is Nothing, "<Nothing>", String.Format("{0}||{1}", result, result.GetType.FullName)))
End If
End Sub
Public Property ObjProp As Object
Public Property StrProp As String
Public Shared Function Test01() As Date
Return If(Nothing, #12:00:00 AM#)
End Function
Public Shared Function Test02() As String
Return If("abc", #12:00:00 AM#)
End Function
Public Shared Function Test03() As String
Return If("cde", Nothing)
End Function
Public Shared Function Test04(a As String) As String
Return If(Nothing, "a" + a)
End Function
Public Shared Function Test05() As Object
Return If(Nothing, CType(CType(Nothing, String), Object))
End Function
Public Shared Function Test06(a As String) As String
Return If(a, "No Value")
End Function
Public Shared Function Test07(a As EmitTest) As Object
Return If(a.ObjProp, New Object)
End Function
Public Shared Function Test08(a As EmitTest) As Object
Return If(a.StrProp, #12:00:00 AM#)
End Function
Public Shared Function Test09(a As EmitTest) As String
Return If(a.StrProp + "abc", "xyz")
End Function
Public Shared Function Test10() As Object
Dim a As String = "abc"
Return If(a, "No Value")
End Function
Public Shared Function Test11() As I1
Dim i As I1 = Nothing
Dim c As CLS = new CLS
Return If(c, i)
End Function
Public Property CharArrProp As Char()
Public Shared Function Test12(a As EmitTest, s As String) As String
Return If(a.CharArrProp, s + "b")
End Function
Public Shared Function Test13(a As EmitTest, s As String) As String
Return If(s + "b", a.CharArrProp)
End Function
Public Shared Function Test14(a As Char()) As String
Return If(a, "b")
End Function
Public Shared Function Test15() As String
Dim a As Char() = Nothing
Return If(a, "b")
End Function
Public Shared Function Test16() As Object
Return If(CType(Nothing, String), "else-branch")
End Function
Interface I1
End Interface
Class CLS
Implements I1
End Class
End Class
</file>
</compilation>,
expectedOutput:=<![CDATA[
Test01: 1/1/0001 12:00:00 AM||System.DateTime
Test02: abc||System.String
Test03: cde||System.String
Test04: az||System.String
Test05: <Nothing>
Test06: xyz||System.String
Test07: System.Object||System.Object
Test08: 1/1/0001 12:00:00 AM||System.DateTime
Test09: abc||System.String
Test10: abc||System.String
Test11: EmitTest+CLS||EmitTest+CLS
Test12: ab||System.String
Test13: ab||System.String
Test14: b||System.String
Test15: b||System.String
Test16: else-branch||System.String
]]>).
VerifyIL("EmitTest.Test16",
<![CDATA[
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldstr "else-branch"
IL_0005: ret
}
]]>).
VerifyIL("EmitTest.Test15",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 1
.locals init (Char() V_0) //a
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: brtrue.s IL_000b
IL_0005: ldstr "b"
IL_000a: ret
IL_000b: ldloc.0
IL_000c: newobj "Sub String..ctor(Char())"
IL_0011: ret
}
]]>).
VerifyIL("EmitTest.Test14",
<![CDATA[
{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0009
IL_0003: ldstr "b"
IL_0008: ret
IL_0009: ldarg.0
IL_000a: newobj "Sub String..ctor(Char())"
IL_000f: ret
}
]]>).
VerifyIL("EmitTest.Test13",
<![CDATA[
{
// Code size 27 (0x1b)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldstr "b"
IL_0006: call "Function String.Concat(String, String) As String"
IL_000b: dup
IL_000c: brtrue.s IL_001a
IL_000e: pop
IL_000f: ldarg.0
IL_0010: callvirt "Function EmitTest.get_CharArrProp() As Char()"
IL_0015: newobj "Sub String..ctor(Char())"
IL_001a: ret
}
]]>).
VerifyIL("EmitTest.Test12",
<![CDATA[
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (Char() V_0)
IL_0000: ldarg.0
IL_0001: callvirt "Function EmitTest.get_CharArrProp() As Char()"
IL_0006: dup
IL_0007: stloc.0
IL_0008: brtrue.s IL_0016
IL_000a: ldarg.1
IL_000b: ldstr "b"
IL_0010: call "Function String.Concat(String, String) As String"
IL_0015: ret
IL_0016: ldloc.0
IL_0017: newobj "Sub String..ctor(Char())"
IL_001c: ret
}
]]>).
VerifyIL("EmitTest.Test11",
<![CDATA[
{
// Code size 13 (0xd)
.maxstack 2
.locals init (EmitTest.I1 V_0) //i
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: newobj "Sub EmitTest.CLS..ctor()"
IL_0007: dup
IL_0008: brtrue.s IL_000c
IL_000a: pop
IL_000b: ldloc.0
IL_000c: ret
}
]]>).
VerifyIL("EmitTest.Test10",
<![CDATA[
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldstr "abc"
IL_0005: dup
IL_0006: brtrue.s IL_000e
IL_0008: pop
IL_0009: ldstr "No Value"
IL_000e: ret
}
]]>).
VerifyIL("EmitTest.Test09",
<![CDATA[
{
// Code size 26 (0x1a)
.maxstack 2
IL_0000: ldarg.0
IL_0001: callvirt "Function EmitTest.get_StrProp() As String"
IL_0006: ldstr "abc"
IL_000b: call "Function String.Concat(String, String) As String"
IL_0010: dup
IL_0011: brtrue.s IL_0019
IL_0013: pop
IL_0014: ldstr "xyz"
IL_0019: ret
}
]]>).
VerifyIL("EmitTest.Test08",
<![CDATA[
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: callvirt "Function EmitTest.get_StrProp() As String"
IL_0006: dup
IL_0007: brtrue.s IL_0014
IL_0009: pop
IL_000a: ldsfld "Date.MinValue As Date"
IL_000f: box "Date"
IL_0014: ret
}
]]>).
VerifyIL("EmitTest.Test07",
<![CDATA[
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: callvirt "Function EmitTest.get_ObjProp() As Object"
IL_0006: dup
IL_0007: brtrue.s IL_000f
IL_0009: pop
IL_000a: newobj "Sub Object..ctor()"
IL_000f: ret
}
]]>).
VerifyIL("EmitTest.Test06",
<![CDATA[
{
// Code size 11 (0xb)
.maxstack 2
IL_0000: ldarg.0
IL_0001: dup
IL_0002: brtrue.s IL_000a
IL_0004: pop
IL_0005: ldstr "No Value"
IL_000a: ret
}
]]>).
VerifyIL("EmitTest.Test05",
<![CDATA[
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldnull
IL_0001: ret
}
]]>).
VerifyIL("EmitTest.Test04",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 2
IL_0000: ldstr "a"
IL_0005: ldarg.0
IL_0006: call "Function String.Concat(String, String) As String"
IL_000b: ret
}
]]>).
VerifyIL("EmitTest.Test03",
<![CDATA[
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldstr "cde"
IL_0005: ret
}
]]>).
VerifyIL("EmitTest.Test02",
<![CDATA[
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldstr "abc"
IL_0005: ret
}
]]>).
VerifyIL("EmitTest.Test01",
<![CDATA[
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldsfld "Date.MinValue As Date"
IL_0005: ret
}
]]>)
End Sub
<Fact()>
Public Sub TestBinaryConditionalExpression2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Runtime.CompilerServices
Class EmitTest
Public Shared Sub Main()
WriteResult("Test01", Test01)
WriteResult("Test02", Test02)
WriteResult("Test03", Test03("+"))
WriteResult("Test04", Test04("+"))
End Sub
Public Shared Sub WriteResult(name As String, result As Object)
System.Console.WriteLine("{0}: {1}", name.PadLeft(10),
If(result Is Nothing, "<Nothing>", String.Format("{0}||{1}", result, result.GetType.FullName)))
End Sub
Public Shared Function Test01() As SS
Return If("+", New SS("-"))
End Function
Public Shared Function Test02() As SS
Dim s As String = "+"
Return If(s, New SS("-"))
End Function
Public Shared Function Test03(s As String) As SS
Return If(s, New SS("-"))
End Function
Public Shared Function Test04(s As String) As SS
Return If(s & "+", New SS("-"))
End Function
End Class
Structure SS
Public V As String
Public Sub New(s As String)
Me.V = s
End Sub
Public Overrides Function ToString() As String
Return V
End Function
Public Shared Widening Operator CType(s As String) As SS
Return New SS(s)
End Operator
End Structure
</file>
</compilation>,
expectedOutput:=<![CDATA[
Test01: +||SS
Test02: +||SS
Test03: +||SS
Test04: ++||SS
]]>).
VerifyIL("EmitTest.Test01",
<![CDATA[
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr "+"
IL_0005: call "Function SS.op_Implicit(String) As SS"
IL_000a: ret
}
]]>).
VerifyIL("EmitTest.Test02",
<![CDATA[
{
// Code size 27 (0x1b)
.maxstack 1
.locals init (String V_0) //s
IL_0000: ldstr "+"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: brtrue.s IL_0014
IL_0009: ldstr "-"
IL_000e: newobj "Sub SS..ctor(String)"
IL_0013: ret
IL_0014: ldloc.0
IL_0015: call "Function SS.op_Implicit(String) As SS"
IL_001a: ret
}
]]>).
VerifyIL("EmitTest.Test03",
<![CDATA[
{
// Code size 21 (0x15)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000e
IL_0003: ldstr "-"
IL_0008: newobj "Sub SS..ctor(String)"
IL_000d: ret
IL_000e: ldarg.0
IL_000f: call "Function SS.op_Implicit(String) As SS"
IL_0014: ret
}
]]>).
VerifyIL("EmitTest.Test04",
<![CDATA[
{
// Code size 33 (0x21)
.maxstack 2
.locals init (String V_0)
IL_0000: ldarg.0
IL_0001: ldstr "+"
IL_0006: call "Function String.Concat(String, String) As String"
IL_000b: dup
IL_000c: stloc.0
IL_000d: brtrue.s IL_001a
IL_000f: ldstr "-"
IL_0014: newobj "Sub SS..ctor(String)"
IL_0019: ret
IL_001a: ldloc.0
IL_001b: call "Function SS.op_Implicit(String) As SS"
IL_0020: ret
}
]]>)
End Sub
<Fact()>
Public Sub TestConditionalRequiringBox()
CompileAndVerify(
<compilation>
<file name="a.vb">
Public Module Program
Public Sub Main()
Dim a As Integer = 1
Dim i As IGoo(Of String) = Nothing
Dim e As New GooVal()
i = If(a > 1, i, e)
System.Console.Write(i.Goo())
End Sub
Interface IGoo(Of T) : Function Goo() As T : End Interface
Structure GooVal : Implements IGoo(Of String)
Public Function Goo() As String Implements IGoo(Of String).Goo
Return "Val "
End Function
End Structure
End Module</file>
</compilation>,
expectedOutput:="Val ").
VerifyIL("Program.Main",
<![CDATA[{
// Code size 41 (0x29)
.maxstack 2
.locals init (Program.IGoo(Of String) V_0, //i
Program.GooVal V_1) //e
IL_0000: ldc.i4.1
IL_0001: ldnull
IL_0002: stloc.0
IL_0003: ldloca.s V_1
IL_0005: initobj "Program.GooVal"
IL_000b: ldc.i4.1
IL_000c: bgt.s IL_001b
IL_000e: ldloc.1
IL_000f: box "Program.GooVal"
IL_0014: castclass "Program.IGoo(Of String)"
IL_0019: br.s IL_001c
IL_001b: ldloc.0
IL_001c: stloc.0
IL_001d: ldloc.0
IL_001e: callvirt "Function Program.IGoo(Of String).Goo() As String"
IL_0023: call "Sub System.Console.Write(String)"
IL_0028: ret
}]]>)
End Sub
<Fact>
Public Sub TestCoalesceRequiringBox()
CompileAndVerify(
<compilation>
<file name="a.vb">
Public Module Program
Public Sub Main()
Dim i As IGoo(Of String) = Nothing
Dim e As New GooVal()
Dim n? As GooVal = e
i = If(i, e)
System.Console.Write(i.Goo())
i = Nothing
i = If(n, i)
System.Console.Write(i.Goo())
End Sub
Interface IGoo(Of T) : Function Goo() As T : End Interface
Structure GooVal : Implements IGoo(Of String)
Public Function Goo() As String Implements IGoo(Of String).Goo
Return "Val "
End Function
End Structure
End Module</file>
</compilation>,
expectedOutput:="Val Val ").
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 90 (0x5a)
.maxstack 2
.locals init (Program.IGoo(Of String) V_0, //i
Program.GooVal V_1, //e
Program.GooVal? V_2) //n
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: initobj "Program.GooVal"
IL_000a: ldloca.s V_2
IL_000c: ldloc.1
IL_000d: call "Sub Program.GooVal?..ctor(Program.GooVal)"
IL_0012: ldloc.0
IL_0013: dup
IL_0014: brtrue.s IL_0022
IL_0016: pop
IL_0017: ldloc.1
IL_0018: box "Program.GooVal"
IL_001d: castclass "Program.IGoo(Of String)"
IL_0022: stloc.0
IL_0023: ldloc.0
IL_0024: callvirt "Function Program.IGoo(Of String).Goo() As String"
IL_0029: call "Sub System.Console.Write(String)"
IL_002e: ldnull
IL_002f: stloc.0
IL_0030: ldloca.s V_2
IL_0032: call "Function Program.GooVal?.get_HasValue() As Boolean"
IL_0037: brtrue.s IL_003c
IL_0039: ldloc.0
IL_003a: br.s IL_004d
IL_003c: ldloca.s V_2
IL_003e: call "Function Program.GooVal?.GetValueOrDefault() As Program.GooVal"
IL_0043: box "Program.GooVal"
IL_0048: castclass "Program.IGoo(Of String)"
IL_004d: stloc.0
IL_004e: ldloc.0
IL_004f: callvirt "Function Program.IGoo(Of String).Goo() As String"
IL_0054: call "Sub System.Console.Write(String)"
IL_0059: ret
}
]]>)
End Sub
<Fact()>
Public Sub TestNullCoalesce_NullableWithDefault_Optimization()
CompileAndVerify(
<compilation>
<file name="a.vb">
Public Module Program
Public Structure S
public _a As Integer
public _b As System.Guid
Public Sub New(a as Integer, b As System.Guid)
_a = a
_b = b
End Sub
Public Overrides Function ToString() As String
Return (_a, _b).ToString()
End Function
End Structure
Public Function CoalesceInt32(x As Integer?) As Integer
Return If(x, 0)
End Function
Public Function CoalesceGeneric(Of T As Structure)(x As T?) As T
Return If(x, CType(Nothing, T))
End Function
public Function CoalesceTuple(x As (a As Boolean, b As System.Guid)?) As (a As Boolean, b As System.Guid)
Return If(x, CType(Nothing, (a As Boolean, b As System.Guid)))
End Function
public Function CoalesceUserStruct(x As S?) As S
Return If(x, CType(Nothing, S))
End Function
public Function CoalesceStructWithImplicitConstructor(x As S?) As S
Return If(x, New S())
End Function
public Sub Main()
System.Console.WriteLine(CoalesceInt32(42))
System.Console.WriteLine(CoalesceInt32(Nothing))
System.Console.WriteLine(CoalesceGeneric(Of System.Guid)(new System.Guid("44ed2f0b-c2fa-4791-81f6-97222fffa466")))
System.Console.WriteLine(CoalesceGeneric(Of System.Guid)(Nothing))
System.Console.WriteLine(CoalesceTuple((true, new System.Guid("1c95cef0-1aae-4adb-a43c-54b2e7c083a0"))))
System.Console.WriteLine(CoalesceTuple(Nothing))
System.Console.WriteLine(CoalesceUserStruct(new S(42, new System.Guid("8683f371-81b4-45f6-aaed-1c665b371594"))))
System.Console.WriteLine(CoalesceUserStruct(Nothing))
System.Console.WriteLine(CoalesceStructWithImplicitConstructor(new S()))
System.Console.WriteLine(CoalesceStructWithImplicitConstructor(Nothing))
End Sub
End Module</file>
</compilation>,
references:={ValueTupleRef, SystemRuntimeFacadeRef},
expectedOutput:=<![CDATA[
42
0
44ed2f0b-c2fa-4791-81f6-97222fffa466
00000000-0000-0000-0000-000000000000
(True, 1c95cef0-1aae-4adb-a43c-54b2e7c083a0)
(False, 00000000-0000-0000-0000-000000000000)
(42, 8683f371-81b4-45f6-aaed-1c665b371594)
(0, 00000000-0000-0000-0000-000000000000)
(0, 00000000-0000-0000-0000-000000000000)
(0, 00000000-0000-0000-0000-000000000000)
]]>).
VerifyIL("Program.CoalesceInt32",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0007: ret
}]]>).
VerifyIL("Program.CoalesceGeneric(Of T)",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call "Function T?.GetValueOrDefault() As T"
IL_0007: ret
}]]>).
VerifyIL("Program.CoalesceTuple",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call "Function (a As Boolean, b As System.Guid)?.GetValueOrDefault() As (a As Boolean, b As System.Guid)"
IL_0007: ret
}]]>).
VerifyIL("Program.CoalesceUserStruct",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call "Function Program.S?.GetValueOrDefault() As Program.S"
IL_0007: ret
}]]>).
VerifyIL("Program.CoalesceStructWithImplicitConstructor",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call "Function Program.S?.GetValueOrDefault() As Program.S"
IL_0007: ret
}]]>)
End Sub
<Fact()>
Public Sub TestNullCoalesce_NullableWithConvertedDefault_Optimization()
CompileAndVerify(
<compilation>
<file name="a.vb">
Public Module Program
Public Function CoalesceDifferentTupleNames(x As (a As Boolean, b As System.Guid, c As String)?) As (a As Boolean, b As System.Guid, c As String)
Return If(x, CType(Nothing, (c As Boolean, d As System.Guid, e As String)))
End Function
Public Sub Main()
System.Console.WriteLine(CoalesceDifferentTupleNames((true, new System.Guid("533d4d3b-5013-461e-ae9e-b98eb593d761"), "value")))
System.Console.WriteLine(CoalesceDifferentTupleNames(Nothing))
End Sub
End Module</file>
</compilation>,
references:={ValueTupleRef, SystemRuntimeFacadeRef},
expectedOutput:=<![CDATA[
(True, 533d4d3b-5013-461e-ae9e-b98eb593d761, value)
(False, 00000000-0000-0000-0000-000000000000, )
]]>).
VerifyIL("Program.CoalesceDifferentTupleNames",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call "Function (a As Boolean, b As System.Guid, c As String)?.GetValueOrDefault() As (a As Boolean, b As System.Guid, c As String)"
IL_0007: ret
}
]]>)
End Sub
<Fact()>
Public Sub TestNullCoalesce_NullableWithNonDefault_NoOptimization()
CompileAndVerify(
<compilation>
<file name="a.vb">
Public Module Program
Public Function CoalesceWithNonDefault1(x As Integer?) As Integer
Return If(x, 2)
End Function
Public Function CoalesceWithNonDefault2(x As Integer?, y As Integer) As Integer
Return If(x, y)
End Function
Public Function CoalesceWithNonDefault3(x As Integer?, y As Integer?) As Integer?
Return If(x, y)
End Function
Public Function CoalesceWithNonDefault4(x As Integer?) As Integer?
Return If(x, Nothing)
End Function
Public Sub WriteLine(value As Object)
System.Console.WriteLine(If(value?.ToString, "*Nothing*"))
End Sub
Public Sub Main
WriteLine(CoalesceWithNonDefault1(42))
WriteLine(CoalesceWithNonDefault1(Nothing))
WriteLine(CoalesceWithNonDefault2(12, 34))
WriteLine(CoalesceWithNonDefault2(Nothing, 34))
WriteLine(CoalesceWithNonDefault3(123, 456))
WriteLine(CoalesceWithNonDefault3(123, Nothing))
WriteLine(CoalesceWithNonDefault3(Nothing, 456))
WriteLine(CoalesceWithNonDefault3(Nothing, Nothing))
WriteLine(CoalesceWithNonDefault4(42))
WriteLine(CoalesceWithNonDefault4(Nothing))
End Sub
End Module</file>
</compilation>,
expectedOutput:=<![CDATA[
42
2
12
34
123
123
456
*Nothing*
42
*Nothing*
]]>).
VerifyIL("Program.CoalesceWithNonDefault1",
<![CDATA[
{
// Code size 19 (0x13)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call "Function Integer?.get_HasValue() As Boolean"
IL_0007: brtrue.s IL_000b
IL_0009: ldc.i4.2
IL_000a: ret
IL_000b: ldarga.s V_0
IL_000d: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0012: ret
}
]]>).
VerifyIL("Program.CoalesceWithNonDefault2",
<![CDATA[
{
// Code size 19 (0x13)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call "Function Integer?.get_HasValue() As Boolean"
IL_0007: brtrue.s IL_000b
IL_0009: ldarg.1
IL_000a: ret
IL_000b: ldarga.s V_0
IL_000d: call "Function Integer?.GetValueOrDefault() As Integer"
IL_0012: ret
}
]]>).
VerifyIL("Program.CoalesceWithNonDefault3",
<![CDATA[
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call "Function Integer?.get_HasValue() As Boolean"
IL_0007: brtrue.s IL_000b
IL_0009: ldarg.1
IL_000a: ret
IL_000b: ldarg.0
IL_000c: ret
}
]]>).
VerifyIL("Program.CoalesceWithNonDefault4",
<![CDATA[
{
// Code size 21 (0x15)
.maxstack 1
.locals init (Integer? V_0)
IL_0000: ldarga.s V_0
IL_0002: call "Function Integer?.get_HasValue() As Boolean"
IL_0007: brtrue.s IL_0013
IL_0009: ldloca.s V_0
IL_000b: initobj "Integer?"
IL_0011: ldloc.0
IL_0012: ret
IL_0013: ldarg.0
IL_0014: ret
}
]]>)
End Sub
<Fact()>
Public Sub TestNullCoalesce_NonNullableWithDefault_NoOptimization()
CompileAndVerify(
<compilation>
<file name="a.vb">
Public Module Program
Public Function CoalesceNonNullableWithDefault(x As String)
Return If(x, Nothing)
End Function
Public Sub WriteLine(value As Object)
System.Console.WriteLine(If(value?.ToString, "*Nothing*"))
End Sub
Public Sub Main()
WriteLine(CoalesceNonNullableWithDefault("value"))
WriteLine(CoalesceNonNullableWithDefault(Nothing))
End Sub
End Module</file>
</compilation>,
expectedOutput:=<![CDATA[
value
*Nothing*
]]>).
VerifyIL("Program.CoalesceNonNullableWithDefault",
<![CDATA[
{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: dup
IL_0002: brtrue.s IL_0006
IL_0004: pop
IL_0005: ldnull
IL_0006: ret
}
]]>)
End Sub
<Fact()>
Public Sub TestNullCoalesce_NullableDefault_MissingGetValueOrDefault()
Dim compilation = CreateCompilation(
<compilation>
<file name="a.vb">
Public Module Program
Public Function Coalesce(x As Integer?)
Return If(x, 0)
End Function
End Module</file>
</compilation>)
compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault)
compilation.AssertTheseEmitDiagnostics(
<errors>
BC35000: Requested operation is not available because the runtime library function 'System.Nullable`1.GetValueOrDefault' is not defined.
Return If(x, 0)
~
</errors>)
End Sub
<Fact()>
Public Sub TestIfExpressionWithNullable()
CompileAndVerify(
<compilation>
<file name="a.vb">
Class EmitTest
Public Shared Sub Main()
WriteResult("Test01", Test01(123))
End Sub
Public Shared Sub WriteResult(name As String, result As Object)
System.Console.WriteLine("{0}: {1}", name.PadLeft(10),
If(result Is Nothing, "<Nothing>", String.Format("{0}||{1}", result, result.GetType.FullName)))
End Sub
Public Shared Function Test01(a As Integer?) As Object
Return If(Nothing, a)
End Function
End Class
</file>
</compilation>,
expectedOutput:=<![CDATA[
Test01: 123||System.Int32
]]>)
End Sub
<Fact()>
Public Sub IfStatement1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim cond As Boolean
Dim cond2 As Boolean
Dim cond3 As Boolean
cond = True
cond2 = True
cond3 = True
If cond Then
Console.WriteLine("ThenPart")
Else If cond2
Console.WriteLine("ElseIf1Part")
Else If cond3
Console.WriteLine("ElseIf2Part")
Else
Console.WriteLine("ElsePart")
End If
Console.WriteLine("After")
End Sub
End Module
</file>
</compilation>,
expectedOutput:="ThenPart" & Environment.NewLine & "After" & Environment.NewLine).
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 70 (0x46)
.maxstack 2
.locals init (Boolean V_0, //cond2
Boolean V_1) //cond3
IL_0000: ldc.i4.1
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.1
IL_0004: stloc.1
IL_0005: brfalse.s IL_0013
IL_0007: ldstr "ThenPart"
IL_000c: call "Sub System.Console.WriteLine(String)"
IL_0011: br.s IL_003b
IL_0013: ldloc.0
IL_0014: brfalse.s IL_0022
IL_0016: ldstr "ElseIf1Part"
IL_001b: call "Sub System.Console.WriteLine(String)"
IL_0020: br.s IL_003b
IL_0022: ldloc.1
IL_0023: brfalse.s IL_0031
IL_0025: ldstr "ElseIf2Part"
IL_002a: call "Sub System.Console.WriteLine(String)"
IL_002f: br.s IL_003b
IL_0031: ldstr "ElsePart"
IL_0036: call "Sub System.Console.WriteLine(String)"
IL_003b: ldstr "After"
IL_0040: call "Sub System.Console.WriteLine(String)"
IL_0045: ret
}
]]>)
End Sub
<Fact()>
Public Sub TestVarianceConversionsDDS()
CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Linq.Expressions
Imports System.Linq
Imports System.Collections
Imports System.Collections.Generic
Imports System.Security
<Assembly: SecurityTransparent()>
Namespace TernaryAndVarianceConversion
Delegate Sub CovariantDelegateWithVoidReturn(Of Out T)()
Delegate Function CovariantDelegateWithValidReturn(Of Out T)() As T
Delegate Sub ContravariantDelegateVoidReturn(Of In T)()
Delegate Sub ContravariantDelegateWithValidInParm(Of In T)(inVal As T)
Interface ICovariantInterface(Of Out T)
Sub CovariantInterfaceMethodWithVoidReturn()
Function CovariantInterfaceMethodWithValidReturn() As T
ReadOnly Property CovariantInterfacePropertyWithValidGetter As T
Sub Test()
End Interface
Interface IContravariantInterface(Of In T)
Sub ContravariantInterfaceMethodWithVoidReturn()
Sub ContravariantInterfaceMethodWithValidInParm(inVal As T)
WriteOnly Property ContravariantInterfacePropertyWithValidSetter As T
Sub Test()
End Interface
Class CovariantInterfaceImpl(Of T) : Implements ICovariantInterface(Of T)
Public Sub CovariantInterfaceMethodWithVoidReturn() Implements ICovariantInterface(Of T).CovariantInterfaceMethodWithVoidReturn
End Sub
Public Function CovariantInterfaceMethodWithValidReturn() As T Implements ICovariantInterface(Of T).CovariantInterfaceMethodWithValidReturn
Return Nothing
End Function
Public ReadOnly Property CovariantInterfacePropertyWithValidGetter As T Implements ICovariantInterface(Of T).CovariantInterfacePropertyWithValidGetter
Get
Return Nothing
End Get
End Property
Public Sub Test() Implements ICovariantInterface(Of T).Test
Console.WriteLine("{0}", GetType(T))
End Sub
End Class
Class ContravariantInterfaceImpl(Of T) : Implements IContravariantInterface(Of T)
Public Sub ContravariantInterfaceMethodWithVoidReturn() Implements IContravariantInterface(Of T).ContravariantInterfaceMethodWithVoidReturn
End Sub
Public Sub ContravariantInterfaceMethodWithValidInParm(inVal As T) Implements IContravariantInterface(Of T).ContravariantInterfaceMethodWithValidInParm
End Sub
Public WriteOnly Property ContravariantInterfacePropertyWithValidSetter As T Implements IContravariantInterface(Of T).ContravariantInterfacePropertyWithValidSetter
Set(value As T)
End Set
End Property
Public Sub Test() Implements IContravariantInterface(Of T).Test
Console.WriteLine("{0}", GetType(T))
End Sub
End Class
Class Animal
End Class
Class Mammal : Inherits Animal
End Class
Class Program
Shared Sub Test(testFlag As Boolean)
Console.WriteLine("Testing with ternary test flag == {0}", testFlag)
' Repro case for bug 7196
Dim EnumerableOfObject As IEnumerable(Of Object) =
If(testFlag,
Enumerable.Repeat(Of String)("string", 1),
Enumerable.Empty(Of Object)())
Console.WriteLine("{0}", EnumerableOfObject.Count())
' Covariant implicit conversion for delegates
Dim covariantDelegateWithVoidReturnOfAnimal As CovariantDelegateWithVoidReturn(Of Animal) = Sub() Console.WriteLine("{0}", GetType(Animal))
Dim covariantDelegateWithVoidReturnOfMammal As CovariantDelegateWithVoidReturn(Of Mammal) = Sub() Console.WriteLine("{0}", GetType(Mammal))
Dim covariantDelegateWithVoidReturnOfAnimalTest As CovariantDelegateWithVoidReturn(Of Animal)
covariantDelegateWithVoidReturnOfAnimalTest = If(testFlag, covariantDelegateWithVoidReturnOfMammal, covariantDelegateWithVoidReturnOfAnimal)
covariantDelegateWithVoidReturnOfAnimalTest()
covariantDelegateWithVoidReturnOfAnimalTest = If(testFlag, covariantDelegateWithVoidReturnOfAnimal, covariantDelegateWithVoidReturnOfMammal)
covariantDelegateWithVoidReturnOfAnimalTest()
Dim covariantDelegateWithValidReturnOfAnimal As CovariantDelegateWithValidReturn(Of Animal) = Function()
Console.WriteLine("{0}", GetType(Animal))
Return Nothing
End Function
Dim covariantDelegateWithValidReturnOfMammal As CovariantDelegateWithValidReturn(Of Mammal) = Function()
Console.WriteLine("{0}", GetType(Mammal))
Return Nothing
End Function
Dim covariantDelegateWithValidReturnOfAnimalTest As CovariantDelegateWithValidReturn(Of Animal)
covariantDelegateWithValidReturnOfAnimalTest = If(testFlag, covariantDelegateWithValidReturnOfMammal, covariantDelegateWithValidReturnOfAnimal)
covariantDelegateWithValidReturnOfAnimalTest()
covariantDelegateWithValidReturnOfAnimalTest = If(testFlag, covariantDelegateWithValidReturnOfAnimal, covariantDelegateWithValidReturnOfMammal)
covariantDelegateWithValidReturnOfAnimalTest()
' Contravariant implicit conversion for delegates
Dim contravariantDelegateVoidReturnOfAnimal As ContravariantDelegateVoidReturn(Of Animal) = Sub() Console.WriteLine("{0}", GetType(Animal))
Dim contravariantDelegateVoidReturnOfMammal As ContravariantDelegateVoidReturn(Of Mammal) = Sub() Console.WriteLine("{0}", GetType(Mammal))
Dim contravariantDelegateVoidReturnOfMammalTest As ContravariantDelegateVoidReturn(Of Mammal)
contravariantDelegateVoidReturnOfMammalTest = If(testFlag, contravariantDelegateVoidReturnOfMammal, contravariantDelegateVoidReturnOfAnimal)
contravariantDelegateVoidReturnOfMammalTest()
contravariantDelegateVoidReturnOfMammalTest = If(testFlag, contravariantDelegateVoidReturnOfAnimal, contravariantDelegateVoidReturnOfMammal)
contravariantDelegateVoidReturnOfMammalTest()
Dim contravariantDelegateWithValidInParmOfAnimal As ContravariantDelegateWithValidInParm(Of Animal) = Sub(t As Animal)
Console.WriteLine("{0}", GetType(Animal))
End Sub
Dim contravariantDelegateWithValidInParmOfMammal As ContravariantDelegateWithValidInParm(Of Mammal) = Sub(t As Mammal)
Console.WriteLine("{0}", GetType(Mammal))
End Sub
Dim contravariantDelegateWithValidInParmOfMammalTest As ContravariantDelegateWithValidInParm(Of Mammal)
contravariantDelegateWithValidInParmOfMammalTest = If(testFlag, contravariantDelegateWithValidInParmOfMammal, contravariantDelegateWithValidInParmOfAnimal)
contravariantDelegateWithValidInParmOfMammalTest(Nothing)
contravariantDelegateWithValidInParmOfMammalTest = If(testFlag, contravariantDelegateWithValidInParmOfAnimal, contravariantDelegateWithValidInParmOfMammal)
contravariantDelegateWithValidInParmOfMammalTest(Nothing)
' Covariant implicit conversion for interfaces
Dim covariantInterfaceOfAnimal As ICovariantInterface(Of Animal) = New CovariantInterfaceImpl(Of Animal)
Dim covariantInterfaceOfMammal As ICovariantInterface(Of Mammal) = New CovariantInterfaceImpl(Of Mammal)()
Dim covariantInterfaceOfAnimalTest As ICovariantInterface(Of Animal)
covariantInterfaceOfAnimalTest = If(testFlag, covariantInterfaceOfMammal, covariantInterfaceOfAnimal)
covariantInterfaceOfAnimalTest.Test()
covariantInterfaceOfAnimalTest = If(testFlag, covariantInterfaceOfAnimal, covariantInterfaceOfMammal)
covariantInterfaceOfAnimalTest.Test()
' Contravariant implicit conversion for interfaces
Dim contravariantInterfaceOfAnimal As IContravariantInterface(Of Animal) = New ContravariantInterfaceImpl(Of Animal)()
Dim contravariantInterfaceOfMammal As IContravariantInterface(Of Mammal) = New ContravariantInterfaceImpl(Of Mammal)
Dim contravariantInterfaceOfMammalTest As IContravariantInterface(Of Mammal)
contravariantInterfaceOfMammalTest = If(testFlag, contravariantInterfaceOfMammal, contravariantInterfaceOfAnimal)
contravariantInterfaceOfMammalTest.Test()
contravariantInterfaceOfMammalTest = If(testFlag, contravariantInterfaceOfAnimal, contravariantInterfaceOfMammal)
contravariantInterfaceOfMammalTest.Test()
' With explicit casting
covariantDelegateWithVoidReturnOfAnimalTest = If(testFlag, DirectCast(DirectCast(covariantDelegateWithVoidReturnOfMammal, CovariantDelegateWithVoidReturn(Of Animal)), CovariantDelegateWithVoidReturn(Of Animal)), covariantDelegateWithVoidReturnOfAnimal)
covariantDelegateWithVoidReturnOfAnimalTest()
covariantDelegateWithVoidReturnOfAnimalTest = If(testFlag, covariantDelegateWithVoidReturnOfAnimal, DirectCast(DirectCast(covariantDelegateWithVoidReturnOfMammal, CovariantDelegateWithVoidReturn(Of Animal)), CovariantDelegateWithVoidReturn(Of Animal)))
covariantDelegateWithVoidReturnOfAnimalTest()
covariantDelegateWithVoidReturnOfAnimalTest = If(testFlag, TryCast(TryCast(covariantDelegateWithVoidReturnOfMammal, CovariantDelegateWithVoidReturn(Of Animal)), CovariantDelegateWithVoidReturn(Of Animal)), covariantDelegateWithVoidReturnOfAnimal)
covariantDelegateWithVoidReturnOfAnimalTest()
covariantDelegateWithVoidReturnOfAnimalTest = If(testFlag, covariantDelegateWithVoidReturnOfAnimal, TryCast(TryCast(covariantDelegateWithVoidReturnOfMammal, CovariantDelegateWithVoidReturn(Of Animal)), CovariantDelegateWithVoidReturn(Of Animal)))
covariantDelegateWithVoidReturnOfAnimalTest()
covariantDelegateWithVoidReturnOfAnimalTest = If(testFlag, CType(TryCast(covariantDelegateWithVoidReturnOfMammal, CovariantDelegateWithVoidReturn(Of Animal)), CovariantDelegateWithVoidReturn(Of Animal)), covariantDelegateWithVoidReturnOfAnimal)
covariantDelegateWithVoidReturnOfAnimalTest()
covariantDelegateWithVoidReturnOfAnimalTest = If(testFlag, covariantDelegateWithVoidReturnOfAnimal, DirectCast(CType(covariantDelegateWithVoidReturnOfMammal, CovariantDelegateWithVoidReturn(Of Animal)), CovariantDelegateWithVoidReturn(Of Animal)))
covariantDelegateWithVoidReturnOfAnimalTest()
' With parens
covariantDelegateWithVoidReturnOfAnimalTest = If(testFlag, (covariantDelegateWithVoidReturnOfMammal), covariantDelegateWithVoidReturnOfAnimal)
covariantDelegateWithVoidReturnOfAnimalTest()
covariantDelegateWithVoidReturnOfAnimalTest = If(testFlag, covariantDelegateWithVoidReturnOfAnimal, (covariantDelegateWithVoidReturnOfMammal))
covariantDelegateWithVoidReturnOfAnimalTest()
covariantDelegateWithVoidReturnOfAnimalTest = If(testFlag, (DirectCast(covariantDelegateWithVoidReturnOfMammal, CovariantDelegateWithVoidReturn(Of Animal))), covariantDelegateWithVoidReturnOfAnimal)
covariantDelegateWithVoidReturnOfAnimalTest()
covariantDelegateWithVoidReturnOfAnimalTest = If(testFlag, covariantDelegateWithVoidReturnOfAnimal, (DirectCast(covariantDelegateWithVoidReturnOfMammal, CovariantDelegateWithVoidReturn(Of Animal))))
covariantDelegateWithVoidReturnOfAnimalTest()
' Bug 291602
Dim intarr = {1, 2, 3}
Dim intlist As IList(Of Integer) = New List(Of Integer)(intarr)
Dim intternary As IList(Of Integer) = If(testFlag, intarr, intlist)
Console.WriteLine(intternary)
End Sub
Public Shared Sub Main()
Test(True)
Test(False)
End Sub
End Class
End Namespace
]]>
</file>
</compilation>,
expectedOutput:=<![CDATA[Testing with ternary test flag == True
1
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
System.Int32[]
Testing with ternary test flag == False
0
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
System.Collections.Generic.List`1[System.Int32]
]]>)
End Sub
<Fact()>
Public Sub ShiftMask()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim s As Integer = 2
Dim v As Integer = 123
v = v >> s
Console.Write(v)
Dim v1 As Long = 123
v1 = v1 << s
Console.Write(v1)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="30492").
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 28 (0x1c)
.maxstack 3
.locals init (Integer V_0) //s
IL_0000: ldc.i4.2
IL_0001: stloc.0
IL_0002: ldc.i4.s 123
IL_0004: ldloc.0
IL_0005: ldc.i4.s 31
IL_0007: and
IL_0008: shr
IL_0009: call "Sub System.Console.Write(Integer)"
IL_000e: ldc.i4.s 123
IL_0010: conv.i8
IL_0011: ldloc.0
IL_0012: ldc.i4.s 63
IL_0014: and
IL_0015: shl
IL_0016: call "Sub System.Console.Write(Long)"
IL_001b: ret
}
]]>)
End Sub
<Fact()>
Public Sub DoLoop1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim breakLoop as Boolean
breakLoop = true
Do While breakLoop
Console.WriteLine("Iterate")
breakLoop = false
Loop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate").
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 20 (0x14)
.maxstack 1
.locals init (Boolean V_0) //breakLoop
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: br.s IL_0010
IL_0004: ldstr "Iterate"
IL_0009: call "Sub System.Console.WriteLine(String)"
IL_000e: ldc.i4.0
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: brtrue.s IL_0004
IL_0013: ret
}
]]>)
End Sub
<Fact()>
Public Sub DoLoop2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim breakLoop as Boolean
breakLoop = true
Do Until breakLoop
Console.WriteLine("Iterate")
breakLoop = false
Loop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="").
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 20 (0x14)
.maxstack 1
.locals init (Boolean V_0) //breakLoop
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: br.s IL_0010
IL_0004: ldstr "Iterate"
IL_0009: call "Sub System.Console.WriteLine(String)"
IL_000e: ldc.i4.0
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: brfalse.s IL_0004
IL_0013: ret
}
]]>)
End Sub
<Fact()>
Public Sub DoLoop3()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim breakLoop as Boolean
breakLoop = true
Do
Console.WriteLine("Iterate")
breakLoop = false
Loop While breakLoop
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Iterate
]]>).
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 1
.locals init (Boolean V_0) //breakLoop
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldstr "Iterate"
IL_0007: call "Sub System.Console.WriteLine(String)"
IL_000c: ldc.i4.0
IL_000d: stloc.0
IL_000e: ldloc.0
IL_000f: brtrue.s IL_0002
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub DoLoop4()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub M()
dim breakLoop as Boolean
breakLoop = true
Do
Console.WriteLine("Iterate")
breakLoop = false
Loop Until breakLoop
End Sub
End Module
</file>
</compilation>).
VerifyIL("M1.M",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 1
.locals init (Boolean V_0) //breakLoop
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldstr "Iterate"
IL_0007: call "Sub System.Console.WriteLine(String)"
IL_000c: ldc.i4.0
IL_000d: stloc.0
IL_000e: ldloc.0
IL_000f: brfalse.s IL_0002
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub DoLoop5()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class C
Sub M()
Do
Console.WriteLine("Iterate")
Loop
End Sub
End Class
</file>
</compilation>).
VerifyIL("C.M",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldstr "Iterate"
IL_0005: call "Sub System.Console.WriteLine(String)"
IL_000a: br.s IL_0000
}
]]>)
End Sub
<Fact()>
Public Sub ExitContinueDoLoop1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim breakLoop as Boolean
dim continueLoop as Boolean
breakLoop = True: continueLoop = true
Do While breakLoop
Console.WriteLine("Stmt1")
If continueLoop Then
Console.WriteLine("Continuing")
continueLoop = false
Continue Do
End If
Console.WriteLine("Exiting")
Exit Do
Console.WriteLine("Stmt2")
Loop
Console.WriteLine("After Loop")
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Stmt1
Continuing
Stmt1
Exiting
After Loop
]]>).
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 59 (0x3b)
.maxstack 1
.locals init (Boolean V_0, //breakLoop
Boolean V_1) //continueLoop
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.1
IL_0003: stloc.1
IL_0004: br.s IL_002d
IL_0006: ldstr "Stmt1"
IL_000b: call "Sub System.Console.WriteLine(String)"
IL_0010: ldloc.1
IL_0011: brfalse.s IL_0021
IL_0013: ldstr "Continuing"
IL_0018: call "Sub System.Console.WriteLine(String)"
IL_001d: ldc.i4.0
IL_001e: stloc.1
IL_001f: br.s IL_002d
IL_0021: ldstr "Exiting"
IL_0026: call "Sub System.Console.WriteLine(String)"
IL_002b: br.s IL_0030
IL_002d: ldloc.0
IL_002e: brtrue.s IL_0006
IL_0030: ldstr "After Loop"
IL_0035: call "Sub System.Console.WriteLine(String)"
IL_003a: ret
}
]]>)
End Sub
<Fact()>
Public Sub PartialMethod1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class CLS
Partial Private Shared Sub PS()
End Sub
Shared Sub TST()
PS()
End Sub
Shared Sub Main()
Dim t = (New CLS()).GetType()
Dim m = t.GetMethod("PS", Reflection.BindingFlags.Static Or Reflection.BindingFlags.NonPublic)
Console.WriteLine(If(m Is Nothing, "Nothing", m.ToString()))
End Sub
End Class
</file>
</compilation>, expectedOutput:="Nothing").
VerifyIL("CLS.TST",
<![CDATA[
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}
]]>)
End Sub
<Fact()>
Public Sub PartialMethod2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Interface I
Sub S()
End Interface
Class C
Implements I
Partial Private Sub S()
End Sub
Private Sub S() Implements I.S
Console.WriteLine("Private Sub S() Implements I.S")
End Sub
Shared Sub Main(args As String())
Dim i As I = New C
i.S()
End Sub
End Class
</file>
</compilation>, expectedOutput:="Private Sub S() Implements I.S")
End Sub
<Fact()>
Public Sub PartialMethod_NonGeneric_Generic()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class C(Of V)
Partial Private Sub S(s As Integer)
End Sub
Private Sub S(s As V)
Console.WriteLine("Success")
End Sub
Public Sub Goo(ByVal z As V)
Me.S(z)
End Sub
End Class
Module M222
Sub Main(args As String())
Dim c As New C(Of Integer)
c.Goo(1)
End Sub
End Module
</file>
</compilation>, expectedOutput:="Success")
End Sub
<Fact()>
Public Sub PartialMethod_Generic_Generic()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class C(Of V)
Partial Private Sub S(s As V)
End Sub
Private Sub S(s As V)
Console.WriteLine("Success")
End Sub
Public Sub Goo(ByVal z As V)
Me.S(z)
End Sub
End Class
Module M222
Sub Main(args As String())
Dim c As New C(Of Integer)
c.Goo(1)
End Sub
End Module
</file>
</compilation>, expectedOutput:="Success")
End Sub
<Fact()>
Public Sub PartialMethod_Generic_NonGeneric()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class C(Of V)
Partial Private Sub S(s As V)
End Sub
Private Sub S(s As Integer)
Console.WriteLine("Success")
End Sub
Public Sub Goo(ByVal z As V)
Me.S(z)
End Sub
End Class
Module M222
Sub Main(args As String())
Dim c As New C(Of Integer)
c.Goo(1)
End Sub
End Module
</file>
</compilation>, expectedOutput:="")
End Sub
<Fact()>
Public Sub PartialMethod_Generic_NonGeneric2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Structure C(Of V)
Partial Private Sub S(s As V)
End Sub
Private Sub S(s As Integer)
Console.WriteLine("Success")
End Sub
Public Sub Goo(ByVal z As Integer)
Me.S(z)
End Sub
End Structure
Module M222
Sub Main(args As String())
Dim c As New C(Of Integer)
c.Goo(1)
End Sub
End Module
</file>
</compilation>, expectedOutput:="Success")
End Sub
<Fact()>
Public Sub PartialMethod_NonGeneric_Generic_Method()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class C
Partial Private Sub S(s As Integer)
End Sub
Private Sub S(Of V)(s As V)
Console.WriteLine("Success")
End Sub
Public Sub Goo(Of V)(ByVal z As V)
Me.S(z)
End Sub
End Class
Module MMM
Sub Main(args As String())
Dim c As New C
c.Goo(1)
End Sub
End Module
</file>
</compilation>, expectedOutput:="Success")
End Sub
<Fact()>
Public Sub PartialMethod_NonGeneric_Generic_Method2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Structure C
Partial Private Sub S(s As Integer)
End Sub
Private Sub S(Of V)(s As V)
Console.WriteLine("Success")
End Sub
Public Sub Goo(ByVal z As Integer)
Me.S(z)
End Sub
End Structure
Module MMM
Sub Main(args As String())
Dim c As New C
c.Goo(1)
End Sub
End Module
</file>
</compilation>, expectedOutput:="")
End Sub
<Fact()>
Public Sub PartialMethod_Generic_NonGeneric_Method()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class C
Partial Private Sub S(Of V)(s As V)
End Sub
Private Sub S(s As Integer)
Console.WriteLine("Success")
End Sub
Public Sub Goo(Of V)(ByVal z As V)
Me.S(z)
End Sub
End Class
Module MMM
Sub Main(args As String())
Dim c As New C
c.Goo(1)
End Sub
End Module
</file>
</compilation>, expectedOutput:="")
End Sub
<Fact()>
Public Sub PartialMethod_Generic_NonGeneric_Method2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Structure C
Partial Private Sub S(Of V)(s As V)
End Sub
Private Sub S(s As Integer)
Console.WriteLine("Success")
End Sub
Public Sub Goo(ByVal z As Integer)
Me.S(z)
End Sub
End Structure
Module MMM
Sub Main(args As String())
Dim c As New C
c.Goo(1)
End Sub
End Module
</file>
</compilation>, expectedOutput:="Success")
End Sub
<Fact()>
Public Sub PartialMethod_ComplexGenerics()
Dim vbCompilation = CreateVisualBasicCompilation("PartialMethod_ComplexGenerics",
<![CDATA[Imports System
Imports System.Collections.Generic
Imports A = C1(Of Integer)
Module Program
Sub Main(args As String())
Dim x = New C1(Of A).C2(Of A)
Dim a1 = New c2(Of Integer)
Dim a2 = New c2(Of A)
Dim a3 As C1(Of A).I(Of A) = Nothing
Dim a4 = New Dictionary(Of C1(Of A), C1(Of A).I(Of A))()
Dim a5 = New ArgumentException
Dim a6 = New c2(Of ArgumentException)
x.Bar(a1, a1, a2,
a1, a3,
a1, a1, a4,
a5, a6)
End Sub
End Module
Partial Class C1(Of T) : Implements C1(Of A).I(Of A)
Interface I(Of J)
End Interface
Partial Class C2(Of K As T)
Partial Private Sub Goo(Of U As {A, T, I(Of K)}, V As {U, A})(x As A, y As T, z As C1(Of T),
aa As K, bb As I(Of K),
cc As U, dd As V, ee As IDictionary(Of C1(Of U), I(Of V)),
ff As Exception, yy As C1(Of ArgumentException))
End Sub
Sub Bar(Of U As {A, T, I(Of K)}, V As {U, A})(x As A, y As T, z As C1(Of T),
aa As K, bb As I(Of K),
cc As U, dd As V, ee As IDictionary(Of C1(Of U), I(Of V)),
ff As Exception, yy As C1(Of ArgumentException))
Goo(x, y, z, aa, bb, cc, dd, ee, ff, yy)
End Sub
End Class
End Class
Class c2(Of T) : Inherits C1(Of T)
End Class
Partial Class C1(Of T)
Partial Class C2(Of K As T)
Private Sub Goo(Of U As {T, I(Of K), C1(Of Integer)}, V As {C1(Of Integer), U})(x As C1(Of Integer), y As T, z As C1(Of T),
aa As K, bb As I(Of K),
cc As U, dd As V, ee As IDictionary(Of C1(Of U), I(Of V)),
ff As Exception, yy As C1(Of ArgumentException))
Console.WriteLine("Success")
End Sub
End Class
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication))
Dim vbVerifier = CompileAndVerify(vbCompilation,
expectedOutput:=<![CDATA[Success
]]>)
vbVerifier.VerifyDiagnostics()
End Sub
<WorkItem(544432, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544432")>
<Fact()>
Public Sub PartialMethod_InNestedStructsAndModules()
Dim vbCompilation = CreateVisualBasicCompilation("PartialMethod_InNestedStructsAndModules",
<![CDATA[Imports System
Public Module M
Private Sub Goo(Of V)(ByRef x As V,
ParamArray y() As Integer)
Console.WriteLine("M.Goo - Integer")
End Sub
Partial Private Sub Goo(Of V)(ByRef x As V,
ParamArray y() As Long)
End Sub
Sub Main()
'Structures
I(Of Integer).S(Of Integer).Test(Of Integer)()
'Modules
Dim x = 1
Dim y = 1L
Goo(x, x, x, x)
Goo(x, x, x, y)
End Sub
Partial Private Sub Goo(Of V)(ByRef x As V,
ParamArray y() As Integer)
End Sub
Private Sub Goo(Of V)(ByRef x As V,
ParamArray y() As Long)
Console.WriteLine("M.Goo - Long")
End Sub
End Module
Interface I(Of T)
Partial Structure S(Of U As T)
Partial Private Sub Goo(Of V As {T, U})(ByRef x As C(Of S(Of V)),
ParamArray y() As Integer)
End Sub
Private Sub Goo(Of V As {T, U})(ByRef x As C(Of S(Of V)),
ParamArray y() As Long)
Console.WriteLine("S.Goo - Long")
End Sub
End Structure
Class C(Of W As Structure)
End Class
Partial Structure S(Of U As T)
Private Sub Goo(Of V As {T, U})(ByRef x As C(Of S(Of V)),
ParamArray y() As Integer)
Console.WriteLine("S.Goo - Integer")
End Sub
Partial Private Sub Goo(Of V As {T, U})(ByRef x As C(Of S(Of V)),
ParamArray y() As Long)
End Sub
Shared Sub Test(Of J As U)()
Dim s = New I(Of T).S(Of U)
Dim c = New I(Of T).C(Of S(Of J))
Dim x = 1
Dim y = 1L
s.Goo(c, x, x, x)
s.Goo(c, x, x, y)
End Sub
End Structure
End Interface]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication))
Dim vbVerifier = CompileAndVerify(vbCompilation,
expectedOutput:=<![CDATA[S.Goo - Integer
S.Goo - Long
M.Goo - Integer
M.Goo - Long
]]>)
vbVerifier.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub EmitCallToConstructorWithParamArrayParameters()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Class Base
Sub New(ParamArray x() As Object)
Console.WriteLine("Base.New(): " + x.Length.ToString())
End Sub
End Class
Class Derived
Inherits Base
End Class
Public Sub Main()
Dim a As New Derived()
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[Base.New(): 0]]>).
VerifyIL("M1.Derived..ctor",
<![CDATA[
{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: newarr "Object"
IL_0007: call "Sub M1.Base..ctor(ParamArray Object())"
IL_000c: ret
}
]]>)
End Sub
' Test access to a parameter (both simple and byref)
<Fact()>
Public Sub Parameter1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub Goo(xParam as Integer, ByRef yParam As Long)
Console.WriteLine(xParam)
Console.WriteLine(yParam)
xParam = 17
yParam = 189
End Sub
Sub Main()
Dim x as Integer
Dim y as Long
x = 143
y = 16442
Console.WriteLine("x = {0}", x)
Console.WriteLine("y = {0}", y)
Goo(x,y)
Console.WriteLine("x = {0}", x)
Console.WriteLine("y = {0}", y)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
x = 143
y = 16442
143
16442
x = 143
y = 189
]]>).
VerifyIL("M1.Goo",
<![CDATA[
{
// Code size 26 (0x1a)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call "Sub System.Console.WriteLine(Integer)"
IL_0006: ldarg.1
IL_0007: ldind.i8
IL_0008: call "Sub System.Console.WriteLine(Long)"
IL_000d: ldc.i4.s 17
IL_000f: starg.s V_0
IL_0011: ldarg.1
IL_0012: ldc.i4 0xbd
IL_0017: conv.i8
IL_0018: stind.i8
IL_0019: ret
}
]]>)
End Sub
' Test that parameterless functions are invoked when in argument lists
<Fact()>
Public Sub ParameterlessFunctionCall()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Function SayHi as string
return "hi"
End Function
Sub Main()
Console.WriteLine(SayHi)
Console.WriteLine(SayHi())
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
hi
hi
]]>).
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 21 (0x15)
.maxstack 1
IL_0000: call "Function M1.SayHi() As String"
IL_0005: call "Sub System.Console.WriteLine(String)"
IL_000a: call "Function M1.SayHi() As String"
IL_000f: call "Sub System.Console.WriteLine(String)"
IL_0014: ret
}
]]>)
End Sub
<ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28046")>
Public Sub ParameterByRefVal()
CompileAndVerify(
<compilation>
<file name="First.1a.vb"><![CDATA[
Imports System
Namespace VBN
Friend Structure SBar
Public Field1 As Decimal
Public Field2 As SGoo
End Structure
End Namespace
]]></file>
<file name="Second.2b.vb"><![CDATA[
Option Strict Off
Imports System
Imports VBN
Module Program
Sub Main(args As String())
Dim sss As VBN.SGoo, ccc As SBar = New SBar()
sss = New SGoo()
Dim val As Short = 9
sss.M1(val)
' () - ByRef
sss.M1((val))
sss.M1(((val)))
Dim ary1() As Short
ary1 = New Short(0) {6}
Dim ary2 As UShort() = New UShort(3) {0, 8, 2, 3}
sss.M1(ary1, ary2, ary1(0), ary2(2))
console.write("{0},{1},{2},{3}|", ary1(2), ary2(1), ary1(0), ary2(2))
Dim v2 As UInteger = 1221
' call UShort
sss.M2(v2)
console.write("{0}|", v2)
sss.M2("121")
ccc.Field2 = sss
ccc.Field1 = 123.456D
Dim v3 As Short() = New Short() {0, 1, -1, -127}
ccc.Field2.M2(ccc, v3(3))
console.write("{0},{1} |", ccc.Field1.ToString(System.Globalization.CultureInfo.InvariantCulture), v3(3))
ccc.Field2.M2(ccc)
console.write("D:{0}|", ccc.Field1.ToString(System.Globalization.CultureInfo.InvariantCulture))
'Dim jag(,)() As SByte = New SByte(1, 1)() {{New SByte() {1}, New SByte() {2}}, {New SByte() {3}, New SByte() {4}}}
Dim jag()() As SByte = New SByte(2)() {New SByte() {-1, 1}, New SByte() {2}, New SByte() {3, -3, -0}}
ccc.Field2.M1(jag(1)(0), jag(2)(2))
console.write("J:{0},{1}", jag(1)(0), jag(2)(2))
End Sub
End Module
]]></file>
<file name="Third.3c.vb"><![CDATA[
Imports System
Namespace VBN
Structure SGoo
Public Sub M1(ByVal x As Object)
console.write("O:{0}|", x)
End Sub
Public Sub M1(ByRef x As Integer)
console.write("I:{0}|", x)
End Sub
Public Sub M1(ByRef x As Short(), ByVal y() As UShort, ByRef z As Short, ByRef p As UShort)
x = New Short() {-1, -2, -3}
y(1) = 1
z = 7
p = Nothing
End Sub
Public Sub M1(ByRef x As SByte, ByVal y As Long)
If (x <= SByte.MaxValue - 2 AndAlso y >= -1) Then
x = 1 + x + 1
y = y - 1 - 1
Else
x = System.Math.Abs(y) - 2 * x
y = x + x
End If
End Sub
Public Sub M1(ByRef x As Object, ByVal y As String)
End Sub
Public Sub M2(ByVal x As SBar, ByRef y As SByte)
x.Field1 = 9.876543
If (y >= SByte.MinValue + 1) Then
y = y - 1
End If
End Sub
Public Sub M2(ByRef x As SBar)
x.Field1 = 9.876543
End Sub
Public Sub M2(ByRef x As UShort)
x = X + 1
If (x <= 123) Then
console.write("{0}|", x)
End If
End Sub
End Structure
End Namespace
]]></file>
</compilation>,
expectedOutput:="O:9|I:9|I:9|-3,1,-1,0|1222|122|123.456,-128 |D:9.876543|J:4,0")
End Sub
<Fact()>
Public Sub ReturnStatementInSub1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub S1()
dim f as boolean = true
if f then
console.WriteLine("true")
return
else
console.WriteLine("false")
return
end if
console.writeline("end")
End Sub
End Module
</file>
</compilation>).
VerifyIL("M1.S1",
<![CDATA[
{
// Code size 25 (0x19)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: brfalse.s IL_000e
IL_0003: ldstr "true"
IL_0008: call "Sub System.Console.WriteLine(String)"
IL_000d: ret
IL_000e: ldstr "false"
IL_0013: call "Sub System.Console.WriteLine(String)"
IL_0018: ret
}
]]>)
End Sub
<Fact()>
Public Sub ReturnStatementInFunction1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Function F1() as boolean
dim f as boolean = true
if f then
console.WriteLine("true")
return true
else
console.WriteLine("false")
return false
end if
console.writeline("end")
return false
End Function
End Module
</file>
</compilation>).
VerifyIL("M1.F1",
<![CDATA[
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (Boolean V_0) //F1
IL_0000: ldc.i4.1
IL_0001: brfalse.s IL_0011
IL_0003: ldstr "true"
IL_0008: call "Sub System.Console.WriteLine(String)"
IL_000d: ldc.i4.1
IL_000e: stloc.0
IL_000f: br.s IL_001d
IL_0011: ldstr "false"
IL_0016: call "Sub System.Console.WriteLine(String)"
IL_001b: ldc.i4.0
IL_001c: stloc.0
IL_001d: ldloc.0
IL_001e: ret
}
]]>)
End Sub
<Fact()>
Public Sub ReturnStatementInDo()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Function F1(x as integer) as integer
do while true
return x
loop
End Function
End Module
</file>
</compilation>).
VerifyIL("M1.F1",
<![CDATA[
{
// Code size 4 (0x4)
.maxstack 1
.locals init (Integer V_0) //F1
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ret
}
]]>)
End Sub
<Fact()>
Public Sub MultipleLocals()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class C
Sub M()
dim a1 as integer = 100, b1, b2, b3 as string, c1 as boolean = false
Console.Write(a1)
Console.Write(b1 & b2 & b3)
Console.Write(c1)
End Sub
End Class
</file>
</compilation>).
VerifyIL("C.M",
<![CDATA[
{
// Code size 29 (0x1d)
.maxstack 4
.locals init (Integer V_0, //a1
String V_1, //b1
String V_2, //b2
String V_3) //b3
IL_0000: ldc.i4.s 100
IL_0002: stloc.0
IL_0003: ldc.i4.0
IL_0004: ldloc.0
IL_0005: call "Sub System.Console.Write(Integer)"
IL_000a: ldloc.1
IL_000b: ldloc.2
IL_000c: ldloc.3
IL_000d: call "Function String.Concat(String, String, String) As String"
IL_0012: call "Sub System.Console.Write(String)"
IL_0017: call "Sub System.Console.Write(Boolean)"
IL_001c: ret
}
]]>)
End Sub
<Fact()>
Public Sub LocalArray1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub M()
dim a?()(,) as integer
dim b(2) as integer
' should be error BC31087
dim c as integer(,)
End Sub
End Module
</file>
</compilation>).
VerifyIL("M1.M",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldc.i4.3
IL_0001: newarr "Integer"
IL_0006: pop
IL_0007: ret
}
]]>)
End Sub
<Fact()>
Public Sub LocalArray2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class C
Sub M()
Dim z As Integer()(,) = New Integer(3)(,) {}
End Sub
End Class
</file>
</compilation>).
VerifyIL("C.M",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldc.i4.4
IL_0001: newarr "Integer(,)"
IL_0006: pop
IL_0007: ret
}
]]>)
End Sub
<WorkItem(538660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538660")>
<Fact()>
Public Sub LocalArray3()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim z1 As Integer() = New Integer(2) {1,2,3}
Dim Z2 as string() = new string() {"a", "b"}
Console.Write(z1(2))
Console.Write(z2(1))
End Sub
End Module
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithModuleName("MODULE"),
expectedOutput:="3b").VerifyIL("M1.Main",
<![CDATA[
{
// Code size 56 (0x38)
.maxstack 4
.locals init (Integer() V_0) //z1
IL_0000: ldc.i4.3
IL_0001: newarr "Integer"
IL_0006: dup
IL_0007: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"
IL_000c: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"
IL_0011: stloc.0
IL_0012: ldc.i4.2
IL_0013: newarr "String"
IL_0018: dup
IL_0019: ldc.i4.0
IL_001a: ldstr "a"
IL_001f: stelem.ref
IL_0020: dup
IL_0021: ldc.i4.1
IL_0022: ldstr "b"
IL_0027: stelem.ref
IL_0028: ldloc.0
IL_0029: ldc.i4.2
IL_002a: ldelem.i4
IL_002b: call "Sub System.Console.Write(Integer)"
IL_0030: ldc.i4.1
IL_0031: ldelem.ref
IL_0032: call "Sub System.Console.Write(String)"
IL_0037: ret
}
]]>)
End Sub
<Fact()>
Public Sub LocalArrayAssign1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub M()
Dim z1(1) As string
z1(0) = "hello"
z1(1) = "world"
End Sub
End Module
</file>
</compilation>).
VerifyIL("M1.M",
<![CDATA[
{
// Code size 22 (0x16)
.maxstack 4
IL_0000: ldc.i4.2
IL_0001: newarr "String"
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldstr "hello"
IL_000d: stelem.ref
IL_000e: ldc.i4.1
IL_000f: ldstr "world"
IL_0014: stelem.ref
IL_0015: ret
}
]]>)
End Sub
<Fact()>
Public Sub ArrayWithTypeChars()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class MyArray
Shared fidx As UInteger
Shared Sub Main()
fidx = 2
Const idx As Long = 9
Dim local As ULong = 5
Dim B04@(local), B05%(5 - 2), B06&(3 - 1)
B04(0) = 1.234D
Console.WriteLine(B04(0).ToString(System.Globalization.CultureInfo.InvariantCulture))
B05%(1) = -12345
Console.WriteLine(B05%(1))
B06(0) = -1%
Console.WriteLine(B06&(0))
End Sub
End Class
</file>
</compilation>,
expectedOutput:=<![CDATA[
1.234
-12345
-1
]]>)
End Sub
<Fact>
<WorkItem(33564, "https://github.com/dotnet/roslyn/issues/33564")>
<WorkItem(529849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529849")>
Public Sub ArrayWithTypeCharsWithStaticLocals()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class MyArray
Shared fidx As UInteger
Shared cul As System.Globalization.CultureInfo = System.Globalization.CultureInfo.InvariantCulture
Shared Sub Main()
fidx = 2
Const idx As Long = 9
Dim local As ULong = 5
Static B01#(3), B02!(idx), B03$(fidx)
B01(0) = 1.1#
B01#(2) = 2.2!
Console.WriteLine(B01(0).ToString("G15", cul))
Console.WriteLine(B01(2).ToString("G15", cul))
B02!(idx - 1) = 0.123
Console.WriteLine(B02(idx - 1).ToString("G6", cul))
B03$(fidx - 1) = "c c"
Console.WriteLine(B03(1))
End Sub
End Class
</file>
</compilation>,
expectedOutput:=<![CDATA[
1.1
2.20000004768372
0.123
c c
]]>)
End Sub
<WorkItem(538660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538660")>
<Fact()>
Public Sub ArrayOneDimension()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Namespace N
Public Class MC
Public CF As String
End Class
Friend Structure MS
Public SF As Mc
End Structure
Class MyArray
Shared fidx As ULong
Shared Sub Main()
fidx = 2
Const idx As Long = 9
Dim local As UInteger = 5
' 12
Dim a1 As SByte() = New SByte(local) {}
a1(0) = 123
a1(fidx + 1) = a1(0)
Console.WriteLine(a1(3))
' 124
Dim lmc As MC = New MC()
lmc.CF = "XXX"
Dim a2 As MC() = New MC(1 + 1) {lmc, New MC(), Nothing}
Console.WriteLine(a2(0).CF)
Dim a4(0) As Date
a4(0) = #12:24:35 PM#
Console.WriteLine(a4(0).ToString("M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture))
End Sub
End Class
End Namespace
</file>
</compilation>,
expectedOutput:=<![CDATA[
123
XXX
1/1/0001 12:24:35 PM
]]>)
End Sub
<WorkItem(538660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538660")>
<WorkItem(529849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529849")>
<Fact>
Public Sub ArrayOneDimensionWithStaticLocals()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Namespace N
Public Class MC
Public CF As String
End Class
Friend Structure MS
Public SF As Mc
End Structure
Class MyArray
Shared fidx As ULong
Shared Sub Main()
fidx = 2
Const idx As Long = 9
Static lms As MS = New MS()
lms.SF = New MC()
lms.SF.CF = "12345"
Static a3 As MS()
a3 = New MS(idx - 7) {New MS(), lms, lms}
Console.WriteLine(a3(1).SF.CF)
End Sub
End Class
End Namespace
</file>
</compilation>,
expectedOutput:=<![CDATA[
12345
]]>)
End Sub
<Fact()>
Public Sub ConstantExpressions()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System.Globalization
Module Module1
Sub Main()
PrintResultBo(False)
PrintResultBo(True)
PrintResultSB(1)
PrintResultBy(2)
PrintResultSh(3)
PrintResultUs(4)
PrintResultIn(5)
PrintResultUI(6)
PrintResultLo(7)
PrintResultUL(8)
'PrintResultDe(-9D)
PrintResultDe(0D)
'PrintResultDe(-1D)
PrintResultDe(1D)
PrintResultDe(14D)
PrintResultDe(79228162514264337593543950335D)
'PrintResultDe(-79228162514264337593543950335D)
'PrintResultDe(-9D)
PrintResultDe(0D)
'PrintResultDe(-1D)
PrintResultDe(1D)
PrintResultDe(14D)
PrintResultDe(79228162514264337593543950335D)
'PrintResultDe(-79228162514264337593543950335D)
PrintResultSi(10)
PrintResultDo(11)
PrintResultSt("12")
PrintResultOb(13)
PrintResultDa(#8/23/1970 3:45:39 AM#)
PrintResultDa(#12:00:00 AM#)
PrintResultDa(#8/23/1970 3:45:39 AM#)
PrintResultDa(#12:00:00 AM#)
PrintResultCh("v"c)
End Sub
Sub PrintResultBo(val As Boolean)
System.Console.WriteLine("Boolean: {0}", val)
End Sub
Sub PrintResultSB(val As SByte)
System.Console.WriteLine("SByte: {0}", val)
End Sub
Sub PrintResultBy(val As Byte)
System.Console.WriteLine("Byte: {0}", val)
End Sub
Sub PrintResultSh(val As Short)
System.Console.WriteLine("Short: {0}", val)
End Sub
Sub PrintResultUs(val As UShort)
System.Console.WriteLine("UShort: {0}", val)
End Sub
Sub PrintResultIn(val As Integer)
System.Console.WriteLine("Integer: {0}", val)
End Sub
Sub PrintResultUI(val As UInteger)
System.Console.WriteLine("UInteger: {0}", val)
End Sub
Sub PrintResultLo(val As Long)
System.Console.WriteLine("Long: {0}", val)
End Sub
Sub PrintResultUL(val As ULong)
System.Console.WriteLine("ULong: {0}", val)
End Sub
Sub PrintResultDe(val As Decimal)
System.Console.WriteLine("Decimal: {0}", val)
End Sub
Sub PrintResultSi(val As Single)
System.Console.WriteLine("Single: {0}", val)
End Sub
Sub PrintResultDo(val As Double)
System.Console.WriteLine("Double: {0}", val)
End Sub
Sub PrintResultDa(val As Date)
System.Console.WriteLine("Date: {0}", val.ToString("M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture))
End Sub
Sub PrintResultCh(val As Char)
System.Console.WriteLine("Char: {0}", val)
End Sub
Sub PrintResultSt(val As String)
System.Console.WriteLine("String: {0}", val)
End Sub
Sub PrintResultOb(val As Object)
System.Console.WriteLine("Object: {0}", val)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Boolean: False
Boolean: True
SByte: 1
Byte: 2
Short: 3
UShort: 4
Integer: 5
UInteger: 6
Long: 7
ULong: 8
Decimal: 0
Decimal: 1
Decimal: 14
Decimal: 79228162514264337593543950335
Decimal: 0
Decimal: 1
Decimal: 14
Decimal: 79228162514264337593543950335
Single: 10
Double: 11
String: 12
Object: 13
Date: 8/23/1970 3:45:39 AM
Date: 1/1/0001 12:00:00 AM
Date: 8/23/1970 3:45:39 AM
Date: 1/1/0001 12:00:00 AM
Char: v
]]>)
End Sub
<Fact()>
Public Sub Conversions01()
CompileAndVerify(
<compilation>
<file name="a.vb">
<%= EmitResourceUtil.ConversionsILGenTestSource %>
</file>
</compilation>,
expectedOutput:=EmitResourceUtil.ConversionsILGenTestBaseline)
End Sub
<Fact()>
Public Sub Conversions02()
CompileAndVerify(
<compilation>
<file name="a.vb">
<%= EmitResourceUtil.ConversionsILGenTestSource1 %>
</file>
</compilation>,
expectedOutput:=EmitResourceUtil.ConversionsILGenTestBaseline1)
End Sub
<Fact()>
Public Sub Conversions03()
CompileAndVerify(
<compilation>
<file name="a.vb">
<%= EmitResourceUtil.ConversionsILGenTestSource2 %>
</file>
</compilation>,
expectedOutput:=<![CDATA[
Conversions from Nothing literal:
Boolean: False
SByte: 0
Byte: 0
Short: 0
UShort: 0
Integer: 0
UInteger: 0
Long: 0
ULong: 0
Single: 0
Double: 0
Decimal: 0
Date: 1/1/0001 12:00:00 AM
String: []
Object: []
Guid: 00000000-0000-0000-0000-000000000000
IComparable: []
ValueType: []
String: []
Guid: 00000000-0000-0000-0000-000000000000
]]>)
End Sub
<Fact()>
Public Sub VirtualCalls()
CompileAndVerify(
<compilation>
<file name="a.vb">
public class M1
public class Boo1
public I1 As Integer
public I2 As Integer
public Sub New()
End Sub
End Class
public class Boo(Of T)
public Sub New()
End Sub
public Sub Moo(x as T)
Dim s1 as string = "hello"
' regular virtual
System.Console.Write(s1.GetType())
DIm iii as integer = 123
' constrained nongeneric
System.Console.Write(iii.GetType())
' regular call
System.Console.Write(iii.ToString())
' constrained generic
Dim s as String = x.ToString()
System.Console.WriteLine(s)
End Sub
End class
public Shared Sub Main()
DIm x as Boo1 = new Boo1()
Dim b as Boo(of Boo1) = new Boo(of Boo1)()
b.Moo(x)
End Sub
End Class
</file>
</compilation>,
expectedOutput:="System.StringSystem.Int32123M1+Boo1").
VerifyIL("M1.Boo(Of T).Moo",
<![CDATA[
{
// Code size 65 (0x41)
.maxstack 1
.locals init (Integer V_0) //iii
IL_0000: ldstr "hello"
IL_0005: callvirt "Function Object.GetType() As System.Type"
IL_000a: call "Sub System.Console.Write(Object)"
IL_000f: ldc.i4.s 123
IL_0011: stloc.0
IL_0012: ldloc.0
IL_0013: box "Integer"
IL_0018: call "Function Object.GetType() As System.Type"
IL_001d: call "Sub System.Console.Write(Object)"
IL_0022: ldloca.s V_0
IL_0024: call "Function Integer.ToString() As String"
IL_0029: call "Sub System.Console.Write(String)"
IL_002e: ldarga.s V_1
IL_0030: constrained. "T"
IL_0036: callvirt "Function Object.ToString() As String"
IL_003b: call "Sub System.Console.WriteLine(String)"
IL_0040: ret
}
]]>)
End Sub
<Fact()>
Public Sub BugInBranchShortening()
CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Module Program
Function moo() As Integer
console.writeline("hello")
Return 5
End Function
Sub Main(args As String())
Dim x As Integer = 0, xx = New Integer()
Dim y As Double = 234
Dim g As Long = 1234
Do While x < 5
If x < 1 Then
Dim s As String = "-1"
Console.Write(s)
ElseIf x < 2 Then
Dim s As String = "-2"
Console.Write(s)
ElseIf x < 3 Then
Dim s As String = "-3"
Console.Write(s)
Else
Dim s As String = "Else"
Dim blah As String = "Should only see in Else, but even Dev10 does not get this right"
Console.Write(s)
Console.Write(s)
End If
x = x + 1
Loop
Console.WriteLine()
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:="-1-2-3ElseElseElseElse")
End Sub
<Fact()>
Public Sub ShortCircuitingOperators()
CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module Program
Sub Main(args As String())
Dim x As Integer = 0, y As Double = 1234.567, z As Long = 12345
Do While x < 5 AndAlso z > 10
If x < 1 OrElse z > 1233 Then
Dim s As String = "-1"
Console.Write(s)
ElseIf x < 2 AndAlso z > 9 OrElse y > 12.34 Then
Dim s As String = "-2"
Console.Write(s)
Else
Dim s As String = "Else"
Console.Write(s)
End If
x = x + 1
z = z \ 10
y = y / 10
Loop
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:="-1-1-2Else")
End Sub
<Fact()>
Public Sub DifferentCaseScopeLocals()
CompileAndVerify(
<compilation>
<file name="xxx.yyy.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports VBN
Module Program
Sub Main(args As String())
Dim x As VBN.IGoo(Of Char, Char) = Nothing, y As CGoo(Of Char, Char), z As SGoo = Nothing, local As Boolean = True
y = New CGoo(Of Char, Char)()
Do
If y IsNot Nothing OrElse x IsNot Nothing Then
'x = DirectCast(y, IGoo(Of Char, Char))
y.ImplF1("q"c, "c"c)
Dim w As String = "If"
y = Nothing
ElseIf x Is Nothing AndAlso y Is Nothing AndAlso z.Field2 Is Nothing Then
z = New SGoo()
z.Field2 = New CGoo(Of SGoo, UShort)
z.Field2.ImplF2("Aa", "Bb", "Cc")
Dim w& = 11223344
Console.Write(w)
Else
SGoo.Field1 = 9D
Console.Write(SGoo.Field1)
Dim w As Boolean = False
Console.Write(w)
local = False
z.Field2.ImplF2("Booooooo")
End If
Loop While local
End Sub
End Module
]]></file>
<file name="Abc.123.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Namespace VBN
Public Interface IGoo(Of T, V)
Sub F1(ByRef x As T, ByVal y As V)
Function F2(ParamArray ary As String()) As String
End Interface
Class CGoo(Of T, V)
'Implements IGoo(Of T, V)
Public Sub ImplF1(ByRef x As T, ByVal y As V) 'Implements IGoo(Of T, V).F1
console.Write(String.Format("-ImpF1:{0},{1}-", x, y))
End Sub
Public Function ImplF2(ParamArray ary As String()) As String 'Implements IGoo(Of T, V).F2
If (ary IsNot Nothing) Then
Console.write("-ImpF2:{0}-", ary(0))
Else
console.write("-ImpF2:NoParam-")
End If
Return "F2"
End Function
End Class
Friend Structure SGoo
Public Shared Field1 As Decimal
Public Field2 As CGoo(Of SGoo, UShort)
End Structure
End Namespace
]]></file>
</compilation>,
expectedOutput:="-ImpF1:q,c--ImpF2:Aa-112233449False-ImpF2:Booooooo-")
End Sub
<Fact()>
Public Sub EnumBackingField()
CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Enum Enum1
A = 1
B
C
End Enum
Sub ChangeIt(ByRef x As Integer)
x = 3
End Sub
Sub Main()
Dim e1 as Enum1 = Enum1.A
e1.value__ = 2
ChangeIt(e1.value__)
System.Console.WriteLine(e1.ToString())
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:="C")
End Sub
#Region "Regressions"
<WorkItem(543277, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543277")>
<Fact()>
Public Sub Bug10931_1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Option Infer On
Imports System
Module Program
Sub Main(args As String())
Dim b = Function() Sub() Return
Goo(Of Func(Of Action(Of Integer)))(b)()(1)
End Sub
Function Goo(Of T)(x As T) As T
Return x
End Function
End Module
</file>
</compilation>,
expectedOutput:="")
End Sub
<WorkItem(538751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538751")>
<Fact()>
Public Sub AssertCondBranchWithLogicOperator()
CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Program
Public Function CompareDouble(ByVal arg1 As Double, ByVal arg2 As Double) As Boolean
Dim delta As Double = 12.1234566
If delta < arg2 Or delta > arg1 Then
Return True
Else
Return False
End If
End Function
Sub Main(args As String())
Dim arg1 As Double = 12.123456
Dim arg2 As Double = 12.1234567
Console.WriteLine(CompareDouble(arg1, arg2))
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:="True")
End Sub
<WorkItem(538752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538752")>
<Fact()>
Public Sub StructureDefaultAccessibilityPublic()
CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports Microsoft.VisualBasic
Namespace VBN
Structure myStruct
Dim x As Integer
Sub M()
Console.Write("PublicSub")
End Sub
End Structure
Module Program
Structure AnotherStruct
Dim y As String
Function Func(ByVal x As Integer) As Integer
Return x
End Function
End Structure
Sub Main()
Dim s1 As myStruct
s1.x = 400
s1.M()
Dim s2 As AnotherStruct
s2.y = "TestString"
Console.Write(s2.Func(s1.x))
End Sub
End Module
End Namespace
]]></file>
</compilation>,
expectedOutput:="PublicSub400")
End Sub
<WorkItem(538800, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538800")>
<Fact>
Public Sub ObjectComparisonWithNoReferenceToVBRuntime()
CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class Program
Sub Main()
Dim o As Object = Nothing
If o = o Then
Console.Write("Pass")
End If
End Sub
End Class
]]></file>
</compilation>, OutputKind.DynamicallyLinkedLibrary).
VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_MissingRuntimeHelper, "o = o").WithArguments("Microsoft.VisualBasic.CompilerServices.Operators.ConditionalCompareObjectEqual"))
End Sub
<Fact>
Public Sub ObjectComparisonWithNoReferenceToVBRuntime_1()
CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class Program
Sub Main()
Dim o As Object = Nothing
o = (o = o)
End Sub
End Class
]]></file>
</compilation>, OutputKind.DynamicallyLinkedLibrary).
VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_MissingRuntimeHelper, "o = o").WithArguments("Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectEqual"))
End Sub
<Fact>
Public Sub ObjectComparisonWithNoReferenceToVBRuntime_2()
CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class Program
Sub Main()
Dim o As Object = Nothing
Dim b As Boolean = (o = o)
End Sub
End Class
]]></file>
</compilation>, OutputKind.DynamicallyLinkedLibrary).
VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_MissingRuntimeHelper, "o = o").WithArguments("Microsoft.VisualBasic.CompilerServices.Operators.ConditionalCompareObjectEqual"))
End Sub
<Fact>
Public Sub ObjectComparisonWithNoReferenceToVBRuntime_3()
CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class Program
Sub Main()
Dim o As Object = Nothing
Dim b As Boolean? = (o = o)
End Sub
End Class
]]></file>
</compilation>, OutputKind.DynamicallyLinkedLibrary).
VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_MissingRuntimeHelper, "o = o").WithArguments("Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectEqual"))
End Sub
<WorkItem(538792, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538792")>
<Fact>
Public Sub InvokeGenericSharedMethods()
CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Public Class c1(Of T) ' Generics
Public Shared Sub test()
Console.WriteLine("Pass")
End Sub
End Class
Module Program
Sub Main()
c1(Of String).test()
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:="Pass")
End Sub
<WorkItem(538865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538865")>
<Fact>
Public Sub TestGetObjectValueCalls()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Class TestClass1
Sub New(x As Object)
End Sub
End Class
Module Module1
Sub M()
Dim o As Object
Dim a As Object() = Nothing
o = a(1)
End Sub
Sub PassByRef(ByRef x As Object)
End Sub
Sub PassByVal(x As Object)
End Sub
Sub Test1(o As Object)
PassByRef(o)
End Sub
Sub Test2(o As Object)
PassByVal(o)
End Sub
Sub Test3(o As Object)
Dim t3 As TestClass1
t3 = New TestClass1(o)
End Sub
Sub Test4(o As Object)
PassByRef((o))
End Sub
Function Test4_1(o As Object) As Object
Return PropertiesWithByRef.P2(o)
End Function
Function Test4_2(o As Object) As Object
Return PropertiesWithByRef.P2((o))
End Function
Sub Test5(o As Object)
o = (o ^ o)
End Sub
Sub Test6(o As Object)
o = (-o)
End Sub
Sub Test7(o As Object)
o = (+o)
End Sub
Sub Test8(o As Object)
o = ((((o / o))))
End Sub
Sub Test9(o As Object)
o = (o Mod o)
End Sub
Sub Test10(o As Object)
o = (o \ o)
End Sub
Sub Test11(o As Object)
o = (o & o)
End Sub
Sub Test12(o As Object)
o = (Not o)
End Sub
Sub Test13(o As Object)
o = (o And o)
End Sub
Sub Test14(o As Object)
o = o AndAlso o
End Sub
Sub Test15(o As Object)
o = (o Or o)
End Sub
Sub Test16(o As Object)
o = o OrElse o
End Sub
Sub Test17(o As Object)
o = (o Xor o)
End Sub
Sub Test18(o As Object)
o = (o * o)
End Sub
Sub Test19(o As Object)
o = (o + o)
End Sub
Sub Test20(o As Object)
o = (o - o)
End Sub
Sub Test21(o As Object)
o = (o << o)
End Sub
Sub Test22(o As Object)
o = (o >> o)
End Sub
Sub Test23(o As Object)
o = (DirectCast(Nothing, String))
End Sub
Sub Test23_1(o As Object)
o = TryCast(TryCast(Nothing, String), Object)
End Sub
Sub Test23_2(o As Object)
o = CType(CType(Nothing, String), Object)
End Sub
Sub Test24(o As Object)
o = (DirectCast("x", Object))
End Sub
Sub Test25(o As Object)
o = (TryCast("x", Object))
End Sub
Sub Test26(o As Object)
o = (CType("x", Object))
End Sub
Sub Test27(o As Object)
o = (DirectCast(DirectCast(o, ValueType), Object))
End Sub
Sub Test28(o As Object)
o = (DirectCast(New Guid(), Object))
End Sub
Sub Test29(o As Object)
o = (CType(New Guid(), Object))
End Sub
Sub Test30(o As Object)
o = (TryCast(New Guid(), Object))
End Sub
Sub Test31(Of T)(o As Object, x As T)
o = (DirectCast(x, Object))
End Sub
Sub Test32(Of T)(o As Object, x As T)
o = (CType(x, Object))
End Sub
Sub Test33(Of T)(o As Object, x As T)
o = (TryCast(x, Object))
End Sub
End Module
Module Program1
Sub Test1()
Dim x As Object = 1
Dim s As Object
s = x
End Sub
Sub Test2()
Dim x As Object = 1
Dim s As Object = x
End Sub
Sub Test3()
Dim x As Object = 1
Dim s As Object = If(fun1(), x, 2)
End Sub
Sub Test4()
Dim x, y As New Object
End Sub
Sub Test5()
Dim x As Object = New Object
End Sub
Sub Test6()
Dim x As Object = 1
Dim y As Integer = P2(x)
End Sub
Sub Test7()
Dim x As System.ValueType = Nothing
PassByRef1(x)
End Sub
Sub Test8()
Dim x As System.Guid = Nothing
PassByRef1(x)
End Sub
Sub Test9()
Dim x As Object = Nothing
PassByRef2(x)
End Sub
Sub Test10()
Dim x As Object = Nothing
PassByRef3(x)
End Sub
Sub Test11()
PassByRef1(P1)
End Sub
Sub PassByRef1(ByRef x As Object)
End Sub
Sub PassByRef2(ByRef x As System.ValueType)
End Sub
Sub PassByRef3(ByRef x As System.Guid)
End Sub
Private Function fun1() As Object
return Nothing
End Function
Property P1 As Object
ReadOnly Property P2(x As Object) As Integer
Get
Return 1
End Get
End Property
End Module
</file>
</compilation>, references:={TestReferences.SymbolsTests.PropertiesWithByRef})
verifier.VerifyIL("Module1.M",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldnull
IL_0001: ldc.i4.1
IL_0002: ldelem.ref
IL_0003: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0008: pop
IL_0009: ret
}
]]>)
verifier.VerifyIL("Module1.Test1",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call "Sub Module1.PassByRef(ByRef Object)"
IL_0007: ret
}
]]>)
verifier.VerifyIL("Module1.Test2",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0006: call "Sub Module1.PassByVal(Object)"
IL_000b: ret
}
]]>)
verifier.VerifyIL("Module1.Test3",
<![CDATA[
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0006: newobj "Sub TestClass1..ctor(Object)"
IL_000b: pop
IL_000c: ret
}
]]>)
verifier.VerifyIL("Module1.Test4",
<![CDATA[
{
// Code size 15 (0xf)
.maxstack 1
.locals init (Object V_0)
IL_0000: ldarg.0
IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call "Sub Module1.PassByRef(ByRef Object)"
IL_000e: ret
}
]]>)
verifier.VerifyIL("Module1.Test4_1",
<![CDATA[
{
// Code size 15 (0xf)
.maxstack 1
.locals init (Object V_0)
IL_0000: ldarg.0
IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call "Function PropertiesWithByRef.get_P2(ByRef Object) As Object"
IL_000e: ret
}
]]>)
verifier.VerifyIL("Module1.Test4_2",
<![CDATA[
{
// Code size 15 (0xf)
.maxstack 1
.locals init (Object V_0)
IL_0000: ldarg.0
IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call "Function PropertiesWithByRef.get_P2(ByRef Object) As Object"
IL_000e: ret
}
]]>)
verifier.VerifyIL("Module1.Test5",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: call "Function Microsoft.VisualBasic.CompilerServices.Operators.ExponentObject(Object, Object) As Object"
IL_0007: starg.s V_0
IL_0009: ret
}
]]>)
verifier.VerifyIL("Module1.Test6",
<![CDATA[
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.CompilerServices.Operators.NegateObject(Object) As Object"
IL_0006: starg.s V_0
IL_0008: ret
}
]]>)
verifier.VerifyIL("Module1.Test7",
<![CDATA[
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.CompilerServices.Operators.PlusObject(Object) As Object"
IL_0006: starg.s V_0
IL_0008: ret
}
]]>)
verifier.VerifyIL("Module1.Test8",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: call "Function Microsoft.VisualBasic.CompilerServices.Operators.DivideObject(Object, Object) As Object"
IL_0007: starg.s V_0
IL_0009: ret
}
]]>)
verifier.VerifyIL("Module1.Test9",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: call "Function Microsoft.VisualBasic.CompilerServices.Operators.ModObject(Object, Object) As Object"
IL_0007: starg.s V_0
IL_0009: ret
}
]]>)
verifier.VerifyIL("Module1.Test10",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: call "Function Microsoft.VisualBasic.CompilerServices.Operators.IntDivideObject(Object, Object) As Object"
IL_0007: starg.s V_0
IL_0009: ret
}
]]>)
verifier.VerifyIL("Module1.Test11",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: call "Function Microsoft.VisualBasic.CompilerServices.Operators.ConcatenateObject(Object, Object) As Object"
IL_0007: starg.s V_0
IL_0009: ret
}
]]>)
verifier.VerifyIL("Module1.Test12",
<![CDATA[
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.CompilerServices.Operators.NotObject(Object) As Object"
IL_0006: starg.s V_0
IL_0008: ret
}
]]>)
verifier.VerifyIL("Module1.Test13",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AndObject(Object, Object) As Object"
IL_0007: starg.s V_0
IL_0009: ret
}
]]>)
verifier.VerifyIL("Module1.Test14",
<![CDATA[
{
// Code size 25 (0x19)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"
IL_0006: brfalse.s IL_0010
IL_0008: ldarg.0
IL_0009: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"
IL_000e: br.s IL_0011
IL_0010: ldc.i4.0
IL_0011: box "Boolean"
IL_0016: starg.s V_0
IL_0018: ret
}
]]>)
verifier.VerifyIL("Module1.Test15",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: call "Function Microsoft.VisualBasic.CompilerServices.Operators.OrObject(Object, Object) As Object"
IL_0007: starg.s V_0
IL_0009: ret
}
]]>)
verifier.VerifyIL("Module1.Test16",
<![CDATA[
{
// Code size 25 (0x19)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"
IL_0006: brtrue.s IL_0010
IL_0008: ldarg.0
IL_0009: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"
IL_000e: br.s IL_0011
IL_0010: ldc.i4.1
IL_0011: box "Boolean"
IL_0016: starg.s V_0
IL_0018: ret
}
]]>)
verifier.VerifyIL("Module1.Test17",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: call "Function Microsoft.VisualBasic.CompilerServices.Operators.XorObject(Object, Object) As Object"
IL_0007: starg.s V_0
IL_0009: ret
}
]]>)
verifier.VerifyIL("Module1.Test18",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: call "Function Microsoft.VisualBasic.CompilerServices.Operators.MultiplyObject(Object, Object) As Object"
IL_0007: starg.s V_0
IL_0009: ret
}
]]>)
verifier.VerifyIL("Module1.Test19",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object"
IL_0007: starg.s V_0
IL_0009: ret
}
]]>)
verifier.VerifyIL("Module1.Test20",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: call "Function Microsoft.VisualBasic.CompilerServices.Operators.SubtractObject(Object, Object) As Object"
IL_0007: starg.s V_0
IL_0009: ret
}
]]>)
verifier.VerifyIL("Module1.Test21",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: call "Function Microsoft.VisualBasic.CompilerServices.Operators.LeftShiftObject(Object, Object) As Object"
IL_0007: starg.s V_0
IL_0009: ret
}
]]>)
verifier.VerifyIL("Module1.Test22",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: call "Function Microsoft.VisualBasic.CompilerServices.Operators.RightShiftObject(Object, Object) As Object"
IL_0007: starg.s V_0
IL_0009: ret
}
]]>)
verifier.VerifyIL("Module1.Test23",
<![CDATA[
{
// Code size 4 (0x4)
.maxstack 1
IL_0000: ldnull
IL_0001: starg.s V_0
IL_0003: ret
}
]]>)
verifier.VerifyIL("Module1.Test23_1",
<![CDATA[
{
// Code size 4 (0x4)
.maxstack 1
IL_0000: ldnull
IL_0001: starg.s V_0
IL_0003: ret
}
]]>)
verifier.VerifyIL("Module1.Test23_2",
<![CDATA[
{
// Code size 4 (0x4)
.maxstack 1
IL_0000: ldnull
IL_0001: starg.s V_0
IL_0003: ret
}
]]>)
verifier.VerifyIL("Module1.Test24",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldstr "x"
IL_0005: starg.s V_0
IL_0007: ret
}
]]>)
verifier.VerifyIL("Module1.Test25",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldstr "x"
IL_0005: starg.s V_0
IL_0007: ret
}
]]>)
verifier.VerifyIL("Module1.Test26",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldstr "x"
IL_0005: starg.s V_0
IL_0007: ret
}
]]>)
verifier.VerifyIL("Module1.Test27",
<![CDATA[
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: ldarg.0
IL_0001: castclass "System.ValueType"
IL_0006: starg.s V_0
IL_0008: ret
}
]]>)
verifier.VerifyIL("Module1.Test28",
<![CDATA[
{
// Code size 17 (0x11)
.maxstack 1
.locals init (System.Guid V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj "System.Guid"
IL_0008: ldloc.0
IL_0009: box "System.Guid"
IL_000e: starg.s V_0
IL_0010: ret
}
]]>)
verifier.VerifyIL("Module1.Test29",
<![CDATA[
{
// Code size 17 (0x11)
.maxstack 1
.locals init (System.Guid V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj "System.Guid"
IL_0008: ldloc.0
IL_0009: box "System.Guid"
IL_000e: starg.s V_0
IL_0010: ret
}
]]>)
verifier.VerifyIL("Module1.Test30",
<![CDATA[
{
// Code size 17 (0x11)
.maxstack 1
.locals init (System.Guid V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj "System.Guid"
IL_0008: ldloc.0
IL_0009: box "System.Guid"
IL_000e: starg.s V_0
IL_0010: ret
}
]]>)
verifier.VerifyIL("Module1.Test31",
<![CDATA[
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: ldarg.1
IL_0001: box "T"
IL_0006: starg.s V_0
IL_0008: ret
}
]]>)
verifier.VerifyIL("Module1.Test32",
<![CDATA[
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: ldarg.1
IL_0001: box "T"
IL_0006: starg.s V_0
IL_0008: ret
}
]]>)
verifier.VerifyIL("Module1.Test33",
<![CDATA[
{
// Code size 14 (0xe)
.maxstack 1
IL_0000: ldarg.1
IL_0001: box "T"
IL_0006: isinst "Object"
IL_000b: starg.s V_0
IL_000d: ret
}
]]>)
verifier.VerifyIL("Program1.Test1",
<![CDATA[
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: box "Integer"
IL_0006: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_000b: pop
IL_000c: ret
}
]]>)
verifier.VerifyIL("Program1.Test2",
<![CDATA[
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: box "Integer"
IL_0006: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_000b: pop
IL_000c: ret
}
]]>)
verifier.VerifyIL("Program1.Test3",
<![CDATA[
{
// Code size 35 (0x23)
.maxstack 1
.locals init (Object V_0) //x
IL_0000: ldc.i4.1
IL_0001: box "Integer"
IL_0006: stloc.0
IL_0007: call "Function Program1.fun1() As Object"
IL_000c: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"
IL_0011: brtrue.s IL_001b
IL_0013: ldc.i4.2
IL_0014: box "Integer"
IL_0019: br.s IL_001c
IL_001b: ldloc.0
IL_001c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0021: pop
IL_0022: ret
}
]]>)
verifier.VerifyIL("Program1.Test4",
<![CDATA[
{
// Code size 23 (0x17)
.maxstack 1
IL_0000: newobj "Sub Object..ctor()"
IL_0005: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_000a: pop
IL_000b: newobj "Sub Object..ctor()"
IL_0010: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0015: pop
IL_0016: ret
}
]]>)
verifier.VerifyIL("Program1.Test5",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: newobj "Sub Object..ctor()"
IL_0005: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_000a: pop
IL_000b: ret
}
]]>)
verifier.VerifyIL("Program1.Test6",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: box "Integer"
IL_0006: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_000b: call "Function Program1.get_P2(Object) As Integer"
IL_0010: pop
IL_0011: ret
}
]]>)
verifier.VerifyIL("Program1.get_P1",
<![CDATA[
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldsfld "Program1._P1 As Object"
IL_0005: ret
}
]]>)
verifier.VerifyIL("Program1.set_P1",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0006: stsfld "Program1._P1 As Object"
IL_000b: ret
}
]]>)
verifier.VerifyIL("Program1.Test7",
<![CDATA[
{
// Code size 17 (0x11)
.maxstack 1
.locals init (Object V_0)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call "Sub Program1.PassByRef1(ByRef Object)"
IL_0009: ldloc.0
IL_000a: castclass "System.ValueType"
IL_000f: pop
IL_0010: ret
}
]]>)
verifier.VerifyIL("Program1.Test8",
<![CDATA[
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (System.Guid V_0,
Object V_1)
IL_0000: ldloca.s V_0
IL_0002: initobj "System.Guid"
IL_0008: ldloc.0
IL_0009: box "System.Guid"
IL_000e: stloc.1
IL_000f: ldloca.s V_1
IL_0011: call "Sub Program1.PassByRef1(ByRef Object)"
IL_0016: ldloc.1
IL_0017: dup
IL_0018: brtrue.s IL_0026
IL_001a: pop
IL_001b: ldloca.s V_0
IL_001d: initobj "System.Guid"
IL_0023: ldloc.0
IL_0024: br.s IL_002b
IL_0026: unbox.any "System.Guid"
IL_002b: pop
IL_002c: ret
}
]]>)
verifier.VerifyIL("Program1.Test9",
<![CDATA[
{
// Code size 17 (0x11)
.maxstack 1
.locals init (System.ValueType V_0)
IL_0000: ldnull
IL_0001: castclass "System.ValueType"
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call "Sub Program1.PassByRef2(ByRef System.ValueType)"
IL_000e: ldloc.0
IL_000f: pop
IL_0010: ret
}
]]>)
verifier.VerifyIL("Program1.Test10",
<![CDATA[
{
// Code size 37 (0x25)
.maxstack 2
.locals init (System.Guid V_0,
System.Guid V_1)
IL_0000: ldnull
IL_0001: dup
IL_0002: brtrue.s IL_0010
IL_0004: pop
IL_0005: ldloca.s V_1
IL_0007: initobj "System.Guid"
IL_000d: ldloc.1
IL_000e: br.s IL_0015
IL_0010: unbox.any "System.Guid"
IL_0015: stloc.0
IL_0016: ldloca.s V_0
IL_0018: call "Sub Program1.PassByRef3(ByRef System.Guid)"
IL_001d: ldloc.0
IL_001e: box "System.Guid"
IL_0023: pop
IL_0024: ret
}
]]>)
verifier.VerifyIL("Program1.Test11",
<![CDATA[
{
// Code size 30 (0x1e)
.maxstack 1
.locals init (Object V_0)
IL_0000: call "Function Program1.get_P1() As Object"
IL_0005: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_000a: stloc.0
IL_000b: ldloca.s V_0
IL_000d: call "Sub Program1.PassByRef1(ByRef Object)"
IL_0012: ldloc.0
IL_0013: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0018: call "Sub Program1.set_P1(Object)"
IL_001d: ret
}
]]>)
End Sub
<WorkItem(540882, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540882")>
<Fact>
Public Sub TestGetObjectValueCalls2()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Sub S()
Dim x As New Object
End Sub
Function Func1(x As Object) As Object
Return X
End Function
Function Func2() As Object
Dim x As New Object
Return X
End Function
End Module
</file>
</compilation>)
verifier.VerifyIL("Module1.S",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: newobj "Sub Object..ctor()"
IL_0005: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_000a: pop
IL_000b: ret
}
]]>)
verifier.VerifyIL("Module1.Func2",
<![CDATA[
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: newobj "Sub Object..ctor()"
IL_0005: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_000a: ret
}
]]>)
verifier.VerifyIL("Module1.Func1",
<![CDATA[
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}
]]>)
verifier.VerifyIL("Module1.Func2",
<![CDATA[
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: newobj "Sub Object..ctor()"
IL_0005: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_000a: ret
}
]]>)
End Sub
<WorkItem(538853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538853")>
<Fact>
Public Sub Bug4597()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Function Count() as integer
return 1
End Function
Sub M()
Dim arr As Integer() = New Integer(2147483647) {}
Dim arr1 As Integer() = New Integer(Count()) {}
Dim arr2 As Integer() = New Integer(-1) {}
End Sub
End Module
</file>
</compilation>).
VerifyIL("M1.M",
<![CDATA[
{
// Code size 32 (0x20)
.maxstack 2
IL_0000: ldc.i4 0x80000000
IL_0005: newarr "Integer"
IL_000a: pop
IL_000b: call "Function M1.Count() As Integer"
IL_0010: ldc.i4.1
IL_0011: add.ovf
IL_0012: newarr "Integer"
IL_0017: pop
IL_0018: ldc.i4.0
IL_0019: newarr "Integer"
IL_001e: pop
IL_001f: ret
}
]]>)
End Sub
<WorkItem(538852, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538852")>
<Fact>
Public Sub Bug4596()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Function Count() as integer
return 1
End Function
Sub M()
Dim by As Byte() = New Byte() {0, 127, 223, 128, 220}
Dim d As Double() = New Double() {1.1F, 2.2F, -3.3F / 0, 4.4F, -5.5F}
Dim b As Boolean() = New Boolean() {True, False, True, False, True}
Dim c As Char() = New Char() {"a"c, "b"c, "c"c, "d"c, "e"c}
End Sub
End Module
</file>
</compilation>, options:=TestOptions.ReleaseDll.WithModuleName("MODULE")).
VerifyIL("M1.M",
<![CDATA[
{
// Code size 73 (0x49)
.maxstack 3
IL_0000: ldc.i4.5
IL_0001: newarr "Byte"
IL_0006: dup
IL_0007: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=5 <PrivateImplementationDetails>.5BD81897B38CE00BCF990B5AED9316FE43E7A3854DA09401C14DF4AF21B2F90D"
IL_000c: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"
IL_0011: pop
IL_0012: ldc.i4.5
IL_0013: newarr "Double"
IL_0018: dup
IL_0019: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=40 <PrivateImplementationDetails>.F9D819AD50107F52959882DF3549DE08003AC644DCC12AFEA2B9BD936EE7D325"
IL_001e: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"
IL_0023: pop
IL_0024: ldc.i4.5
IL_0025: newarr "Boolean"
IL_002a: dup
IL_002b: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=5 <PrivateImplementationDetails>.A4E9167DC11A5B8BA7E09C85BAFDEA0B6E0B399CE50086545509017050B33097"
IL_0030: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"
IL_0035: pop
IL_0036: ldc.i4.5
IL_0037: newarr "Char"
IL_003c: dup
IL_003d: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=10 <PrivateImplementationDetails>.DC0F42A41F058686A364AF5B6BD49175C5B2CF3C4D5AE95417448BE3517B4008"
IL_0042: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"
IL_0047: pop
IL_0048: ret
}
]]>)
End Sub
<Fact>
Public Sub ArrayInitFromBlobEnum()
CompileAndVerify(
<compilation>
<file name="a.vb">
Module M1
Sub M()
Dim x As System.TypeCode() = {
System.TypeCode.Boolean,
System.TypeCode.Byte,
System.TypeCode.Char,
System.TypeCode.DateTime,
System.TypeCode.DBNull}
End Sub
End Module
</file>
</compilation>).
VerifyIL("M1.M",
<![CDATA[
{
// Code size 29 (0x1d)
.maxstack 4
IL_0000: ldc.i4.5
IL_0001: newarr "System.TypeCode"
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4.3
IL_0009: stelem.i4
IL_000a: dup
IL_000b: ldc.i4.1
IL_000c: ldc.i4.6
IL_000d: stelem.i4
IL_000e: dup
IL_000f: ldc.i4.2
IL_0010: ldc.i4.4
IL_0011: stelem.i4
IL_0012: dup
IL_0013: ldc.i4.3
IL_0014: ldc.i4.s 16
IL_0016: stelem.i4
IL_0017: dup
IL_0018: ldc.i4.4
IL_0019: ldc.i4.2
IL_001a: stelem.i4
IL_001b: pop
IL_001c: ret
}
]]>)
End Sub
<Fact>
Public Sub ArrayInitFromBlobEnumNetFx45()
' In NetFx 4.5 and higher, we can use fast literal initialization for enums
CompileAndVerify(CreateCompilationWithMscorlib45AndVBRuntime(
<compilation>
<file name="a.vb">
Module M1
Sub M()
Dim x As System.TypeCode() = {
System.TypeCode.Boolean,
System.TypeCode.Byte,
System.TypeCode.Char,
System.TypeCode.DateTime,
System.TypeCode.DBNull}
End Sub
End Module
</file>
</compilation>, options:=TestOptions.ReleaseDll.WithModuleName("MODULE"))).VerifyIL("M1.M",
<![CDATA[
{
// Code size 19 (0x13)
.maxstack 3
IL_0000: ldc.i4.5
IL_0001: newarr "System.TypeCode"
IL_0006: dup
IL_0007: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=20 <PrivateImplementationDetails>.095C4722BB84316FEEE41ADFDAFED13FECA8836A520BDE3AB77C52F5C9F6B620"
IL_000c: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"
IL_0011: pop
IL_0012: ret
}
]]>)
End Sub
<Fact>
Public Sub TryCastAndPropertyAccess()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class Clazz
Public Property Prop As String
End Class
Module M1
Sub M()
Dim c As New Clazz()
Dim d = TryCast(c.Prop, Object)
End Sub
End Module
</file>
</compilation>).
VerifyIL("M1.M",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: newobj "Sub Clazz..ctor()"
IL_0005: callvirt "Function Clazz.get_Prop() As String"
IL_000a: pop
IL_000b: ret
}
]]>)
End Sub
''' <summary>
''' Won't fix :(
''' </summary>
''' <remarks></remarks>
<Fact, WorkItem(527773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527773")>
Public Sub ConstantLiteralToDecimal()
CompileAndVerify(
<compilation>
<file name="a.b.vb"><![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Program
Sub Main()
Print(0) ' ldc.i4.0 - decimal.ctor(int32)
Print(1) ' ldc.i4.1 - decimal.ctor(int32)
Print(8) ' ldc.i4.8 - decimal.ctor(int32)
Print(-1) ' ldc.i4.m1 - decimal.ctor(int32)
Print(-128) ' ldc.i4.s - decimal.ctor(int32)
Print(2147483647) ' ldc.i4 - - decimal.ctor(int32)
Print(-2147483648) ' ldc.i4 - - decimal.ctor(int32)
Print(4294967295) ' ldc.i4 - - decimal.ctor(uint32)
Print(9223372036854775807) ' ldc.i8 - decimal.ctor(int64)
Print(-9223372036854775807) ' ldc.i8 - decimal.ctor(int64)
Print(18446744073709551615UL) ' ldc.i8 - decimal.ctor(uint64)
Print(-79228162514264337593543950335D) ' decimal.ctor(int32, int32, int32, bool, byte)
Print(12345.679F) '? ldc.r4 - decimal.ctor(Single)
End Sub
Public Sub Print(ByVal val As Decimal)
Console.WriteLine(val)
End Sub
End Module
]]></file>
</compilation>).
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 192 (0xc0)
.maxstack 5
IL_0000: ldsfld "Decimal.Zero As Decimal"
IL_0005: call "Sub Program.Print(Decimal)"
IL_000a: ldsfld "Decimal.One As Decimal"
IL_000f: call "Sub Program.Print(Decimal)"
IL_0014: ldc.i4.8
IL_0015: conv.i8
IL_0016: newobj "Sub Decimal..ctor(Long)"
IL_001b: call "Sub Program.Print(Decimal)"
IL_0020: ldsfld "Decimal.MinusOne As Decimal"
IL_0025: call "Sub Program.Print(Decimal)"
IL_002a: ldc.i4.s -128
IL_002c: conv.i8
IL_002d: newobj "Sub Decimal..ctor(Long)"
IL_0032: call "Sub Program.Print(Decimal)"
IL_0037: ldc.i4 0x7fffffff
IL_003c: conv.i8
IL_003d: newobj "Sub Decimal..ctor(Long)"
IL_0042: call "Sub Program.Print(Decimal)"
IL_0047: ldc.i4 0x80000000
IL_004c: conv.i8
IL_004d: newobj "Sub Decimal..ctor(Long)"
IL_0052: call "Sub Program.Print(Decimal)"
IL_0057: ldc.i4.m1
IL_0058: conv.u8
IL_0059: newobj "Sub Decimal..ctor(Long)"
IL_005e: call "Sub Program.Print(Decimal)"
IL_0063: ldc.i4.m1
IL_0064: ldc.i4 0x7fffffff
IL_0069: ldc.i4.0
IL_006a: ldc.i4.0
IL_006b: ldc.i4.0
IL_006c: newobj "Sub Decimal..ctor(Integer, Integer, Integer, Boolean, Byte)"
IL_0071: call "Sub Program.Print(Decimal)"
IL_0076: ldc.i4.m1
IL_0077: ldc.i4 0x7fffffff
IL_007c: ldc.i4.0
IL_007d: ldc.i4.1
IL_007e: ldc.i4.0
IL_007f: newobj "Sub Decimal..ctor(Integer, Integer, Integer, Boolean, Byte)"
IL_0084: call "Sub Program.Print(Decimal)"
IL_0089: ldc.i4.m1
IL_008a: ldc.i4.m1
IL_008b: ldc.i4.0
IL_008c: ldc.i4.0
IL_008d: ldc.i4.0
IL_008e: newobj "Sub Decimal..ctor(Integer, Integer, Integer, Boolean, Byte)"
IL_0093: call "Sub Program.Print(Decimal)"
IL_0098: ldc.i4.m1
IL_0099: ldc.i4.m1
IL_009a: ldc.i4.m1
IL_009b: ldc.i4.1
IL_009c: ldc.i4.0
IL_009d: newobj "Sub Decimal..ctor(Integer, Integer, Integer, Boolean, Byte)"
IL_00a2: call "Sub Program.Print(Decimal)"
IL_00a7: ldc.i4 0x85f0d5ff
IL_00ac: ldc.i4 0x7048
IL_00b1: ldc.i4.0
IL_00b2: ldc.i4.0
IL_00b3: ldc.i4.s 10
IL_00b5: newobj "Sub Decimal..ctor(Integer, Integer, Integer, Boolean, Byte)"
IL_00ba: call "Sub Program.Print(Decimal)"
IL_00bf: ret
}
]]>)
End Sub
#End Region
<Fact>
Public Sub Enum1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Enum E1
x = 42
y
End Enum
Module M1
Sub Main()
Console.Write(E1.x)
Console.Write(E1.y)
Console.Write(System.Enum.Parse(E1.y.GetType(), "42"))
End Sub
End Module
</file>
</compilation>,
expectedOutput:="4243x").
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 47 (0x2f)
.maxstack 2
IL_0000: ldc.i4.s 42
IL_0002: call "Sub System.Console.Write(Integer)"
IL_0007: ldc.i4.s 43
IL_0009: call "Sub System.Console.Write(Integer)"
IL_000e: ldc.i4.s 43
IL_0010: box "E1"
IL_0015: call "Function Object.GetType() As System.Type"
IL_001a: ldstr "42"
IL_001f: call "Function System.Enum.Parse(System.Type, String) As Object"
IL_0024: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0029: call "Sub System.Console.Write(Object)"
IL_002e: ret
}
]]>)
End Sub
<Fact>
Public Sub CallsOnConst()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub Main()
Console.Write(42.ToString())
Console.Write(42.GetType())
Console.Write(Integer.MaxValue.ToString())
Console.Write(Integer.MaxValue.GetType())
End Sub
End Module
</file>
</compilation>,
expectedOutput:=" 42System.Int322147483647System.Int32").
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 71 (0x47)
.maxstack 1
.locals init (Integer V_0)
IL_0000: ldc.i4.s 42
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: call "Function Integer.ToString() As String"
IL_000a: call "Sub System.Console.Write(String)"
IL_000f: ldc.i4.s 42
IL_0011: box "Integer"
IL_0016: call "Function Object.GetType() As System.Type"
IL_001b: call "Sub System.Console.Write(Object)"
IL_0020: ldc.i4 0x7fffffff
IL_0025: stloc.0
IL_0026: ldloca.s V_0
IL_0028: call "Function Integer.ToString() As String"
IL_002d: call "Sub System.Console.Write(String)"
IL_0032: ldc.i4 0x7fffffff
IL_0037: box "Integer"
IL_003c: call "Function Object.GetType() As System.Type"
IL_0041: call "Sub System.Console.Write(Object)"
IL_0046: ret
}
]]>)
End Sub
<WorkItem(539920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539920")>
<Fact>
Public Sub TestNestedFunctionLambdas()
CompileAndVerify(
<compilation>
<file name="Program.vb">
Imports System
Module Program
Sub Main()
Goo(Function(x) Function() x)
End Sub
Sub Goo(x As Func(Of String, Func(Of String)))
Console.WriteLine(x.Invoke("ABC").Invoke().ToLower())
End Sub
End Module
</file>
</compilation>,
expectedOutput:="abc")
End Sub
<WorkItem(540121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540121")>
<Fact>
Public Sub TestEmitBinaryTrueAndFalseExpressionForDebug()
CompileAndVerify(
<compilation>
<file name="Module1.vb">
Module Module1
Sub Main()
If True And False Then
End If
End Sub
End Module
</file>
</compilation>,
expectedOutput:="")
End Sub
<WorkItem(540121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540121")>
<Fact>
Public Sub BooleanAndOrInDebug()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Module M1
Sub Main()
Dim b1 As Boolean = True
Dim b2 As Boolean = False
If b1 And b2 Then
End If
If False Or True Then
End If
If False And True Then
End If
End Sub
End Module
</file>
</compilation>,
options:=TestOptions.DebugExe,
expectedOutput:="")
c.VerifyIL("M1.Main", "
{
// Code size 25 (0x19)
.maxstack 2
.locals init (Boolean V_0, //b1
Boolean V_1, //b2
Boolean V_2,
Boolean V_3,
Boolean V_4)
-IL_0000: nop
-IL_0001: ldc.i4.1
IL_0002: stloc.0
-IL_0003: ldc.i4.0
IL_0004: stloc.1
-IL_0005: ldloc.0
IL_0006: ldloc.1
IL_0007: and
IL_0008: stloc.2
~IL_0009: ldloc.2
IL_000a: brfalse.s IL_000d
-IL_000c: nop
-IL_000d: nop
-IL_000e: ldc.i4.1
IL_000f: stloc.3
-IL_0010: nop
-IL_0011: nop
-IL_0012: ldc.i4.0
IL_0013: stloc.s V_4
IL_0015: br.s IL_0017
-IL_0017: nop
-IL_0018: ret
}
", sequencePoints:="M1.Main")
End Sub
<Fact>
Public Sub ForLoopSimple()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub Main()
For i as integer = 1 to 10 step 1
i = i + 1
Console.Write(i)
Next
End Sub
End Module
</file>
</compilation>,
expectedOutput:="246810").
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 22 (0x16)
.maxstack 2
.locals init (Integer V_0) //i
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.1
IL_0004: add.ovf
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: call "Sub System.Console.Write(Integer)"
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: add.ovf
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: ldc.i4.s 10
IL_0013: ble.s IL_0002
IL_0015: ret
}
]]>)
End Sub
<Fact>
Public Sub ForLoopSimple1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Dim i as integer = 42
Sub Main()
For i = 1 to 10 step 1
i = i + 1
Console.Write(i)
Next
End Sub
End Module
</file>
</compilation>,
expectedOutput:="246810").
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 50 (0x32)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: stsfld "M1.i As Integer"
IL_0006: ldsfld "M1.i As Integer"
IL_000b: ldc.i4.1
IL_000c: add.ovf
IL_000d: stsfld "M1.i As Integer"
IL_0012: ldsfld "M1.i As Integer"
IL_0017: call "Sub System.Console.Write(Integer)"
IL_001c: ldsfld "M1.i As Integer"
IL_0021: ldc.i4.1
IL_0022: add.ovf
IL_0023: stsfld "M1.i As Integer"
IL_0028: ldsfld "M1.i As Integer"
IL_002d: ldc.i4.s 10
IL_002f: ble.s IL_0006
IL_0031: ret
}
]]>)
End Sub
<Fact>
Public Sub ForLoopSimple2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Dim i as integer = 42
Sub Main()
For i = 1 to 20 step 1
if i > 10
exit for
End if
if i mod 2 = 0
Console.Write(i)
Continue For
end if
Next
End Sub
End Module
</file>
</compilation>,
expectedOutput:="246810").
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 56 (0x38)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: stsfld "M1.i As Integer"
IL_0006: ldsfld "M1.i As Integer"
IL_000b: ldc.i4.s 10
IL_000d: bgt.s IL_0037
IL_000f: ldsfld "M1.i As Integer"
IL_0014: ldc.i4.2
IL_0015: rem
IL_0016: brtrue.s IL_0022
IL_0018: ldsfld "M1.i As Integer"
IL_001d: call "Sub System.Console.Write(Integer)"
IL_0022: ldsfld "M1.i As Integer"
IL_0027: ldc.i4.1
IL_0028: add.ovf
IL_0029: stsfld "M1.i As Integer"
IL_002e: ldsfld "M1.i As Integer"
IL_0033: ldc.i4.s 20
IL_0035: ble.s IL_0006
IL_0037: ret
}
]]>)
End Sub
<Fact>
Public Sub ForLoopNonConst()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Dim p1 As Integer
Sub Main()
p1 = 3
For p1 = 6 To p1 * 4 Step p1 - 2
Console.Write(p1)
Next
Console.Write(" ")
Console.Write(p1)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="6789101112 13").
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 91 (0x5b)
.maxstack 3
.locals init (Integer V_0,
Integer V_1)
IL_0000: ldc.i4.3
IL_0001: stsfld "M1.p1 As Integer"
IL_0006: ldsfld "M1.p1 As Integer"
IL_000b: ldc.i4.4
IL_000c: mul.ovf
IL_000d: stloc.0
IL_000e: ldsfld "M1.p1 As Integer"
IL_0013: ldc.i4.2
IL_0014: sub.ovf
IL_0015: stloc.1
IL_0016: ldc.i4.6
IL_0017: stsfld "M1.p1 As Integer"
IL_001c: br.s IL_0034
IL_001e: ldsfld "M1.p1 As Integer"
IL_0023: call "Sub System.Console.Write(Integer)"
IL_0028: ldsfld "M1.p1 As Integer"
IL_002d: ldloc.1
IL_002e: add.ovf
IL_002f: stsfld "M1.p1 As Integer"
IL_0034: ldloc.1
IL_0035: ldc.i4.s 31
IL_0037: shr
IL_0038: ldsfld "M1.p1 As Integer"
IL_003d: xor
IL_003e: ldloc.1
IL_003f: ldc.i4.s 31
IL_0041: shr
IL_0042: ldloc.0
IL_0043: xor
IL_0044: ble.s IL_001e
IL_0046: ldstr " "
IL_004b: call "Sub System.Console.Write(String)"
IL_0050: ldsfld "M1.p1 As Integer"
IL_0055: call "Sub System.Console.Write(Integer)"
IL_005a: ret
}
]]>)
End Sub
<WorkItem(540443, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540443")>
<Fact>
Public Sub LoadReadOnlyField()
CompileAndVerify(
<compilation>
<file name="a.vb">
Class A
Public ReadOnly Value As Integer
Public Sub New(v As Integer)
Value = v
Value.ToString
End Sub
Public Overrides Function ToString() As String
Return Value.ToString()
End Function
private sub goo(byref x as integer)
end sub
private sub moo()
goo(Value)
end sub
End Class
</file>
</compilation>).
VerifyIL("A.ToString",
<![CDATA[
{
// Code size 15 (0xf)
.maxstack 1
.locals init (Integer V_0)
IL_0000: ldarg.0
IL_0001: ldfld "A.Value As Integer"
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call "Function Integer.ToString() As String"
IL_000e: ret
}
]]>).
VerifyIL("A..ctor",
<![CDATA[
{
// Code size 26 (0x1a)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call "Sub Object..ctor()"
IL_0006: ldarg.0
IL_0007: ldarg.1
IL_0008: stfld "A.Value As Integer"
IL_000d: ldarg.0
IL_000e: ldflda "A.Value As Integer"
IL_0013: call "Function Integer.ToString() As String"
IL_0018: pop
IL_0019: ret
}
]]>).
VerifyIL("A.moo",
<![CDATA[
{
// Code size 16 (0x10)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld "A.Value As Integer"
IL_0007: stloc.0
IL_0008: ldloca.s V_0
IL_000a: call "Sub A.goo(ByRef Integer)"
IL_000f: ret
}
]]>)
End Sub
<Fact>
Public Sub ConstByRef()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Dim i as integer = 42
Sub Main()
Goo(Integer.MaxValue)
End Sub
Sub Goo(ByRef x as integer)
x = 42
End Sub
End Module
</file>
</compilation>,
expectedOutput:="").
VerifyIL("M1.Main",
<![CDATA[
{
// Code size 14 (0xe)
.maxstack 1
.locals init (Integer V_0)
IL_0000: ldc.i4 0x7fffffff
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call "Sub M1.Goo(ByRef Integer)"
IL_000d: ret
}
]]>)
End Sub
' Constructor initializers don't bind yet
<WorkItem(7926, "DevDiv_Projects/Roslyn")>
<WorkItem(541123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541123")>
<Fact>
Public Sub StructDefaultConstructorInitializer()
CompileAndVerify(
<compilation>
<file name="a.vb">
Structure S
Public Sub New(x As Integer)
Me.New() ' Note: not allowed in Dev10
End Sub
End Structure
</file>
</compilation>).
VerifyIL("S..ctor(Integer)",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: initobj "S"
IL_0007: ret
}
]]>)
End Sub
<Fact>
Public Sub StructConstructorCallWithSideEffects()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class C1
Public Sub New(s As String)
Console.WriteLine("C1.New(""" + s + """)")
End Sub
Public Property P As String
Get
Console.WriteLine("C1.P.Get")
Return Nothing
End Get
Set(value As String)
Console.WriteLine("C1.P.Set")
End Set
End Property
End Class
Structure S1
Public Shared FLD As C1 = New C1("S1.FLD")
Public Sub New(x As C1)
Me.New(x.P)
Console.WriteLine("S1.New(x As C1)")
End Sub
Public Sub New(ByRef x As String)
Console.WriteLine("S1.New(x As String)")
End Sub
Shared Sub Main()
Dim s1 As S1 = New S1(FLD)
End Sub
End Structure
</file>
</compilation>, expectedOutput:=<![CDATA[
C1.New("S1.FLD")
C1.P.Get
S1.New(x As String)
C1.P.Set
S1.New(x As C1)
]]>).
VerifyIL("S1..cctor()",
<![CDATA[
{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldstr "S1.FLD"
IL_0005: newobj "Sub C1..ctor(String)"
IL_000a: stsfld "S1.FLD As C1"
IL_000f: ret
}
]]>).
VerifyIL("S1..ctor(C1)",
<![CDATA[
{
// Code size 35 (0x23)
.maxstack 3
.locals init (C1 V_0,
String V_1)
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: dup
IL_0003: stloc.0
IL_0004: callvirt "Function C1.get_P() As String"
IL_0009: stloc.1
IL_000a: ldloca.s V_1
IL_000c: call "Sub S1..ctor(ByRef String)"
IL_0011: ldloc.0
IL_0012: ldloc.1
IL_0013: callvirt "Sub C1.set_P(String)"
IL_0018: ldstr "S1.New(x As C1)"
IL_001d: call "Sub System.Console.WriteLine(String)"
IL_0022: ret
}
]]>).
VerifyIL("S1..ctor(ByRef String)",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 1
IL_0000: ldarg.0
IL_0001: initobj "S1"
IL_0007: ldstr "S1.New(x As String)"
IL_000c: call "Sub System.Console.WriteLine(String)"
IL_0011: ret
}
]]>)
End Sub
<WorkItem(543751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543751")>
<Fact>
Public Sub StructConstructorWithOptionalParametersCSVB()
Dim csCompilation = CreateCSharpCompilation("CSDll",
<![CDATA[
using System;
public struct SymbolModifiers
{
public SymbolModifiers(bool isStatic = true, bool isSupa = true)
{
Console.Write("isStatic = " + isStatic.ToString() + ", isSupa = " + isSupa.ToString() + "; ");
}
}
]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("VBDll",
<![CDATA[
Class S
Shared Sub Main(args() As String)
Dim z1 = New SymbolModifiers(isSupa:=False)
Dim z2 = New SymbolModifiers(isStatic:=False)
Dim z3 = New SymbolModifiers()
End Sub
End Class
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
Dim vbexeVerifier = CompileAndVerify(vbCompilation,
expectedOutput:="isStatic = True, isSupa = False; isStatic = False, isSupa = True; ")
vbexeVerifier.VerifyDiagnostics()
End Sub
<WorkItem(543751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543751")>
<Fact>
Public Sub StructConstructorWithOptionalParametersVBVB()
Dim vbCompilationA = CreateVisualBasicCompilation("VBDllA",
<![CDATA[
Imports System
Public Structure STRUCT
Public Sub New(Optional ByVal x As Integer = 0)
Console.WriteLine("Public Sub New(Optional ByVal x As Integer = 0)")
End Sub
End Structure
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
vbCompilationA.VerifyDiagnostics()
Dim vbCompilationB = CreateVisualBasicCompilation("VBExeB",
<![CDATA[
Class S
Shared Sub Main(args() As String)
Dim z1 = New STRUCT(1)
Dim z2 = New STRUCT()
End Sub
End Class
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={vbCompilationA})
Dim vbexeVerifier = CompileAndVerify(vbCompilationB,
expectedOutput:="Public Sub New(Optional ByVal x As Integer = 0)")
vbexeVerifier.VerifyDiagnostics()
End Sub
<WorkItem(543751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543751")>
<Fact>
Public Sub StructConstructorWithOptionalParametersVBVB2()
Dim vbCompilationA = CreateVisualBasicCompilation("VBDllA",
<![CDATA[
Imports System
Public Structure STRUCT
Public Sub New(ParamArray x() As Integer)
Console.WriteLine("ParamArray x() As Integer")
End Sub
End Structure
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
vbCompilationA.VerifyDiagnostics()
Dim vbCompilationB = CreateVisualBasicCompilation("VBExeB",
<![CDATA[
Class S
Shared Sub Main(args() As String)
Dim z1 = New STRUCT(1)
Dim z2 = New STRUCT()
End Sub
End Class
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={vbCompilationA})
Dim vbexeVerifier = CompileAndVerify(vbCompilationB,
expectedOutput:="ParamArray x() As Integer")
vbexeVerifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub OverridingFunctionsOverloadedOnOptionalParameters()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class base
Public Overridable Sub f(x As Integer)
Console.WriteLine("BASE: Public Overridable Sub f(x As Integer)")
End Sub
Public Overridable Sub f(x As Integer, Optional y As Integer = 0)
Console.WriteLine("BASE: Public Overridable Sub f(x As Integer, Optional y As Integer = 0)")
End Sub
Public Overridable Sub f(x As Integer, Optional y As String = "")
Console.WriteLine("BASE: Public Overridable Sub f(x As Integer, Optional y As String = """")")
End Sub
End Class
Class derived
Inherits base
Public Overrides Sub f(x As Integer)
Console.WriteLine("DERIVED: Public Overridable Sub f(x As Integer)")
End Sub
Public Overrides Sub f(x As Integer, Optional y As Integer = 0)
Console.WriteLine("DERIVED: Public Overridable Sub f(x As Integer, Optional y As Integer = 0)")
End Sub
Public Overrides Sub f(x As Integer, Optional y As String = "")
Console.WriteLine("DERIVED: Public Overridable Sub f(x As Integer, Optional y As String = """")")
End Sub
End Class
Module Program
Sub Main(args As String())
Test(New base)
Test(New derived)
End Sub
Sub Test(b As base)
b.f(1)
b.f(1, 2)
b.f(1, "")
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[
BASE: Public Overridable Sub f(x As Integer)
BASE: Public Overridable Sub f(x As Integer, Optional y As Integer = 0)
BASE: Public Overridable Sub f(x As Integer, Optional y As String = "")
DERIVED: Public Overridable Sub f(x As Integer)
DERIVED: Public Overridable Sub f(x As Integer, Optional y As Integer = 0)
DERIVED: Public Overridable Sub f(x As Integer, Optional y As String = "")
]]>)
End Sub
<Fact>
Public Sub OverridingFunctionsOverloadedOnOptionalParameters2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class base1
Public Overridable Sub f(x As Integer)
Console.WriteLine("BASE1: f(x As Integer)")
End Sub
Public Overridable Sub f(x As Integer, Optional y As String = "")
Console.WriteLine("BASE1: f(x As Integer, Optional y As String = """")")
End Sub
End Class
Class base2
Inherits base1
Public Overridable Overloads Sub f(x As Integer, Optional y As Integer = 0)
Console.WriteLine("BASE2: f(x As Integer, Optional y As Integer = 0)")
End Sub
End Class
Class derived
Inherits base2
Public Overrides Sub f(x As Integer)
Console.WriteLine("DERIVED: f(x As Integer)")
End Sub
Public Overrides Sub f(x As Integer, Optional y As Integer = 0)
Console.WriteLine("DERIVED: f(x As Integer, Optional y As Integer = 0)")
End Sub
Public Overrides Sub f(x As Integer, Optional y As String = "")
Console.WriteLine("DERIVED: f(x As Integer, Optional y As String = """")")
End Sub
End Class
Module Program
Sub Main(args As String())
Test(New base2)
Test(New derived)
End Sub
Sub Test(b As base2)
b.f(1)
b.f(1, 2)
b.f(1, "")
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[
BASE2: f(x As Integer, Optional y As Integer = 0)
BASE2: f(x As Integer, Optional y As Integer = 0)
BASE1: f(x As Integer, Optional y As String = "")
DERIVED: f(x As Integer, Optional y As Integer = 0)
DERIVED: f(x As Integer, Optional y As Integer = 0)
DERIVED: f(x As Integer, Optional y As String = "")
]]>)
End Sub
<WorkItem(543751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543751")>
<Fact>
Public Sub OverloadsWithOnlyOptionalParameters()
Dim csCompilation = CreateCSharpCompilation("CSDll",
<![CDATA[
using System;
public class OverloadsUsingOptional
{
public static void M(int k, int l = 0)
{
Console.Write("M(int k, int l = 0);");
}
public static void M(int k, int l = 0, int m = 0)
{
Console.Write("M(int k, int l = 0, int m = 0);");
}
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("VBDll",
<![CDATA[
Class S
Shared Sub Main(args() As String)
OverloadsUsingOptional.M(1, 2)
OverloadsUsingOptional.M(1, 2, 3)
End Sub
End Class
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
Dim vbexeVerifier = CompileAndVerify(vbCompilation,
expectedOutput:="M(int k, int l = 0);M(int k, int l = 0, int m = 0);")
vbexeVerifier.VerifyDiagnostics()
End Sub
<WorkItem(543751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543751")>
<Fact>
Public Sub OverloadsWithOnlyOptionalParameters2()
Dim csCompilation = CreateCSharpCompilation("CSDll",
<![CDATA[
using System;
public class OverloadsUsingOptional
{
public static void M(int k, int l = 0)
{
Console.Write("M(int k, int l = 0);");
}
public static void M(int k, int l = 0, int m = 0)
{
Console.Write("M(int k, int l = 0, int m = 0);");
}
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("VBDll",
<![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class S
Shared Sub Main(args() As String)
OverloadsUsingOptional.M(1)
End Sub
End Class
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
CompilationUtils.AssertTheseDiagnostics(vbCompilation,
<errors>
BC30521: Overload resolution failed because no accessible 'M' is most specific for these arguments:
'Public Shared Overloads Sub M(k As Integer, [l As Integer = 0])': Not most specific.
'Public Shared Overloads Sub M(k As Integer, [l As Integer = 0], [m As Integer = 0])': Not most specific.
OverloadsUsingOptional.M(1)
~
</errors>)
End Sub
<Fact>
Public Sub StructureConstructorsWithOptionalAndParamArrayParameters()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Namespace N
Structure A
Public Sub New(Optional x As Integer = 0)
Console.Write("New(Optional x As Integer = 0);")
End Sub
Public Sub New(ParamArray x As Integer())
Console.Write("New(ParamArray x As Integer());")
End Sub
Public Shared Sub Main()
Dim a1 As New A
Dim a2 As New A(1)
Dim a3 As New A(1, 2)
End Sub
End Structure
End Namespace
</file>
</compilation>, expectedOutput:="New(Optional x As Integer = 0);New(ParamArray x As Integer());")
End Sub
<Fact>
Public Sub HidingBySignatureWithOptionalParameters()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
MustInherit Class A
Public MustOverride Sub f(Optional x As String = "")
End Class
MustInherit Class B
Inherits A
Public MustOverride Overloads Sub f()
End Class
Class C
Inherits B
Public Overloads Overrides Sub f(Optional x As String = "")
Console.Write("f(Optional x As String = "");")
End Sub
Public Overloads Overrides Sub f()
Console.Write("f();")
End Sub
Public Shared Sub Main()
Dim c As New C
c.f()
c.f("")
End Sub
End Class
</file>
</compilation>, expectedOutput:="f();f(Optional x As String = "");")
End Sub
<Fact>
Public Sub HidingBySignatureWithOptionalParameters2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class A
Public Overridable Sub f(Optional x As String = "")
End Sub
End Class
Class B
Inherits A
Public Overridable Overloads Sub f()
End Sub
End Class
Class BB
Inherits B
Private Overloads Sub f()
End Sub
Private Overloads Sub f(Optional x As String = "")
End Sub
End Class
Class C
Inherits BB
Public Overloads Overrides Sub f(Optional x As String = "")
Console.Write("f(Optional x As String = "");")
End Sub
Public Overloads Overrides Sub f()
Console.Write("f();")
End Sub
Public Shared Sub Main()
Dim c As New C
c.f()
c.f("")
End Sub
End Class
</file>
</compilation>, expectedOutput:="f();f(Optional x As String = "");")
End Sub
<Fact>
Public Sub ImplicitStructParameterlessConstructorCallWithMe()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Structure S1
Public Sub New(x As Integer)
End Sub
Shared Sub Main()
End Sub
End Structure
</file>
</compilation>).
VerifyIL("S1..ctor(Integer)",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: initobj "S1"
IL_0007: ret
}
]]>)
End Sub
<Fact>
Public Sub ExplicitStructParameterlessConstructorCallWithMe()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Structure S1
Public Sub New(x As Integer)
Me.New()
End Sub
Shared Sub Main()
End Sub
End Structure
</file>
</compilation>).
VerifyIL("S1..ctor(Integer)",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: initobj "S1"
IL_0007: ret
}
]]>)
End Sub
<WorkItem(7926, "DevDiv_Projects/Roslyn")>
<WorkItem(541123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541123")>
<Fact>
Public Sub StructNonDefaultConstructorInitializer()
CompileAndVerify(
<compilation>
<file name="a.vb">
Structure S
Public Sub New(x As Integer)
End Sub
Public Sub New(x As Integer, y as String)
Me.New(x)
End Sub
End Structure
</file>
</compilation>).
VerifyIL("S..ctor(Integer, String)",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call "Sub S..ctor(Integer)"
IL_0007: ret
}
]]>)
End Sub
<Fact>
Public Sub PartiallyInitializedValue_PublicConstructor_Fields()
Dim vbSource =
<compilation>
<file name="a.vb">
Imports System
Structure S
Public Sub New(i As Integer)
End Sub
End Structure
Class C
Dim Fld As S
Dim FldArr(4) As S
Sub M()
Me.Fld = New S(1)
Me.FldArr(1) = New S(1)
Try
Me.Fld = New S(1)
Me.FldArr(1) = New S(1)
Catch ex As Exception
End Try
End Sub
End Class
</file>
</compilation>
CompileAndVerify(vbSource).
VerifyIL("C.M",
<![CDATA[
{
// Code size 77 (0x4d)
.maxstack 3
.locals init (System.Exception V_0) //ex
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: newobj "Sub S..ctor(Integer)"
IL_0007: stfld "C.Fld As S"
IL_000c: ldarg.0
IL_000d: ldfld "C.FldArr As S()"
IL_0012: ldc.i4.1
IL_0013: ldc.i4.1
IL_0014: newobj "Sub S..ctor(Integer)"
IL_0019: stelem "S"
.try
{
IL_001e: ldarg.0
IL_001f: ldc.i4.1
IL_0020: newobj "Sub S..ctor(Integer)"
IL_0025: stfld "C.Fld As S"
IL_002a: ldarg.0
IL_002b: ldfld "C.FldArr As S()"
IL_0030: ldc.i4.1
IL_0031: ldc.i4.1
IL_0032: newobj "Sub S..ctor(Integer)"
IL_0037: stelem "S"
IL_003c: leave.s IL_004c
}
catch System.Exception
{
IL_003e: dup
IL_003f: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0044: stloc.0
IL_0045: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_004a: leave.s IL_004c
}
IL_004c: ret
}
]]>)
End Sub
<Fact>
Public Sub PartiallyInitializedValue_PublicConstructor_Locals()
Dim vbSource =
<compilation>
<file name="a.vb">
Imports System
Structure S
Public Sub New(i As Integer)
End Sub
End Structure
Class C
Sub M()
Dim loc As S
Dim locArr(4) As S
loc = New S(1)
locArr(1) = New S(1)
Try
loc = New S(1)
locArr(1) = New S(1)
Catch ex As Exception
End Try
End Sub
End Class
</file>
</compilation>
CompileAndVerify(vbSource).
VerifyIL("C.M",
<![CDATA[
{
// Code size 64 (0x40)
.maxstack 3
.locals init (S() V_0, //locArr
System.Exception V_1) //ex
IL_0000: ldc.i4.5
IL_0001: newarr "S"
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: newobj "Sub S..ctor(Integer)"
IL_000d: pop
IL_000e: ldloc.0
IL_000f: ldc.i4.1
IL_0010: ldc.i4.1
IL_0011: newobj "Sub S..ctor(Integer)"
IL_0016: stelem "S"
.try
{
IL_001b: ldc.i4.1
IL_001c: newobj "Sub S..ctor(Integer)"
IL_0021: pop
IL_0022: ldloc.0
IL_0023: ldc.i4.1
IL_0024: ldc.i4.1
IL_0025: newobj "Sub S..ctor(Integer)"
IL_002a: stelem "S"
IL_002f: leave.s IL_003f
}
catch System.Exception
{
IL_0031: dup
IL_0032: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0037: stloc.1
IL_0038: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_003d: leave.s IL_003f
}
IL_003f: ret
}
]]>)
End Sub
<Fact>
Public Sub PartiallyInitializedValue_PublicConstructor_LocalInLoop()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Structure S
Public x As Integer
Public y As Integer
Public Sub New(_x As Integer)
Me.x = _x
Throw New System.Exception()
End Sub
Public Sub New(_x As Integer, _y As Integer)
Me.x = _x
Me.y = _y
End Sub
End Structure
Class C
Shared Sub Main()
Dim i As Integer = 0
While i < 2
Try
Dim a As S
Console.WriteLine("x={0}, y={1}", a.x, a.y)
a = New S(i+1, 2)
a = New S(10)
Catch ex As Exception
End Try
i = i + 1
End While
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[
x=0, y=0
x=1, y=2
]]>).
VerifyIL("C.Main",
<![CDATA[
{
// Code size 80 (0x50)
.maxstack 3
.locals init (Integer V_0, //i
S V_1, //a
System.Exception V_2) //ex
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: br.s IL_004b
IL_0004: nop
.try
{
IL_0005: ldstr "x={0}, y={1}"
IL_000a: ldloc.1
IL_000b: ldfld "S.x As Integer"
IL_0010: box "Integer"
IL_0015: ldloc.1
IL_0016: ldfld "S.y As Integer"
IL_001b: box "Integer"
IL_0020: call "Sub System.Console.WriteLine(String, Object, Object)"
IL_0025: ldloc.0
IL_0026: ldc.i4.1
IL_0027: add.ovf
IL_0028: ldc.i4.2
IL_0029: newobj "Sub S..ctor(Integer, Integer)"
IL_002e: stloc.1
IL_002f: ldc.i4.s 10
IL_0031: newobj "Sub S..ctor(Integer)"
IL_0036: stloc.1
IL_0037: leave.s IL_0047
}
catch System.Exception
{
IL_0039: dup
IL_003a: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_003f: stloc.2
IL_0040: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0045: leave.s IL_0047
}
IL_0047: ldloc.0
IL_0048: ldc.i4.1
IL_0049: add.ovf
IL_004a: stloc.0
IL_004b: ldloc.0
IL_004c: ldc.i4.2
IL_004d: blt.s IL_0004
IL_004f: ret
}
]]>)
End Sub
<Fact>
Public Sub PartiallyInitializedValue_PublicConstructor_LocalDeclaration()
Dim vbSource =
<compilation>
<file name="a.vb">
Imports System
Structure S
Public Sub New(i As Integer)
End Sub
End Structure
Class C
Sub M()
Try
Dim loc1 As New S(1) ' cannot escape because cannot be used before declaration
Dim loc2 As S = New S(1) ' cannot escape because cannot be used before declaration
loc1 = New S(1) ' can escape
Catch ex As Exception
End Try
End Sub
End Class
</file>
</compilation>
CompileAndVerify(vbSource).
VerifyIL("C.M",
<![CDATA[
{
// Code size 38 (0x26)
.maxstack 2
.locals init (System.Exception V_0) //ex
.try
{
IL_0000: ldc.i4.1
IL_0001: newobj "Sub S..ctor(Integer)"
IL_0006: pop
IL_0007: ldc.i4.1
IL_0008: newobj "Sub S..ctor(Integer)"
IL_000d: pop
IL_000e: ldc.i4.1
IL_000f: newobj "Sub S..ctor(Integer)"
IL_0014: pop
IL_0015: leave.s IL_0025
}
catch System.Exception
{
IL_0017: dup
IL_0018: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_001d: stloc.0
IL_001e: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0023: leave.s IL_0025
}
IL_0025: ret
}
]]>)
End Sub
<Fact>
Public Sub PartiallyInitializedValue_PublicConstructor_LocalDeclaration_SideEffects()
Dim vbSource =
<compilation>
<file name="a.vb">
Imports System
Structure S
Public Sub New(ByRef i As Integer)
End Sub
End Structure
Class C
Property AutoProp As Integer
Sub M()
Dim loc0 As New S(AutoProp) ' cannot escape
loc0 = New S(AutoProp) ' cannot escape
Try
Dim loc1 As New S(AutoProp) ' cannot escape because cannot be used before declaration
loc1 = New S(AutoProp) ' can escape
Catch ex As Exception
End Try
End Sub
End Class
</file>
</compilation>
' NOTE: Current implementation does not support optimization for constructor calls with side effects
CompileAndVerify(vbSource).
VerifyIL("C.M",
<![CDATA[
{
// Code size 105 (0x69)
.maxstack 3
.locals init (Integer V_0,
System.Exception V_1) //ex
IL_0000: ldarg.0
IL_0001: call "Function C.get_AutoProp() As Integer"
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: newobj "Sub S..ctor(ByRef Integer)"
IL_000e: ldarg.0
IL_000f: ldloc.0
IL_0010: call "Sub C.set_AutoProp(Integer)"
IL_0015: pop
IL_0016: ldarg.0
IL_0017: call "Function C.get_AutoProp() As Integer"
IL_001c: stloc.0
IL_001d: ldloca.s V_0
IL_001f: newobj "Sub S..ctor(ByRef Integer)"
IL_0024: ldarg.0
IL_0025: ldloc.0
IL_0026: call "Sub C.set_AutoProp(Integer)"
IL_002b: pop
.try
{
IL_002c: ldarg.0
IL_002d: call "Function C.get_AutoProp() As Integer"
IL_0032: stloc.0
IL_0033: ldloca.s V_0
IL_0035: newobj "Sub S..ctor(ByRef Integer)"
IL_003a: ldarg.0
IL_003b: ldloc.0
IL_003c: call "Sub C.set_AutoProp(Integer)"
IL_0041: pop
IL_0042: ldarg.0
IL_0043: call "Function C.get_AutoProp() As Integer"
IL_0048: stloc.0
IL_0049: ldloca.s V_0
IL_004b: newobj "Sub S..ctor(ByRef Integer)"
IL_0050: ldarg.0
IL_0051: ldloc.0
IL_0052: call "Sub C.set_AutoProp(Integer)"
IL_0057: pop
IL_0058: leave.s IL_0068
}
catch System.Exception
{
IL_005a: dup
IL_005b: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0060: stloc.1
IL_0061: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0066: leave.s IL_0068
}
IL_0068: ret
}
]]>)
End Sub
<Fact>
Public Sub PartiallyInitializedValue_PublicConstructor_Params()
Dim vbSource =
<compilation>
<file name="a.vb">
Imports System
Structure S
Public Sub New(i As Integer)
End Sub
End Structure
Class C
Sub M(paramByVal As S, ByRef paramByRef As S)
paramByVal = New S(1)
paramByRef = New S(1)
Try
paramByVal = New S(1)
paramByRef = New S(1)
Catch ex As Exception
End Try
End Sub
End Class
</file>
</compilation>
CompileAndVerify(vbSource).
VerifyIL("C.M",
<![CDATA[
{
// Code size 57 (0x39)
.maxstack 2
.locals init (System.Exception V_0) //ex
IL_0000: ldarga.s V_1
IL_0002: ldc.i4.1
IL_0003: call "Sub S..ctor(Integer)"
IL_0008: ldarg.2
IL_0009: ldc.i4.1
IL_000a: newobj "Sub S..ctor(Integer)"
IL_000f: stobj "S"
.try
{
IL_0014: ldc.i4.1
IL_0015: newobj "Sub S..ctor(Integer)"
IL_001a: starg.s V_1
IL_001c: ldarg.2
IL_001d: ldc.i4.1
IL_001e: newobj "Sub S..ctor(Integer)"
IL_0023: stobj "S"
IL_0028: leave.s IL_0038
}
catch System.Exception
{
IL_002a: dup
IL_002b: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0030: stloc.0
IL_0031: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0036: leave.s IL_0038
}
IL_0038: ret
}
]]>)
End Sub
<Fact>
Public Sub PartiallyInitializedValue_PublicParameterlessConstructor_Fields()
Dim ilSource = <![CDATA[
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.pack 0
.size 1
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ret
}
}
]]>
Dim vbSource =
<compilation>
<file name="a.vb">
Imports System
Class C
Dim Fld As S
Dim FldArr(4) As S
Sub M()
Me.Fld = New S()
Me.FldArr(1) = New S()
Try
Me.Fld = New S()
Me.FldArr(1) = New S()
Catch ex As Exception
End Try
End Sub
End Class
</file>
</compilation>
CompileWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDll).
VerifyIL("C.M",
<![CDATA[
{
// Code size 73 (0x49)
.maxstack 3
.locals init (System.Exception V_0) //ex
IL_0000: ldarg.0
IL_0001: newobj "Sub S..ctor()"
IL_0006: stfld "C.Fld As S"
IL_000b: ldarg.0
IL_000c: ldfld "C.FldArr As S()"
IL_0011: ldc.i4.1
IL_0012: newobj "Sub S..ctor()"
IL_0017: stelem "S"
.try
{
IL_001c: ldarg.0
IL_001d: newobj "Sub S..ctor()"
IL_0022: stfld "C.Fld As S"
IL_0027: ldarg.0
IL_0028: ldfld "C.FldArr As S()"
IL_002d: ldc.i4.1
IL_002e: newobj "Sub S..ctor()"
IL_0033: stelem "S"
IL_0038: leave.s IL_0048
}
catch System.Exception
{
IL_003a: dup
IL_003b: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0040: stloc.0
IL_0041: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0046: leave.s IL_0048
}
IL_0048: ret
}
]]>)
End Sub
<Fact>
Public Sub PartiallyInitializedValue_PublicParameterlessConstructor_Locals()
Dim ilSource = <![CDATA[
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.pack 0
.size 1
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ret
}
}
]]>
Dim vbSource =
<compilation>
<file name="a.vb">
Imports System
Class C
Sub M()
Dim loc As S
Dim locArr(4) As S
loc = New S()
locArr(1) = New S()
Try
loc = New S()
locArr(1) = New S()
Catch ex As Exception
End Try
End Sub
End Class
</file>
</compilation>
CompileWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDll).
VerifyIL("C.M",
<![CDATA[
{
// Code size 60 (0x3c)
.maxstack 3
.locals init (S() V_0, //locArr
System.Exception V_1) //ex
IL_0000: ldc.i4.5
IL_0001: newarr "S"
IL_0006: stloc.0
IL_0007: newobj "Sub S..ctor()"
IL_000c: pop
IL_000d: ldloc.0
IL_000e: ldc.i4.1
IL_000f: newobj "Sub S..ctor()"
IL_0014: stelem "S"
.try
{
IL_0019: newobj "Sub S..ctor()"
IL_001e: pop
IL_001f: ldloc.0
IL_0020: ldc.i4.1
IL_0021: newobj "Sub S..ctor()"
IL_0026: stelem "S"
IL_002b: leave.s IL_003b
}
catch System.Exception
{
IL_002d: dup
IL_002e: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0033: stloc.1
IL_0034: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0039: leave.s IL_003b
}
IL_003b: ret
}
]]>)
End Sub
<Fact>
Public Sub PartiallyInitializedValue_PublicParameterlessConstructor_Params()
Dim ilSource = <![CDATA[
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.pack 0
.size 1
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ret
}
}
]]>
Dim vbSource =
<compilation>
<file name="a.vb">
Imports System
Class C
Sub M(paramByVal As S, ByRef paramByRef As S)
paramByVal = New S()
paramByRef = New S()
Try
paramByVal = New S()
paramByRef = New S()
Catch ex As Exception
End Try
End Sub
End Class
</file>
</compilation>
' TODO (tomat): verification fails
CompileWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDll).
VerifyIL("C.M",
<![CDATA[
{
// Code size 53 (0x35)
.maxstack 2
.locals init (System.Exception V_0) //ex
IL_0000: ldarga.s V_1
IL_0002: call "Sub S..ctor()"
IL_0007: ldarg.2
IL_0008: newobj "Sub S..ctor()"
IL_000d: stobj "S"
.try
{
IL_0012: newobj "Sub S..ctor()"
IL_0017: starg.s V_1
IL_0019: ldarg.2
IL_001a: newobj "Sub S..ctor()"
IL_001f: stobj "S"
IL_0024: leave.s IL_0034
}
catch System.Exception
{
IL_0026: dup
IL_0027: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_002c: stloc.0
IL_002d: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0032: leave.s IL_0034
}
IL_0034: ret
}
]]>)
End Sub
<Fact>
Public Sub PartiallyInitializedValue_NoParameterlessConstructor_Fields()
Dim ilSource = <![CDATA[
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.pack 0
.size 1
}
]]>
Dim vbSource =
<compilation>
<file name="a.vb">
Imports System
Class C
Dim Fld As S
Dim FldArr(4) As S
Sub M()
Me.Fld = New S()
Me.FldArr(1) = New S()
Try
Me.Fld = New S()
Me.FldArr(1) = New S()
Catch ex As Exception
End Try
End Sub
End Class
</file>
</compilation>
CompileWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDll).
VerifyIL("C.M",
<![CDATA[
{
// Code size 77 (0x4d)
.maxstack 2
.locals init (System.Exception V_0) //ex
IL_0000: ldarg.0
IL_0001: ldflda "C.Fld As S"
IL_0006: initobj "S"
IL_000c: ldarg.0
IL_000d: ldfld "C.FldArr As S()"
IL_0012: ldc.i4.1
IL_0013: ldelema "S"
IL_0018: initobj "S"
.try
{
IL_001e: ldarg.0
IL_001f: ldflda "C.Fld As S"
IL_0024: initobj "S"
IL_002a: ldarg.0
IL_002b: ldfld "C.FldArr As S()"
IL_0030: ldc.i4.1
IL_0031: ldelema "S"
IL_0036: initobj "S"
IL_003c: leave.s IL_004c
}
catch System.Exception
{
IL_003e: dup
IL_003f: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0044: stloc.0
IL_0045: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_004a: leave.s IL_004c
}
IL_004c: ret
}
]]>)
End Sub
<Fact>
Public Sub PartiallyInitializedValue_NoParameterlessConstructor_Locals()
Dim ilSource = <![CDATA[
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.pack 0
.size 1
}
]]>
Dim vbSource =
<compilation>
<file name="a.vb">
Imports System
Class C
Sub M()
Dim loc As S
Dim locArr(4) As S
loc = New S()
locArr(1) = New S()
Try
loc = New S()
locArr(1) = New S()
Catch ex As Exception
End Try
End Sub
End Class
</file>
</compilation>
CompileWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDll).
VerifyIL("C.M",
<![CDATA[
{
// Code size 50 (0x32)
.maxstack 2
.locals init (S() V_0, //locArr
System.Exception V_1) //ex
IL_0000: ldc.i4.5
IL_0001: newarr "S"
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: ldelema "S"
IL_000e: initobj "S"
.try
{
IL_0014: ldloc.0
IL_0015: ldc.i4.1
IL_0016: ldelema "S"
IL_001b: initobj "S"
IL_0021: leave.s IL_0031
}
catch System.Exception
{
IL_0023: dup
IL_0024: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0029: stloc.1
IL_002a: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_002f: leave.s IL_0031
}
IL_0031: ret
}
]]>)
End Sub
<Fact>
Public Sub PartiallyInitializedValue_NoParameterlessConstructor_Params()
Dim ilSource = <![CDATA[
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.pack 0
.size 1
}
]]>
Dim vbSource =
<compilation>
<file name="a.vb">
Imports System
Class C
Sub M(paramByVal As S, ByRef paramByRef As S)
paramByVal = New S()
paramByRef = New S()
Try
paramByVal = New S()
paramByRef = New S()
Catch ex As Exception
End Try
End Sub
End Class
</file>
</compilation>
CompileWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDll).
VerifyIL("C.M",
<![CDATA[
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (System.Exception V_0) //ex
IL_0000: ldarga.s V_1
IL_0002: initobj "S"
IL_0008: ldarg.2
IL_0009: initobj "S"
.try
{
IL_000f: ldarga.s V_1
IL_0011: initobj "S"
IL_0017: ldarg.2
IL_0018: initobj "S"
IL_001e: leave.s IL_002e
}
catch System.Exception
{
IL_0020: dup
IL_0021: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0026: stloc.0
IL_0027: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_002c: leave.s IL_002e
}
IL_002e: ret
}
]]>)
End Sub
<WorkItem(541123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541123")>
<WorkItem(541308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541308")>
<Fact>
Public Sub PublicParameterlessConstructorInMetadata_Public()
Dim ilSource = <![CDATA[
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.pack 0
.size 1
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ret
}
}
]]>
Dim vbSource =
<compilation>
<file name="a.vb">
Option Infer Off
Class C
Shared Sub Main()
Dim s As S = New S()
s = Nothing
s = New S()
SS(Nothing)
SS(New S())
Dim a = (New S()).ToString()
s = DirectCast(Nothing, S)
End Sub
Shared Sub SS(s As S)
End Sub
End Class
</file>
</compilation>
CompileWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDll).
VerifyIL("C.Main",
<![CDATA[
{
// Code size 64 (0x40)
.maxstack 1
.locals init (S V_0)
IL_0000: newobj "Sub S..ctor()"
IL_0005: pop
IL_0006: newobj "Sub S..ctor()"
IL_000b: pop
IL_000c: ldloca.s V_0
IL_000e: initobj "S"
IL_0014: ldloc.0
IL_0015: call "Sub C.SS(S)"
IL_001a: newobj "Sub S..ctor()"
IL_001f: call "Sub C.SS(S)"
IL_0024: newobj "Sub S..ctor()"
IL_0029: stloc.0
IL_002a: ldloca.s V_0
IL_002c: constrained. "S"
IL_0032: callvirt "Function System.ValueType.ToString() As String"
IL_0037: pop
IL_0038: ldnull
IL_0039: unbox.any "S"
IL_003e: pop
IL_003f: ret
}
]]>)
End Sub
<WorkItem(541308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541308")>
<Fact>
Public Sub PublicParameterlessConstructorInMetadata_Protected()
Dim ilSource = <![CDATA[
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.pack 0
.size 1
.method family hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ret
}
}
]]>
Dim vbSource =
<compilation>
<file name="a.vb">
Option Infer Off
Class C
Shared Sub Main()
Dim s As S = New S()
s = Nothing
s = New S()
SS(Nothing)
SS(New S())
Dim a = (New S()).ToString()
s = DirectCast(Nothing, S)
End Sub
Shared Sub SS(s As S)
End Sub
End Class
</file>
</compilation>
CompileWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDll).
VerifyIL("C.Main",
<![CDATA[
{
// Code size 60 (0x3c)
.maxstack 1
.locals init (S V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj "S"
IL_0008: ldloc.0
IL_0009: call "Sub C.SS(S)"
IL_000e: ldloca.s V_0
IL_0010: initobj "S"
IL_0016: ldloc.0
IL_0017: call "Sub C.SS(S)"
IL_001c: ldloca.s V_0
IL_001e: initobj "S"
IL_0024: ldloc.0
IL_0025: stloc.0
IL_0026: ldloca.s V_0
IL_0028: constrained. "S"
IL_002e: callvirt "Function System.ValueType.ToString() As String"
IL_0033: pop
IL_0034: ldnull
IL_0035: unbox.any "S"
IL_003a: pop
IL_003b: ret
}
]]>)
End Sub
<WorkItem(541308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541308")>
<Fact>
Public Sub PublicParameterlessConstructorInMetadata_Private()
Dim ilSource = <![CDATA[
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.pack 0
.size 1
.method private hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ret
}
}
]]>
Dim vbSource =
<compilation>
<file name="a.vb">
Option Infer Off
Class C
Shared Sub Main()
Dim s As S = New S()
s = Nothing
s = New S()
SS(Nothing)
SS(New S())
Dim a = (New S()).ToString()
s = DirectCast(Nothing, S)
End Sub
Shared Sub SS(s As S)
End Sub
End Class
</file>
</compilation>
CompileWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDll).
VerifyIL("C.Main",
<![CDATA[
{
// Code size 60 (0x3c)
.maxstack 1
.locals init (S V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj "S"
IL_0008: ldloc.0
IL_0009: call "Sub C.SS(S)"
IL_000e: ldloca.s V_0
IL_0010: initobj "S"
IL_0016: ldloc.0
IL_0017: call "Sub C.SS(S)"
IL_001c: ldloca.s V_0
IL_001e: initobj "S"
IL_0024: ldloc.0
IL_0025: stloc.0
IL_0026: ldloca.s V_0
IL_0028: constrained. "S"
IL_002e: callvirt "Function System.ValueType.ToString() As String"
IL_0033: pop
IL_0034: ldnull
IL_0035: unbox.any "S"
IL_003a: pop
IL_003b: ret
}
]]>)
End Sub
<Fact>
Public Sub PublicParameterlessConstructorInMetadata_Private_D()
Dim ilSource = <![CDATA[
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.pack 0
.size 1
.method private hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ret
}
}
]]>
Dim vbSource =
<compilation>
<file name="a.vb">
Option Infer Off
Class C
Shared Sub Main()
Dim s As S = New S()
s = Nothing
s = New S()
SS(Nothing)
SS(New S())
Dim a = (New S()).ToString()
s = DirectCast(Nothing, S)
End Sub
Shared Sub SS(s As S)
End Sub
End Class
</file>
</compilation>
CompileWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDebugDll).
VerifyIL("C.Main",
<![CDATA[
{
// Code size 84 (0x54)
.maxstack 1
.locals init (S V_0, //s
Object V_1, //a
S V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj "S"
IL_0008: ldloca.s V_0
IL_000a: initobj "S"
IL_0010: ldloca.s V_0
IL_0012: initobj "S"
IL_0018: ldloca.s V_2
IL_001a: initobj "S"
IL_0020: ldloc.2
IL_0021: call "Sub C.SS(S)"
IL_0026: ldloca.s V_2
IL_0028: initobj "S"
IL_002e: ldloc.2
IL_002f: call "Sub C.SS(S)"
IL_0034: ldloca.s V_2
IL_0036: initobj "S"
IL_003c: ldloc.2
IL_003d: stloc.2
IL_003e: ldloca.s V_2
IL_0040: constrained. "S"
IL_0046: callvirt "Function System.ValueType.ToString() As String"
IL_004b: stloc.1
IL_004c: ldnull
IL_004d: unbox.any "S"
IL_0052: stloc.0
IL_0053: ret
}
]]>)
End Sub
<WorkItem(541308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541308")>
<Fact>
Public Sub PublicParameterlessConstructorInMetadata_OptionalParameter()
Dim ilSource = <![CDATA[
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.pack 0
.size 1
.method private hidebysig specialname rtspecialname
instance void .ctor([opt] int32 a) cil managed
{
.param [2] = int32(0x0000007B)
ret
}
}
]]>
Dim vbSource =
<compilation>
<file name="a.vb">
Option Infer Off
Class C
Shared Sub Main()
Dim s As S = New S()
s = Nothing
s = New S()
SS(Nothing)
SS(New S())
Dim a = (New S()).ToString()
s = DirectCast(Nothing, S)
End Sub
Shared Sub SS(s As S)
End Sub
End Class
</file>
</compilation>
CompileWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDll).
VerifyIL("C.Main",
<![CDATA[
{
// Code size 60 (0x3c)
.maxstack 1
.locals init (S V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj "S"
IL_0008: ldloc.0
IL_0009: call "Sub C.SS(S)"
IL_000e: ldloca.s V_0
IL_0010: initobj "S"
IL_0016: ldloc.0
IL_0017: call "Sub C.SS(S)"
IL_001c: ldloca.s V_0
IL_001e: initobj "S"
IL_0024: ldloc.0
IL_0025: stloc.0
IL_0026: ldloca.s V_0
IL_0028: constrained. "S"
IL_002e: callvirt "Function System.ValueType.ToString() As String"
IL_0033: pop
IL_0034: ldnull
IL_0035: unbox.any "S"
IL_003a: pop
IL_003b: ret
}
]]>)
End Sub
<WorkItem(541308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541308")>
<Fact>
Public Sub SimpleStructInstantiationAndAssigningNothing()
Dim ilSource = <![CDATA[
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.pack 0
.size 1
}
]]>
Dim vbSource =
<compilation>
<file name="a.vb">
Option Infer Off
Class C
Shared Sub Main()
Dim s As S = New S()
s = Nothing
s = New S()
SS(Nothing)
SS(New S())
Dim a = (New S()).ToString()
s = DirectCast(Nothing, S)
End Sub
Shared Sub SS(s As S)
End Sub
End Class
</file>
</compilation>
CompileWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDll).
VerifyIL("C.Main",
<![CDATA[
{
// Code size 60 (0x3c)
.maxstack 1
.locals init (S V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj "S"
IL_0008: ldloc.0
IL_0009: call "Sub C.SS(S)"
IL_000e: ldloca.s V_0
IL_0010: initobj "S"
IL_0016: ldloc.0
IL_0017: call "Sub C.SS(S)"
IL_001c: ldloca.s V_0
IL_001e: initobj "S"
IL_0024: ldloc.0
IL_0025: stloc.0
IL_0026: ldloca.s V_0
IL_0028: constrained. "S"
IL_002e: callvirt "Function System.ValueType.ToString() As String"
IL_0033: pop
IL_0034: ldnull
IL_0035: unbox.any "S"
IL_003a: pop
IL_003b: ret
}
]]>)
End Sub
<WorkItem(541308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541308")>
<Fact>
Public Sub TypeParameterInitializationWithNothing()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class CT(Of X)
Public Sub T()
Dim a As X = Nothing
End Sub
End Class
Module EmitTest
Sub Main()
End Sub
End Module
</file>
</compilation>, expectedOutput:="").
VerifyIL("CT(Of X).T()",
<![CDATA[
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}
]]>)
End Sub
<WorkItem(541308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541308")>
<Fact()>
Public Sub TypeParameterInitializationWithNothing_StructConstraint()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class CT(Of X As Structure)
Public Sub T()
Dim a As X = New X()
a = Nothing
a = New X()
End Sub
End Class
Module EmitTest
Sub Main()
End Sub
End Module
</file>
</compilation>, expectedOutput:="").
VerifyIL("CT(Of X).T()",
<![CDATA[
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: call "Function System.Activator.CreateInstance(Of X)() As X"
IL_0005: pop
IL_0006: call "Function System.Activator.CreateInstance(Of X)() As X"
IL_000b: pop
IL_000c: ret
}
]]>)
End Sub
<WorkItem(541308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541308")>
<Fact()>
Public Sub TypeParameterInitializationWithNothing_NewConstraint()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class CT(Of X As New)
Public Sub T()
Dim a As X = New X()
a = Nothing
a = New X()
End Sub
End Class
Module EmitTest
Sub Main()
End Sub
End Module
</file>
</compilation>, expectedOutput:="").
VerifyIL("CT(Of X).T()",
<![CDATA[
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: call "Function System.Activator.CreateInstance(Of X)() As X"
IL_0005: pop
IL_0006: call "Function System.Activator.CreateInstance(Of X)() As X"
IL_000b: pop
IL_000c: ret
}
]]>)
End Sub
<WorkItem(541308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541308")>
<Fact>
Public Sub StructInstantiationWithParameters()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Infer Off
Imports System
Structure S
Public Sub New(i As Integer)
End Sub
End Structure
Module EmitTest
Public Sub Main()
Dim s As S = New S(1)
s = New S(1)
Dim a = (New S(1)).ToString()
End Sub
End Module
</file>
</compilation>, expectedOutput:="").
VerifyIL("EmitTest.Main",
<![CDATA[
{
// Code size 36 (0x24)
.maxstack 1
.locals init (S V_0)
IL_0000: ldc.i4.1
IL_0001: newobj "Sub S..ctor(Integer)"
IL_0006: pop
IL_0007: ldc.i4.1
IL_0008: newobj "Sub S..ctor(Integer)"
IL_000d: pop
IL_000e: ldc.i4.1
IL_000f: newobj "Sub S..ctor(Integer)"
IL_0014: stloc.0
IL_0015: ldloca.s V_0
IL_0017: constrained. "S"
IL_001d: callvirt "Function System.ValueType.ToString() As String"
IL_0022: pop
IL_0023: ret
}
]]>)
End Sub
<WorkItem(541123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541123")>
<WorkItem(541309, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541309")>
<Fact>
Public Sub PrivateParameterlessConstructorInMetadata()
Dim ilSource = <![CDATA[
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.pack 0
.size 1
.method private hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ret
}
}
]]>
Dim vbSource =
<compilation>
<file name="a.vb">
Class C
Shared Sub Main()
Dim s as S = New S()
s = Nothing
End Sub
End Class
</file>
</compilation>
' CONSIDER: This is the dev10 behavior.
' Shouldn't there be an error for trying to call an inaccessible ctor?
' NOTE: Current behavior is to skip private constructor and use 'initobj'
CompileWithCustomILSource(vbSource, ilSource.Value, TestOptions.ReleaseDll).
VerifyIL("C.Main",
<![CDATA[
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}
]]>)
End Sub
<Fact>
Public Sub TestAsNewWithMultipleLocals()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module EmitTest
Class C
private shared _sharedState as integer = 0
public _p as integer = 0
Public Sub New()
_sharedState = _sharedState + 1
_p = _sharedState
End Sub
Public ReadOnly Property P as integer
Get
return _p
End Get
End Property
End Class
Sub Main()
Dim x, y as New C()
Console.WriteLine(x.P)
Console.WriteLine(y.P)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1
2
]]>).
VerifyIL("EmitTest.Main",
<![CDATA[
{
// Code size 33 (0x21)
.maxstack 2
.locals init (EmitTest.C V_0) //x
IL_0000: newobj "Sub EmitTest.C..ctor()"
IL_0005: stloc.0
IL_0006: newobj "Sub EmitTest.C..ctor()"
IL_000b: ldloc.0
IL_000c: callvirt "Function EmitTest.C.get_P() As Integer"
IL_0011: call "Sub System.Console.WriteLine(Integer)"
IL_0016: callvirt "Function EmitTest.C.get_P() As Integer"
IL_001b: call "Sub System.Console.WriteLine(Integer)"
IL_0020: ret
}
]]>)
End Sub
<WorkItem(540533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540533")>
<Fact()>
Public Sub Bug6817()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub goo()
apCompare(1.CompareTo(2))
Exit Sub
End Sub
Sub Main()
goo
End Sub
End Module
Public Module M2
Public Sub apCompare(ActualValue As Object)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="").
VerifyIL("M1.goo",
<![CDATA[
{
// Code size 21 (0x15)
.maxstack 2
.locals init (Integer V_0)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: ldc.i4.2
IL_0005: call "Function Integer.CompareTo(Integer) As Integer"
IL_000a: box "Integer"
IL_000f: call "Sub M2.apCompare(Object)"
IL_0014: ret
}
]]>)
End Sub
<WorkItem(8597, "DevDiv_Projects/Roslyn")>
<Fact>
Public Sub OpenGenericWithAliasQualifierInGetType()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports OuterOfString = Outer(Of String)
Imports OuterOfInt = Outer(Of Integer)
Public Class Outer(Of T)
Public Class Inner(Of U)
End Class
End Class
Public Module Module1
Public Sub Main()
Console.WriteLine(GetType(OuterOfString.Inner(Of )) Is GetType(OuterOfInt.Inner(Of )))
End Sub
End Module
</file>
</compilation>,
expectedOutput:="True")
End Sub
<Fact>
Public Sub ArrayLongLength()
CompileAndVerify(
<compilation>
<file name="a.vb">
public Module A
Public Sub Main()
Dim arr As Integer() = New Integer(4) {}
System.Console.Write(arr.LongLength + 1)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="6").
VerifyIL("A.Main",
<![CDATA[
{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldc.i4.5
IL_0001: newarr "Integer"
IL_0006: ldlen
IL_0007: conv.i8
IL_0008: ldc.i4.1
IL_0009: conv.i8
IL_000a: add.ovf
IL_000b: call "Sub System.Console.Write(Long)"
IL_0010: ret
}
]]>)
End Sub
<WorkItem(528679, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528679")>
<Fact()>
Public Sub FunctionCallWhileOptionInferOn()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Option Infer On
Public Class MyClass1
Const global_y As Long = 20
Public Shared Sub Main()
End Sub
Function goo(ByRef x As Integer) As Integer
x = x + 10
Return x + 10
End Function
Sub goo1()
Dim global_y As Integer = goo(global_y)
End Sub
End Class
</file>
</compilation>,
expectedOutput:="").
VerifyIL("MyClass1.goo1",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 2
.locals init (Integer V_0) //global_y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call "Function MyClass1.goo(ByRef Integer) As Integer"
IL_0008: stloc.0
IL_0009: ret
}]]>)
End Sub
' Verify that the metadata for an attribute with a serialized an enum type with generics and nested class is correctly written by compiler and read by reflection.
<WorkItem(541278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541278")>
<Fact>
Public Sub EmittingAttributesWithGenericsAndNestedClasses()
CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
<AttributeUsageAttribute(AttributeTargets.All, AllowMultiple:=True)>
Class A
Inherits Attribute
Public Sub New(x As Object)
Y = x
End Sub
Public Property Y As Object
End Class
Class B(Of T1)
Class D(Of T2)
Enum ED
AED = &HFEDCBA
End Enum
End Class
Class C
Enum EC
AEC = 1
End Enum
End Class
Enum EB
AEB = &HABCDEF
End Enum
End Class
<A(B(Of Integer).EB.AEB)>
<A(B(Of Integer).D(Of Byte).ED.AED)>
<A(B(Of Integer).C.EC.AEC)>
Class C
End Class
Module m1
Sub Main()
Dim c1 As New C()
For Each a As A In c1.GetType().GetCustomAttributes(False)
Console.WriteLine(a.Y)
Next
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[
AEB
AED
AEC
]]>).
VerifyIL("m1.Main",
<![CDATA[
{
// Code size 55 (0x37)
.maxstack 2
.locals init (Object() V_0,
Integer V_1)
IL_0000: newobj "Sub C..ctor()"
IL_0005: callvirt "Function Object.GetType() As System.Type"
IL_000a: ldc.i4.0
IL_000b: callvirt "Function System.Reflection.MemberInfo.GetCustomAttributes(Boolean) As Object()"
IL_0010: stloc.0
IL_0011: ldc.i4.0
IL_0012: stloc.1
IL_0013: br.s IL_0030
IL_0015: ldloc.0
IL_0016: ldloc.1
IL_0017: ldelem.ref
IL_0018: castclass "A"
IL_001d: callvirt "Function A.get_Y() As Object"
IL_0022: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0027: call "Sub System.Console.WriteLine(Object)"
IL_002c: ldloc.1
IL_002d: ldc.i4.1
IL_002e: add.ovf
IL_002f: stloc.1
IL_0030: ldloc.1
IL_0031: ldloc.0
IL_0032: ldlen
IL_0033: conv.i4
IL_0034: blt.s IL_0015
IL_0036: ret
}
]]>)
End Sub
<Fact>
Public Sub NewEnum001()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class A
Enum E1
AAA
End Enum
Shared Sub Main()
Dim e as DayOfWeek = New DayOfWeek()
Console.Write(e.ToString)
Dim e1 as E1 = New E1()
Console.Writeline(e1.ToString)
End Sub
End Class
</file>
</compilation>,
expectedOutput:="SundayAAA").
VerifyIL("A.Main",
<![CDATA[
{
// Code size 53 (0x35)
.maxstack 1
.locals init (System.DayOfWeek V_0, //e
A.E1 V_1) //e1
IL_0000: ldloca.s V_0
IL_0002: initobj "System.DayOfWeek"
IL_0008: ldloca.s V_0
IL_000a: constrained. "System.DayOfWeek"
IL_0010: callvirt "Function System.Enum.ToString() As String"
IL_0015: call "Sub System.Console.Write(String)"
IL_001a: ldloca.s V_1
IL_001c: initobj "A.E1"
IL_0022: ldloca.s V_1
IL_0024: constrained. "A.E1"
IL_002a: callvirt "Function System.Enum.ToString() As String"
IL_002f: call "Sub System.Console.WriteLine(String)"
IL_0034: ret
}
]]>)
End Sub
<WorkItem(542593, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542593")>
<Fact>
Public Sub InheritClassFromRetargetedAssemblyReference()
Dim ref1 = New VisualBasicCompilationReference(CompilationUtils.CreateEmptyCompilationWithReferences(
<compilation>
<file name="a.vb">
Imports System.Collections.Generic
Imports System.Collections
Public Class C1(Of T)
Implements IEnumerable(Of T)
Public Function GetEnumerator() As IEnumerator(Of T) Implements IEnumerable(Of T).GetEnumerator
Return Nothing
End Function
Public Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator
Return Nothing
End Function
End Class
</file>
</compilation>, references:={MetadataReference.CreateFromImage(TestResources.NetFX.v4_0_21006.mscorlib.AsImmutableOrNull())}))
Dim comp = CompilationUtils.CreateEmptyCompilationWithReferences(
<compilation>
<file name="b.vb">
Imports System.Collections.Generic
Imports System.Collections
Public Class C2(Of U)
Inherits C1(Of U)
Implements IEnumerable(Of U)
Public Function GetEnumerator2() As IEnumerator(Of U) Implements IEnumerable(Of U).GetEnumerator
Return GetEnumerator1()
End Function
End Class
</file>
</compilation>, references:={MetadataReference.CreateFromImage(TestResources.NetFX.v4_0_30319.mscorlib.AsImmutableOrNull()), ref1})
CompileAndVerify(comp)
Dim classC1 = DirectCast(comp.GlobalNamespace.GetMembers("C1").First(), NamedTypeSymbol)
Dim c1GetEnumerator = DirectCast(classC1.GetMembers("GetEnumerator").First(), MethodSymbol)
Assert.IsType(Of Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting.RetargetingMethodSymbol)(c1GetEnumerator)
Dim classC2 = DirectCast(comp.GlobalNamespace.GetMembers("C2").First(), NamedTypeSymbol)
Dim c2GetEnumerator2 = DirectCast(classC2.GetMembers("GetEnumerator2").First(), MethodSymbol)
Assert.Equal(c1GetEnumerator.ExplicitInterfaceImplementations(0).OriginalDefinition,
c2GetEnumerator2.ExplicitInterfaceImplementations(0).OriginalDefinition)
End Sub
<WorkItem(542593, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542593")>
<Fact>
Public Sub InheritClassFromRetargetedAssemblyReferenceProperty()
Dim ref1 = New VisualBasicCompilationReference(CompilationUtils.CreateEmptyCompilationWithReferences(
<compilation>
<file name="a.vb">
Imports System.Collections.Generic
Imports System.Collections
Public Class C1
Implements IEnumerator
Public ReadOnly Property Current1 As Object Implements System.Collections.IEnumerator.Current
Get
Return Nothing
End Get
End Property
Public Function MoveNext1() As Boolean Implements System.Collections.IEnumerator.MoveNext
Return False
End Function
Public Sub Reset1() Implements System.Collections.IEnumerator.Reset
End Sub
End Class
</file>
</compilation>, references:={MetadataReference.CreateFromImage(TestResources.NetFX.v4_0_21006.mscorlib.AsImmutableOrNull())}))
Dim comp = CompilationUtils.CreateEmptyCompilationWithReferences(
<compilation>
<file name="b.vb">
Imports System.Collections.Generic
Imports System.Collections
Public Class C2
Inherits C1
Implements IEnumerator
Public ReadOnly Property Current2 As Object Implements System.Collections.IEnumerator.Current
Get
Return Current1
End Get
End Property
Public Function MoveNext2() As Boolean Implements System.Collections.IEnumerator.MoveNext
Return MoveNext1()
End Function
Public Sub Reset2() Implements System.Collections.IEnumerator.Reset
Reset1()
End Sub
End Class
</file>
</compilation>, references:={MetadataReference.CreateFromImage(TestResources.NetFX.v4_0_30319.mscorlib.AsImmutableOrNull()), ref1})
Dim compilationVerifier = CompileAndVerify(comp)
Dim classC1 = DirectCast(comp.GlobalNamespace.GetMembers("C1").First(), NamedTypeSymbol)
Dim c1Current1 = DirectCast(classC1.GetMembers("Current1").First(), PropertySymbol)
Assert.IsType(Of Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting.RetargetingPropertySymbol)(c1Current1)
Dim classC2 = DirectCast(comp.GlobalNamespace.GetMembers("C2").First(), NamedTypeSymbol)
Dim c2Current2 = DirectCast(classC2.GetMembers("Current2").First(), PropertySymbol)
Assert.Equal(c1Current1.ExplicitInterfaceImplementations(0),
c2Current2.ExplicitInterfaceImplementations(0))
End Sub
<WorkItem(9850, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub NullableConversion()
CompileAndVerify(
<compilation>
<file name="a.vb">
Module M
Function F() As Object
Dim o As Integer? = 0
Return o
End Function
End Module
</file>
</compilation>)
End Sub
<WorkItem(9852, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub NullableIsNothing()
CompileAndVerify(
<compilation>
<file name="a.vb">
Module M
Function F1(o As Integer?) As Boolean
Return o Is Nothing
End Function
Function F2(o As Integer?) As Boolean
Return o IsNot Nothing
End Function
End Module
</file>
</compilation>)
End Sub
<Fact>
Public Sub MetadataTypeName()
Dim source =
<compilation>
<file name="a.vb">
Namespace Goo
Class B
End Class
End Namespace
Namespace GOO
Class C
End Class
End Namespace
Namespace GoO.Bar
Partial Class D
End Class
End Namespace
Namespace goo.Baz
Class E
End Class
End Namespace
Namespace goO
Namespace Bar
Class F
End Class
End Namespace
End Namespace
Namespace GOo.Bar
Partial Class D
End Class
End Namespace
Namespace Global.PROJEcT.Quuz
Class A
End Class
End Namespace
Namespace Global
Namespace SYStem
Class G
End Class
End Namespace
End Namespace
</file>
</compilation>
Dim comp = CompileAndVerify(source, options:=TestOptions.ReleaseDll.WithRootNamespace("Project"), validator:=
Sub(a)
AssertEx.SetEqual({"<Module>",
"PROJEcT.Quuz.A",
"Project.GOO.C",
"Project.GoO.Bar.D",
"Project.Goo.B",
"Project.goO.Bar.F",
"Project.goo.Baz.E",
"SYStem.G"}, MetadataValidation.GetFullTypeNames(a.GetMetadataReader()))
End Sub)
End Sub
<Fact, WorkItem(542974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542974")>
Public Sub LogicalOrWithBinaryExpressionOperands()
Dim comp = CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim a = "1"
Dim b = 0.0
If a <> "1" Or b > 0.1 Then
System.Console.WriteLine("Fail")
Else
System.Console.WriteLine("Pass")
End If
End Sub
End Module
</file>
</compilation>, options:=TestOptions.DebugDll)
comp.VerifyIL("Module1.Main", <![CDATA[
{
// Code size 77 (0x4d)
.maxstack 3
.locals init (String V_0, //a
Double V_1, //b
Boolean V_2)
IL_0000: nop
IL_0001: ldstr "1"
IL_0006: stloc.0
IL_0007: ldc.r8 0
IL_0010: stloc.1
IL_0011: ldloc.0
IL_0012: ldstr "1"
IL_0017: ldc.i4.0
IL_0018: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_001d: ldc.i4.0
IL_001e: cgt.un
IL_0020: ldloc.1
IL_0021: ldc.r8 0.1
IL_002a: cgt
IL_002c: or
IL_002d: stloc.2
IL_002e: ldloc.2
IL_002f: brfalse.s IL_003f
IL_0031: ldstr "Fail"
IL_0036: call "Sub System.Console.WriteLine(String)"
IL_003b: nop
IL_003c: nop
IL_003d: br.s IL_004c
IL_003f: nop
IL_0040: ldstr "Pass"
IL_0045: call "Sub System.Console.WriteLine(String)"
IL_004a: nop
IL_004b: nop
IL_004c: ret
}
]]>)
End Sub
<WorkItem(543243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543243")>
<Fact()>
Public Sub TestAutoProperty()
Dim vbCompilation = CreateVisualBasicCompilation("TestAutoProperty",
<![CDATA[Public Module Program
Property P As Integer
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim vbVerifier = CompileAndVerify(vbCompilation, expectedSignatures:=
{
Signature("Program", "P", ".property readwrite static System.Int32 P"),
Signature("Program", "get_P", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public specialname static System.Int32 get_P() cil managed"),
Signature("Program", "set_P", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public specialname static System.Void set_P(System.Int32 AutoPropertyValue) cil managed")
})
vbVerifier.VerifyDiagnostics()
End Sub
<WorkItem(543243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543243")>
<Fact()>
Public Sub TestOrInDebug()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim a = "1"
Dim b = 0.0
If a < > "1" Or b > 0.1 Then
System.Console.WriteLine("Fail")
Else
System.Console.WriteLine("Pass")
End If
End Sub
End Module
</file>
</compilation>,
options:=TestOptions.DebugExe,
expectedOutput:="Pass")
c.VerifyIL("Module1.Main", <![CDATA[
{
// Code size 77 (0x4d)
.maxstack 3
.locals init (String V_0, //a
Double V_1, //b
Boolean V_2)
IL_0000: nop
IL_0001: ldstr "1"
IL_0006: stloc.0
IL_0007: ldc.r8 0
IL_0010: stloc.1
IL_0011: ldloc.0
IL_0012: ldstr "1"
IL_0017: ldc.i4.0
IL_0018: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"
IL_001d: ldc.i4.0
IL_001e: cgt.un
IL_0020: ldloc.1
IL_0021: ldc.r8 0.1
IL_002a: cgt
IL_002c: or
IL_002d: stloc.2
IL_002e: ldloc.2
IL_002f: brfalse.s IL_003f
IL_0031: ldstr "Fail"
IL_0036: call "Sub System.Console.WriteLine(String)"
IL_003b: nop
IL_003c: nop
IL_003d: br.s IL_004c
IL_003f: nop
IL_0040: ldstr "Pass"
IL_0045: call "Sub System.Console.WriteLine(String)"
IL_004a: nop
IL_004b: nop
IL_004c: ret
}
]]>)
End Sub
<WorkItem(539392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539392")>
<Fact()>
Public Sub DecimalBinaryOp_01()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Main()
Console.WriteLine(Decimal.MaxValue + 0)
End Sub
End Module
</file>
</compilation>, expectedOutput:="79228162514264337593543950335").
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 16 (0x10)
.maxstack 5
IL_0000: ldc.i4.m1
IL_0001: ldc.i4.m1
IL_0002: ldc.i4.m1
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: newobj "Sub Decimal..ctor(Integer, Integer, Integer, Boolean, Byte)"
IL_000a: call "Sub System.Console.WriteLine(Decimal)"
IL_000f: ret
}
]]>)
End Sub
<WorkItem(543611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543611")>
<Fact()>
Public Sub CompareToOnDecimalLiteral()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Main()
Console.WriteLine(1D.CompareTo(2D))
End Sub
End Module
</file>
</compilation>, expectedOutput:="-1").
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (Decimal V_0)
IL_0000: ldsfld "Decimal.One As Decimal"
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: ldc.i4.2
IL_0009: conv.i8
IL_000a: newobj "Sub Decimal..ctor(Long)"
IL_000f: call "Function Decimal.CompareTo(Decimal) As Integer"
IL_0014: call "Sub System.Console.WriteLine(Integer)"
IL_0019: ret
}
]]>)
End Sub
<WorkItem(543611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543611")>
<Fact()>
Public Sub CallOnReadonlyValField()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class Test
Structure C1
Public x As Decimal
End Structure
Shared Function Goo() As C1
Return New C1()
End Function
Shared Sub Main()
Console.Write(Goo().x.CompareTo(Decimal.One))
End Sub
End Class
</file>
</compilation>, expectedOutput:="-1").
VerifyIL("Test.Main",
<![CDATA[
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (Test.C1 V_0)
IL_0000: call "Function Test.Goo() As Test.C1"
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: ldflda "Test.C1.x As Decimal"
IL_000d: ldsfld "Decimal.One As Decimal"
IL_0012: call "Function Decimal.CompareTo(Decimal) As Integer"
IL_0017: call "Sub System.Console.Write(Integer)"
IL_001c: ret
}
]]>)
End Sub
<Fact()>
Public Sub CallOnReadonlyValFieldNested()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class Program
Public Shared Sub Main()
Dim c = New cls1()
c.y.mutate(123)
c.y.n.n.mutate(456)
Console.WriteLine(c.y.n.n.num)
End Sub
End Class
Class cls1
Public ReadOnly y As MyManagedStruct = New MyManagedStruct(42)
End Class
Structure MyManagedStruct
Public Structure Nested
Public n As Nested1
Public Structure Nested1
Public num As Integer
Public Sub mutate(x As Integer)
num = x
End Sub
End Structure
End Structure
Public n As Nested
Public Sub mutate(x As Integer)
n.n.num = x
End Sub
Public Sub New(x As Integer)
n.n.num = x
End Sub
End Structure
</file>
</compilation>, expectedOutput:="42").
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 76 (0x4c)
.maxstack 3
.locals init (MyManagedStruct V_0)
IL_0000: newobj "Sub cls1..ctor()"
IL_0005: dup
IL_0006: ldfld "cls1.y As MyManagedStruct"
IL_000b: stloc.0
IL_000c: ldloca.s V_0
IL_000e: ldc.i4.s 123
IL_0010: call "Sub MyManagedStruct.mutate(Integer)"
IL_0015: dup
IL_0016: ldfld "cls1.y As MyManagedStruct"
IL_001b: stloc.0
IL_001c: ldloca.s V_0
IL_001e: ldflda "MyManagedStruct.n As MyManagedStruct.Nested"
IL_0023: ldflda "MyManagedStruct.Nested.n As MyManagedStruct.Nested.Nested1"
IL_0028: ldc.i4 0x1c8
IL_002d: call "Sub MyManagedStruct.Nested.Nested1.mutate(Integer)"
IL_0032: ldfld "cls1.y As MyManagedStruct"
IL_0037: ldfld "MyManagedStruct.n As MyManagedStruct.Nested"
IL_003c: ldfld "MyManagedStruct.Nested.n As MyManagedStruct.Nested.Nested1"
IL_0041: ldfld "MyManagedStruct.Nested.Nested1.num As Integer"
IL_0046: call "Sub System.Console.WriteLine(Integer)"
IL_004b: ret
}
]]>)
End Sub
<WorkItem(543611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543611")>
<Fact()>
Public Sub MultipleconstsByRef()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Main()
' Expecting to have exactly 3 decimal temps here
' more than 3 is redundant
' less than 3 is not possible
moo(1D, 1D, 1D)
moo(1D, 1D, 1D)
moo(1D, 1D, 1D)
End Sub
Sub moo(ByRef x As Decimal, ByRef y As Decimal, ByRef z As Decimal)
End Sub
End Module
</file>
</compilation>, expectedOutput:="").
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 88 (0x58)
.maxstack 3
.locals init (Decimal V_0,
Decimal V_1,
Decimal V_2)
IL_0000: ldsfld "Decimal.One As Decimal"
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: ldsfld "Decimal.One As Decimal"
IL_000d: stloc.1
IL_000e: ldloca.s V_1
IL_0010: ldsfld "Decimal.One As Decimal"
IL_0015: stloc.2
IL_0016: ldloca.s V_2
IL_0018: call "Sub Program.moo(ByRef Decimal, ByRef Decimal, ByRef Decimal)"
IL_001d: ldsfld "Decimal.One As Decimal"
IL_0022: stloc.2
IL_0023: ldloca.s V_2
IL_0025: ldsfld "Decimal.One As Decimal"
IL_002a: stloc.1
IL_002b: ldloca.s V_1
IL_002d: ldsfld "Decimal.One As Decimal"
IL_0032: stloc.0
IL_0033: ldloca.s V_0
IL_0035: call "Sub Program.moo(ByRef Decimal, ByRef Decimal, ByRef Decimal)"
IL_003a: ldsfld "Decimal.One As Decimal"
IL_003f: stloc.0
IL_0040: ldloca.s V_0
IL_0042: ldsfld "Decimal.One As Decimal"
IL_0047: stloc.1
IL_0048: ldloca.s V_1
IL_004a: ldsfld "Decimal.One As Decimal"
IL_004f: stloc.2
IL_0050: ldloca.s V_2
IL_0052: call "Sub Program.moo(ByRef Decimal, ByRef Decimal, ByRef Decimal)"
IL_0057: ret
}
]]>)
End Sub
<WorkItem(638119, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638119")>
<Fact()>
Public Sub ArrayInitZero()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Main()
Dim saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture
Try
Test()
Finally
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture
End Try
End Sub
Sub Test()
' no element inits
Dim arrB1 = new boolean() {false, false, false}
System.Console.WriteLine(arrB1(0))
' no element inits
Dim arrE1 = new Exception() {Nothing, Nothing, Nothing}
System.Console.WriteLine(arrE1(0))
' 1 element init
Dim arrB2 = new boolean() {false, true, false}
System.Console.WriteLine(arrB2(1))
' 1 element init
Dim arrE2 = new Exception() {Nothing, new Exception(), Nothing, Nothing, Nothing, Nothing, Nothing}
System.Console.WriteLine(arrE2(1))
' blob init
Dim arrB3 = new boolean() {true, false, true, true}
System.Console.WriteLine(arrB3(2))
End Sub
End Module
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithModuleName("MODULE"), expectedOutput:=<![CDATA[False
True
System.Exception: Exception of type 'System.Exception' was thrown.
True
]]>).
VerifyIL("Program.Test",
<![CDATA[
{
// Code size 89 (0x59)
.maxstack 4
IL_0000: ldc.i4.3
IL_0001: newarr "Boolean"
IL_0006: ldc.i4.0
IL_0007: ldelem.u1
IL_0008: call "Sub System.Console.WriteLine(Boolean)"
IL_000d: ldc.i4.3
IL_000e: newarr "System.Exception"
IL_0013: ldc.i4.0
IL_0014: ldelem.ref
IL_0015: call "Sub System.Console.WriteLine(Object)"
IL_001a: ldc.i4.3
IL_001b: newarr "Boolean"
IL_0020: dup
IL_0021: ldc.i4.1
IL_0022: ldc.i4.1
IL_0023: stelem.i1
IL_0024: ldc.i4.1
IL_0025: ldelem.u1
IL_0026: call "Sub System.Console.WriteLine(Boolean)"
IL_002b: ldc.i4.7
IL_002c: newarr "System.Exception"
IL_0031: dup
IL_0032: ldc.i4.1
IL_0033: newobj "Sub System.Exception..ctor()"
IL_0038: stelem.ref
IL_0039: ldc.i4.1
IL_003a: ldelem.ref
IL_003b: call "Sub System.Console.WriteLine(Object)"
IL_0040: ldc.i4.4
IL_0041: newarr "Boolean"
IL_0046: dup
IL_0047: ldtoken "Integer <PrivateImplementationDetails>.52A5C4A10657220CAC05C63ADFA923C7771C55D868A58EE360EB3D1511985C3E"
IL_004c: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"
IL_0051: ldc.i4.2
IL_0052: ldelem.u1
IL_0053: call "Sub System.Console.WriteLine(Boolean)"
IL_0058: ret
}
]]>)
End Sub
<Fact()>
Public Sub ArrayInitZero_D()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Main()
Dim saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture
Try
Test()
Finally
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture
End Try
End Sub
Sub Test()
' no element inits
Dim arrB1 = new boolean() {false, false, false}
System.Console.WriteLine(arrB1(0))
' no element inits
Dim arrE1 = new Exception() {Nothing, Nothing, Nothing}
System.Console.WriteLine(arrE1(0))
' 1 element init
Dim arrB2 = new boolean() {false, true, false}
System.Console.WriteLine(arrB2(1))
' 1 element init
Dim arrE2 = new Exception() {Nothing, new Exception(), Nothing, Nothing, Nothing, Nothing, Nothing}
System.Console.WriteLine(arrE2(1))
' blob init
Dim arrB3 = new boolean() {true, false, true, true}
System.Console.WriteLine(arrB3(2))
End Sub
End Module
</file>
</compilation>, options:=TestOptions.ReleaseDebugExe.WithModuleName("MODULE"), expectedOutput:=<![CDATA[False
True
System.Exception: Exception of type 'System.Exception' was thrown.
True
]]>).
VerifyIL("Program.Test",
<![CDATA[
{
// Code size 101 (0x65)
.maxstack 4
.locals init (Boolean() V_0, //arrB1
System.Exception() V_1, //arrE1
Boolean() V_2, //arrB2
System.Exception() V_3, //arrE2
Boolean() V_4) //arrB3
IL_0000: ldc.i4.3
IL_0001: newarr "Boolean"
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.0
IL_0009: ldelem.u1
IL_000a: call "Sub System.Console.WriteLine(Boolean)"
IL_000f: ldc.i4.3
IL_0010: newarr "System.Exception"
IL_0015: stloc.1
IL_0016: ldloc.1
IL_0017: ldc.i4.0
IL_0018: ldelem.ref
IL_0019: call "Sub System.Console.WriteLine(Object)"
IL_001e: ldc.i4.3
IL_001f: newarr "Boolean"
IL_0024: dup
IL_0025: ldc.i4.1
IL_0026: ldc.i4.1
IL_0027: stelem.i1
IL_0028: stloc.2
IL_0029: ldloc.2
IL_002a: ldc.i4.1
IL_002b: ldelem.u1
IL_002c: call "Sub System.Console.WriteLine(Boolean)"
IL_0031: ldc.i4.7
IL_0032: newarr "System.Exception"
IL_0037: dup
IL_0038: ldc.i4.1
IL_0039: newobj "Sub System.Exception..ctor()"
IL_003e: stelem.ref
IL_003f: stloc.3
IL_0040: ldloc.3
IL_0041: ldc.i4.1
IL_0042: ldelem.ref
IL_0043: call "Sub System.Console.WriteLine(Object)"
IL_0048: ldc.i4.4
IL_0049: newarr "Boolean"
IL_004e: dup
IL_004f: ldtoken "Integer <PrivateImplementationDetails>.52A5C4A10657220CAC05C63ADFA923C7771C55D868A58EE360EB3D1511985C3E"
IL_0054: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"
IL_0059: stloc.s V_4
IL_005b: ldloc.s V_4
IL_005d: ldc.i4.2
IL_005e: ldelem.u1
IL_005f: call "Sub System.Console.WriteLine(Boolean)"
IL_0064: ret
}
]]>)
End Sub
<WorkItem(529162, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529162")>
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub TestMSVBTypeNameAPI()
Dim vbCompilation = CreateVisualBasicCompilation("TestMSVBTypeNameAPI",
<![CDATA[Public Module Program
Sub Main()
Dim x = 0UI
System.Console.WriteLine(Microsoft.VisualBasic.Information.TypeName(x))
End Sub
End Module]]>,
compilationOptions:=TestOptions.ReleaseExe)
Dim vbVerifier = CompileAndVerify(vbCompilation, expectedOutput:="UInteger")
vbVerifier.VerifyDiagnostics()
vbVerifier.VerifyIL("Program.Main", <![CDATA[
{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: box "UInteger"
IL_0006: call "Function Microsoft.VisualBasic.CompilerServices.Versioned.TypeName(Object) As String"
IL_000b: call "Sub System.Console.WriteLine(String)"
IL_0010: ret
}]]>)
End Sub
<WorkItem(11640, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub TestDecimalConversionCDec01()
CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports Microsoft.VisualBasic
Imports System.Math
Class Test
Public Shared Sub Main()
If CDec(36%) <> 36@ Then
System.Console.WriteLine("FAIL")
Else
System.Console.WriteLine("PASS")
End If
End Sub
End Class]]>
</file>
</compilation>, expectedOutput:="PASS").
VerifyIL("Test.Main", <![CDATA[
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr "PASS"
IL_0005: call "Sub System.Console.WriteLine(String)"
IL_000a: ret
}
]]>)
End Sub
<WorkItem(543757, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543757")>
<Fact()>
Public Sub TestNotXor()
CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module Program
Dim f As Boolean = False
Dim t As Boolean = True
Sub Main(args As String())
Dim q As Boolean = Not (f Xor t)
Console.Write(q)
q = Not(Not (f Xor t))
Console.Write(q)
End Sub
End Module
]]>
</file>
</compilation>, expectedOutput:="FalseTrue").
VerifyIL("Program.Main", <![CDATA[
{
// Code size 34 (0x22)
.maxstack 2
IL_0000: ldsfld "Program.f As Boolean"
IL_0005: ldsfld "Program.t As Boolean"
IL_000a: ceq
IL_000c: call "Sub System.Console.Write(Boolean)"
IL_0011: ldsfld "Program.f As Boolean"
IL_0016: ldsfld "Program.t As Boolean"
IL_001b: xor
IL_001c: call "Sub System.Console.Write(Boolean)"
IL_0021: ret
}
]]>)
End Sub
<Fact()>
Public Sub NotEqualIntegralAndFloat()
CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Class Class1
Shared Sub Main()
Dim i As Integer = -1
Dim result As Boolean = i <> 0
If (result) Then
System.Console.Write("notequal1")
End If
result = i = 0
If (result) Then
System.Console.Write("equal1")
End If
Dim d As Double = -1
result = d <> 0
If (result) Then
System.Console.Write("notequal2")
End If
result = d = 0
If (result) Then
System.Console.Write("equal2")
End If
End Sub
End Class
]]>
</file>
</compilation>, expectedOutput:="notequal1notequal2").
VerifyIL("Class1.Main", <![CDATA[
{
// Code size 92 (0x5c)
.maxstack 3
IL_0000: ldc.i4.m1
IL_0001: dup
IL_0002: ldc.i4.0
IL_0003: cgt.un
IL_0005: brfalse.s IL_0011
IL_0007: ldstr "notequal1"
IL_000c: call "Sub System.Console.Write(String)"
IL_0011: ldc.i4.0
IL_0012: ceq
IL_0014: brfalse.s IL_0020
IL_0016: ldstr "equal1"
IL_001b: call "Sub System.Console.Write(String)"
IL_0020: ldc.r8 -1
IL_0029: dup
IL_002a: ldc.r8 0
IL_0033: ceq
IL_0035: ldc.i4.0
IL_0036: ceq
IL_0038: brfalse.s IL_0044
IL_003a: ldstr "notequal2"
IL_003f: call "Sub System.Console.Write(String)"
IL_0044: ldc.r8 0
IL_004d: ceq
IL_004f: brfalse.s IL_005b
IL_0051: ldstr "equal2"
IL_0056: call "Sub System.Console.Write(String)"
IL_005b: ret
}
]]>)
End Sub
<Fact(), WorkItem(544128, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544128")>
Public Sub CodeGenLambdaNarrowingRelaxation()
CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class HasAutoProps
Property Scen11() As Func(Of String, Integer) = Function(y As Integer) y.ToString()
End Class
]]>
</file>
</compilation>)
End Sub
<Fact(), WorkItem(544182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544182")>
Public Sub OverrideImplementMembersWithOptArguments()
Dim optParameterSource = <![CDATA[
.class interface public abstract auto ansi IAnimal
{
.method public newslot abstract strict virtual
instance void MakeNoise([opt] int32 pitch) cil managed
{
} // end of method IAnimal::MakeNoise
.method public newslot specialname abstract strict virtual
instance class IAnimal get_Descendants([opt] int32 generation) cil managed
{
} // end of method IAnimal::get_Descendants
.property instance class IAnimal Descendants(int32)
{
.get instance class IAnimal IAnimal::get_Descendants(int32)
} // end of property IAnimal::Descendants
} // end of class IAnimal
.class public abstract auto ansi AbstractAnimal
extends [mscorlib]System.Object
{
.method family specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method AbstractAnimal::.ctor
.method public newslot abstract strict virtual
instance void MakeNoise([opt] int32 pitch) cil managed
{
} // end of method AbstractAnimal::MakeNoise
.method public newslot specialname abstract strict virtual
instance class AbstractAnimal get_Descendants([opt] int32 generation) cil managed
{
} // end of method AbstractAnimal::get_Descendants
.property instance class AbstractAnimal
Descendants(int32)
{
.get instance class AbstractAnimal AbstractAnimal::get_Descendants(int32)
} // end of property AbstractAnimal::Descendants
} // end of class AbstractAnimal
]]>.Value
Dim vbSource =
<compilation>
<file name="a.vb">
Class Bandicoot : Implements IAnimal
Sub MakeNoise(Optional pitch As Integer = 20000) Implements IAnimal.MakeNoise
End Sub
ReadOnly Property Descendants(Optional generation As Integer = 0) As IAnimal Implements IAnimal.Descendants
Get
Return Nothing
End Get
End Property
End Class
Class Platypus : Inherits AbstractAnimal
Public Overrides Sub MakeNoise(Optional pitch As Integer = 2500)
End Sub
Public Overrides ReadOnly Property Descendants(Optional generation As Integer = 6) As AbstractAnimal
Get
Return Nothing
End Get
End Property
End Class
</file>
</compilation>
CompileWithCustomILSource(vbSource, optParameterSource)
End Sub
<Fact()>
Public Sub MyClassAssign()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub Main()
End Sub
End Module
Structure S
Private F As Object
Sub M()
MyClass.F = Nothing
End Sub
End Structure
</file>
</compilation>,
expectedOutput:="").
VerifyIL("S.M",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldnull
IL_0002: stfld "S.F As Object"
IL_0007: ret
}
]]>)
End Sub
<Fact()>
Public Sub TestHostProtectionAttributeWithoutSecurityAction()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub Main()
End Sub
End Module
<System.Security.Permissions.HostProtectionAttribute(UI := true)>
Class C1
End Class
</file>
</compilation>,
expectedOutput:="")
End Sub
<WorkItem(545201, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545201")>
<Fact()>
Public Sub TestConversionMultiDimArrayToIList()
Dim vbCompilation = CreateVisualBasicCompilation("TestConversionMultiDimArrayToIList",
<![CDATA[Imports System
Imports System.Collections
Module Program
Sub Main(args As String())
Test.Scen1(Of Exception, Integer).Scen1()
Test.Scen1(Of Exception, Integer).Scen1({1, 2, 3, 4})
End Sub
End Module
Module Test
Class Scen1(Of T, U)
Public Shared Sub Scen1()
Try
Dim a As T, b As T
'T(,,)->IList
Dim l4 As IList = {{{a, b}, {a, b}}}
Console.WriteLine("PASS")
Catch ex As Exception
Console.WriteLine(ex.ToString())
End Try
End Sub
Public Shared Sub Scen1(d() as U)
Try
'U(,,)->IList
Dim l4 As IList = {{{d(0), d(1)}, {d(2), d(3)}}}
Console.WriteLine("{0}", l4.GetType())
dim a4 as integer(,,) = l4
for i = 0 to a4.GetLength(0) - 1
for j = 0 to a4.GetLength(1) - 1
for k = 0 to a4.GetLength(2) - 1
Console.WriteLine("{0}", a4(i, j, k))
next
next
next
Console.WriteLine("PASS")
Catch ex As Exception
Console.WriteLine(ex.ToString())
End Try
End Sub
End Class
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication))
Dim vbVerifier = CompileAndVerify(vbCompilation,
expectedOutput:=<![CDATA[
PASS
System.Int32[,,]
1
2
3
4
PASS
]]>)
vbVerifier.VerifyDiagnostics()
End Sub
<WorkItem(545349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545349")>
<Fact()>
Public Sub CompoundPropGeneric()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Imports System.Linq
Public Class Test
Public Shared Sub Main()
Dim s As New S1
TestINop(s)
End Sub
Public Shared Sub TestINop(Of T As I)(a As T)
' should call Getter and Setter on same instance
Nop(a).IntPropI += 1
End Sub
Public Shared Function Nop(Of T)(a As T) As T
Return a
End Function
End Class
Public Interface I
Property IntPropI As Integer
End Interface
Public Structure S1
Implements I
Private x As Integer
Public Property IntPropI As Integer Implements I.IntPropI
Get
x += 1
Return x
End Get
Set(value As Integer)
x += 1
Console.WriteLine(x)
End Set
End Property
End Structure
</file>
</compilation>,
expectedOutput:="2").
VerifyIL("Test.TestINop(Of T)(T)",
<![CDATA[
{
// Code size 36 (0x24)
.maxstack 3
.locals init (T V_0)
IL_0000: ldarg.0
IL_0001: call "Function Test.Nop(Of T)(T) As T"
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: ldloca.s V_0
IL_000b: constrained. "T"
IL_0011: callvirt "Function I.get_IntPropI() As Integer"
IL_0016: ldc.i4.1
IL_0017: add.ovf
IL_0018: constrained. "T"
IL_001e: callvirt "Sub I.set_IntPropI(Integer)"
IL_0023: ret
}
]]>)
End Sub
<Fact()>
Public Sub IsComImport()
Dim validator As Action(Of ModuleSymbol) = Sub([module])
Dim globalNamespace = [module].GlobalNamespace
Dim type = globalNamespace.GetMember(Of NamedTypeSymbol)("A")
Assert.True(type.IsComImport())
type = globalNamespace.GetMember(Of NamedTypeSymbol)("B")
Assert.True(type.IsComImport())
type = globalNamespace.GetMember(Of NamedTypeSymbol)("C")
Assert.False(type.IsComImport())
End Sub
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Runtime.InteropServices
<ComImport()>
<Guid("48C6BFCA-35EB-4537-8A13-DB15C86B61D4")>
Class A
End Class
<ComImport()>
Class B
Public Sub New()
MyBase.New()
End Sub
End Class
Class C
End Class
]]></file>
</compilation>)
CompileAndVerify(compilation, sourceSymbolValidator:=validator, symbolValidator:=validator, verify:=Verification.Passes)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsWindowsTypes)>
Public Sub ComImportMethods()
Dim sourceValidator As Action(Of ModuleSymbol) = Sub([module])
Dim expectedMethodImplAttributes As System.Reflection.MethodImplAttributes = MethodImplAttributes.Managed Or
MethodImplAttributes.Runtime Or MethodImplAttributes.InternalCall
Dim globalNamespace = [module].GlobalNamespace
Dim typeA = globalNamespace.GetMember(Of NamedTypeSymbol)("A")
Assert.True(typeA.IsComImport())
Assert.Equal(1, typeA.GetAttributes().Length)
Dim ctorA = typeA.InstanceConstructors.First()
Assert.Equal(expectedMethodImplAttributes, ctorA.ImplementationAttributes)
Dim methodGoo = DirectCast(typeA.GetMembers("Goo").First(), MethodSymbol)
Assert.Equal(expectedMethodImplAttributes, methodGoo.ImplementationAttributes)
Dim typeB = globalNamespace.GetMember(Of NamedTypeSymbol)("B")
Assert.True(typeB.IsComImport())
Assert.Equal(1, typeB.GetAttributes().Length)
Dim ctorB = typeB.InstanceConstructors.First()
Assert.True(DirectCast(ctorB, Cci.IMethodDefinition).IsExternal)
Assert.Equal(expectedMethodImplAttributes, ctorB.ImplementationAttributes)
End Sub
Dim metadataValidator As Action(Of ModuleSymbol) = Sub([module])
Dim globalNamespace = [module].GlobalNamespace
' ComImportAttribute: Pseudo custom attribute shouldn't have been emitted
Dim typeA = globalNamespace.GetMember(Of NamedTypeSymbol)("A")
Assert.True(typeA.IsComImport())
Assert.Equal(0, typeA.GetAttributes().Length)
Dim typeB = globalNamespace.GetMember(Of NamedTypeSymbol)("B")
Assert.True(typeB.IsComImport())
Assert.Equal(0, typeB.GetAttributes().Length)
Dim ctorB As MethodSymbol = typeB.InstanceConstructors.First()
Assert.True(ctorB.IsExternalMethod)
End Sub
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Imports System
Imports System.Runtime.InteropServices
<ComImport()>
Class A
Public Sub New()
Console.WriteLine("FAIL")
End Sub
Public Shared Function Goo() As Integer
Console.WriteLine("FAIL")
Return 0
End Function
End Class
<ComImport()>
Class B
End Class
Module M1
Sub Main()
Try
Dim a = new A()
Catch ex As Exception
Console.Write("PASS1, ")
End Try
Try
A.Goo()
Catch ex As Exception
Console.WriteLine("PASS2")
End Try
End Sub
End Module
]]></file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(compilation, sourceSymbolValidator:=sourceValidator, expectedOutput:="PASS1, PASS2")
End Sub
<Fact()>
Public Sub ExitPropertyDefaultReturnValue()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Class Program
Property P As Integer
Get
Exit Property
End Get
Set(ByVal value As Integer)
Exit Property
End Set
End Property
End Class
]]></file>
</compilation>)
' NOTE: warning, not error for missing return value.
compilation.VerifyDiagnostics(
Diagnostic(ERRID.WRN_DefAsgNoRetValPropVal1, "End Get").WithArguments("P"))
Dim verifier = CompileAndVerify(compilation)
verifier.VerifyIL("Program.get_P", <![CDATA[
{
// Code size 2 (0x2)
.maxstack 1
.locals init (Integer V_0) //P
IL_0000: ldloc.0
IL_0001: ret
}
]]>)
verifier.VerifyIL("Program.set_P", <![CDATA[
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}
]]>)
End Sub
<Fact()>
Public Sub ExitPropertyGetterSetReturnValue()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Class Program
Property P As Integer
Get
P = 1
Exit Property
End Get
Set(ByVal value As Integer)
Exit Property
End Set
End Property
End Class
]]></file>
</compilation>)
compilation.VerifyDiagnostics()
Dim verifier = CompileAndVerify(compilation)
verifier.VerifyIL("Program.get_P", <![CDATA[
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: ret
}
]]>)
End Sub
<Fact()>
Public Sub ExitPropertySetterSetReturnValue()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Class Program
Property P As Integer
Get
Exit Property
End Get
Set(ByVal value As Integer)
P = 1
Exit Property
End Set
End Property
End Class
]]></file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC42355: Property 'P' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Get
~~~~~~~
BC42026: Expression recursively calls the containing property 'Public Property P As Integer'.
P = 1
~
</expected>)
' NOTE: call setter - doesn't set return value.
Dim verifier = CompileAndVerify(compilation)
verifier.VerifyIL("Program.set_P", <![CDATA[
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: call "Sub Program.set_P(Integer)"
IL_0007: ret
}
]]>)
End Sub
<Fact()>
Public Sub ExitPropertyOutput()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="c.vb"><![CDATA[
Imports System
Class Program
Shared Sub Main()
Console.WriteLine(Prop2)
Prop2 += 1
Console.WriteLine(Prop2)
End Sub
Shared _prop2 As Integer = 1
Shared Property Prop2 As Integer
Get
Console.WriteLine("In get")
Prop2 = _prop2
Exit Property
End Get
Set(ByVal value As Integer)
Console.WriteLine("In set")
_prop2 = value
Exit Property
End Set
End Property
End Class
]]></file>
</compilation>, options:=TestOptions.ReleaseExe)
Dim verifier = CompileAndVerify(compilation, expectedOutput:=<![CDATA[
In get
1
In get
In set
In get
2
]]>)
End Sub
<WorkItem(545716, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545716")>
<Fact()>
Public Sub Regress14344()
CompileAndVerify(
<compilation>
<file name="a.vb">
Class EdmFunction
Private Shared Sub SetFunctionAttribute(ByRef field As Byte, attribute As byte)
field += field And attribute
End Sub
End Class
</file>
</compilation>).
VerifyIL("EdmFunction.SetFunctionAttribute",
<![CDATA[
{
// Code size 11 (0xb)
.maxstack 4
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldind.u1
IL_0003: ldarg.0
IL_0004: ldind.u1
IL_0005: ldarg.1
IL_0006: and
IL_0007: add
IL_0008: conv.ovf.u1.un
IL_0009: stind.i1
IL_000a: ret
}
]]>)
End Sub
<WorkItem(546189, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546189")>
<Fact()>
Public Sub Regress15299()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim x As Long = -3
Try
Dim y As ULong = x
Console.WriteLine(y)
Catch ex As OverflowException
System.Console.WriteLine("pass")
End Try
End Sub
End Module
</file>
</compilation>, expectedOutput:="pass").
VerifyIL("Module1.Main",
<![CDATA[
{
// Code size 38 (0x26)
.maxstack 2
.locals init (Long V_0, //x
System.OverflowException V_1) //ex
IL_0000: ldc.i4.s -3
IL_0002: conv.i8
IL_0003: stloc.0
.try
{
IL_0004: ldloc.0
IL_0005: conv.ovf.u8
IL_0006: call "Sub System.Console.WriteLine(ULong)"
IL_000b: leave.s IL_0025
}
catch System.OverflowException
{
IL_000d: dup
IL_000e: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0013: stloc.1
IL_0014: ldstr "pass"
IL_0019: call "Sub System.Console.WriteLine(String)"
IL_001e: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0023: leave.s IL_0025
}
IL_0025: ret
}
]]>)
End Sub
<WorkItem(546422, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546422")>
<Fact()>
Public Sub LateBindingToSystemArrayIndex01()
CompileAndVerify(
<compilation>
<file name="a.vb">
option strict off
Imports System
Module Module1
Sub Main()
Console.WriteLine(getTypes().Length)
End Sub
Function getTypes() As Array
Dim types As Array = {1, 2, 3, 4}
Dim s(types.Length - 1) As Object
Dim arr As Array
arr = Array.CreateInstance(New Integer.GetType, 12)
Dim i As Integer
For i = 0 To types.Length - 1
arr(i) = types.GetValue(i)
Next
Return arr
End Function
End Module
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithModuleName("MODULE"), expectedOutput:="12").
VerifyIL("Module1.getTypes",
<![CDATA[
{
// Code size 116 (0x74)
.maxstack 6
.locals init (System.Array V_0, //types
System.Array V_1, //arr
Integer V_2, //i
Integer V_3)
IL_0000: ldc.i4.4
IL_0001: newarr "Integer"
IL_0006: dup
IL_0007: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=16 <PrivateImplementationDetails>.CF97ADEEDB59E05BFD73A2B4C2A8885708C4F4F70C84C64B27120E72AB733B72"
IL_000c: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"
IL_0011: stloc.0
IL_0012: ldloc.0
IL_0013: callvirt "Function System.Array.get_Length() As Integer"
IL_0018: ldc.i4.1
IL_0019: sub.ovf
IL_001a: ldc.i4.1
IL_001b: add.ovf
IL_001c: newarr "Object"
IL_0021: pop
IL_0022: ldloca.s V_3
IL_0024: initobj "Integer"
IL_002a: ldloc.3
IL_002b: box "Integer"
IL_0030: call "Function Object.GetType() As System.Type"
IL_0035: ldc.i4.s 12
IL_0037: call "Function System.Array.CreateInstance(System.Type, Integer) As System.Array"
IL_003c: stloc.1
IL_003d: ldloc.0
IL_003e: callvirt "Function System.Array.get_Length() As Integer"
IL_0043: ldc.i4.1
IL_0044: sub.ovf
IL_0045: stloc.3
IL_0046: ldc.i4.0
IL_0047: stloc.2
IL_0048: br.s IL_006e
IL_004a: ldloc.1
IL_004b: ldc.i4.2
IL_004c: newarr "Object"
IL_0051: dup
IL_0052: ldc.i4.0
IL_0053: ldloc.2
IL_0054: box "Integer"
IL_0059: stelem.ref
IL_005a: dup
IL_005b: ldc.i4.1
IL_005c: ldloc.0
IL_005d: ldloc.2
IL_005e: callvirt "Function System.Array.GetValue(Integer) As Object"
IL_0063: stelem.ref
IL_0064: ldnull
IL_0065: call "Sub Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateIndexSet(Object, Object(), String())"
IL_006a: ldloc.2
IL_006b: ldc.i4.1
IL_006c: add.ovf
IL_006d: stloc.2
IL_006e: ldloc.2
IL_006f: ldloc.3
IL_0070: ble.s IL_004a
IL_0072: ldloc.1
IL_0073: ret
}
]]>)
End Sub
<WorkItem(546422, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546422")>
<Fact()>
Public Sub LateBindingToSystemArrayIndex01_D()
CompileAndVerify(
<compilation>
<file name="a.vb">
option strict off
Imports System
Module Module1
Sub Main()
Console.WriteLine(getTypes().Length)
End Sub
Function getTypes() As Array
Dim types As Array = {1, 2, 3, 4}
Dim s(types.Length - 1) As Object
Dim arr As Array
arr = Array.CreateInstance(New Integer.GetType, 12)
Dim i As Integer
For i = 0 To types.Length - 1
arr(i) = types.GetValue(i)
Next
Return arr
End Function
End Module
</file>
</compilation>, options:=TestOptions.ReleaseDebugExe.WithModuleName("MODULE"), expectedOutput:="12").
VerifyIL("Module1.getTypes",
<![CDATA[
{
// Code size 127 (0x7f)
.maxstack 6
.locals init (System.Array V_0, //getTypes
System.Array V_1, //types
Object() V_2, //s
System.Array V_3, //arr
Integer V_4, //i
Integer V_5,
Integer V_6)
IL_0000: ldc.i4.4
IL_0001: newarr "Integer"
IL_0006: dup
IL_0007: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=16 <PrivateImplementationDetails>.CF97ADEEDB59E05BFD73A2B4C2A8885708C4F4F70C84C64B27120E72AB733B72"
IL_000c: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"
IL_0011: stloc.1
IL_0012: ldloc.1
IL_0013: callvirt "Function System.Array.get_Length() As Integer"
IL_0018: ldc.i4.1
IL_0019: sub.ovf
IL_001a: ldc.i4.1
IL_001b: add.ovf
IL_001c: newarr "Object"
IL_0021: stloc.2
IL_0022: ldloca.s V_5
IL_0024: initobj "Integer"
IL_002a: ldloc.s V_5
IL_002c: box "Integer"
IL_0031: call "Function Object.GetType() As System.Type"
IL_0036: ldc.i4.s 12
IL_0038: call "Function System.Array.CreateInstance(System.Type, Integer) As System.Array"
IL_003d: stloc.3
IL_003e: ldloc.1
IL_003f: callvirt "Function System.Array.get_Length() As Integer"
IL_0044: ldc.i4.1
IL_0045: sub.ovf
IL_0046: stloc.s V_6
IL_0048: ldc.i4.0
IL_0049: stloc.s V_4
IL_004b: br.s IL_0075
IL_004d: ldloc.3
IL_004e: ldc.i4.2
IL_004f: newarr "Object"
IL_0054: dup
IL_0055: ldc.i4.0
IL_0056: ldloc.s V_4
IL_0058: box "Integer"
IL_005d: stelem.ref
IL_005e: dup
IL_005f: ldc.i4.1
IL_0060: ldloc.1
IL_0061: ldloc.s V_4
IL_0063: callvirt "Function System.Array.GetValue(Integer) As Object"
IL_0068: stelem.ref
IL_0069: ldnull
IL_006a: call "Sub Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateIndexSet(Object, Object(), String())"
IL_006f: ldloc.s V_4
IL_0071: ldc.i4.1
IL_0072: add.ovf
IL_0073: stloc.s V_4
IL_0075: ldloc.s V_4
IL_0077: ldloc.s V_6
IL_0079: ble.s IL_004d
IL_007b: ldloc.3
IL_007c: stloc.0
IL_007d: ldloc.0
IL_007e: ret
}
]]>)
End Sub
<WorkItem(575547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/575547")>
<Fact()>
Public Sub LateBindingToSystemArrayIndex02()
' Option Strict On
Dim source1 =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Class C
Public Function F() As System.Array
Return Nothing
End Function
End Class
Module M
Sub M(o As C)
Dim value As Object
value = o.F(1)
o.F(2) = value
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(source1)
compilation1.AssertTheseDiagnostics(
<expected>
BC30574: Option Strict On disallows late binding.
value = o.F(1)
~
BC30574: Option Strict On disallows late binding.
o.F(2) = value
~
</expected>)
' Option Strict Off
Dim source2 =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict Off
Class C
Public Function F() As System.Array
Return Nothing
End Function
End Class
Module M
Sub M(o As C)
Dim value As Object
value = o.F(1)
o.F(2) = value
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntime(source2)
compilation2.AssertNoErrors()
End Sub
<Fact(), WorkItem(546860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546860")>
Public Sub Bug17007()
CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
System.Console.WriteLine(Test1(100))
End Sub
Function Test1(x as Integer) As Integer
return Test2(x,-x)
End Function
Function Test2(x as Integer, y as Integer) As Integer
return y
End Function
End Module
</file>
</compilation>, options:=TestOptions.ReleaseExe,
expectedOutput:=
<![CDATA[
-100
]]>)
End Sub
<Fact>
Public Sub InitializeComponentTest()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Public Sub Main()
End Sub
End Module
<Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Class FromDesigner1
Sub InitializeComponenT()
End Sub
Sub New(a As Integer)
MyBase.New()
End Sub
Sub New(a As Byte)
Dim x = Sub()
InitializeComponenT()
End Sub
End Sub
Sub New(a As Short)
If False Then
InitializeComponenT()
End If
End Sub
Sub New(a As SByte)
Me.New(CShort(a))
End Sub
Shared Sub New()
End Sub
Sub New(a As Long)
M1()
End Sub
Sub M1()
M2()
End Sub
Sub M2()
M1()
M3()
End Sub
Sub M3()
M1()
M2()
M3()
InitializeComponent()
End Sub
End Class
<Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Class FromDesigner2
Shared Sub InitializeComponent()
End Sub
Sub New(b As Integer)
MyBase.New()
End Sub
Sub New(b As Byte)
End Sub
End Class
<Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Class FromDesigner3
Private field As Integer = 1
Private Shared sharedField As Integer = 2
Sub InitializeComponent()
End Sub
End Class
<Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Class FromDesigner4
Private field As Integer = 1
Sub InitializeComponent(Of T)()
End Sub
End Class
<Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Class FromDesigner5
Sub InitializeComponent()
End Sub
Sub New(c As Integer)
End Sub
End Class
<Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Class FromDesigner6
Sub InitializeComponent()
End Sub
Sub New(c As Integer)
MyClass.New()
End Sub
Sub New()
InitializeComponent()
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
AssertTheseEmitDiagnostics(compilation,
<expected>
BC40054: 'Public Sub New(a As Integer)' in designer-generated type 'FromDesigner1' should call InitializeComponent method.
Sub New(a As Integer)
~~~
BC40054: 'Public Sub New(c As Integer)' in designer-generated type 'FromDesigner5' should call InitializeComponent method.
Sub New(c As Integer)
~~~
</expected>)
Dim compilationVerifier = CompileAndVerify(compilation)
compilationVerifier.VerifyIL("FromDesigner3..ctor",
<![CDATA[
{
// Code size 20 (0x14)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call "Sub Object..ctor()"
IL_0006: ldarg.0
IL_0007: ldc.i4.1
IL_0008: stfld "FromDesigner3.field As Integer"
IL_000d: ldarg.0
IL_000e: call "Sub FromDesigner3.InitializeComponent()"
IL_0013: ret
}
]]>)
compilationVerifier.VerifyIL("FromDesigner3..cctor",
<![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.2
IL_0001: stsfld "FromDesigner3.sharedField As Integer"
IL_0006: ret
}
]]>)
compilationVerifier.VerifyIL("FromDesigner4..ctor",
<![CDATA[
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call "Sub Object..ctor()"
IL_0006: ldarg.0
IL_0007: ldc.i4.1
IL_0008: stfld "FromDesigner4.field As Integer"
IL_000d: ret
}
]]>)
compilationVerifier.VerifyIL("FromDesigner5..ctor",
<![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Sub Object..ctor()"
IL_0006: ret
}
]]>)
End Sub
<WorkItem(530067, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530067")>
<Fact>
Public Sub NopAfterCall()
' For a nop to be inserted after a call, two conditions must be met:
' 1) sub (vs function)
' 2) debug build
Dim source =
<compilation>
<file name="a.vb">
Module C
Sub Main()
S()
F()
End Sub
Sub S()
End Sub
Function F() As Integer
Return 1
End Function
End Module
</file>
</compilation>
Dim compRelease = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.ReleaseExe)
Dim compDebug = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.DebugExe)
' (2) is not met.
CompileAndVerify(compRelease).VerifyIL("C.Main",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: call "Sub C.S()"
IL_0005: call "Function C.F() As Integer"
IL_000a: pop
IL_000b: ret
}
]]>)
' S meets (1), but F does not (it doesn't need a nop since it has a pop).
CompileAndVerify(compDebug).VerifyIL("C.Main",
<![CDATA[
{
// Code size 14 (0xe)
.maxstack 1
IL_0000: nop
IL_0001: call "Sub C.S()"
IL_0006: nop
IL_0007: call "Function C.F() As Integer"
IL_000c: pop
IL_000d: ret
}
]]>)
End Sub
<WorkItem(529162, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529162")>
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub Bug529162()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq.Expressions
Module Module1
Sub Main()
Dim TestCallByName As Expression(Of Action) = Sub() Microsoft.VisualBasic.Interaction.CallByName(Nothing, Nothing, Nothing)
Print(TestCallByName)
Dim TestIsNumeric As Expression(Of Action) = Sub() Microsoft.VisualBasic.Information.IsNumeric(Nothing)
Print(TestIsNumeric)
Dim TestTypeName As Expression(Of Action) = Sub() Microsoft.VisualBasic.Information.TypeName(Nothing)
Print(TestTypeName)
Dim TestSystemTypeName As Expression(Of Action) = Sub() Microsoft.VisualBasic.Information.SystemTypeName(Nothing)
Print(TestSystemTypeName)
Dim TestVbTypeName As Expression(Of Action) = Sub() Microsoft.VisualBasic.Information.VbTypeName(Nothing)
Print(TestVbTypeName)
End Sub
Sub Print(expr As Expression(Of Action))
Dim [call] = DirectCast(expr.Body, MethodCallExpression)
System.Console.WriteLine("{0} - {1}", [call].Method.DeclaringType, [call].Method)
End Sub
Sub TestCallByName()
Microsoft.VisualBasic.Interaction.CallByName(Nothing, Nothing, Nothing)
End Sub
Sub TestIsNumeric()
Microsoft.VisualBasic.Information.IsNumeric(Nothing)
End Sub
Sub TestTypeName()
Microsoft.VisualBasic.Information.TypeName(Nothing)
End Sub
Sub TestSystemTypeName()
Microsoft.VisualBasic.Information.SystemTypeName(Nothing)
End Sub
Sub TestVbTypeName()
Microsoft.VisualBasic.Information.VbTypeName(Nothing)
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, TestOptions.ReleaseExe)
Dim verifier = CompileAndVerify(compilation,
<![CDATA[
Microsoft.VisualBasic.CompilerServices.Versioned - System.Object CallByName(System.Object, System.String, Microsoft.VisualBasic.CallType, System.Object[])
Microsoft.VisualBasic.CompilerServices.Versioned - Boolean IsNumeric(System.Object)
Microsoft.VisualBasic.CompilerServices.Versioned - System.String TypeName(System.Object)
Microsoft.VisualBasic.CompilerServices.Versioned - System.String SystemTypeName(System.String)
Microsoft.VisualBasic.CompilerServices.Versioned - System.String VbTypeName(System.String)
]]>)
verifier.VerifyIL("Module1.TestCallByName",
<![CDATA[
{
// Code size 16 (0x10)
.maxstack 4
IL_0000: ldnull
IL_0001: ldnull
IL_0002: ldc.i4.0
IL_0003: ldc.i4.0
IL_0004: newarr "Object"
IL_0009: call "Function Microsoft.VisualBasic.CompilerServices.Versioned.CallByName(Object, String, Microsoft.VisualBasic.CallType, ParamArray Object()) As Object"
IL_000e: pop
IL_000f: ret
}
]]>)
verifier.VerifyIL("Module1.TestIsNumeric",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldnull
IL_0001: call "Function Microsoft.VisualBasic.CompilerServices.Versioned.IsNumeric(Object) As Boolean"
IL_0006: pop
IL_0007: ret
}
]]>)
verifier.VerifyIL("Module1.TestTypeName",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldnull
IL_0001: call "Function Microsoft.VisualBasic.CompilerServices.Versioned.TypeName(Object) As String"
IL_0006: pop
IL_0007: ret
}
]]>)
verifier.VerifyIL("Module1.TestSystemTypeName",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldnull
IL_0001: call "Function Microsoft.VisualBasic.CompilerServices.Versioned.SystemTypeName(String) As String"
IL_0006: pop
IL_0007: ret
}
]]>)
verifier.VerifyIL("Module1.TestVbTypeName",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldnull
IL_0001: call "Function Microsoft.VisualBasic.CompilerServices.Versioned.VbTypeName(String) As String"
IL_0006: pop
IL_0007: ret
}
]]>)
End Sub
<WorkItem(653588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/653588")>
<Fact()>
Public Sub UnusedStructFieldLoad()
CompileAndVerify(
<compilation>
<file name="a.vb">
Structure S1
Public field As Integer
Public Sub New(v As Integer)
Me.field = v
End Sub
End Structure
Class A
Shared Sub Main()
Dim x = (New S1()).field
Dim y = (New S1(42)).field
End Sub
End Class
</file>
</compilation>, expectedOutput:="").
VerifyIL("A.Main",
<![CDATA[
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: ldc.i4.s 42
IL_0002: newobj "Sub S1..ctor(Integer)"
IL_0007: pop
IL_0008: ret
}
]]>)
End Sub
<WorkItem(531166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531166")>
<Fact()>
Public Sub LoadingEnumValue__()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Program
Function Goo() As AttributeTargets
Return AttributeTargets.All
End Function
Sub Main(args As String())
Console.Write(Goo().value__)
End Sub
End Module
</file>
</compilation>, expectedOutput:="32767").
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 19 (0x13)
.maxstack 1
.locals init (System.AttributeTargets V_0)
IL_0000: call "Function Program.Goo() As System.AttributeTargets"
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: ldfld "System.AttributeTargets.value__ As Integer"
IL_000d: call "Sub System.Console.Write(Integer)"
IL_0012: ret
}
]]>)
End Sub
<WorkItem(665317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665317")>
<Fact()>
Public Sub InitGenericElement()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class A
End Class
Class B : Inherits A
End Class
Class Program
Shared Sub Goo(Of T As Class)(array As T())
array(0) = Nothing
End Sub
Shared Sub Bar(Of T)(array As T())
array(0) = Nothing
End Sub
Shared Sub Baz(Of T)(array As T()())
array(0) = Nothing
End Sub
Shared Sub Main()
Dim array = New B(5) {}
Goo(Of A)(array)
Bar(Of A)(array)
Dim array1 = New B(5)() {}
Baz(Of A)(array1)
End Sub
End Class
</file>
</compilation>, expectedOutput:="").
VerifyIL("Program.Goo(Of T)(T())",
<![CDATA[
{
// Code size 17 (0x11)
.maxstack 3
.locals init (T V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldloca.s V_0
IL_0004: initobj "T"
IL_000a: ldloc.0
IL_000b: stelem "T"
IL_0010: ret
}
]]>).
VerifyIL("Program.Bar(Of T)(T())",
<![CDATA[
{
// Code size 17 (0x11)
.maxstack 3
.locals init (T V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldloca.s V_0
IL_0004: initobj "T"
IL_000a: ldloc.0
IL_000b: stelem "T"
IL_0010: ret
}
]]>).
VerifyIL("Program.Baz(Of T)(T()())",
<![CDATA[
{
// Code size 5 (0x5)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldnull
IL_0003: stelem.ref
IL_0004: ret
}
]]>)
End Sub
<WorkItem(718502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718502")>
<Fact()>
Public Sub UnaryMinusInCondition()
CompileAndVerify(
<compilation>
<file name="a.vb">
imports system
Class A
private shared x as integer = 42
Shared Sub Main()
if --x = 0
Console.Write(0)
end if
if ++x = 0
Console.Write(0)
end if
if --x <> 0
Console.Write(1)
end if
if ++x <> 0
Console.Write(1)
end if
End Sub
End Class
</file>
</compilation>, expectedOutput:="11").
VerifyIL("A.Main",
<![CDATA[
{
// Code size 61 (0x3d)
.maxstack 3
IL_0000: ldc.i4.0
IL_0001: ldc.i4.0
IL_0002: ldsfld "A.x As Integer"
IL_0007: sub.ovf
IL_0008: sub.ovf
IL_0009: brtrue.s IL_0011
IL_000b: ldc.i4.0
IL_000c: call "Sub System.Console.Write(Integer)"
IL_0011: ldsfld "A.x As Integer"
IL_0016: brtrue.s IL_001e
IL_0018: ldc.i4.0
IL_0019: call "Sub System.Console.Write(Integer)"
IL_001e: ldc.i4.0
IL_001f: ldc.i4.0
IL_0020: ldsfld "A.x As Integer"
IL_0025: sub.ovf
IL_0026: sub.ovf
IL_0027: brfalse.s IL_002f
IL_0029: ldc.i4.1
IL_002a: call "Sub System.Console.Write(Integer)"
IL_002f: ldsfld "A.x As Integer"
IL_0034: brfalse.s IL_003c
IL_0036: ldc.i4.1
IL_0037: call "Sub System.Console.Write(Integer)"
IL_003c: ret
}
]]>)
End Sub
<WorkItem(745103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/745103")>
<Fact()>
Public Sub TestCompoundOnAFieldOfGeneric()
CompileAndVerify(
<compilation>
<file name="a.vb">
Class Module1
Shared Sub Main()
Dim x = New c0()
test(Of c0).Repro1(x)
System.Console.Write(x.x)
test(Of c0).Repro2(x)
System.Console.Write(x.x)
End Sub
End Class
Class c0
Public x As Integer
Public Property P1 As Integer
Get
Return x
End Get
Set(value As Integer)
x = value
End Set
End Property
Default Public Property Item(i As Integer) As Integer
Get
Return x
End Get
Set(value As Integer)
x = value
End Set
End Property
Public Shared Function Goo(arg As c0) As Integer
Return 1
End Function
Public Function Goo() As Integer
Return 1
End Function
End Class
Class test(Of T As c0)
Public Shared Sub Repro1(arg As T)
arg.x += 1
arg.P1 += 1
arg(1) += 1
End Sub
Public Shared Sub Repro2(arg As T)
arg.x = c0.Goo(arg)
arg.x = arg.Goo()
End Sub
End class
</file>
</compilation>, expectedOutput:="31").
VerifyIL("test(Of T).Repro1(T)",
<![CDATA[
{
// Code size 77 (0x4d)
.maxstack 4
.locals init (Integer& V_0)
IL_0000: ldarg.0
IL_0001: box "T"
IL_0006: ldflda "c0.x As Integer"
IL_000b: dup
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ldind.i4
IL_000f: ldc.i4.1
IL_0010: add.ovf
IL_0011: stind.i4
IL_0012: ldarga.s V_0
IL_0014: ldarga.s V_0
IL_0016: constrained. "T"
IL_001c: callvirt "Function c0.get_P1() As Integer"
IL_0021: ldc.i4.1
IL_0022: add.ovf
IL_0023: constrained. "T"
IL_0029: callvirt "Sub c0.set_P1(Integer)"
IL_002e: ldarga.s V_0
IL_0030: ldc.i4.1
IL_0031: ldarga.s V_0
IL_0033: ldc.i4.1
IL_0034: constrained. "T"
IL_003a: callvirt "Function c0.get_Item(Integer) As Integer"
IL_003f: ldc.i4.1
IL_0040: add.ovf
IL_0041: constrained. "T"
IL_0047: callvirt "Sub c0.set_Item(Integer, Integer)"
IL_004c: ret
}
]]>).
VerifyIL("test(Of T).Repro2(T)",
<![CDATA[
{
// Code size 52 (0x34)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box "T"
IL_0006: ldarg.0
IL_0007: box "T"
IL_000c: castclass "c0"
IL_0011: call "Function c0.Goo(c0) As Integer"
IL_0016: stfld "c0.x As Integer"
IL_001b: ldarg.0
IL_001c: box "T"
IL_0021: ldarga.s V_0
IL_0023: constrained. "T"
IL_0029: callvirt "Function c0.Goo() As Integer"
IL_002e: stfld "c0.x As Integer"
IL_0033: ret
}
]]>)
End Sub
<Fact()>
Public Sub CallFinalMethodOnTypeParam()
CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Test1(New cls1())
Test1(New cls2())
Test2(New cls2())
End Sub
Sub Test1(Of T As cls1)(arg As T)
arg.Goo()
End Sub
Sub Test2(Of T As cls2)(arg As T)
arg.Goo()
End Sub
End Module
Class cls0
Overridable Sub Goo()
End Sub
End Class
Class cls1 : Inherits cls0
Public NotOverridable Overrides Sub Goo()
System.Console.Write("Goo")
End Sub
End Class
Class cls2 : Inherits cls1
End Class
</file>
</compilation>, expectedOutput:="GooGooGoo").
VerifyIL("Module1.Test1(Of T)(T)",
<![CDATA[
{
// Code size 14 (0xe)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: constrained. "T"
IL_0008: callvirt "Sub cls1.Goo()"
IL_000d: ret
}
]]>).
VerifyIL("Module1.Test2(Of T)(T)",
<![CDATA[
{
// Code size 14 (0xe)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: constrained. "T"
IL_0008: callvirt "Sub cls1.Goo()"
IL_000d: ret
}
]]>)
End Sub
<WorkItem(770557, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770557")>
<Fact()>
Public Sub BoolConditionDebug001()
CompileAndVerify(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.InteropServices
<StructLayout(LayoutKind.Explicit)>
Public Structure BoolBreaker
<FieldOffset(0)> Public i As Int32
<FieldOffset(0)> Public bool As Boolean
End Structure
Friend Module Module1
Sub Main()
Dim x As BoolBreaker
x.i = 2
If x.bool <> True Then
Console.Write("i=2 -> x.bool <> True ") ' Roslyn
Else
Console.Write("i=2 -> x.bool = True ") ' Native
End If
x.i = 2147483647
If x.bool <> True Then
Console.Write("i=2147483647 -> x.bool <> True ")
Else
Console.Write("i=21474836472 -> x.bool = True ")
End If
End Sub
End Module
]]>
</file>
</compilation>, expectedOutput:="i=2 -> x.bool = True i=21474836472 -> x.bool = True").
VerifyIL("Module1.Main",
<![CDATA[
{
// Code size 80 (0x50)
.maxstack 2
.locals init (BoolBreaker V_0) //x
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.2
IL_0003: stfld "BoolBreaker.i As Integer"
IL_0008: ldloc.0
IL_0009: ldfld "BoolBreaker.bool As Boolean"
IL_000e: brtrue.s IL_001c
IL_0010: ldstr "i=2 -> x.bool <> True "
IL_0015: call "Sub System.Console.Write(String)"
IL_001a: br.s IL_0026
IL_001c: ldstr "i=2 -> x.bool = True "
IL_0021: call "Sub System.Console.Write(String)"
IL_0026: ldloca.s V_0
IL_0028: ldc.i4 0x7fffffff
IL_002d: stfld "BoolBreaker.i As Integer"
IL_0032: ldloc.0
IL_0033: ldfld "BoolBreaker.bool As Boolean"
IL_0038: brtrue.s IL_0045
IL_003a: ldstr "i=2147483647 -> x.bool <> True "
IL_003f: call "Sub System.Console.Write(String)"
IL_0044: ret
IL_0045: ldstr "i=21474836472 -> x.bool = True "
IL_004a: call "Sub System.Console.Write(String)"
IL_004f: ret
}
]]>)
End Sub
<WorkItem(770557, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770557")>
<Fact()>
Public Sub BoolConditionDebug002()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.InteropServices
<StructLayout(LayoutKind.Explicit)>
Public Structure BoolBreaker
<FieldOffset(0)> Public i As Int32
<FieldOffset(0)> Public bool As Boolean
End Structure
Friend Module Module1
Sub Main()
Dim x As BoolBreaker
x.i = 2
If x.bool <> True Then
Console.Write("i=2 -> x.bool <> True ") ' Roslyn
Else
Console.Write("i=2 -> x.bool = True ") ' Native
End If
x.i = 2147483647
If x.bool <> True Then
Console.Write("i=2147483647 -> x.bool <> True ")
Else
Console.Write("i=21474836472 -> x.bool = True ")
End If
End Sub
End Module
]]>
</file>
</compilation>, options:=TestOptions.DebugExe,
expectedOutput:="i=2 -> x.bool = True i=21474836472 -> x.bool = True")
c.VerifyIL("Module1.Main",
<![CDATA[
{
// Code size 102 (0x66)
.maxstack 2
.locals init (BoolBreaker V_0, //x
Boolean V_1,
Boolean V_2)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.2
IL_0004: stfld "BoolBreaker.i As Integer"
IL_0009: ldloc.0
IL_000a: ldfld "BoolBreaker.bool As Boolean"
IL_000f: ldc.i4.0
IL_0010: ceq
IL_0012: stloc.1
IL_0013: ldloc.1
IL_0014: brfalse.s IL_0024
IL_0016: ldstr "i=2 -> x.bool <> True "
IL_001b: call "Sub System.Console.Write(String)"
IL_0020: nop
IL_0021: nop
IL_0022: br.s IL_0031
IL_0024: nop
IL_0025: ldstr "i=2 -> x.bool = True "
IL_002a: call "Sub System.Console.Write(String)"
IL_002f: nop
IL_0030: nop
IL_0031: ldloca.s V_0
IL_0033: ldc.i4 0x7fffffff
IL_0038: stfld "BoolBreaker.i As Integer"
IL_003d: ldloc.0
IL_003e: ldfld "BoolBreaker.bool As Boolean"
IL_0043: ldc.i4.0
IL_0044: ceq
IL_0046: stloc.2
IL_0047: ldloc.2
IL_0048: brfalse.s IL_0058
IL_004a: ldstr "i=2147483647 -> x.bool <> True "
IL_004f: call "Sub System.Console.Write(String)"
IL_0054: nop
IL_0055: nop
IL_0056: br.s IL_0065
IL_0058: nop
IL_0059: ldstr "i=21474836472 -> x.bool = True "
IL_005e: call "Sub System.Console.Write(String)"
IL_0063: nop
IL_0064: nop
IL_0065: ret
}
]]>)
End Sub
<WorkItem(797996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797996")>
<Fact()>
Public Sub MissingMember_Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean()
Dim compilation = CreateEmptyCompilation(
<compilation>
<file name="a.vb"><![CDATA[
Namespace System
Public Class [Object]
End Class
Public Structure Void
End Structure
Public Class ValueType
End Class
Public Structure Int32
End Structure
Public Structure UInt32
End Structure
Public Structure Nullable(Of T)
End Structure
Public Class [String]
End Class
End Namespace
Class C
Shared Sub M(s As String)
Select Case s
Case "A"
Case "B"
End Select
End Sub
End Class
]]></file>
</compilation>)
AssertTheseEmitDiagnostics(compilation,
<errors>
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Operators.CompareString' is not defined.
Select Case s
~
BC35000: Requested operation is not available because the runtime library function 'System.String.get_Chars' is not defined.
Select Case s
~
</errors>)
End Sub
' As above with Microsoft.VisualBasic.CompilerServices.EmbeddedOperators defined.
<WorkItem(797996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797996")>
<Fact()>
Public Sub MissingMember_Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean()
Dim compilation = CreateEmptyCompilation(
<compilation>
<file name="a.vb"><![CDATA[
Namespace System
Public Class [Object]
End Class
Public Structure Void
End Structure
Public Class ValueType
End Class
Public Structure Int32
End Structure
Public Structure UInt32
End Structure
Public Structure Nullable(Of T)
End Structure
Public Class [String]
End Class
End Namespace
Namespace Microsoft.VisualBasic.CompilerServices
Public Class EmbeddedOperators
End Class
End Namespace
Class C
Shared Sub M(s As String)
Select Case s
Case "A"
Case "B"
End Select
End Sub
End Class
]]></file>
</compilation>)
AssertTheseEmitDiagnostics(compilation,
<errors>
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.EmbeddedOperators.CompareString' is not defined.
Select Case s
~
BC35000: Requested operation is not available because the runtime library function 'System.String.get_Chars' is not defined.
Select Case s
~
</errors>)
End Sub
<WorkItem(797996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797996")>
<Fact()>
Public Sub MissingMember_System_Type__GetTypeFromHandle()
Dim compilation = CreateEmptyCompilation(
<compilation>
<file name="a.vb"><![CDATA[
Namespace System
Public Class [Object]
End Class
Public Structure Void
End Structure
Public Class ValueType
End Class
Public Structure Int32
End Structure
Public Structure Nullable(Of T)
End Structure
Public Class [Type]
End Class
End Namespace
Class C
Shared F As Object = GetType(C)
End Class
]]></file>
</compilation>)
AssertTheseEmitDiagnostics(compilation,
<errors>
BC35000: Requested operation is not available because the runtime library function 'System.Type.GetTypeFromHandle' is not defined.
Shared F As Object = GetType(C)
~~~~~~~~~~
</errors>)
End Sub
<WorkItem(797996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797996")>
<Fact()>
Public Sub MissingMember_Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError()
Dim compilation = CreateEmptyCompilation(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Namespace System
Public Class [Object]
End Class
Public Structure Void
End Structure
Public Class ValueType
End Class
Public Class Exception
End Class
End Namespace
Class C
Shared Sub M()
Try
Dim o = Nothing
Catch e As Exception
End Try
End Sub
End Class
]]></file>
</compilation>)
AssertTheseEmitDiagnostics(compilation,
<errors>
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError' is not defined.
Catch e As Exception
~~~~~~~~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError' is not defined.
Catch e As Exception
~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<WorkItem(765569, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/765569")>
<Fact()>
Public Sub ConstMatchesType()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Public Enum LineStyle
Dot
Dash
End Enum
Friend Class A
Public shared Sub Main()
Const linestyle As LineStyle = LineStyle.Dot
Console.WriteLine(linestyle)
End Sub
End CLass
</file>
</compilation>, expectedOutput:="0").
VerifyIL("A.Main",
<![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: call "Sub System.Console.WriteLine(Integer)"
IL_0006: ret
}
]]>)
End Sub
<WorkItem(824308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824308")>
<Fact()>
Public Sub ConstCircular001()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Public Enum LineStyle
Dot
Dash
End Enum
Friend Class A
Public shared Sub Main()
Const blah As LineStyle = blah Or LineStyle.Dot
Console.WriteLine(blah)
End Sub
End CLass
]]></file>
</compilation>)
comp.AssertTheseDiagnostics(
<errors>
BC30500: Constant 'blah' cannot depend on its own value.
Const blah As LineStyle = blah Or LineStyle.Dot
~~~~
</errors>)
End Sub
<WorkItem(824308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824308")>
<Fact()>
Public Sub ConstCircular002()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Public Enum LineStyle
Dot
Dash
End Enum
Friend Class A
Public shared Sub Main()
Const blah = blah Or LineStyle.Dot
Console.WriteLine(blah)
End Sub
End CLass
]]></file>
</compilation>)
comp.AssertTheseDiagnostics(
<errors>
BC30500: Constant 'blah' cannot depend on its own value.
Const blah = blah Or LineStyle.Dot
~~~~
BC42104: Variable 'blah' is used before it has been assigned a value. A null reference exception could result at runtime.
Const blah = blah Or LineStyle.Dot
~~~~
</errors>)
End Sub
<WorkItem(824308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824308")>
<Fact()>
Public Sub ConstCircular003()
Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Public Enum LineStyle
Dot
Dash
End Enum
Friend Class A
Public shared Sub Main()
Const blah As Object = blah Or LineStyle.Dot
Const blah1 As Object = blah1
Console.WriteLine(blah)
End Sub
End CLass
]]></file>
</compilation>)
comp.AssertTheseDiagnostics(
<errors>
BC30500: Constant 'blah' cannot depend on its own value.
Const blah As Object = blah Or LineStyle.Dot
~~~~
BC42104: Variable 'blah' is used before it has been assigned a value. A null reference exception could result at runtime.
Const blah As Object = blah Or LineStyle.Dot
~~~~
BC30500: Constant 'blah1' cannot depend on its own value.
Const blah1 As Object = blah1
~~~~~
BC42104: Variable 'blah1' is used before it has been assigned a value. A null reference exception could result at runtime.
Const blah1 As Object = blah1
~~~~~
</errors>)
End Sub
<Fact>
<WorkItem(4196, "https://github.com/dotnet/roslyn/issues/4196")>
Public Sub BadDefaultParameterValue()
Dim source =
<compilation>
<file name="a.vb">
Imports BadDefaultParameterValue
Module C
Sub Main
Util.M("test")
End Sub
End Module
</file>
</compilation>
Dim testReference = AssemblyMetadata.CreateFromImage(TestResources.Repros.BadDefaultParameterValue).GetReference()
Dim compilation = CompileAndVerify(source, references:=New MetadataReference() {testReference})
compilation.VerifyIL("C.Main",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 2
IL_0000: ldstr "test"
IL_0005: ldnull
IL_0006: call "Sub BadDefaultParameterValue.Util.M(String, String)"
IL_000b: ret
}]]>)
End Sub
<ConditionalFact(GetType(NoIOperationValidation))>
<WorkItem(5395, "https://github.com/dotnet/roslyn/issues/5395")>
Public Sub EmitSequenceOfBinaryExpressions_01()
Dim source =
$"
Class Test
Shared Sub Main()
Dim f = new Long(4096-1) {{}}
for i As Integer = 0 To 4095
f(i) = 4096 - i
Next
System.Console.WriteLine(If(Calculate1(f) = Calculate2(f), ""True"", ""False""))
End Sub
Shared Function Calculate1(f As Long()) As Long
Return {BuildSequenceOfBinaryExpressions_01()}
End Function
Shared Function Calculate2(f As Long()) As Long
Dim result as Long = 0
Dim i as Integer
For i = 0 To f.Length - 1
result+=(i + 1)*f(i)
Next
return result + (i + 1)
End Function
End Class
"
Dim compilation = CreateCompilationWithMscorlib40({source}, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:="True")
End Sub
Private Shared Function BuildSequenceOfBinaryExpressions_01(Optional count As Integer = 4096) As String
Dim builder = New System.Text.StringBuilder()
Dim i As Integer
For i = 0 To count - 1
builder.Append(i + 1)
builder.Append(" * ")
builder.Append("f(")
builder.Append(i)
builder.Append(") + ")
Next
builder.Append(i + 1)
Return builder.ToString()
End Function
<ConditionalFact(GetType(NoIOperationValidation))>
<WorkItem(5395, "https://github.com/dotnet/roslyn/issues/5395")>
Public Sub EmitSequenceOfBinaryExpressions_02()
Dim source =
$"
Class Test
Shared Sub Main()
Dim f = new Long(4096-1) {{}}
for i As Integer = 0 To 4095
f(i) = 4096 - i
Next
System.Console.WriteLine(Calculate(f))
End Sub
Shared Function Calculate(f As Long()) As Double
Return {BuildSequenceOfBinaryExpressions_01()}
End Function
End Class
"
Dim compilation = CreateCompilationWithMscorlib40({source}, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
CompileAndVerify(compilation, expectedOutput:="11461640193")
End Sub
<ConditionalFact(GetType(NoIOperationValidation))>
<WorkItem(6077, "https://github.com/dotnet/roslyn/issues/6077")>
<WorkItem(5395, "https://github.com/dotnet/roslyn/issues/5395")>
Public Sub EmitSequenceOfBinaryExpressions_03()
Dim diagnostics = ImmutableArray(Of Diagnostic).Empty
Const start = 8192
Const [step] = 4096
Const limit = start * 4
For count As Integer = start To limit Step [step]
Dim source =
$"
Class Test
Shared Sub Main()
End Sub
Shared Function Calculate(a As Boolean(), f As Boolean()) As Boolean
Return {BuildSequenceOfBinaryExpressions_03(count)}
End Function
End Class
"
Dim compilation = CreateCompilationWithMscorlib40({source}, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
diagnostics = compilation.GetEmitDiagnostics()
If Not diagnostics.IsEmpty Then
Exit For
End If
Next
diagnostics.Verify(
Diagnostic(ERRID.ERR_TooLongOrComplexExpression, "a").WithLocation(7, 16)
)
End Sub
Private Shared Function BuildSequenceOfBinaryExpressions_03(Optional count As Integer = 8192) As String
Dim builder = New System.Text.StringBuilder()
Dim i As Integer
For i = 0 To count - 1
builder.Append("a(")
builder.Append(i)
builder.Append(")")
builder.Append(" AndAlso ")
builder.Append("f(")
builder.Append(i)
builder.Append(") OrElse ")
Next
builder.Append("a(")
builder.Append(i)
builder.Append(")")
Return builder.ToString()
End Function
<ConditionalFact(GetType(NoIOperationValidation))>
<WorkItem(5395, "https://github.com/dotnet/roslyn/issues/5395")>
Public Sub EmitSequenceOfBinaryExpressions_04()
Dim size = 8192
Dim source =
$"
Class Test
Shared Sub Main()
Dim f = new Single?({size}-1) {{}}
for i As Integer = 0 To ({size} - 1)
f(i) = 4096 - i
Next
System.Console.WriteLine(Calculate(f))
End Sub
Shared Function Calculate(f As Single?()) As Double?
Return {BuildSequenceOfBinaryExpressions_01(size)}
End Function
End Class
"
Dim compilation = CreateCompilationWithMscorlib40({source}, options:=TestOptions.ReleaseExe)
compilation.VerifyEmitDiagnostics(
Diagnostic(ERRID.ERR_TooLongOrComplexExpression, "1").WithLocation(13, 16)
)
End Sub
<ConditionalFact(GetType(NoIOperationValidation))>
<WorkItem(5395, "https://github.com/dotnet/roslyn/issues/5395")>
Public Sub EmitSequenceOfBinaryExpressions_05()
Dim count As Integer = 50
Dim source =
$"
Class Test
Shared Sub Main()
Test1()
Test2()
End Sub
Shared Sub Test1()
Dim f = new Double({count}-1) {{}}
for i As Integer = 0 To {count}-1
f(i) = 4096 - i
Next
System.Console.WriteLine(Calculate(f))
End Sub
Shared Function Calculate(f As Double()) As Double
Return {BuildSequenceOfBinaryExpressions_01(count)}
End Function
Shared Sub Test2()
Dim f = new Double?({count}-1) {{}}
for i As Integer = 0 To {count}-1
f(i) = 4096 - i
Next
System.Console.WriteLine(Calculate(f))
End Sub
Shared Function Calculate(f As Double?()) As Double?
Return {BuildSequenceOfBinaryExpressions_01(count)}
End Function
End Class
"
Dim compilation = CreateCompilationWithMscorlib40({source}, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:="5180801
5180801")
End Sub
<ConditionalFact(GetType(NoIOperationValidation), GetType(WindowsOnly))>
<WorkItem(5395, "https://github.com/dotnet/roslyn/issues/5395")>
Public Sub EmitSequenceOfBinaryExpressions_06()
Dim source =
$"
Class Test
Shared Sub Main()
End Sub
Shared Function Calculate(a As S1(), f As S1()) As Boolean
Return {BuildSequenceOfBinaryExpressions_03()}
End Function
End Class
Structure S1
Public Shared Operator And(x As S1, y As S1) As S1
Return New S1()
End Operator
Public Shared Operator Or(x As S1, y As S1) As S1
Return New S1()
End Operator
Public Shared Operator IsTrue(x As S1) As Boolean
Return True
End Operator
Public Shared Operator IsFalse(x As S1) As Boolean
Return True
End Operator
Public Shared Widening Operator CType(x As S1) As Boolean
Return True
End Operator
End Structure
"
Dim compilation = CreateCompilationWithMscorlib40({source}, options:=TestOptions.ReleaseExe.WithOverflowChecks(True))
compilation.VerifyEmitDiagnostics(
Diagnostic(ERRID.ERR_TooLongOrComplexExpression, "a").WithLocation(7, 16),
Diagnostic(ERRID.ERR_TooLongOrComplexExpression, "a").WithLocation(7, 16),
Diagnostic(ERRID.ERR_TooLongOrComplexExpression, "a").WithLocation(7, 16)
)
End Sub
<Fact()>
Public Sub InplaceCtorUsesLocal()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Private arr As S1() = New S1(1) {}
Structure S1
Public a, b As Integer
Public Sub New(a As Integer, b As Integer)
Me.a = a
Me.b = b
End Sub
Public Sub New(a As Integer)
Me.a = a
End Sub
End Structure
Sub Main()
Dim arg = System.Math.Max(1, 2)
Dim val = New S1(arg, arg)
arr(0) = val
System.Console.WriteLine(arr(0).a)
End Sub
End Module
]]>
</file>
</compilation>, options:=TestOptions.ReleaseExe,
expectedOutput:="2")
c.VerifyIL("Module1.Main",
<![CDATA[
{
// Code size 51 (0x33)
.maxstack 3
.locals init (Integer V_0, //arg
Module1.S1 V_1) //val
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: call "Function System.Math.Max(Integer, Integer) As Integer"
IL_0007: stloc.0
IL_0008: ldloca.s V_1
IL_000a: ldloc.0
IL_000b: ldloc.0
IL_000c: call "Sub Module1.S1..ctor(Integer, Integer)"
IL_0011: ldsfld "Module1.arr As Module1.S1()"
IL_0016: ldc.i4.0
IL_0017: ldloc.1
IL_0018: stelem "Module1.S1"
IL_001d: ldsfld "Module1.arr As Module1.S1()"
IL_0022: ldc.i4.0
IL_0023: ldelema "Module1.S1"
IL_0028: ldfld "Module1.S1.a As Integer"
IL_002d: call "Sub System.Console.WriteLine(Integer)"
IL_0032: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(33564, "https://github.com/dotnet/roslyn/issues/33564")>
<WorkItem(7148, "https://github.com/dotnet/roslyn/issues/7148")>
Public Sub Issue7148_1()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Public Class TestClass
Private _rotation As Decimal
Private Sub CalculateDimensions()
_rotation *= 180 / System.Math.PI 'This line causes '"vbc.exe" exited with code -2146232797'
End Sub
Shared Sub Main()
Dim x as New TestClass()
x._rotation = 1
x.CalculateDimensions()
System.Console.WriteLine(x._rotation)
End Sub
End Class
</file>
</compilation>, options:=TestOptions.ReleaseExe,
expectedOutput:="57.2957795130823")
c.VerifyIL("TestClass.CalculateDimensions",
<![CDATA[
{
// Code size 40 (0x28)
.maxstack 3
.locals init (Decimal& V_0)
IL_0000: ldarg.0
IL_0001: ldflda "TestClass._rotation As Decimal"
IL_0006: dup
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldobj "Decimal"
IL_000e: call "Function System.Convert.ToDouble(Decimal) As Double"
IL_0013: ldc.r8 57.2957795130823
IL_001c: mul
IL_001d: newobj "Sub Decimal..ctor(Double)"
IL_0022: stobj "Decimal"
IL_0027: ret
}
]]>)
End Sub
<Fact()>
<WorkItem(33564, "https://github.com/dotnet/roslyn/issues/33564")>
<WorkItem(7148, "https://github.com/dotnet/roslyn/issues/7148")>
Public Sub Issue7148_2()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Public Class TestClass
Private Shared Sub CalculateDimensions(_rotation As Decimal())
_rotation(GetIndex()) *= 180 / System.Math.PI 'This line causes '"vbc.exe" exited with code -2146232797'
End Sub
Private Shared Function GetIndex() As Integer
Return 0
End Function
Shared Sub Main()
Dim _rotation(0) as Decimal
_rotation(0) = 1
CalculateDimensions(_rotation)
System.Console.WriteLine(_rotation(0))
End Sub
End Class
</file>
</compilation>, options:=TestOptions.ReleaseExe,
expectedOutput:="57.2957795130823")
c.VerifyIL("TestClass.CalculateDimensions",
<![CDATA[
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (Decimal& V_0)
IL_0000: ldarg.0
IL_0001: call "Function TestClass.GetIndex() As Integer"
IL_0006: ldelema "Decimal"
IL_000b: dup
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ldobj "Decimal"
IL_0013: call "Function System.Convert.ToDouble(Decimal) As Double"
IL_0018: ldc.r8 57.2957795130823
IL_0021: mul
IL_0022: newobj "Sub Decimal..ctor(Double)"
IL_0027: stobj "Decimal"
IL_002c: ret
}
]]>)
End Sub
<Fact, WorkItem(9703, "https://github.com/dotnet/roslyn/issues/9703")>
Public Sub IgnoredConversion()
CompileAndVerify(
<compilation>
<file name="ignoreNullableValue.vb">
Module MainModule
Public Class Form1
Public Class BadCompiler
Public Property Value As Date?
End Class
Private TestObj As BadCompiler = New BadCompiler()
Public Sub IPE()
Dim o as Object
o = TestObj.Value
End Sub
End Class
Public Sub Main()
Dim f = new Form1
f.IPE()
End Sub
End Module
</file>
</compilation>).
VerifyIL("MainModule.Form1.IPE",
<![CDATA[
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld "MainModule.Form1.TestObj As MainModule.Form1.BadCompiler"
IL_0006: callvirt "Function MainModule.Form1.BadCompiler.get_Value() As Date?"
IL_000b: pop
IL_000c: ret
}
]]>)
End Sub
<Fact, WorkItem(15672, "https://github.com/dotnet/roslyn/pull/15672")>
Public Sub ConditionalAccessOffOfUnconstrainedDefault1()
Dim c = CompileAndVerify(
<compilation>
<file name="ignoreNullableValue.vb">
Module Module1
Public Sub Main()
Test(42)
Test("")
End Sub
Public Sub Test(of T)(arg as T)
System.Console.WriteLine(DirectCast(Nothing, T)?.ToString())
End Sub
End Module
</file>
</compilation>, options:=TestOptions.ReleaseExe,
expectedOutput:="0")
c.VerifyIL("Module1.Test",
<![CDATA[
{
// Code size 48 (0x30)
.maxstack 1
.locals init (T V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj "T"
IL_0008: ldloc.0
IL_0009: box "T"
IL_000e: brtrue.s IL_0013
IL_0010: ldnull
IL_0011: br.s IL_002a
IL_0013: ldloca.s V_0
IL_0015: initobj "T"
IL_001b: ldloc.0
IL_001c: stloc.0
IL_001d: ldloca.s V_0
IL_001f: constrained. "T"
IL_0025: callvirt "Function Object.ToString() As String"
IL_002a: call "Sub System.Console.WriteLine(String)"
IL_002f: ret
}
]]>)
End Sub
<Fact, WorkItem(22533, "https://github.com/dotnet/roslyn/issues/22533")>
Public Sub TestExplicitDoubleConversionEmitted()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Program
Function M() As Boolean
Dim dValue As Double = 600.1
Dim mbytDeciWgt As Byte = 1
Return CDbl(dValue) > CDbl(dValue + CDbl(10 ^ -mbytDeciWgt))
End Function
End Module
</file>
</compilation>).
VerifyIL("Program.M",
<![CDATA[
{
// Code size 39 (0x27)
.maxstack 4
.locals init (Double V_0, //dValue
Byte V_1) //mbytDeciWgt
IL_0000: ldc.r8 600.1
IL_0009: stloc.0
IL_000a: ldc.i4.1
IL_000b: stloc.1
IL_000c: ldloc.0
IL_000d: conv.r8
IL_000e: ldloc.0
IL_000f: ldc.r8 10
IL_0018: ldloc.1
IL_0019: neg
IL_001a: conv.ovf.i2
IL_001b: conv.r8
IL_001c: call "Function System.Math.Pow(Double, Double) As Double"
IL_0021: conv.r8
IL_0022: add
IL_0023: conv.r8
IL_0024: cgt
IL_0026: ret
}
]]>)
End Sub
<Fact, WorkItem(22533, "https://github.com/dotnet/roslyn/issues/22533")>
Public Sub TestImplicitDoubleConversionEmitted()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Program
Function M() As Boolean
Dim dValue As Double = 600.1
Dim mbytDeciWgt As Byte = 1
Return dValue > dValue + (10 ^ -mbytDeciWgt)
End Function
End Module
</file>
</compilation>).
VerifyIL("Program.M",
<![CDATA[
{
// Code size 34 (0x22)
.maxstack 4
.locals init (Byte V_0) //mbytDeciWgt
IL_0000: ldc.r8 600.1
IL_0009: ldc.i4.1
IL_000a: stloc.0
IL_000b: dup
IL_000c: ldc.r8 10
IL_0015: ldloc.0
IL_0016: neg
IL_0017: conv.ovf.i2
IL_0018: conv.r8
IL_0019: call "Function System.Math.Pow(Double, Double) As Double"
IL_001e: add
IL_001f: cgt
IL_0021: ret
}
]]>)
End Sub
<Fact, WorkItem(22533, "https://github.com/dotnet/roslyn/issues/22533")>
Public Sub TestExplicitSingleConversionEmitted()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Program
Function M() As Boolean
Dim dValue As Single = 600.1
Dim mbytDeciWgt As Byte = 1
Return CSng(dValue) > CSng(dValue + CSng(10 ^ -mbytDeciWgt))
End Function
End Module
</file>
</compilation>).
VerifyIL("Program.M",
<![CDATA[
{
// Code size 35 (0x23)
.maxstack 4
.locals init (Single V_0, //dValue
Byte V_1) //mbytDeciWgt
IL_0000: ldc.r4 600.1
IL_0005: stloc.0
IL_0006: ldc.i4.1
IL_0007: stloc.1
IL_0008: ldloc.0
IL_0009: conv.r4
IL_000a: ldloc.0
IL_000b: ldc.r8 10
IL_0014: ldloc.1
IL_0015: neg
IL_0016: conv.ovf.i2
IL_0017: conv.r8
IL_0018: call "Function System.Math.Pow(Double, Double) As Double"
IL_001d: conv.r4
IL_001e: add
IL_001f: conv.r4
IL_0020: cgt
IL_0022: ret
}
]]>)
End Sub
<Fact, WorkItem(22533, "https://github.com/dotnet/roslyn/issues/22533")>
Public Sub TestExplicitSingleConversionNotEmittedOnConstantValue()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Program
Function M() As Boolean
Dim dValue As Single = 600.1
Dim mbytDeciWgt As Byte = 1
Return CSng(dValue) > CSng(CSng(600) + CSng(0.1))
End Function
End Module
</file>
</compilation>).
VerifyIL("Program.M",
<![CDATA[
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldc.r4 600.1
IL_0005: conv.r4
IL_0006: ldc.r4 600.1
IL_000b: cgt
IL_000d: ret
}
]]>)
End Sub
<Fact>
Public Sub ArrayElementByReference_Invariant()
Dim comp =
<compilation>
<file>
Option Strict Off
Module M
Sub Main()
F(New String() {"b"})
End Sub
Sub F(a() As String)
G(a)
System.Console.Write(a(0))
End Sub
Sub G(a() As String)
H(a(0))
End Sub
Sub H(ByRef s As String)
s = s.ToUpper()
End Sub
End Module
</file>
</compilation>
CompileAndVerify(comp, expectedOutput:="B").
VerifyIL("M.G",
<![CDATA[
{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldelema "String"
IL_0007: call "Sub M.H(ByRef String)"
IL_000c: ret
}
]]>)
End Sub
<Fact, WorkItem(547533, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=547533")>
Public Sub ArrayElementByReference_Covariant()
Dim comp =
<compilation>
<file>
Option Strict Off
Module M
Sub Main()
F(New Object() {"a"})
F(New String() {"b"})
End Sub
Sub F(a() As Object)
G(a)
System.Console.Write(a(0))
End Sub
Sub G(a() As Object)
H(a(0))
End Sub
Sub H(ByRef s As String)
s = s.ToUpper()
End Sub
End Module
</file>
</compilation>
CompileAndVerify(comp, expectedOutput:="AB").
VerifyIL("M.G",
<![CDATA[
{
// Code size 21 (0x15)
.maxstack 3
.locals init (String V_0)
IL_0000: ldarg.0
IL_0001: dup
IL_0002: ldc.i4.0
IL_0003: ldelem.ref
IL_0004: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Object) As String"
IL_0009: stloc.0
IL_000a: ldloca.s V_0
IL_000c: call "Sub M.H(ByRef String)"
IL_0011: ldc.i4.0
IL_0012: ldloc.0
IL_0013: stelem.ref
IL_0014: ret
}
]]>)
End Sub
' Generated code results in ArrayTypeMismatchException,
' matching native compiler.
<Fact, WorkItem(547533, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=547533")>
Public Sub ArrayElementByReferenceBase_Covariant()
Dim comp =
<compilation>
<file>
Option Strict Off
Module M
Sub Main()
F(New Object() {"a"})
F(New String() {"b"})
End Sub
Sub F(a() As Object)
Try
G(a)
System.Console.Write(a(0))
Catch e As System.Exception
System.Console.Write(e.GetType().Name)
End Try
End Sub
Sub G(a() As Object)
H(a(0))
End Sub
Sub H(ByRef s As Object)
s = s.ToString().ToUpper()
End Sub
End Module
</file>
</compilation>
CompileAndVerify(comp, expectedOutput:="AArrayTypeMismatchException").
VerifyIL("M.G",
<![CDATA[
{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldelema "Object"
IL_0007: call "Sub M.H(ByRef Object)"
IL_000c: ret
}
]]>)
End Sub
<Fact, WorkItem(547533, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=547533")>
Public Sub ArrayElementByReference_TypeParameter()
Dim comp =
<compilation>
<file>
Option Strict Off
Module M
Sub Main()
Dim a = New String() { "b" }
Dim b = New B()
b.F(a)
System.Console.Write(a(0))
End Sub
End Module
MustInherit Class A(Of T)
Friend MustOverride Sub F(Of U As T)(a() As U)
End Class
Class B
Inherits A(Of String)
Friend Overrides Sub F(Of U As String)(a() As U)
G(a(0))
End Sub
Sub G(ByRef s As String)
s = s.ToUpper()
End Sub
End Class
</file>
</compilation>
CompileAndVerify(comp, expectedOutput:="B").
VerifyIL("B.F",
<![CDATA[
{
// Code size 42 (0x2a)
.maxstack 3
.locals init (U() V_0,
String V_1)
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: dup
IL_0003: stloc.0
IL_0004: ldc.i4.0
IL_0005: ldelem "U"
IL_000a: box "U"
IL_000f: castclass "String"
IL_0014: stloc.1
IL_0015: ldloca.s V_1
IL_0017: call "Sub B.G(ByRef String)"
IL_001c: ldloc.0
IL_001d: ldc.i4.0
IL_001e: ldloc.1
IL_001f: unbox.any "U"
IL_0024: stelem "U"
IL_0029: ret
}
]]>)
End Sub
<Fact, WorkItem(547533, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=547533")>
Public Sub ArrayElementByReference_StructConstraint()
Dim comp =
<compilation>
<file>
Option Strict Off
Module M
Sub Main()
Dim a = New Integer() { 1 }
Dim b = New B()
b.F(a)
System.Console.Write(a(0))
End Sub
End Module
MustInherit Class A(Of T)
Friend MustOverride Sub F(Of U As {T, Structure})(a() As U)
End Class
Class B
Inherits A(Of Integer)
Friend Overrides Sub F(Of U As {Integer, Structure})(a() As U)
G(a(0))
End Sub
Sub G(ByRef i As Integer)
i += 1
End Sub
End Class
</file>
</compilation>
CompileAndVerify(comp, expectedOutput:="2").
VerifyIL("B.F",
<![CDATA[
{
// Code size 47 (0x2f)
.maxstack 3
.locals init (U() V_0,
Integer V_1)
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: dup
IL_0003: stloc.0
IL_0004: ldc.i4.0
IL_0005: ldelem "U"
IL_000a: box "U"
IL_000f: unbox.any "Integer"
IL_0014: stloc.1
IL_0015: ldloca.s V_1
IL_0017: call "Sub B.G(ByRef Integer)"
IL_001c: ldloc.0
IL_001d: ldc.i4.0
IL_001e: ldloc.1
IL_001f: box "Integer"
IL_0024: unbox.any "U"
IL_0029: stelem "U"
IL_002e: ret
}
]]>)
End Sub
<Fact>
Public Sub ArrayElementByReference_ValueType()
Dim comp =
<compilation>
<file>
Option Strict Off
Module M
Sub Main()
F(New Integer() {1})
End Sub
Sub F(a() As Integer)
G(a)
System.Console.Write(a(0))
End Sub
Sub G(a() As Integer)
H(a(0))
End Sub
Sub H(ByRef i As Integer)
i = 2
End Sub
End Module
</file>
</compilation>
CompileAndVerify(comp, expectedOutput:="2").
VerifyIL("M.G",
<![CDATA[
{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldelema "Integer"
IL_0007: call "Sub M.H(ByRef Integer)"
IL_000c: ret
}
]]>)
End Sub
<Fact>
Public Sub ArrayElementCompoundAssignment_Invariant()
Dim comp =
<compilation>
<file>
Option Strict Off
Module M
Sub Main()
F(New String() {""}, "B")
End Sub
Sub F(a() As String, s As String)
G(a, s)
System.Console.Write(a(0))
End Sub
Sub G(a() As String, s As String)
a(0) += s
End Sub
End Module
</file>
</compilation>
CompileAndVerify(comp, expectedOutput:="B").
VerifyIL("M.G",
<![CDATA[
{
// Code size 19 (0x13)
.maxstack 3
.locals init (String& V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldelema "String"
IL_0007: dup
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: ldind.ref
IL_000b: ldarg.1
IL_000c: call "Function String.Concat(String, String) As String"
IL_0011: stind.ref
IL_0012: ret
}
]]>)
End Sub
<Fact, WorkItem(547533, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=547533")>
Public Sub ArrayElementCompoundAssignment_Covariant()
Dim comp =
<compilation>
<file>
Option Strict Off
Module M
Sub Main()
F(New Object() {""}, "A")
F(New String() {""}, "B")
End Sub
Sub F(a() As Object, s As String)
G(a, s)
System.Console.Write(a(0))
End Sub
Sub G(a() As Object, s As String)
a(0) += s
End Sub
End Module
</file>
</compilation>
CompileAndVerify(comp, expectedOutput:="AB").
VerifyIL("M.G",
<![CDATA[
{
// Code size 15 (0xf)
.maxstack 4
.locals init (Object() V_0)
IL_0000: ldarg.0
IL_0001: dup
IL_0002: stloc.0
IL_0003: ldc.i4.0
IL_0004: ldloc.0
IL_0005: ldc.i4.0
IL_0006: ldelem.ref
IL_0007: ldarg.1
IL_0008: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object"
IL_000d: stelem.ref
IL_000e: ret
}
]]>)
End Sub
<Fact>
Public Sub ArrayElementCompoundAssignment_ValueType()
Dim comp =
<compilation>
<file>
Option Strict Off
Module M
Sub Main()
F(New Integer() {1}, 2)
End Sub
Sub F(a() As Integer, i As Integer)
G(a, i)
System.Console.Write(a(0))
End Sub
Sub G(a() As Integer, i As Integer)
a(0) += i
End Sub
End Module
</file>
</compilation>
CompileAndVerify(comp, expectedOutput:="3").
VerifyIL("M.G",
<![CDATA[
{
// Code size 15 (0xf)
.maxstack 3
.locals init (Integer& V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldelema "Integer"
IL_0007: dup
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: ldind.i4
IL_000b: ldarg.1
IL_000c: add.ovf
IL_000d: stind.i4
IL_000e: ret
}
]]>)
End Sub
<Fact, WorkItem(547533, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=547533")>
Public Sub ArrayElementCompoundAssignment_Covariant_NonConstantIndex()
Dim comp =
<compilation>
<file>
Option Strict Off
Module M
Sub Main()
F(New Object() {""}, "A")
F(New String() {""}, "B")
End Sub
Sub F(a() As Object, s As String)
G(a, s)
System.Console.Write(a(0))
End Sub
Sub G(a() As Object, s As String)
a(Index(a)) += s
End Sub
Function Index(arg As Object) As Integer
System.Console.Write(arg.GetType().Name)
Return 0
End Function
End Module
</file>
</compilation>
CompileAndVerify(comp, expectedOutput:="Object[]AString[]B").
VerifyIL("M.G",
<![CDATA[
{
// Code size 22 (0x16)
.maxstack 4
.locals init (Object() V_0,
Integer V_1)
IL_0000: ldarg.0
IL_0001: dup
IL_0002: stloc.0
IL_0003: ldarg.0
IL_0004: call "Function M.Index(Object) As Integer"
IL_0009: dup
IL_000a: stloc.1
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: ldelem.ref
IL_000e: ldarg.1
IL_000f: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object"
IL_0014: stelem.ref
IL_0015: ret
}
]]>)
End Sub
<Fact>
Public Sub ArrayElementWithBlock_Invariant()
Dim comp =
<compilation>
<file>
Option Strict Off
Module M
Sub Main()
F(New String() {"B"})
End Sub
Sub F(a() As String)
System.Console.Write(G(a))
End Sub
Function G(a() As String) As String
With a(0)
Return .ToString() + .ToLower()
End With
End Function
End Module
</file>
</compilation>
CompileAndVerify(comp, expectedOutput:="Bb").
VerifyIL("M.G",
<![CDATA[
{
// Code size 22 (0x16)
.maxstack 2
.locals init (String V_0) //$W0
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldelem.ref
IL_0003: stloc.0
IL_0004: ldloc.0
IL_0005: callvirt "Function String.ToString() As String"
IL_000a: ldloc.0
IL_000b: callvirt "Function String.ToLower() As String"
IL_0010: call "Function String.Concat(String, String) As String"
IL_0015: ret
}
]]>)
End Sub
<Fact>
Public Sub ArrayElementWithBlock_Covariant()
Dim comp =
<compilation>
<file>
Option Strict Off
Module M
Sub Main()
F(New Object() {"A"})
F(New String() {"B"})
End Sub
Sub F(a() As Object)
System.Console.Write(G(a))
End Sub
Function G(a() As Object) As String
With a(0)
Return .ToString() + .ToLower()
End With
End Function
End Module
</file>
</compilation>
CompileAndVerify(comp, expectedOutput:="AaBb").
VerifyIL("M.G",
<![CDATA[
{
// Code size 42 (0x2a)
.maxstack 8
.locals init (Object V_0) //$W0
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldelem.ref
IL_0003: stloc.0
IL_0004: ldloc.0
IL_0005: callvirt "Function Object.ToString() As String"
IL_000a: ldloc.0
IL_000b: ldnull
IL_000c: ldstr "ToLower"
IL_0011: ldc.i4.0
IL_0012: newarr "Object"
IL_0017: ldnull
IL_0018: ldnull
IL_0019: ldnull
IL_001a: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_001f: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object"
IL_0024: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Object) As String"
IL_0029: ret
}
]]>)
End Sub
<Fact>
Public Sub ArrayElementWithBlock_ValueType()
Dim comp =
<compilation>
<file>
Option Strict Off
Module M
Sub Main()
F(New Integer() {1})
End Sub
Sub F(a() As Integer)
System.Console.Write(G(a))
End Sub
Function G(a() As Integer) As String
With a(0)
Return .ToString() + .ToString()
End With
End Function
End Module
</file>
</compilation>
CompileAndVerify(comp, expectedOutput:="11").
VerifyIL("M.G",
<![CDATA[
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (Integer& V_0) //$W0
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldelema "Integer"
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: call "Function Integer.ToString() As String"
IL_000e: ldloc.0
IL_000f: call "Function Integer.ToString() As String"
IL_0014: call "Function String.Concat(String, String) As String"
IL_0019: ret
}
]]>)
End Sub
Public Sub NormalizedNaN()
CompileAndVerify(
<compilation>
<file name="a.vb">
Class Program
Shared Sub Main()
CheckNaN(Double.NaN)
CheckNaN(Single.NaN)
CheckNaN(0.0 / 0.0)
CheckNaN(0.0 / -0.0)
Dim inf As Double = 1.0 / 0.0
CheckNaN(inf + Double.NaN)
CheckNaN(inf - Double.NaN)
CheckNaN(-Double.NaN)
End Sub
Shared Sub CheckNaN(nan As Double)
Dim expected As Long = &HFFF8000000000000
Dim actual As Long = System.BitConverter.DoubleToInt64Bits(nan)
If expected <> actual Then
Throw New System.Exception($"expected=0X{expected: X} actual=0X{actual:X}")
End If
End Sub
End Class
</file>
</compilation>,
expectedOutput:=<![CDATA[
]]>)
End Sub
End Class
End Namespace
|
reaction1989/roslyn
|
src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenTests.vb
|
Visual Basic
|
apache-2.0
| 395,644
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.Label1 = New System.Windows.Forms.Label()
Me.Label2 = New System.Windows.Forms.Label()
Me.Label3 = New System.Windows.Forms.Label()
Me.Label4 = New System.Windows.Forms.Label()
Me.Button5 = New System.Windows.Forms.Button()
Me.Button3 = New System.Windows.Forms.Button()
Me.Button4 = New System.Windows.Forms.Button()
Me.Button2 = New System.Windows.Forms.Button()
Me.Button1 = New System.Windows.Forms.Button()
Me.SuspendLayout()
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Font = New System.Drawing.Font("Verdana", 14.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label1.ForeColor = System.Drawing.Color.Navy
Me.Label1.Location = New System.Drawing.Point(14, 9)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(303, 23)
Me.Label1.TabIndex = 5
Me.Label1.Text = "Please select an option below:"
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.ForeColor = System.Drawing.Color.FromArgb(CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer))
Me.Label2.Location = New System.Drawing.Point(75, 48)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(256, 39)
Me.Label2.TabIndex = 6
Me.Label2.Text = "Record a voice with an amazing quality and" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "later convert it to a wide range of f" & _
"ormats" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "for different devices."
'
'Label3
'
Me.Label3.AutoSize = True
Me.Label3.ForeColor = System.Drawing.Color.FromArgb(CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer))
Me.Label3.Location = New System.Drawing.Point(75, 99)
Me.Label3.Name = "Label3"
Me.Label3.Size = New System.Drawing.Size(242, 39)
Me.Label3.TabIndex = 7
Me.Label3.Text = "Record a video directly from your screen" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "and an internal camera simultaneously" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & _
"with a great performance." & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10)
'
'Label4
'
Me.Label4.AutoSize = True
Me.Label4.ForeColor = System.Drawing.Color.FromArgb(CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer))
Me.Label4.Location = New System.Drawing.Point(75, 150)
Me.Label4.Name = "Label4"
Me.Label4.Size = New System.Drawing.Size(241, 39)
Me.Label4.TabIndex = 8
Me.Label4.Text = "Convert, merge existing audio and video" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "files into a wide range of formants," & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "in" & _
"cluding, WMV MP3, MP4, and more."
'
'Button5
'
Me.Button5.Image = Global.WindowsApplication1.My.Resources.Resources.buynow
Me.Button5.Location = New System.Drawing.Point(206, 205)
Me.Button5.Name = "Button5"
Me.Button5.Size = New System.Drawing.Size(52, 45)
Me.Button5.TabIndex = 10
Me.Button5.UseVisualStyleBackColor = True
'
'Button3
'
Me.Button3.Image = Global.WindowsApplication1.My.Resources.Resources.lock2
Me.Button3.Location = New System.Drawing.Point(264, 205)
Me.Button3.Name = "Button3"
Me.Button3.Size = New System.Drawing.Size(52, 45)
Me.Button3.TabIndex = 9
Me.Button3.UseVisualStyleBackColor = True
'
'Button4
'
Me.Button4.Image = Global.WindowsApplication1.My.Resources.Resources.icon4
Me.Button4.Location = New System.Drawing.Point(17, 150)
Me.Button4.Name = "Button4"
Me.Button4.Size = New System.Drawing.Size(52, 45)
Me.Button4.TabIndex = 4
Me.Button4.UseVisualStyleBackColor = True
'
'Button2
'
Me.Button2.Image = Global.WindowsApplication1.My.Resources.Resources.icon3
Me.Button2.Location = New System.Drawing.Point(17, 99)
Me.Button2.Name = "Button2"
Me.Button2.Size = New System.Drawing.Size(52, 45)
Me.Button2.TabIndex = 3
Me.Button2.UseVisualStyleBackColor = True
'
'Button1
'
Me.Button1.Image = Global.WindowsApplication1.My.Resources.Resources.icon11
Me.Button1.Location = New System.Drawing.Point(17, 48)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(52, 45)
Me.Button1.TabIndex = 0
Me.Button1.UseVisualStyleBackColor = True
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(335, 262)
Me.Controls.Add(Me.Button5)
Me.Controls.Add(Me.Button3)
Me.Controls.Add(Me.Label4)
Me.Controls.Add(Me.Label3)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.Button4)
Me.Controls.Add(Me.Button2)
Me.Controls.Add(Me.Button1)
Me.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
Me.MaximizeBox = False
Me.Name = "Form1"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "Digital Tools Collection"
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents Button1 As System.Windows.Forms.Button
Friend WithEvents Button2 As System.Windows.Forms.Button
Friend WithEvents Button4 As System.Windows.Forms.Button
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents Label3 As System.Windows.Forms.Label
Friend WithEvents Label4 As System.Windows.Forms.Label
Friend WithEvents Button3 As System.Windows.Forms.Button
Friend WithEvents Button5 As System.Windows.Forms.Button
End Class
|
SerialKeyManager/Examples
|
Digital Tools Collection/Digital Tools Collection/Form1.Designer.vb
|
Visual Basic
|
bsd-3-clause
| 7,569
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.VisualStudio.GraphModel
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression
Public Class IsCalledByGraphQueryTests
<WpfFact, Trait(Traits.Feature, Traits.Features.Progression)>
Public Async Function IsCalledBySimpleTests() As Threading.Tasks.Task
Using testState = Await ProgressionTestState.CreateAsync(
<Workspace>
<Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj">
<Document FilePath="Z:\Project.cs">
class A
{
public $$A() { }
public virtual void Run() { }
}
class B : A
{
public B() { }
override public void Run() { var x = new A(); x.Run(); }
}
class C
{
public C() { }
public void Foo()
{
var x = new B();
x.Run();
}
}
</Document>
</Project>
</Workspace>)
Dim inputGraph = await testState.GetGraphWithMarkedSymbolNodeAsync()
Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New IsCalledByGraphQuery(), GraphContextDirection.Target)
AssertSimplifiedGraphIs(
outputContext.Graph,
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="(@1 Type=A Member=.ctor)" Category="CodeSchema_Method" CodeSchemaProperty_IsConstructor="True" CodeSchemaProperty_IsPublic="True" CommonLabel="A" Icon="Microsoft.VisualStudio.Method.Public" Label="A"/>
<Node Id="(@1 Type=B Member=Run)" Category="CodeSchema_Method" CodeSchemaProperty_IsPublic="True" CommonLabel="Run" Icon="Microsoft.VisualStudio.Method.Public" IsOverloaded="True" Label="Run"/>
</Nodes>
<Links>
<Link Source="(@1 Type=B Member=Run)" Target="(@1 Type=A Member=.ctor)" Category="CodeSchema_Calls"/>
</Links>
<IdentifierAliases>
<Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/>
</IdentifierAliases>
</DirectedGraph>)
End Using
End Function
End Class
End Namespace
|
VPashkov/roslyn
|
src/VisualStudio/Core/Test/Progression/IsCalledByGraphQueryTests.vb
|
Visual Basic
|
apache-2.0
| 2,705
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.34003
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("FindDuplicateFiles.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set(ByVal value As Global.System.Globalization.CultureInfo)
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
Petermarcu/Projects
|
Console/FindDuplicateFiles/FindDuplicateFiles/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,727
|
#Region "License"
' The MIT License (MIT)
'
' Copyright (c) 2018 Richard L King (TradeWright Software Systems)
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
#End Region
Friend Class RequestContractDetailsGenerator
Inherits GeneratorBase
Implements IGenerator
Private Delegate Sub RequestContractDetailsDelegate(pRequestId As Integer, pContract As Contract, pIncludeExpired As Boolean, pSecIdType As String, pSecId As String)
Private Const ModuleName As String = NameOf(RequestContractDetailsGenerator)
Friend Overrides ReadOnly Property GeneratorDelegate As [Delegate] Implements IGenerator.GeneratorDelegate
Get
Return New RequestContractDetailsDelegate(AddressOf requestContractDetails)
End Get
End Property
Friend Overrides ReadOnly Property MessageType As ApiSocketOutMsgType
Get
Return ApiSocketOutMsgType.RequestContractData
End Get
End Property
Private Sub requestContractDetails(pRequestId As Integer, pContract As Contract, pIncludeExpired As Boolean, pSecIdType As String, pSecId As String)
Const VERSION As Integer = 8
If ConnectionState <> ApiConnectionState.Connected Then Throw New InvalidOperationException("Not connected")
Dim lWriter = CreateOutputMessageGenerator()
StartMessage(lWriter, ApiSocketOutMsgType.RequestContractData)
lWriter.AddInteger(VERSION, "Version")
lWriter.AddInteger(IdManager.GetTwsId(pRequestId, IdType.ContractData), "Request id")
lWriter.AddContract(pContract, "Contract")
lWriter.AddBoolean(pIncludeExpired, "Include expired")
lWriter.AddString(pSecIdType, "SecIdType")
lWriter.AddString(pSecId, "SecId")
lWriter.SendMessage(_EventConsumers.SocketDataConsumer)
End Sub
End Class
|
tradewright/tradewright-twsapi
|
src/IBApi/Generators/RequestContractDetailsGenerator.vb
|
Visual Basic
|
mit
| 2,844
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("main")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("Microsoft")>
<Assembly: AssemblyProduct("main")>
<Assembly: AssemblyCopyright("Copyright © Microsoft 2017")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("310b3fae-5539-477d-af35-e61804d520da")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
LonerganResearch/LR_Auto_Transcript
|
main/main/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,135
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.544
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("setting")> _
Public Property setting() As String
Get
Return CType(Me("setting"),String)
End Get
Set
Me("setting") = value
End Set
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.KeyStatus.My.MySettings
Get
Return Global.KeyStatus.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
Walkman100/KeyStatus
|
My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 3,372
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.DebuggerIntelliSense
Public Class CSharpDebuggerIntellisenseTests
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionOnTypeCharacter() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("arg")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("arg", state.GetCurrentViewLineText())
Await state.AssertCompletionSession()
state.SendTab()
Assert.Equal("args", state.GetCurrentViewLineText())
End Using
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionOnTypeCharacterInImmediateWindow() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.SendTypeChars("arg")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("arg", state.GetCurrentViewLineText())
Await state.AssertCompletionSession()
state.SendTab()
Assert.Equal("args", state.GetCurrentViewLineText())
End Using
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function LocalsInBlockAfterInstructionPointer() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static void Main(string[] args)
[|{|]
int x = 3;
string bar = "goo";
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.SendTypeChars("x")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("x")
state.SendBackspace()
state.SendTypeChars("bar")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("bar")
state.SendTab()
Assert.Equal("bar", state.GetCurrentViewLineText())
End Using
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionAfterReturn() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static void Main(string[] args)
[|{|]
int x = 3;
string bar = "goo";
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.SendTypeChars("bar")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("bar")
state.SendTab()
Assert.Equal("bar", state.GetCurrentViewLineText())
state.SendReturn()
Assert.Equal("", state.GetCurrentViewLineText())
state.SendTypeChars("bar")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("bar")
state.SendTab()
Assert.Equal(" bar", state.GetCurrentViewLineText())
End Using
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function ExecutedUnexecutedLocals() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static void Main(string[] args)
{
string goo = "green";
[|string bar = "goo";|]
string green = "yellow";
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("goo")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("goo")
state.SendTab()
state.SendTypeChars(".ToS")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("ToString")
For i As Integer = 0 To 7
state.SendBackspace()
Next
state.SendTypeChars("green")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("green")
state.SendTab()
state.SendTypeChars(".ToS")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("ToString")
End Using
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Sub Locals1()
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static void Main()
{
{
[|int variable1 = 0;|]
}
Console.Write(0);
int variable2 = 0;
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("variable")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsContainAll("variable1", "variable2")
End Using
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Sub Locals2()
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static void Main()
{
{
int variable1 = 0;
[|}|]
Console.Write(0);
int variable2 = 0;
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("variable")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsContainAll("variable1", "variable2")
End Using
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Sub Locals3()
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static void Main()
{
{
int variable1 = 0;
}
[|Console.Write(0);|]
int variable2 = 0;
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("variable")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsContainNone("variable1")
Await state.AssertCompletionItemsContainAll("variable2")
End Using
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Sub Locals4()
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static void Main()
{
{
int variable1 = 0;
}
Console.Write(0);
[|int variable2 = 0;|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("variable")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsContainNone("variable1")
Await state.AssertCompletionItemsContainAll("variable2")
End Using
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Sub Locals5()
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static void Main()
{
{
int variable1 = 0;
}
Console.Write(0);
int variable2 = 0;
[|}|]
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("variable")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsContainNone("variable1")
Await state.AssertCompletionItemsContainAll("variable2")
End Using
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Sub Locals6()
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static void Main()
{
{
int variable1 = 0;
}
Console.Write(0);
int variable2 = 0;
}
[|}|]</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("variable")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsContainNone("variable1")
Await state.AssertCompletionItemsContainNone("variable2")
End Using
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Sub SignatureHelpInParameterizedConstructor()
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static void Main(string[] args)
{
string goo = "green";
[|string bar = "goo";|]
string green = "yellow";
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("new string(")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSignatureHelpSession()
End Using
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Sub SignatureHelpInMethodCall()
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static void something(string z, int b)
{
}
static void Main(string[] args)
{
string goo = "green";
[|string bar = "goo";|]
string green = "yellow";
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("something(")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSignatureHelpSession()
End Using
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Sub SignatureHelpInGenericMethodCall()
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static void something<T>(<T> z, int b)
{
return z
}
static void Main(string[] args)
{
string goo = "green";
[|string bar = "goo";|]
string green = "yellow";
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("something<int>(")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSignatureHelpSession()
End Using
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function InstructionPointerInForeach() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static void Main(string[] args)
{
int OOO = 3;
foreach (var z in "goo")
{
[|var q = 1;|]
}
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
Await VerifyCompletionAndDotAfter("q", state)
Await VerifyCompletionAndDotAfter("OOO", state)
End Using
End Function
<WorkItem(531165, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531165")>
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Sub ClassDesigner1()
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static int STATICINT;
static void Main(string[] args)
{
}
[| |] public void M1()
{
throw new System.NotImplementedException();
}
}
</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("STATICI")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsContainNone("STATICINT")
End Using
End Sub
<WorkItem(531167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531167")>
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Sub ClassDesigner2()
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static void Main(string[] args)
{
}
[| |] void M1()
{
}
}
</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("1")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertNoCompletionSession()
End Using
End Sub
<WorkItem(1124544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1124544")>
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Sub CompletionUsesContextBufferPositions()
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.
(1,3): error CS1001: Identifier expected
e.
(1,3): error CS1001: Identifier expected
e.
(1,3): error CS1001: Identifier expected
e.
(1,3): error CS1001: Identifier expected
e.
(1,3): error CS1001: Identifier expected
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
$$</Document>
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.SendTypeChars("arg")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("arg", state.GetCurrentViewLineText())
Await state.AssertCompletionSession()
state.SendTab()
Assert.Equal("args", state.GetCurrentViewLineText())
End Using
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Sub CompletionOnTypeCharacterInLinkedFileContext()
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
123123123123123123123123123 + $$</Document>
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj">
<Document FilePath="C.cs">
{
static void Main(string[] args)
[|{|]
}
}
</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.SendTypeChars("arg")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("123123123123123123123123123 + arg", state.GetCurrentViewLineText())
state.SendTab()
Assert.Contains("args", state.GetCurrentViewLineText())
End Using
End Sub
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function TypeNumberAtStartOfViewDoesNotCrash() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("4")
Await state.AssertNoCompletionSession()
End Using
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function BuilderSettingRetainedBetweenComputations_Watch() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, isImmediateWindow:=False)
state.SendTypeChars("args")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("args", state.GetCurrentViewLineText())
Await state.AssertCompletionSession()
Assert.True(state.CurrentCompletionPresenterSession.SuggestionMode)
state.SendToggleCompletionMode()
Await state.WaitForAsynchronousOperationsAsync()
Assert.False(state.CurrentCompletionPresenterSession.SuggestionMode)
state.SendTypeChars(".")
Await state.WaitForAsynchronousOperationsAsync()
Assert.False(state.CurrentCompletionPresenterSession.SuggestionMode)
End Using
End Function
<ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function BuilderSettingRetainedBetweenComputations_Watch_Immediate() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$</Document>
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, isImmediateWindow:=True)
state.SendTypeChars("args")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("args", state.GetCurrentViewLineText())
Await state.AssertCompletionSession()
Assert.True(state.CurrentCompletionPresenterSession.SuggestionMode)
state.SendToggleCompletionMode()
Await state.WaitForAsynchronousOperationsAsync()
Assert.False(state.CurrentCompletionPresenterSession.SuggestionMode)
state.SendTypeChars(".")
Await state.WaitForAsynchronousOperationsAsync()
Assert.False(state.CurrentCompletionPresenterSession.SuggestionMode)
End Using
End Function
Private Async Function VerifyCompletionAndDotAfter(item As String, state As TestState) As Task
state.SendTypeChars(item)
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem(item)
state.SendTab()
state.SendTypeChars(".")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionSession()
For i As Integer = 0 To item.Length
state.SendBackspace()
Next
End Function
End Class
End Namespace
|
Hosch250/roslyn
|
src/VisualStudio/Core/Test/DebuggerIntelliSense/CSharpDebuggerIntellisenseTests.vb
|
Visual Basic
|
apache-2.0
| 28,356
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.DocumentationComments
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.SignatureHelp
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp
<ExportSignatureHelpProvider("InvocationExpressionSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]>
Partial Friend Class InvocationExpressionSignatureHelpProvider
Inherits AbstractVisualBasicSignatureHelpProvider
<ImportingConstructor>
Public Sub New()
End Sub
Public Overrides Function IsTriggerCharacter(ch As Char) As Boolean
Return ch = "("c OrElse ch = ","c
End Function
Public Overrides Function IsRetriggerCharacter(ch As Char) As Boolean
Return ch = ")"c
End Function
Public Overrides Function GetCurrentArgumentState(root As SyntaxNode, position As Integer, syntaxFacts As ISyntaxFactsService, currentSpan As TextSpan, cancellationToken As CancellationToken) As SignatureHelpState
Dim expression As InvocationExpressionSyntax = Nothing
If TryGetInvocationExpression(root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, expression) AndAlso
currentSpan.Start = SignatureHelpUtilities.GetSignatureHelpSpan(expression.ArgumentList).Start Then
Return SignatureHelpUtilities.GetSignatureHelpState(expression.ArgumentList, position)
End If
Return Nothing
End Function
Private Function TryGetInvocationExpression(root As SyntaxNode, position As Integer, syntaxFacts As ISyntaxFactsService, triggerReason As SignatureHelpTriggerReason, cancellationToken As CancellationToken, ByRef expression As InvocationExpressionSyntax) As Boolean
If Not CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, AddressOf IsTriggerToken, AddressOf IsArgumentListToken, cancellationToken, expression) Then
Return False
End If
Return expression.ArgumentList IsNot Nothing
End Function
Private Shared Function IsTriggerToken(token As SyntaxToken) As Boolean
Return (token.Kind = SyntaxKind.OpenParenToken OrElse token.Kind = SyntaxKind.CommaToken) AndAlso
TypeOf token.Parent Is ArgumentListSyntax AndAlso
TypeOf token.Parent.Parent Is InvocationExpressionSyntax
End Function
Private Shared Function IsArgumentListToken(node As InvocationExpressionSyntax, token As SyntaxToken) As Boolean
Return node.ArgumentList IsNot Nothing AndAlso
node.ArgumentList.Span.Contains(token.SpanStart) AndAlso
token <> node.ArgumentList.CloseParenToken
End Function
Protected Overrides Async Function GetItemsWorkerAsync(document As Document, position As Integer, triggerInfo As SignatureHelpTriggerInfo, cancellationToken As CancellationToken) As Task(Of SignatureHelpItems)
Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
Dim invocationExpression As InvocationExpressionSyntax = Nothing
If Not TryGetInvocationExpression(root, position, document.GetLanguageService(Of ISyntaxFactsService), triggerInfo.TriggerReason, cancellationToken, invocationExpression) Then
Return Nothing
End If
Dim semanticModel = Await document.GetSemanticModelForNodeAsync(invocationExpression, cancellationToken).ConfigureAwait(False)
Dim within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken)
If within Is Nothing Then
Return Nothing
End If
Dim targetExpression = If(invocationExpression.Expression Is Nothing AndAlso invocationExpression.Parent.IsKind(SyntaxKind.ConditionalAccessExpression),
DirectCast(invocationExpression.Parent, ConditionalAccessExpressionSyntax).Expression,
invocationExpression.Expression)
' get the regular signature help items
Dim symbolDisplayService = document.GetLanguageService(Of ISymbolDisplayService)()
Dim memberGroup = semanticModel.GetMemberGroup(targetExpression, cancellationToken).
FilterToVisibleAndBrowsableSymbolsAndNotUnsafeSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation)
' try to bind to the actual method
Dim symbolInfo = semanticModel.GetSymbolInfo(invocationExpression, cancellationToken)
Dim matchedMethodSymbol = TryCast(symbolInfo.Symbol, IMethodSymbol)
' if the symbol could be bound, replace that item in the symbol list
If matchedMethodSymbol IsNot Nothing AndAlso matchedMethodSymbol.IsGenericMethod Then
memberGroup = memberGroup.SelectAsArray(Function(m) If(Equals(matchedMethodSymbol.OriginalDefinition, m), matchedMethodSymbol, m))
End If
Dim enclosingSymbol = semanticModel.GetEnclosingSymbol(position)
If enclosingSymbol.IsConstructor() Then
memberGroup = memberGroup.WhereAsArray(Function(m) Not m.Equals(enclosingSymbol))
End If
memberGroup = memberGroup.Sort(symbolDisplayService, semanticModel, invocationExpression.SpanStart)
Dim typeInfo = semanticModel.GetTypeInfo(targetExpression, cancellationToken)
Dim expressionType = If(typeInfo.Type, typeInfo.ConvertedType)
Dim defaultProperties =
If(expressionType Is Nothing,
SpecializedCollections.EmptyList(Of IPropertySymbol),
semanticModel.LookupSymbols(position, expressionType, includeReducedExtensionMethods:=True).
OfType(Of IPropertySymbol).
ToImmutableArrayOrEmpty().
WhereAsArray(Function(p) p.IsIndexer).
FilterToVisibleAndBrowsableSymbolsAndNotUnsafeSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation).
Sort(symbolDisplayService, semanticModel, invocationExpression.SpanStart))
Dim anonymousTypeDisplayService = document.GetLanguageService(Of IAnonymousTypeDisplayService)()
Dim documentationCommentFormattingService = document.GetLanguageService(Of IDocumentationCommentFormattingService)()
Dim items = New List(Of SignatureHelpItem)
If memberGroup.Count > 0 Then
items.AddRange(GetMemberGroupItems(invocationExpression, semanticModel, symbolDisplayService, anonymousTypeDisplayService, documentationCommentFormattingService, within, memberGroup, cancellationToken))
End If
If expressionType.IsDelegateType() Then
items.AddRange(GetDelegateInvokeItems(invocationExpression, semanticModel, symbolDisplayService, anonymousTypeDisplayService, documentationCommentFormattingService, within, DirectCast(expressionType, INamedTypeSymbol), cancellationToken))
End If
If defaultProperties.Count > 0 Then
items.AddRange(GetElementAccessItems(targetExpression, semanticModel, symbolDisplayService, anonymousTypeDisplayService, documentationCommentFormattingService, within, defaultProperties, cancellationToken))
End If
Dim textSpan = SignatureHelpUtilities.GetSignatureHelpSpan(invocationExpression.ArgumentList)
Dim syntaxFacts = document.GetLanguageService(Of ISyntaxFactsService)
Dim selectedItem = TryGetSelectedIndex(memberGroup, symbolInfo)
Return CreateSignatureHelpItems(items, textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem)
End Function
End Class
End Namespace
|
nguerrera/roslyn
|
src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.vb
|
Visual Basic
|
apache-2.0
| 8,390
|
' Copyright (c) 2015 ZZZ Projects. All rights reserved
' Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods)
' Website: http://www.zzzprojects.com/
' Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927
' All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library
Imports System.Globalization
Public Module Extensions_143
''' <summary>
''' A DateTime extension method that converts this object to a long date time string.
''' </summary>
''' <param name="this">The @this to act on.</param>
''' <returns>The given data converted to a string.</returns>
<System.Runtime.CompilerServices.Extension> _
Public Function ToLongDateTimeString(this As DateTime) As String
Return this.ToString("F", DateTimeFormatInfo.CurrentInfo)
End Function
''' <summary>
''' A DateTime extension method that converts this object to a long date time string.
''' </summary>
''' <param name="this">The @this to act on.</param>
''' <param name="culture">The culture.</param>
''' <returns>The given data converted to a string.</returns>
<System.Runtime.CompilerServices.Extension> _
Public Function ToLongDateTimeString(this As DateTime, culture As String) As String
Return this.ToString("F", New CultureInfo(culture))
End Function
''' <summary>
''' A DateTime extension method that converts this object to a long date time string.
''' </summary>
''' <param name="this">The @this to act on.</param>
''' <param name="culture">The culture.</param>
''' <returns>The given data converted to a string.</returns>
<System.Runtime.CompilerServices.Extension> _
Public Function ToLongDateTimeString(this As DateTime, culture As CultureInfo) As String
Return this.ToString("F", culture)
End Function
End Module
|
huoxudong125/Z.ExtensionMethods
|
src (VB.NET)/Z.ExtensionMethods.VB/Z.Core/System.DateTime/ToDateTimeFormat/DateTime.ToLongDateTimeString.vb
|
Visual Basic
|
mit
| 1,837
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders
Public Class PartialTypeCompletionProviderTests
Inherits AbstractVisualBasicCompletionProviderTests
Public Sub New(workspaceFixture As VisualBasicTestWorkspaceFixture)
MyBase.New(workspaceFixture)
End Sub
Friend Overrides Function CreateCompletionProvider() As CompletionListProvider
Return New PartialTypeCompletionProvider()
End Function
<WorkItem(578224)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestRecommendTypesWithoutPartial() As Task
Dim text = <text>Class C
End Class
Partial Class $$</text>
Await VerifyItemExistsAsync(text.Value, "C")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestPartialClass1() As Task
Dim text = <text>Partial Class C
End Class
Partial Class $$</text>
Await VerifyItemExistsAsync(text.Value, "C")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestPartialGenericClass1() As Task
Dim text = <text>Class Bar
End Class
Partial Class C(Of Bar)
End Class
Partial Class $$</text>
Await VerifyItemExistsAsync(text.Value, "C(Of Bar)")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestPartialGenericClassCommitOnParen() As Task
' TODO(DustinCa): This is testing the wrong behavior and will need to be updated to the commented expected
' result when https://github.com/dotnet/roslyn/issues/4137 is fixed.
Dim text = <text>Class Bar
End Class
Partial Class C(Of Bar)
End Class
Partial Class $$</text>
Dim expected = <text>Class Bar
End Class
Partial Class C(Of Bar)
End Class
Partial Class C(Of Bar)(</text>
' Dim expected = <text>Class Bar
'End Class
'Partial Class C(Of Bar)
'End Class
'Partial Class C(</text>
Await VerifyProviderCommitAsync(text.Value, "C(Of Bar)", expected.Value, "("c, "", SourceCodeKind.Regular)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestPartialGenericClassCommitOnTab() As Task
Dim text = <text>Class Bar
End Class
Partial Class C(Of Bar)
End Class
Partial Class $$</text>
Dim expected = <text>Class Bar
End Class
Partial Class C(Of Bar)
End Class
Partial Class C(Of Bar)</text>
Await VerifyProviderCommitAsync(text.Value, "C(Of Bar)", expected.Value, Nothing, "", SourceCodeKind.Regular)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestPartialClassWithModifiers() As Task
Dim text = <text>Partial Class C
End Class
Partial Protected Class $$</text>
Await VerifyItemExistsAsync(text.Value, "C")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestPartialStruct() As Task
Dim text = <text>Partial Structure S
End Structure
Partial Structure $$</text>
Await VerifyItemExistsAsync(text.Value, "S")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestPartialInterface() As Task
Dim text = <text>Partial Interface I
End Interface
Partial Interface $$</text>
Await VerifyItemExistsAsync(text.Value, "I")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestPartialModule() As Task
Dim text = <text>Partial Module M
End Module
Partial Module $$</text>
Await VerifyItemExistsAsync(text.Value, "M")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestTypeKindMatches1() As Task
Dim text = <text>Partial Structure S
End Structure
Partial Class $$</text>
Await VerifyNoItemsExistAsync(text.Value)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestTypeKindMatches2() As Task
Dim text = <text>Partial Class C
End Class
Partial Structure $$</text>
Await VerifyNoItemsExistAsync(text.Value)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestPartialClassesInSameNamespace() As Task
Dim text = <text>Namespace N
Partial Class Foo
End Class
End Namespace
Namespace N
Partial Class $$
End Namespace</text>
Await VerifyItemExistsAsync(text.Value, "Foo")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotPartialClassesAcrossDifferentNamespaces() As Task
Dim text = <text>Namespace N
Partial Class Foo
End Class
End Namespace
Partial Class $$</text>
Await VerifyNoItemsExistAsync(text.Value)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestIncludeConstraints() As Task
Dim text = <text>
Partial Class C1(Of T As Exception)
End Class
Partial Class $$</text>
Await VerifyItemExistsAsync(text.Value, "C1(Of T As Exception)")
End Function
<WorkItem(578122)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDoNotSuggestCurrentMember() As Task
Dim text = <text>
Partial Class F$$
</text>
Await VerifyNoItemsExistAsync(text.Value)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotInTrivia() As Task
Dim text = <text>
Partial Class C1
End Class
Partial Class '$$</text>
Await VerifyNoItemsExistAsync(text.Value)
End Function
End Class
End Namespace
|
VPashkov/roslyn
|
src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/PartialTypeCompletionProviderTests.vb
|
Visual Basic
|
apache-2.0
| 6,836
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.VisualStudio.Text
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.Mocks
Friend NotInheritable Class MockTextPoint
Implements EnvDTE.TextPoint
Private ReadOnly _point As VirtualTreePoint
Private ReadOnly _tabSize As Integer
Public Sub New(point As VirtualTreePoint, tabSize As Integer)
_point = point
_tabSize = tabSize
End Sub
Public ReadOnly Property AbsoluteCharOffset As Integer Implements EnvDTE.TextPoint.AbsoluteCharOffset
Get
' DTE TextPoints count each newline as a single character regardless
' of what the actual newline character is. So, we have to walk through all the lines
' and add up the length of each line + 1.
'
' VS performs this same computation in GetAbsoluteOffset in env\msenv\textmgr\autoutil.cpp.
Dim result = 0
Dim containingLine = _point.GetContainingLine()
For Each textLine In _point.Text.Lines
If textLine.LineNumber >= containingLine.LineNumber Then
Exit For
End If
result += textLine.Span.Length + 1
Next
result += _point.Position - containingLine.Start
Return result + 1
End Get
End Property
Public ReadOnly Property AtEndOfDocument As Boolean Implements EnvDTE.TextPoint.AtEndOfDocument
Get
Return _point.Position = _point.Text.Length
End Get
End Property
Public ReadOnly Property AtEndOfLine As Boolean Implements EnvDTE.TextPoint.AtEndOfLine
Get
Return _point.Position = _point.GetContainingLine().End
End Get
End Property
Public ReadOnly Property AtStartOfDocument As Boolean Implements EnvDTE.TextPoint.AtStartOfDocument
Get
Return _point.Position = 0
End Get
End Property
Public ReadOnly Property AtStartOfLine As Boolean Implements EnvDTE.TextPoint.AtStartOfLine
Get
Return _point.Position = _point.GetContainingLine().Start
End Get
End Property
Public ReadOnly Property CodeElement(Scope As EnvDTE.vsCMElement) As EnvDTE.CodeElement Implements EnvDTE.TextPoint.CodeElement
Get
Throw New NotImplementedException
End Get
End Property
Public Function CreateEditPoint() As EnvDTE.EditPoint Implements EnvDTE.TextPoint.CreateEditPoint
Throw New NotImplementedException
End Function
Public ReadOnly Property DisplayColumn As Integer Implements EnvDTE.TextPoint.DisplayColumn
Get
Throw New NotImplementedException
End Get
End Property
Public ReadOnly Property DTE As EnvDTE.DTE Implements EnvDTE.TextPoint.DTE
Get
Throw New NotImplementedException
End Get
End Property
Public Function EqualTo(Point As EnvDTE.TextPoint) As Boolean Implements EnvDTE.TextPoint.EqualTo
Return Me.AbsoluteCharOffset = Point.AbsoluteCharOffset
End Function
Public Function GreaterThan(Point As EnvDTE.TextPoint) As Boolean Implements EnvDTE.TextPoint.GreaterThan
Return Me.AbsoluteCharOffset > Point.AbsoluteCharOffset
End Function
Public Function LessThan(Point As EnvDTE.TextPoint) As Boolean Implements EnvDTE.TextPoint.LessThan
Return Me.AbsoluteCharOffset < Point.AbsoluteCharOffset
End Function
Public ReadOnly Property Line As Integer Implements EnvDTE.TextPoint.Line
Get
' These line numbers start at 1!
Return _point.GetContainingLine().LineNumber + 1
End Get
End Property
Public ReadOnly Property LineCharOffset As Integer Implements EnvDTE.TextPoint.LineCharOffset
Get
Dim result = _point.Position - _point.GetContainingLine().Start + 1
If _point.IsInVirtualSpace Then
result += _point.VirtualSpaces
End If
Return result
End Get
End Property
Public ReadOnly Property LineLength As Integer Implements EnvDTE.TextPoint.LineLength
Get
Dim line = _point.GetContainingLine()
Return line.End - line.Start
End Get
End Property
Public ReadOnly Property Parent As EnvDTE.TextDocument Implements EnvDTE.TextPoint.Parent
Get
Return CreateEditPoint().Parent
End Get
End Property
Public Function TryToShow(Optional How As EnvDTE.vsPaneShowHow = EnvDTE.vsPaneShowHow.vsPaneShowCentered, Optional PointOrCount As Object = Nothing) As Boolean Implements EnvDTE.TextPoint.TryToShow
Throw New NotImplementedException
End Function
End Class
End Namespace
|
davkean/roslyn
|
src/VisualStudio/TestUtilities2/CodeModel/Mocks/MockTextPoint.vb
|
Visual Basic
|
apache-2.0
| 5,480
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.Implementation.TodoComments
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.SolutionCrawler
Imports Microsoft.CodeAnalysis.Text
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.TodoComment
Public Class TodoCommentTests
<Fact>
Public Async Function TestSingleLineTodoComment_Colon() As Task
Dim code = <code>' [|TODO:test|]</code>
Await TestAsync(code)
End Function
<Fact>
Public Async Function TestSingleLineTodoComment_Space() As Task
Dim code = <code>' [|TODO test|]</code>
Await TestAsync(code)
End Function
<Fact>
Public Async Function TestSingleLineTodoComment_Underscore() As Task
Dim code = <code>' TODO_test</code>
Await TestAsync(code)
End Function
<Fact>
Public Async Function TestSingleLineTodoComment_Number() As Task
Dim code = <code>' TODO1 test</code>
Await TestAsync(code)
End Function
<Fact>
Public Async Function TestSingleLineTodoComment_Quote() As Task
Dim code = <code>' "TODO test"</code>
Await TestAsync(code)
End Function
<Fact>
Public Async Function TestSingleLineTodoComment_Middle() As Task
Dim code = <code>' Hello TODO test</code>
Await TestAsync(code)
End Function
<Fact>
Public Async Function TestSingleLineTodoComment_Document() As Task
Dim code = <code>''' [|TODO test|]</code>
Await TestAsync(code)
End Function
<Fact>
Public Async Function TestSingleLineTodoComment_Preprocessor1() As Task
Dim code = <code>#If DEBUG Then ' [|TODO test|]</code>
Await TestAsync(code)
End Function
<Fact>
Public Async Function TestSingleLineTodoComment_Preprocessor2() As Task
Dim code = <code>#If DEBUG Then ''' [|TODO test|]</code>
Await TestAsync(code)
End Function
<Fact>
Public Async Function TestSingleLineTodoComment_Region() As Task
Dim code = <code>#Region ' [|TODO test |]</code>
Await TestAsync(code)
End Function
<Fact>
Public Async Function TestSingleLineTodoComment_EndRegion() As Task
Dim code = <code>#End Region ' [|TODO test |]</code>
Await TestAsync(code)
End Function
<Fact>
Public Async Function TestSingleLineTodoComment_TrailingSpan() As Task
Dim code = <code>' [|TODO test |]</code>
Await TestAsync(code)
End Function
<Fact>
Public Async Function TestSingleLineTodoComment_REM() As Task
Dim code = <code>REM [|TODO test |]</code>
Await TestAsync(code)
End Function
<Fact>
Public Async Function TestSingleLineTodoComment_Preprocessor_REM() As Task
Dim code = <code>#If Debug Then REM [|TODO test |]</code>
Await TestAsync(code)
End Function
<Fact>
Public Async Function TestSinglelineDocumentComment_Multiline() As Task
Dim code = <code>
''' <summary>
''' [|TODO : test |]
''' </summary>
''' [|UNDONE: test2 |]</code>
Await TestAsync(code)
End Function
<Fact>
<WorkItem(606010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/606010")>
Public Async Function TestLeftRightSingleQuote() As Task
Dim code = <code>
‘[|todo fullwidth 1|]
’[|todo fullwidth 2|]
</code>
Await TestAsync(code)
End Function
<Fact>
<WorkItem(606019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/606019")>
Public Async Function TestHalfFullTodo() As Task
Dim code = <code>
'[|todo whatever|]
</code>
Await TestAsync(code)
End Function
<Fact>
<WorkItem(627723, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627723")>
Public Async Function TestSingleQuote_Invalid1() As Task
Dim code = <code>
'' todo whatever
</code>
Await TestAsync(code)
End Function
<Fact>
<WorkItem(627723, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627723")>
Public Async Function TestSingleQuote_Invalid2() As Task
Dim code = <code>
'''' todo whatever
</code>
Await TestAsync(code)
End Function
<Fact>
<WorkItem(627723, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627723")>
Public Async Function TestSingleQuote_Invalid3() As Task
Dim code = <code>
' '' todo whatever
</code>
Await TestAsync(code)
End Function
Private Shared Async Function TestAsync(codeWithMarker As XElement) As Tasks.Task
Dim code As String = Nothing
Dim list As IList(Of TextSpan) = Nothing
MarkupTestFile.GetSpans(codeWithMarker.NormalizedValue, code, list)
Using workspace = Await TestWorkspace.CreateVisualBasicAsync(code)
Dim commentTokens = New TodoCommentTokens()
Dim provider = New TodoCommentIncrementalAnalyzerProvider(commentTokens)
Dim worker = DirectCast(provider.CreateIncrementalAnalyzer(workspace), TodoCommentIncrementalAnalyzer)
Dim document = workspace.Documents.First()
Dim documentId = document.Id
Await worker.AnalyzeSyntaxAsync(workspace.CurrentSolution.GetDocument(documentId), InvocationReasons.Empty, CancellationToken.None)
Dim todoLists = worker.GetItems_TestingOnly(documentId)
Assert.Equal(todoLists.Count, list.Count)
For i = 0 To todoLists.Count - 1 Step 1
Dim todo = todoLists(i)
Dim span = list(i)
Dim line = document.InitialTextSnapshot.GetLineFromPosition(span.Start)
Assert.Equal(todo.MappedLine, line.LineNumber)
Assert.Equal(todo.MappedColumn, span.Start - line.Start.Position)
Assert.Equal(todo.Message, code.Substring(span.Start, span.Length))
Next
End Using
End Function
End Class
End Namespace
|
bbarry/roslyn
|
src/EditorFeatures/VisualBasicTest/TodoComment/TodoCommentTests.vb
|
Visual Basic
|
apache-2.0
| 7,061
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration
<[UseExportProvider]>
Public Class MultiLineLambdaTests
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyWithFunctionLambda()
VerifyStatementEndConstructApplied(
before:="Class c1
Sub goo()
Dim x = Function()
End Sub
End Class",
beforeCaret:={2, -1},
after:="Class c1
Sub goo()
Dim x = Function()
End Function
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyWithFunctionLambdaWithMissingEndFunction()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo()
Dim x = Function()
End Class",
beforeCaret:={2, -1},
after:="Class c1
Function goo()
Dim x = Function()
End Function
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyWithSubLambda()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo()
Dim x = Sub()
End Function
End Class",
beforeCaret:={2, -1},
after:="Class c1
Function goo()
Dim x = Sub()
End Sub
End Function
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(544362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544362")>
Public Sub TestApplyWithSubLambdaWithNoParameterParenthesis()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo()
Dim x = Sub
End Function
End Class",
beforeCaret:={2, -1},
after:="Class c1
Function goo()
Dim x = Sub()
End Sub
End Function
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(544362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544362")>
Public Sub TestApplyWithSubLambdaInsideMethodCall()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo()
M(Sub())
End Function
End Class",
beforeCaret:={2, 11},
after:="Class c1
Function goo()
M(Sub()
End Sub)
End Function
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(544362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544362")>
Public Sub TestApplyWithSubLambdaAndStatementInsideMethodCall()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo()
M(Sub() Exit Sub)
End Function
End Class",
beforeCaret:={2, 11},
after:="Class c1
Function goo()
M(Sub()
Exit Sub
End Sub)
End Function
End Class",
afterCaret:={3, 10})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(544362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544362")>
Public Sub TestApplyWithFunctionLambdaInsideMethodCall()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo()
M(Function() 1)
End Function
End Class",
beforeCaret:={2, 17},
after:="Class c1
Function goo()
M(Function()
Return 1
End Function)
End Function
End Class",
afterCaret:={3, 17})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyAnonymousType()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = New With {.x = Function(x)
End Sub
End Class",
beforeCaret:={2, -1},
after:="Class C
Sub s()
Dim x = New With {.x = Function(x)
End Function
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifySingleLineLambdaFunc()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub s()
Dim x = Function(x) x
End Sub
End Class",
caret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifySingleLineLambdaSub()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub s()
Dim y = Sub(x As Integer) x.ToString()
End Sub
End Class",
caret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyAsDefaultParameterValue()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s(Optional ByVal f As Func(Of String, String) = Function(x As String)
End Class",
beforeCaret:={1, -1},
after:="Class C
Sub s(Optional ByVal f As Func(Of String, String) = Function(x As String)
End Function
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyNestedLambda()
VerifyStatementEndConstructApplied(
before:="Class C
sub s
Dim x = Function (x)
Dim y = function(y)
End Function
End sub
End Class",
beforeCaret:={3, -1},
after:="Class C
sub s
Dim x = Function (x)
Dim y = function(y)
End function
End Function
End sub
End Class",
afterCaret:={4, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyInField()
VerifyStatementEndConstructApplied(
before:="Class C
Dim x = Sub()
End Class",
beforeCaret:={1, -1},
after:="Class C
Dim x = Sub()
End Sub
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyInvalidLambdaSyntax()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub s()
Sub(x)
End Sub
End Class",
caret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyNotAppliedIfSubLambdaContainsEndSub()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub s()
Dim x = Sub() End Sub
End Sub
End Class",
caret:={2, 21})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyNotAppliedIfSyntaxIsFunctionLambdaContainsEndFunction()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub s()
Dim x = Function() End Function
End Sub
End Class",
caret:={2, 26})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyLambdaWithImplicitLC()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub s()
Dim x = Function(y As Integer) y +
End Sub
End Class",
caret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyLambdaWithMissingParenthesis()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = Function
End Sub
End Class",
beforeCaret:={2, -1},
after:="Class C
Sub s()
Dim x = Function()
End Function
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifySingleLineSubLambdaToMultiLine()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = Sub() f()
End Sub
End Class",
beforeCaret:={2, 21},
after:="Class C
Sub s()
Dim x = Sub()
f()
End Sub
End Sub
End Class",
afterCaret:={3, 20})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(530683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530683")>
Public Sub TestVerifySingleLineSubLambdaToMultiLineWithTrailingTrivia()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = Sub() f() ' Invokes f()
End Sub
End Class",
beforeCaret:={2, 21},
after:="Class C
Sub s()
Dim x = Sub()
f() ' Invokes f()
End Sub
End Sub
End Class",
afterCaret:={3, 20})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifySingleLineFunctionLambdaToMultiLine()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = Function() f()
End Sub
End Class",
beforeCaret:={2, 27},
after:="Class C
Sub s()
Dim x = Function()
Return f()
End Function
End Sub
End Class",
afterCaret:={3, 27})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(530683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530683")>
Public Sub TestVerifySingleLineFunctionLambdaToMultiLineWithTrailingTrivia()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = Function() 4 ' Returns Constant 4
End Sub
End Class",
beforeCaret:={2, 27},
after:="Class C
Sub s()
Dim x = Function()
Return 4 ' Returns Constant 4
End Function
End Sub
End Class",
afterCaret:={3, 27})
End Sub
<WorkItem(1922, "https://github.com/dotnet/roslyn/issues/1922")>
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(530683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530683")>
Public Sub TestVerifySingleLineFunctionLambdaToMultiLineInsideXMLTag()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = <xml><%= Function()%></xml>
End Sub
End Class",
beforeCaret:={2, 35},
after:="Class C
Sub s()
Dim x = <xml><%= Function()
End Function %></xml>
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WorkItem(1922, "https://github.com/dotnet/roslyn/issues/1922")>
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(530683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530683")>
Public Sub TestVerifySingleLineSubLambdaToMultiLineInsideXMLTag()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = <xml><%= Sub()%></xml>
End Sub
End Class",
beforeCaret:={2, 30},
after:="Class C
Sub s()
Dim x = <xml><%= Sub()
End Sub %></xml>
End Sub
End Class",
afterCaret:={3, -1})
End Sub
End Class
End Namespace
|
VSadov/roslyn
|
src/EditorFeatures/VisualBasicTest/EndConstructGeneration/MultiLineLambdaTests.vb
|
Visual Basic
|
apache-2.0
| 12,688
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
'-----------------------------------------------------------------------------
' Contains the definition of the DeclarationContext
'-----------------------------------------------------------------------------
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports InternalSyntaxFactory = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.SyntaxFactory
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Friend Class TypeBlockContext
Inherits DeclarationContext
Protected _inheritsDecls As SyntaxList(Of InheritsStatementSyntax)
Private _implementsDecls As SyntaxList(Of ImplementsStatementSyntax)
Protected _state As SyntaxKind
Friend Sub New(contextKind As SyntaxKind, statement As StatementSyntax, prevContext As BlockContext)
MyBase.New(contextKind, statement, prevContext)
Debug.Assert(contextKind = SyntaxKind.ModuleBlock OrElse contextKind = SyntaxKind.ClassBlock OrElse
contextKind = SyntaxKind.StructureBlock OrElse contextKind = SyntaxKind.InterfaceBlock)
Debug.Assert(BlockKind = SyntaxKind.ModuleBlock OrElse BlockKind = SyntaxKind.ClassBlock OrElse
BlockKind = SyntaxKind.StructureBlock OrElse BlockKind = SyntaxKind.InterfaceBlock)
_state = SyntaxKind.None
End Sub
Friend Overrides Function ProcessSyntax(node As VisualBasicSyntaxNode) As BlockContext
Do
Select Case _state
Case SyntaxKind.None
Select Case node.Kind
Case SyntaxKind.InheritsStatement
_state = SyntaxKind.InheritsStatement
Case SyntaxKind.ImplementsStatement
_state = SyntaxKind.ImplementsStatement
Case Else
_state = SyntaxKind.ClassStatement
End Select
Case SyntaxKind.InheritsStatement
Select Case node.Kind
Case SyntaxKind.InheritsStatement
Add(node)
Exit Do
Case Else
_inheritsDecls = BaseDeclarations(Of InheritsStatementSyntax)()
_state = SyntaxKind.ImplementsStatement
End Select
Case SyntaxKind.ImplementsStatement
Select Case node.Kind
Case SyntaxKind.ImplementsStatement
Add(node)
Exit Do
Case Else
_implementsDecls = BaseDeclarations(Of ImplementsStatementSyntax)()
_state = SyntaxKind.ClassStatement ' done with base decls
End Select
Case Else
Return MyBase.ProcessSyntax(node)
End Select
Loop
Return Me
End Function
Friend Overrides Function CreateBlockSyntax(endStmt As StatementSyntax) As VisualBasicSyntaxNode
Dim beginBlockStmt As TypeStatementSyntax = Nothing
Dim endBlockStmt As EndBlockStatementSyntax = DirectCast(endStmt, EndBlockStatementSyntax)
GetBeginEndStatements(beginBlockStmt, endBlockStmt)
If _state <> SyntaxKind.ClassStatement Then
Select Case _state
Case SyntaxKind.InheritsStatement
_inheritsDecls = BaseDeclarations(Of InheritsStatementSyntax)()
Case SyntaxKind.ImplementsStatement
_implementsDecls = BaseDeclarations(Of ImplementsStatementSyntax)()
End Select
_state = SyntaxKind.ClassStatement
End If
Dim result = InternalSyntaxFactory.TypeBlock(BlockKind, beginBlockStmt,
_inheritsDecls,
_implementsDecls,
Body(),
endBlockStmt)
FreeStatements()
Return result
End Function
End Class
End Namespace
|
MatthieuMEZIL/roslyn
|
src/Compilers/VisualBasic/Portable/Parser/BlockContexts/TypeBlockContext.vb
|
Visual Basic
|
apache-2.0
| 4,680
|
Option Explicit On
Option Strict On
Public Class ExpressionNode
Implements AstNode
Public left As ExpressionNode
Public right As ExpressionNode
Public opr As Token
Public token As Token
Public value As String
Public type As String
Public Function getChildren() As List(Of AstNode) Implements AstNode.getChildren
Return New List(Of AstNode)({left, right})
End Function
End Class
|
ananse/ananse
|
src/ast/nodes/ExpressionNode.vb
|
Visual Basic
|
mit
| 429
|
Imports System
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports Telerik.Web.UI
Imports SistFoncreagro.BussinesLogic
Imports SistFoncreagro.BussinessEntities
Public Class WebForm1
Inherits System.Web.UI.Page
Private _dataItem As Object = Nothing
Dim ConvenioBL As New ConvenioBL
Dim _Convenio As Convenio
Dim nConvenio As New Convenio
Dim DesemBL As New DesembolsoBL
Dim nDesem As New Desembolso
Dim _Desem As Desembolso
Dim Idconvenio As String
Public Function ValidarFecha(ByVal Valor As Date) As String
Dim MisFunciones As New Funciones
Dim miFecha As String = MisFunciones.CampoFecha(Valor)
Return miFecha
End Function
Public Function AnioFecha(ByVal Valor As Date) As String
Dim miFecha As String = Year(Valor).ToString
Return miFecha
End Function
Public Function ValidarNumero(ByVal Valor As Decimal) As String
Dim MisFunciones As New Funciones
Dim miNumero As String = MisFunciones.CampoNumero(Valor)
Return miNumero
End Function
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim miId As String
miId = Request.QueryString("IdConvenio")
HFIdConvenio.Value = miId
Dim EsAdenda As String
EsAdenda = Request.QueryString("A")
If Not Page.IsPostBack Then
Me.Button2.Attributes.Add("onClick", "NuevoConveMarco(" & Request.QueryString("IdConvenio") & "); return false;")
End If
If EsAdenda = "AD" Then
RadTabStrip1.SelectedIndex = 2
Datos.SelectedIndex = 2
Exit Sub
End If
If Not Me.Page.IsPostBack Then
RadTabStrip1.SelectedIndex = 0
Datos.SelectedIndex = 0
If miId = "0" Then
'campos vacios
TxtNombre.Text = ""
TxtCodigo.Text = ""
TxtMontoIni.Text = ""
CbFase.Text = ""
CbEstado.Text = ""
DtFechaFirma.SelectedDate = DateValue("01/01/1985")
DTInicio.SelectedDate = DateValue("01/01/1985")
DTFin.SelectedDate = DateValue("01/01/1985")
BtnGrabar.Visible = True
BtnActualizar.Visible = False
Ver_ConvenioMarco(False)
ChConvenioMarco.Checked = False
Else
Call Llenar_Datos_Convenio(miId)
BtnGrabar.Visible = False
BtnActualizar.Visible = True
TxtMontoIni.Enabled = False
DtFechaFirma.Enabled = False
DTInicio.Enabled = False
DTFin.Enabled = False
End If
End If
End Sub
Private Sub Llenar_Datos_Convenio(ByVal mIdConvenio As String)
'nConvenio = New Convenio
nConvenio = ConvenioBL.GetFromConvenioByIdConvenio(mIdConvenio)
TxtCodigo.Text = nConvenio.Codigo
TxtNombre.Text = nConvenio.Nombre
TxtMontoIni.Text = nConvenio.MontoInicial
CbFase.Text = nConvenio.FaseCont
CbEstado.Text = nConvenio.Estado
If DateValue(nConvenio.FechaFirma) = ("01/01/0001") Then DtFechaFirma.SelectedDate = "01/01/1985" Else DtFechaFirma.SelectedDate = DateValue(nConvenio.FechaFirma)
If DateValue(nConvenio.FecIni) = ("01/01/0001") Then DTInicio.SelectedDate = "01/01/1985" Else DTInicio.SelectedDate = DateValue(nConvenio.FecIni)
If DateValue(nConvenio.FecFin) = ("01/01/0001") Then DTFin.SelectedDate = "01/01/1985" Else DTFin.SelectedDate = DateValue(nConvenio.FecFin)
If nConvenio.IdConveMarco = 0 Then
ChConvenioMarco.Checked = False
Ver_ConvenioMarco(False)
Else
CbConveMarco.SelectedValue = nConvenio.IdConveMarco
ChConvenioMarco.Checked = True
Ver_ConvenioMarco(True)
End If
End Sub
Protected Sub BtnGrabar_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles BtnGrabar.Click
Call Grabar_Datos_Convenio()
Response.Redirect("~\Monitoreo\Formularios\FrmBuscarConvenio.aspx")
End Sub
Private Sub Grabar_Datos_Convenio()
If TxtCodigo.Text = "" Then MsgBox("Ingrese el código del convenio", vbCritical, "Error") : Exit Sub
If TxtNombre.Text = "" Then MsgBox("Ingrese el nombre del convenio", vbCritical, "Error") : Exit Sub
If DateValue(DTFin.SelectedDate) < DateValue(DTInicio.SelectedDate) Then MsgBox("Las fechas de inicio y fin son incorrectas", vbCritical, "Error") : Exit Sub
If DateValue(DtFechaFirma.SelectedDate) > DateValue(DTInicio.SelectedDate) Then MsgBox("Las fechas de inicio y firma son incorrectas", vbCritical, "Error") : Exit Sub
Dim miId As Int32
nConvenio.Codigo = UCase(TxtCodigo.Text)
nConvenio.Nombre = UCase(TxtNombre.Text)
If Len(DTInicio.SelectedDate) = 0 Then nConvenio.FecIni = DateValue("01/01/1985") Else nConvenio.FecIni = DateValue(DTInicio.SelectedDate)
If Len(DTFin.SelectedDate) = 0 Then nConvenio.FecFin = DateValue("01/01/1985") Else nConvenio.FecFin = DateValue(DTFin.SelectedDate)
If Len(DtFechaFirma.SelectedDate) = 0 Then nConvenio.FechaFirma = DateValue("01/01/1985") Else nConvenio.FechaFirma = DateValue(DtFechaFirma.SelectedDate)
nConvenio.IdMoneda = CbMoneda.SelectedValue
nConvenio.MontoInicial = CDbl(TxtMontoIni.Text)
nConvenio.IdTipConv = CbTipoConvenio.SelectedValue
nConvenio.FaseCont = UCase(CbFase.Text)
nConvenio.Estado = UCase(CbEstado.Text)
If ChConvenioMarco.Checked = True Then nConvenio.IdConveMarco = CInt(CbConveMarco.SelectedValue) Else nConvenio.IdConveMarco = 0
miId = ConvenioBL.SaveConvenio(nConvenio)
HFIdConvenio.Value = miId.ToString
End Sub
Protected Sub BtnActualizar_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles BtnActualizar.Click
Dim miId As String
miId = Request.QueryString("IdConvenio")
nConvenio = ConvenioBL.GetFromConvenioByIdConvenio(miId)
nConvenio.IdConvenio = miId
nConvenio.Codigo = UCase(TxtCodigo.Text)
nConvenio.Nombre = UCase(TxtNombre.Text)
nConvenio.IdMoneda = CbMoneda.SelectedValue
nConvenio.MontoInicial = CDbl(TxtMontoIni.Text)
nConvenio.IdTipConv = CbTipoConvenio.SelectedValue
nConvenio.FaseCont = UCase(CbFase.Text)
nConvenio.Estado = UCase(CbEstado.Text)
If ChConvenioMarco.Checked = True Then nConvenio.IdConveMarco = CInt(CbConveMarco.SelectedValue) Else nConvenio.IdConveMarco = 0
If Len(DTInicio.SelectedDate) = 0 Then nConvenio.FecIni = DateValue("01/01/1985") Else nConvenio.FecIni = DateValue(DTInicio.SelectedDate)
If Len(DTFin.SelectedDate) = 0 Then nConvenio.FecFin = DateValue("01/01/1985") Else nConvenio.FecFin = DateValue(DTFin.SelectedDate)
If Len(DtFechaFirma.SelectedDate) = 0 Then nConvenio.FechaFirma = DateValue("01/01/1985") Else nConvenio.FechaFirma = DateValue(DtFechaFirma.SelectedDate)
ConvenioBL.SaveConvenio(nConvenio)
Response.Redirect("~\Monitoreo\Formularios\FrmBuscarConvenio.aspx")
End Sub
Protected Sub RadTabStrip1_TabClick(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadTabStripEventArgs) Handles RadTabStrip1.TabClick
Dim nTab, miId As String
miId = Request.QueryString("IdConvenio")
nTab = e.Tab.Text
If nTab = "Datos Generales" And miId <> "0" Then
Call Llenar_Datos_Convenio(miId)
ElseIf nTab = "Desembolsos" Then
RadTabStrip1.SelectedIndex = 1
Datos.SelectedIndex = 1
ElseIf nTab = "Adenda" Then
RadTabStrip1.SelectedIndex = 2
Datos.SelectedIndex = 2
Call Mostrar_Adenda(miId)
End If
End Sub
Private Sub Mostrar_Adenda(ByVal mIdConvenio)
PanelAdenda.Visible = False
End Sub
Protected Sub BtnAceptarDesem_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles BtnAceptarDesem.Click
Grabar_Desembolso("NUEVO")
End Sub
Private Sub Grabar_Desembolso(ByVal mAccion As String)
Dim miId As String
Dim idDesem As Int32
miId = Request.QueryString("IdConvenio")
nDesem.IdConvenio = miId
'nDesem.Numero = CInt(TxtNumDesem.Text)
If Len(DtFeDesem.SelectedDate) = 0 Then nDesem.FechaProg = "01/01/1985" Else nDesem.FechaProg = DateValue(DtFeDesem.SelectedDate)
'If Len(DtFecEjec.SelectedDate) = 0 Then nDesem.FechaEjec = "01/01/1985" Else nDesem.FechaEjec = DateValue(DtFecEjec.SelectedDate)
If TxtMontoDesem.Text <> "" Then nDesem.MontoProg = CDbl(TxtMontoDesem.Text)
'If TxtMontoEjec.Text <> "" Then nDesem.MontoEjec = CDbl(TxtMontoEjec.Text)
nDesem.Estado = UCase(CbEstadoDesem.Text)
nDesem.IdProveedorCliente = Integer.Parse(CbInstitucionDesem.SelectedValue)
If mAccion = "NUEVO" Then
idDesem = DesemBL.SaveDesembolso(nDesem)
TxtIdDesem.Text = idDesem
ElseIf mAccion = "EDITAR" Then
nDesem.IdDesembolso = CInt(TxtIdDesem.Text)
DesemBL.SaveDesembolso(nDesem)
End If
RadGrid1.DataBind()
PanelDesem.Visible = False
End Sub
Private Sub Limpiar_Campos_Desembolso()
TxtNumDesem.Text = ""
DtFeDesem.Clear()
TxtMontoEjec.Text = ""
DtFecEjec.Clear()
TxtMontoDesem.Text = ""
TxtIdDesem.Text = ""
End Sub
Private Sub Llenar_Datos_Desem(ByVal mIdDesem As Int32)
_Desem = DesemBL.GetFromDesembolsoByIdDesembolso(mIdDesem)
TxtNumDesem.Text = _Desem.Numero
If DateValue(_Desem.FechaProg) <> "01/01/0001" Then DtFeDesem.SelectedDate = DateValue(_Desem.FechaProg) Else DtFeDesem.Clear()
TxtMontoDesem.Text = _Desem.MontoProg
'If DateValue(_Desem.FechaEjec) <> "01/01/0001" Then DtFecEjec.SelectedDate = DateValue(_Desem.FechaEjec) Else DtFecEjec.Clear()
TxtMontoEjec.Text = _Desem.MontoEjec
CbEstadoDesem.Text = _Desem.Estado
End Sub
Private Sub CbConveMarco_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemEventArgs) Handles CbConveMarco.ItemDataBound
'e.Item.Text = (DirectCast(e.Item.DataItem, SistFoncreagro.BussinessEntities.ConveMarco)).Marco.ToString()
'e.Item.Value = (DirectCast(e.Item.DataItem, SistFoncreagro.BussinessEntities.ConveMarco)).IdConveMarco.ToString()
End Sub
Private Sub CbConveMarco_ItemsRequested(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs) Handles CbConveMarco.ItemsRequested
'If e.Text.Length > 3 Then
' Me.OdsConveMarco.SelectParameters("_Texto").DefaultValue = e.Text.ToString
' Me.CbConveMarco.DataBind()
'End If
End Sub
Protected Sub AJAX_MANAGER_AjaxRequest(ByVal sender As Object, ByVal e As Telerik.Web.UI.AjaxRequestEventArgs) Handles AJAX_MANAGER.AjaxRequest
If e.Argument.StartsWith("ActualizarCombo") Then
Dim j() As String
Dim idConveMarco As Int32
j = Split(e.Argument, "|")
idConveMarco = Convert.ToInt32(j(1))
Me.CbConveMarco.DataBind()
Me.CbConveMarco.SelectedValue = idConveMarco
End If
End Sub
Protected Sub BtnNuevoDesem_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles BtnNuevoDesem.Click
PanelDesem.Visible = True
Limpiar_Campos_Desembolso()
BtnActDesem.Visible = False
BtnAceptarDesem.Visible = True
End Sub
Protected Sub BtnCancelDesem_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles BtnCancelDesem.Click
PanelDesem.Visible = False
End Sub
Protected Sub BtnActDesem_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles BtnActDesem.Click
Grabar_Desembolso("EDITAR")
End Sub
Protected Sub BtnNuevoAd_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles BtnNuevoAd.Click
PanelAdenda.Visible = True
Call Limpiar_Adenda()
End Sub
Private Sub Limpiar_Adenda()
ChTiempo.Checked = False
ChCosto.Checked = False
ChAlcance.Checked = False
PanelAdAlcance.Visible = False
PanelAdCosto.Visible = False
PanelAdTiempo.Visible = False
PanelAdenda.Visible = True
FileUploadControl.Visible = True
TxtDescAd.Visible = True
TxtIdAdenda.Text = ""
TxtMontoAd.Text = ""
DtFeFinAd.Clear()
DtFirmaAd.Clear()
DtFeFinVigAd.Clear()
DtFeIniVigAd.Clear()
TxtNumAd.Text = ""
TxtJustif.Text = ""
TxtRespAd.Text = ""
End Sub
Protected Sub BtnGrabarAd_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles BtnGrabarAd.Click
Dim miIdConvenio As String
Dim idAdenda As Int32
miIdConvenio = Request.QueryString("IdConvenio")
Dim _AdendaBL As New AdendaBL
Dim _Adenda As New Adenda
_Adenda.IdConvenio = miIdConvenio
_Adenda.Motivo = UCase(TxtJustif.Text)
_Adenda.Responsable = UCase(TxtRespAd.Text)
If Len(DtFeIniVigAd.SelectedDate) = 0 Then _Adenda.VigenciaIni = "01/01/1985" Else _Adenda.VigenciaIni = DateValue(DtFeIniVigAd.SelectedDate)
If Len(DtFeFinVigAd.SelectedDate) = 0 Then _Adenda.VigenciaFin = "01/01/1985" Else _Adenda.VigenciaFin = DateValue(DtFeFinVigAd.SelectedDate)
If Len(DtFirmaAd.SelectedDate) = 0 Then _Adenda.Fecha = "01/01/1985" Else _Adenda.Fecha = DateValue(DtFirmaAd.SelectedDate)
_Adenda.Costo = ChCosto.Checked
If TxtMontoAd.Text <> "" Then _Adenda.Monto = CDbl(TxtMontoAd.Text)
_Adenda.Tiempo = ChTiempo.Checked
If Len(DtFeFinAd.SelectedDate) = 0 Then _Adenda.FechaFin = "01/01/1985" Else _Adenda.FechaFin = DateValue(DtFeFinAd.SelectedDate)
_Adenda.Alcance = ChAlcance.Checked
If TxtIdAdenda.Text = "" Then
idAdenda = _AdendaBL.SaveAdenda(_Adenda)
TxtIdAdenda.Text = idAdenda
ElseIf TxtIdAdenda.Text <> "" Then
idAdenda = CInt(TxtIdAdenda.Text)
_Adenda.IdAdenda = idAdenda
_AdendaBL.SaveAdenda(_Adenda)
End If
If GridView3.Rows.Count = 0 And FileUploadControl.FileName <> "" Then
If ChAlcance.Checked = True Then
SaveFile(FileUploadControl.PostedFile, "ADENDA", "Adenda", idAdenda, TxtDescAd.Text)
end if
End If
GridView2.DataBind()
PanelAdenda.Visible = False
End Sub
private Sub SaveFile(ByVal file As HttpPostedFile, ByVal mTabla As String, ByVal CarpetaDestino As String, ByVal mIdTabla As Int32, ByVal mDesArchivo As String)
Dim savePath As String = Server.MapPath("~\Archivos\Monitoreo\" + CarpetaDestino + "\")
Dim fileName As String = FileUploadControl.FileName
Dim pathToCheck As String = savePath + fileName
Dim tempfileName As String
tempfileName = ""
If (System.IO.File.Exists(pathToCheck)) Then
Dim counter As Integer = 2
While (System.IO.File.Exists(pathToCheck))
tempfileName = counter.ToString() + fileName
pathToCheck = savePath + tempfileName
counter = counter + 1
End While
fileName = tempfileName
End If
savePath += fileName
FileUploadControl.SaveAs(savePath)
Adjunto_BD(fileName, 0, mTabla, mIdTabla, mDesArchivo)
End Sub
Private Sub Adjunto_BD(ByVal mRuta As String, ByVal mIdAjunto As Int32, ByVal mTabla As String, ByVal mIdTabla As Int32, ByVal mDesArchivo As String)
Dim AdjuntoBL As New AdjMonitBL
Dim mAdjunto As New AdjMonit
Dim IdAdj As Integer
If mIdAjunto <> 0 Then mAdjunto.IdAdjMonit = mIdAjunto
mAdjunto.Id = mIdTabla
mAdjunto.Tabla = mTabla
mAdjunto.Ruta = mRuta
mAdjunto.Descripcion = mDesArchivo
mAdjunto.Fecha = DateValue(Date.Now)
IdAdj = AdjuntoBL.SaveAdjMonit(mAdjunto)
End Sub
Protected Sub ChCosto_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ChCosto.CheckedChanged
PanelAdCosto.Visible = ChCosto.Checked
End Sub
Protected Sub ChTiempo_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ChTiempo.CheckedChanged
PanelAdTiempo.Visible = ChTiempo.Checked
End Sub
Protected Sub ChAlcance_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ChAlcance.CheckedChanged
PanelAdAlcance.Visible = ChAlcance.Checked
End Sub
Protected Sub BtnCancelAd_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles BtnCancelAd.Click
PanelAdenda.Visible = False
End Sub
Private Sub Llenar_Datos_Adenda(ByVal mIdAdenda As Int32)
Dim _AdendaBL As New AdendaBL
Dim _Adenda As New Adenda
_Adenda = _AdendaBL.GetFromAdendaByIdAdenda(mIdAdenda)
TxtNumAd.Text = _Adenda.Numero
TxtJustif.Text = _Adenda.Motivo
TxtRespAd.Text = _Adenda.Responsable
If DateValue(_Adenda.Fecha) <> "01/01/0001" Then DtFirmaAd.SelectedDate = DateValue(_Adenda.Fecha) Else DtFirmaAd.Clear()
If DateValue(_Adenda.VigenciaIni) <> "01/01/0001" Then DtFeIniVigAd.SelectedDate = DateValue(_Adenda.VigenciaIni) Else DtFeIniVigAd.Clear()
If DateValue(_Adenda.VigenciaFin) <> "01/01/0001" Then DtFeFinVigAd.SelectedDate = DateValue(_Adenda.VigenciaFin) Else DtFeFinVigAd.Clear()
ChCosto.Checked = _Adenda.Costo
ChTiempo.Checked = _Adenda.Tiempo
ChAlcance.Checked = _Adenda.Alcance
PanelAdAlcance.Visible = ChAlcance.Checked
PanelAdCosto.Visible = ChCosto.Checked
PanelAdTiempo.Visible = ChTiempo.Checked
If ChTiempo.Checked = True Then
If DateValue(_Adenda.FechaFin) <> "01/01/0001" Then DtFeFinAd.SelectedDate = DateValue(_Adenda.FechaFin) Else DtFeFinAd.Clear()
End If
If ChCosto.Checked = True Then
TxtMontoAd.Text = _Adenda.Monto
End If
If ChAlcance.Checked = True Then
GridView3.DataBind()
If GridView3.Rows.Count = 0 Then
FileUploadControl.Visible = True
TxtDescAd.Visible = True
Else
FileUploadControl.Visible = False
TxtDescAd.Visible = False
End If
End If
End Sub
Protected Sub GridView3_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView3.RowEditing
Dim id As String
id = GridView3.DataKeys(e.NewEditIndex).Values("IdAdjMonit").ToString()
e.Cancel = True
Dim _AdendaArchivoBL As New AdjMonitBL
Dim _AdendaArchivo As New AdjMonit
_AdendaArchivo = _AdendaArchivoBL.GetADJMONITByIdAdjMonit(id)
Dim NomArch As String = _AdendaArchivo.Ruta
Dim archivo As String = (Server.MapPath("~\Archivos\Monitoreo\Adenda\" + NomArch))
Try
My.Computer.FileSystem.DeleteFile(archivo, FileIO.UIOption.AllDialogs, FileIO.RecycleOption.SendToRecycleBin, FileIO.UICancelOption.DoNothing)
Dim AdjuntoBL As New AdjMonitBL
AdjuntoBL.DeleteAdjMonit(CInt(id))
GridView3.DataBind()
Catch ex As Exception
MsgBox(ex.Message.ToString, MsgBoxStyle.Critical)
End Try
End Sub
Protected Sub SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles GridView2.SelectedIndexChanged, GridView3.SelectedIndexChanged
PanelAdenda.Visible = True
Dim id As String
id = GridView2.SelectedDataKey.Value.ToString()
If id.ToString <> TxtIdAdenda.Text Then
TxtIdAdenda.Text = id
Call Llenar_Datos_Adenda(CInt(id))
End If
End Sub
Protected Sub SelectedIndexChanged1(ByVal sender As Object, ByVal e As EventArgs) Handles GridView3.SelectedIndexChanged, GridView3.SelectedIndexChanged, GridView3.SelectedIndexChanged, GridView3.SelectedIndexChanged, GridView3.SelectedIndexChanged, GridView3.SelectedIndexChanged, GridView3.SelectedIndexChanged, GridView3.SelectedIndexChanged
Dim id As String
id = GridView3.SelectedDataKey.Value.ToString()
Dim NomArchivo As String = GridView3.Rows(GridView3.SelectedIndex).Cells(3).Text
'Dim myFile As ProcessStartInfo
'myFile = New ProcessStartInfo(Server.MapPath("~\Monitoreo\Archivos\Adenda\" + NomArchivo))
'Process.Start(myFile)
System.Diagnostics.Process.Start("~\Archivos\Monitoreo\Adenda\" + NomArchivo)
End Sub
Protected Sub BtnEliminarAd_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
Dim BtnEliminar As ImageButton = CType(sender, ImageButton)
If BtnEliminar.CommandName = "BorrarAd" Then
Dim id As String
id = BtnEliminar.CommandArgument
Dim _AdendaArchivoBL As New AdjMonitBL
Dim _AdendaArchivo As New List(Of AdjMonit)
_AdendaArchivo = _AdendaArchivoBL.GetADJMONITByIdAndTabla(id, "ADENDA")
If _AdendaArchivo.Count > 0 Then
Dim NomArch As String = (Server.MapPath("~\Archivos\Monitoreo\Adenda\" + _AdendaArchivo(0).Ruta))
'borra el archivo y el usuario confirma
'My.Computer.FileSystem.DeleteFile(NomArch, FileIO.UIOption.AllDialogs, FileIO.RecycleOption.SendToRecycleBin, FileIO.UICancelOption.DoNothing)
'Borra el archivo
My.Computer.FileSystem.DeleteFile(NomArch)
End If
Dim _AdendaBL As New AdendaBL
_AdendaBL.DeleteAdenda(id)
GridView2.DataBind()
End If
End Sub
Protected Sub ChConvenioMarco_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ChConvenioMarco.CheckedChanged
Ver_ConvenioMarco(ChConvenioMarco.Checked)
End Sub
Private Sub Ver_ConvenioMarco(ByVal sw1 As Boolean)
LblConvenioMarco.Visible = sw1
CbConveMarco.Visible = sw1
Button2.Visible = sw1
RFVConvenioMarco.Visible = sw1
End Sub
Private Sub RGInstitucion_DeleteCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RGInstitucion.DeleteCommand
Dim _InstitucionBL As New InstitucionBL
Dim _Institucion As New Institucion
Dim EditedItem As GridEditableItem
EditedItem = CType(e.Item, GridEditableItem)
Dim miId As Int32
miId = EditedItem.OwnerTableView.DataKeyValues(EditedItem.ItemIndex)("IdInstitucion")
_InstitucionBL.DeleteInstitucion(miId)
RGInstitucion.DataBind()
End Sub
Protected Sub RGInstitucion_InsertCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RGInstitucion.InsertCommand
Dim _InstitucionBL As New InstitucionBL
Dim _Institucion As New Institucion
Dim mUserControl As UserControl = CType(e.Item.FindControl(GridEditFormItem.EditFormUserControlID), UserControl)
Dim idInstitucion As Int32
Dim sw As Boolean
sw = False
If HFIdConvenio.Value = "0" Then
Call Grabar_Datos_Convenio()
sw = True
End If
_Institucion.IdConvenio = Integer.Parse(HFIdConvenio.Value)
_Institucion.IdProveedorCliente = (CType(mUserControl.FindControl("CbInstitucion"), RadComboBox).SelectedValue)
_Institucion.Tipo = (CType(mUserControl.FindControl("CbTipo"), DropDownList).SelectedValue)
idInstitucion = _InstitucionBL.SaveInstitucion(_Institucion)
If sw = False Then
RGInstitucion.DataBind()
Else
Response.Redirect("~\Monitoreo\Formularios\FrmDatosConvenio.aspx?IdConvenio=" + HFIdConvenio.Value)
End If
End Sub
Protected Sub RadGrid1_ItemCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.ItemCommand
If e.CommandName = "Select" Then
PanelDesem.Visible = True
Dim id As String
Dim editedItem As GridEditableItem = CType(e.Item, GridEditableItem)
id = editedItem.OwnerTableView.DataKeyValues(editedItem.ItemIndex)("IdDesembolso")
TxtIdDesem.Text = id
Call Llenar_Datos_Desem(Integer.Parse(id))
BtnAceptarDesem.Visible = False
BtnActDesem.Visible = True
End If
End Sub
Protected Sub RadGrid1_DeleteCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.DeleteCommand
Dim id As Int32
Dim editedItem As GridEditableItem = CType(e.Item, GridEditableItem)
id = Integer.Parse(editedItem.OwnerTableView.DataKeyValues(editedItem.ItemIndex)("IdDesembolso"))
Dim _DesemBL As New DesembolsoBL
_DesemBL.DeleteDesembolso(id)
RadGrid1.DataBind()
End Sub
Private Sub RGObs_DeleteCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RGObs.DeleteCommand
Dim editedItem As GridEditableItem = CType(e.Item, GridEditableItem)
Dim _Id As Int32
_Id = Integer.Parse(editedItem.OwnerTableView.DataKeyValues(editedItem.ItemIndex)("IdObservacion"))
Dim _ObsBL As New ObservacionBL
_ObsBL.DeleteObservacion(_Id)
RGObs.DataBind()
End Sub
Protected Sub RGObs_InsertCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RGObs.InsertCommand
Dim mUserControl As UserControl = CType(e.Item.FindControl(GridEditFormItem.EditFormUserControlID), UserControl)
Dim _Obs As New Observacion
Dim _ObsBL As New ObservacionBL
_Obs.Id = Integer.Parse(HFIdConvenio.Value)
_Obs.Observacion = UCase(CType(mUserControl.FindControl("txtObs"), TextBox).Text)
_Obs.Tabla = "CONVENIO"
_ObsBL.InsertObservacion(_Obs)
RGObs.DataBind()
End Sub
Private Sub RGObs_UpdateCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RGObs.UpdateCommand
Dim mUserControl As UserControl = CType(e.Item.FindControl(GridEditFormItem.EditFormUserControlID), UserControl)
Dim editedItem As GridEditableItem = CType(e.Item, GridEditableItem)
Dim _Id As Int32
Dim _Obs As String
_Obs = UCase(CType(mUserControl.FindControl("txtObs"), TextBox).Text)
_Id = Integer.Parse(editedItem.OwnerTableView.DataKeyValues(editedItem.ItemIndex)("IdObservacion"))
Dim _ObsBL As New ObservacionBL
_ObsBL.UpdateObservacion(_Id, _Obs)
RGObs.DataBind()
End Sub
Protected Sub BtnVerAd_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
End Sub
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.WebSite/Monitoreo/Formularios/FrmDatosConvenio.aspx.vb
|
Visual Basic
|
mit
| 27,250
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.Teaq.Tests.vbUsage.My.MySettings
Get
Return Global.Teaq.Tests.vbUsage.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
bkjuice/teaq
|
src/Teaq.Tests.vbUsage/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,926
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("Scientific Calculator")>
<Assembly: AssemblyDescription("A Scientific Calculator, sponsored to Social Systems, programmed by Sam Herring.")>
<Assembly: AssemblyCompany("Social Systems")>
<Assembly: AssemblyProduct("Scientific Calculator")>
<Assembly: AssemblyCopyright("Copyright © Social Systems 2010")>
<Assembly: AssemblyTrademark("Social Systems")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("0390ed9c-ed9a-440f-ab9d-2ddd4c260014")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
SammyHerring/Scientific-Calculator-VB
|
Source/CALCULATOR/My Project/AssemblyInfo.vb
|
Visual Basic
|
cc0-1.0
| 1,317
|
'------------------------------------------------------------------------------
' <auto-generated>
' Dieser Code wurde von einem Tool generiert.
' Laufzeitversion:4.0.30319.237
'
' Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
' der Code erneut generiert wird.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Imports System
Namespace My.Resources
'Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert
'-Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert.
'Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen
'mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu.
'''<summary>
''' Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("Authentication.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle
''' Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
wschult23/LOOM.NET
|
Deploy/RapierLoom.Examples/05-Authentication/VB/My Project/Resources.Designer.vb
|
Visual Basic
|
apache-2.0
| 2,941
|
Imports Gears
Imports Gears.DataSource
Namespace DataSource
Public Class JOB
Inherits GearsDataSource
Public Sub New(ByVal conStr As String)
MyBase.New(conStr, SqlBuilder.DS("EMP"))
End Sub
Public Overrides Function makeSqlBuilder(ByVal data As Gears.GearsDTO) As SqlBuilder
Dim sqlb As SqlBuilder = MyBase.makeSqlBuilder(data)
sqlb.addSelection(SqlBuilder.S("JOB").inGroup.ASC)
sqlb.addSelection(SqlBuilder.S("JOB").asName("JOB_TEXT"))
Return sqlb
End Function
End Class
End Namespace
|
icoxfog417/Gears
|
GearsTest/DataSource/JOB.vb
|
Visual Basic
|
apache-2.0
| 606
|
' Copyright 2015, Google Inc. All Rights Reserved.
'
' Licensed under the Apache License, Version 2.0 (the "License")
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http:'www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
' Author: api.anash@gmail.com (Anash P. Oommen)
Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201506
Imports Google.Api.Ads.Common.Lib
Imports System
Imports System.Collections.Generic
Imports System.IO
Namespace Google.Api.Ads.AdWords.Examples.VB.v201506
''' <summary>
''' This code example adds a feed that syncs feed items from a Google
''' My Business (GMB) account and associates the feed with a customer.
'''
''' Tags: CustomerFeedService.mutate, FeedItemService.mutate
''' Tags: FeedMappingService.mutate, FeedService.mutate
''' </summary>
Public Class AddGoogleMyBusinessLocationExtensions
Inherits ExampleBase
''' <summary>
''' The placeholder type for location extensions. See the Placeholder
''' reference page for a list of all the placeholder types and fields.
'''
''' https://developers.google.com/adwords/api/docs/appendix/placeholders
''' </summary>
Private Const PLACEHOLDER_LOCATION As Integer = 7
''' <summary>
''' Main method, to run this code example as a standalone application.
''' </summary>
''' <param name="args">The command line arguments.</param>
Public Shared Sub Main(ByVal args As String())
Dim codeExample As New AddGoogleMyBusinessLocationExtensions
Console.WriteLine(codeExample.Description)
Dim user As New AdWordsUser
Try
' The email address of either an owner or a manager of the GMB account.
Dim gmbEmailAddress As String = "INSERT_GMB_EMAIL_ADDRESS_HERE"
' Refresh the access token so that there's a valid access token.
user.OAuthProvider.RefreshAccessToken()
' If the gmbEmailAddress above is the same user you used to generate
' your AdWords API refresh token, leave the assignment below unchanged.
' Otherwise, to obtain an access token for your GMB account, run the
' OAuth Token generator utility while logged in as the same user as
' gmbEmailAddress. Copy and paste the AccessToken value into the
' assignment below.
Dim gmbAccessToken As String = user.OAuthProvider.AccessToken
' If the gmbEmailAddress above is for a GMB manager instead of the GMB
' account owner, then set businessAccountIdentifier to the +Page ID of
' a location for which the manager has access. See the location
' extensions guide at
' https://developers.google.com/adwords/api/docs/guides/feed-services-locations
' for details.
Dim businessAccountIdentifier As String = Nothing
codeExample.Run(user, gmbEmailAddress, gmbAccessToken, _
businessAccountIdentifier)
Catch ex As Exception
Console.WriteLine("An exception occurred while running this code example. {0}", _
ExampleUtilities.FormatException(ex))
End Try
End Sub
''' <summary>
''' Returns a description about the code example.
''' </summary>
Public Overrides ReadOnly Property Description() As String
Get
Return "This code example adds a feed that syncs feed items from a Google my Business " & _
"(GMB) account and associates the feed with a customer."
End Get
End Property
''' <summary>
''' Runs the code example.
''' </summary>
''' <param name="user">The AdWords user.</param>
''' <param name="gmbEmailAddress">The email address for Google My Business
''' account.</param>
''' <param name="gmbAccessToken">The OAuth2 access token for Google
''' My Business account.</param>
''' <param name="businessAccountIdentifier">The account identifier for
''' Google My Business account.</param>
Public Sub Run(ByVal user As AdWordsUser, ByVal gmbEmailAddress As String, _
ByVal gmbAccessToken As String, ByVal businessAccountIdentifier As String)
' Get the FeedService.
Dim feedService As FeedService = CType(user.GetService( _
AdWordsService.v201506.FeedService), FeedService)
' Get the CustomerFeedService.
Dim customerFeedService As CustomerFeedService = CType(user.GetService( _
AdWordsService.v201506.CustomerFeedService), CustomerFeedService)
' Create a feed that will sync to the Google My Business account
' specified by gmbEmailAddress. Do not add FeedAttributes to this object,
' as AdWords will add them automatically because this will be a
' system generated feed.
Dim gmbFeed As New Feed()
gmbFeed.name = String.Format("Google My Business feed #{0}", _
ExampleUtilities.GetRandomString())
Dim feedData As New PlacesLocationFeedData()
feedData.emailAddress = gmbEmailAddress
feedData.businessAccountIdentifier = businessAccountIdentifier
Dim oAuthInfo As New OAuthInfo()
oAuthInfo.httpMethod = "GET"
' Permissions for the AdWords API scope will also cover GMB.
oAuthInfo.httpRequestUrl = user.Config.GetDefaultOAuth2Scope()
oAuthInfo.httpAuthorizationHeader = String.Format("Bearer {0}", gmbAccessToken)
feedData.oAuthInfo = oAuthInfo
gmbFeed.systemFeedGenerationData = feedData
' Since this feed's feed items will be managed by AdWords,
' you must set its origin to ADWORDS.
gmbFeed.origin = FeedOrigin.ADWORDS
' Create an operation to add the feed.
Dim feedOperation As New FeedOperation()
feedOperation.operand = gmbFeed
feedOperation.operator = [Operator].ADD
Try
' Add the feed. Since it is a system generated feed, AdWords will
' automatically:
' 1. Set up the FeedAttributes on the feed.
' 2. Set up a FeedMapping that associates the FeedAttributes of the
' Feed with the placeholder fields of the LOCATION placeholder type.
Dim addFeedResult As FeedReturnValue = feedService.mutate( _
New FeedOperation() {feedOperation})
Dim addedFeed As Feed = addFeedResult.value(0)
Console.WriteLine("Added GMB feed with ID {0}", addedFeed.id)
' Add a CustomerFeed that associates the feed with this customer for
' the LOCATION placeholder type.
Dim customerFeed As New CustomerFeed()
customerFeed.feedId = addedFeed.id
customerFeed.placeholderTypes = New Integer() {PLACEHOLDER_LOCATION}
' Create a matching function that will always evaluate to true.
Dim customerMatchingFunction As New [Function]()
Dim constOperand As New ConstantOperand()
constOperand.type = ConstantOperandConstantType.BOOLEAN
constOperand.booleanValue = True
customerMatchingFunction.lhsOperand = New FunctionArgumentOperand() {constOperand}
customerMatchingFunction.operator = FunctionOperator.IDENTITY
customerFeed.matchingFunction = customerMatchingFunction
' Create an operation to add the customer feed.
Dim customerFeedOperation As New CustomerFeedOperation()
customerFeedOperation.operand = customerFeed
customerFeedOperation.operator = [Operator].ADD
' After the completion of the Feed ADD operation above the added feed
' will not be available for usage in a CustomerFeed until the sync
' between the AdWords and GMB accounts completes. The loop below
' will retry adding the CustomerFeed up to ten times with an
' exponential back-off policy.
Dim addedCustomerFeed As CustomerFeed = Nothing
Dim config As New AdWordsAppConfig()
config.RetryCount = 10
Dim errorHandler As New ErrorHandler(config)
Do
Try
Dim customerFeedResult As CustomerFeedReturnValue = _
customerFeedService.mutate(New CustomerFeedOperation() {customerFeedOperation})
addedCustomerFeed = customerFeedResult.value(0)
Console.WriteLine("Added CustomerFeed for feed ID {0} and placeholder type {1}", _
addedCustomerFeed.feedId, addedCustomerFeed.placeholderTypes(0))
Exit Try
Catch e As AdWordsApiException
Dim apiException As ApiException = CType(e.ApiException, ApiException)
For Each apiError As ApiError In apiException.errors
If TypeOf apiError Is CustomerFeedError Then
If (DirectCast(apiError, CustomerFeedError).reason = _
CustomerFeedErrorReason.MISSING_FEEDMAPPING_FOR_PLACEHOLDER_TYPE) Then
errorHandler.DoExponentialBackoff()
errorHandler.IncrementRetriedAttempts()
Else
Throw
End If
End If
Next
End Try
Loop While (errorHandler.HaveMoreRetryAttemptsLeft())
' OPTIONAL: Create a CampaignFeed to specify which FeedItems to use at
' the Campaign level. This will be similar to the CampaignFeed in the
' AddSiteLinks example, except you can also filter based on the
' business name and category of each FeedItem by using a
' FeedAttributeOperand in your matching function.
' OPTIONAL: Create an AdGroupFeed for even more fine grained control
' over which feed items are used at the AdGroup level.
Catch ex As Exception
Throw New System.ApplicationException("Failed to create customer feed.", ex)
End Try
End Sub
End Class
End Namespace
|
stevemanderson/googleads-dotnet-lib
|
examples/AdWords/Vb/v201506/Extensions/AddGoogleMyBusinessLocationExtensions.vb
|
Visual Basic
|
apache-2.0
| 10,043
|
Public Class AddLine
Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
End Sub
'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents txtSource As System.Windows.Forms.TextBox
Friend WithEvents lblSource As System.Windows.Forms.Label
Friend WithEvents txtTypeOfTransition As System.Windows.Forms.TextBox
Friend WithEvents lblTypeOfTransition As System.Windows.Forms.Label
Friend WithEvents txtHigherEnergyLevel As System.Windows.Forms.TextBox
Friend WithEvents txtLowerEnergyLevel As System.Windows.Forms.TextBox
Friend WithEvents lblHigherEnergyLevel As System.Windows.Forms.Label
Friend WithEvents lblLowerEnergyLevel As System.Windows.Forms.Label
Friend WithEvents txtWavelength As System.Windows.Forms.TextBox
Friend WithEvents txtSpeciesCode As System.Windows.Forms.TextBox
Friend WithEvents lblWavelength As System.Windows.Forms.Label
Friend WithEvents lblSpeciesCode As System.Windows.Forms.Label
Friend WithEvents txtDampingFactor As System.Windows.Forms.TextBox
Friend WithEvents txtLogGF As System.Windows.Forms.TextBox
Friend WithEvents lblDampingFactor As System.Windows.Forms.Label
Friend WithEvents lblLogGF As System.Windows.Forms.Label
Friend WithEvents lblInstructions As System.Windows.Forms.Label
Friend WithEvents cmdCancel As System.Windows.Forms.Button
Friend WithEvents cmdOK As System.Windows.Forms.Button
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.txtSource = New System.Windows.Forms.TextBox()
Me.lblSource = New System.Windows.Forms.Label()
Me.txtTypeOfTransition = New System.Windows.Forms.TextBox()
Me.lblTypeOfTransition = New System.Windows.Forms.Label()
Me.txtHigherEnergyLevel = New System.Windows.Forms.TextBox()
Me.txtLowerEnergyLevel = New System.Windows.Forms.TextBox()
Me.lblHigherEnergyLevel = New System.Windows.Forms.Label()
Me.lblLowerEnergyLevel = New System.Windows.Forms.Label()
Me.txtWavelength = New System.Windows.Forms.TextBox()
Me.txtSpeciesCode = New System.Windows.Forms.TextBox()
Me.lblWavelength = New System.Windows.Forms.Label()
Me.lblSpeciesCode = New System.Windows.Forms.Label()
Me.txtDampingFactor = New System.Windows.Forms.TextBox()
Me.txtLogGF = New System.Windows.Forms.TextBox()
Me.lblDampingFactor = New System.Windows.Forms.Label()
Me.lblLogGF = New System.Windows.Forms.Label()
Me.lblInstructions = New System.Windows.Forms.Label()
Me.cmdCancel = New System.Windows.Forms.Button()
Me.cmdOK = New System.Windows.Forms.Button()
Me.SuspendLayout()
'
'txtSource
'
Me.txtSource.Location = New System.Drawing.Point(120, 224)
Me.txtSource.Name = "txtSource"
Me.txtSource.Size = New System.Drawing.Size(96, 20)
Me.txtSource.TabIndex = 7
Me.txtSource.Text = ""
'
'lblSource
'
Me.lblSource.Location = New System.Drawing.Point(16, 224)
Me.lblSource.Name = "lblSource"
Me.lblSource.Size = New System.Drawing.Size(104, 20)
Me.lblSource.TabIndex = 18
Me.lblSource.Text = "Source"
Me.lblSource.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'txtTypeOfTransition
'
Me.txtTypeOfTransition.Location = New System.Drawing.Point(120, 200)
Me.txtTypeOfTransition.Name = "txtTypeOfTransition"
Me.txtTypeOfTransition.Size = New System.Drawing.Size(96, 20)
Me.txtTypeOfTransition.TabIndex = 6
Me.txtTypeOfTransition.Text = ""
'
'lblTypeOfTransition
'
Me.lblTypeOfTransition.Location = New System.Drawing.Point(16, 200)
Me.lblTypeOfTransition.Name = "lblTypeOfTransition"
Me.lblTypeOfTransition.Size = New System.Drawing.Size(104, 20)
Me.lblTypeOfTransition.TabIndex = 17
Me.lblTypeOfTransition.Text = "Type of transition"
Me.lblTypeOfTransition.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'txtHigherEnergyLevel
'
Me.txtHigherEnergyLevel.Location = New System.Drawing.Point(120, 128)
Me.txtHigherEnergyLevel.Name = "txtHigherEnergyLevel"
Me.txtHigherEnergyLevel.Size = New System.Drawing.Size(96, 20)
Me.txtHigherEnergyLevel.TabIndex = 3
Me.txtHigherEnergyLevel.Text = ""
'
'txtLowerEnergyLevel
'
Me.txtLowerEnergyLevel.Location = New System.Drawing.Point(120, 104)
Me.txtLowerEnergyLevel.Name = "txtLowerEnergyLevel"
Me.txtLowerEnergyLevel.Size = New System.Drawing.Size(96, 20)
Me.txtLowerEnergyLevel.TabIndex = 2
Me.txtLowerEnergyLevel.Text = ""
'
'lblHigherEnergyLevel
'
Me.lblHigherEnergyLevel.Location = New System.Drawing.Point(16, 128)
Me.lblHigherEnergyLevel.Name = "lblHigherEnergyLevel"
Me.lblHigherEnergyLevel.Size = New System.Drawing.Size(104, 20)
Me.lblHigherEnergyLevel.TabIndex = 14
Me.lblHigherEnergyLevel.Text = "Higher energy level"
Me.lblHigherEnergyLevel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'lblLowerEnergyLevel
'
Me.lblLowerEnergyLevel.Location = New System.Drawing.Point(16, 104)
Me.lblLowerEnergyLevel.Name = "lblLowerEnergyLevel"
Me.lblLowerEnergyLevel.Size = New System.Drawing.Size(104, 20)
Me.lblLowerEnergyLevel.TabIndex = 13
Me.lblLowerEnergyLevel.Text = "Lower energy level"
Me.lblLowerEnergyLevel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'txtWavelength
'
Me.txtWavelength.Location = New System.Drawing.Point(120, 56)
Me.txtWavelength.Name = "txtWavelength"
Me.txtWavelength.Size = New System.Drawing.Size(96, 20)
Me.txtWavelength.TabIndex = 0
Me.txtWavelength.Text = ""
'
'txtSpeciesCode
'
Me.txtSpeciesCode.Location = New System.Drawing.Point(120, 80)
Me.txtSpeciesCode.Name = "txtSpeciesCode"
Me.txtSpeciesCode.Size = New System.Drawing.Size(96, 20)
Me.txtSpeciesCode.TabIndex = 1
Me.txtSpeciesCode.Text = ""
'
'lblWavelength
'
Me.lblWavelength.Location = New System.Drawing.Point(16, 56)
Me.lblWavelength.Name = "lblWavelength"
Me.lblWavelength.Size = New System.Drawing.Size(104, 20)
Me.lblWavelength.TabIndex = 11
Me.lblWavelength.Text = "Wavelength"
Me.lblWavelength.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'lblSpeciesCode
'
Me.lblSpeciesCode.Location = New System.Drawing.Point(16, 80)
Me.lblSpeciesCode.Name = "lblSpeciesCode"
Me.lblSpeciesCode.Size = New System.Drawing.Size(104, 20)
Me.lblSpeciesCode.TabIndex = 12
Me.lblSpeciesCode.Text = "Species code"
Me.lblSpeciesCode.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'txtDampingFactor
'
Me.txtDampingFactor.Location = New System.Drawing.Point(120, 176)
Me.txtDampingFactor.Name = "txtDampingFactor"
Me.txtDampingFactor.Size = New System.Drawing.Size(96, 20)
Me.txtDampingFactor.TabIndex = 5
Me.txtDampingFactor.Text = ""
'
'txtLogGF
'
Me.txtLogGF.Location = New System.Drawing.Point(120, 152)
Me.txtLogGF.Name = "txtLogGF"
Me.txtLogGF.Size = New System.Drawing.Size(96, 20)
Me.txtLogGF.TabIndex = 4
Me.txtLogGF.Text = ""
'
'lblDampingFactor
'
Me.lblDampingFactor.Location = New System.Drawing.Point(16, 176)
Me.lblDampingFactor.Name = "lblDampingFactor"
Me.lblDampingFactor.Size = New System.Drawing.Size(104, 20)
Me.lblDampingFactor.TabIndex = 16
Me.lblDampingFactor.Text = "Damping Factor"
Me.lblDampingFactor.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'lblLogGF
'
Me.lblLogGF.Location = New System.Drawing.Point(16, 152)
Me.lblLogGF.Name = "lblLogGF"
Me.lblLogGF.Size = New System.Drawing.Size(104, 20)
Me.lblLogGF.TabIndex = 15
Me.lblLogGF.Text = "Log (GF)"
Me.lblLogGF.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'lblInstructions
'
Me.lblInstructions.Location = New System.Drawing.Point(16, 16)
Me.lblInstructions.Name = "lblInstructions"
Me.lblInstructions.Size = New System.Drawing.Size(200, 32)
Me.lblInstructions.TabIndex = 10
Me.lblInstructions.Text = "Type in the atomic parameters for new spectral line:"
Me.lblInstructions.TextAlign = System.Drawing.ContentAlignment.TopCenter
'
'cmdCancel
'
Me.cmdCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.cmdCancel.Location = New System.Drawing.Point(120, 264)
Me.cmdCancel.Name = "cmdCancel"
Me.cmdCancel.Size = New System.Drawing.Size(64, 24)
Me.cmdCancel.TabIndex = 9
Me.cmdCancel.Text = "Cancel"
'
'cmdOK
'
Me.cmdOK.DialogResult = System.Windows.Forms.DialogResult.OK
Me.cmdOK.Location = New System.Drawing.Point(40, 264)
Me.cmdOK.Name = "cmdOK"
Me.cmdOK.Size = New System.Drawing.Size(64, 24)
Me.cmdOK.TabIndex = 8
Me.cmdOK.Text = "OK"
'
'AddLine
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(232, 302)
Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.cmdOK, Me.cmdCancel, Me.lblInstructions, Me.txtSource, Me.lblSource, Me.txtTypeOfTransition, Me.lblTypeOfTransition, Me.txtHigherEnergyLevel, Me.txtLowerEnergyLevel, Me.lblHigherEnergyLevel, Me.lblLowerEnergyLevel, Me.txtWavelength, Me.txtSpeciesCode, Me.lblWavelength, Me.lblSpeciesCode, Me.txtDampingFactor, Me.txtLogGF, Me.lblDampingFactor, Me.lblLogGF})
Me.Name = "AddLine"
Me.Text = "New Spectral Line"
Me.ResumeLayout(False)
End Sub
#End Region
Public Wavelength As Single
Public SpeciesCode As Single
Public LowerEnergyLevel As Integer
Public HigherEnergyLevel As Integer
Public LogGF As Single
Public DampingFactor As Single
Public TypeOfTransition As Integer
Public Source As String
Private Sub txtWavelength_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtWavelength.KeyDown
If e.KeyCode = Keys.Enter Then
txtSpeciesCode.Focus()
End If
End Sub
Private Sub txtSpeciesCode_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtSpeciesCode.KeyDown
If e.KeyCode = Keys.Enter Then
txtLowerEnergyLevel.Focus()
End If
End Sub
Private Sub txtLowerEnergyLevel_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtLowerEnergyLevel.KeyDown
If e.KeyCode = Keys.Enter Then
txtHigherEnergyLevel.Focus()
End If
End Sub
Private Sub txtHigherEnergyLevel_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtHigherEnergyLevel.KeyDown
If e.KeyCode = Keys.Enter Then
txtLogGF.Focus()
End If
End Sub
Private Sub txtLogGF_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtLogGF.KeyDown
If e.KeyCode = Keys.Enter Then
txtDampingFactor.Focus()
End If
End Sub
Private Sub txtDampingFactor_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtDampingFactor.KeyDown
If e.KeyCode = Keys.Enter Then
txtTypeOfTransition.Focus()
End If
End Sub
Private Sub txtTypeOfTransition_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtTypeOfTransition.KeyDown
If e.KeyCode = Keys.Enter Then
txtSource.Focus()
End If
End Sub
Private Sub txtSource_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtSource.KeyDown
If e.KeyCode = Keys.Enter Then
txtWavelength.Focus()
End If
End Sub
Private Sub cmdCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCancel.Click
Me.Close()
End Sub
Private Sub cmdOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdOK.Click
Try
Wavelength = CSng(txtWavelength.Text)
SpeciesCode = CSng(txtSpeciesCode.Text)
LowerEnergyLevel = CInt(txtLowerEnergyLevel.Text)
HigherEnergyLevel = CInt(txtHigherEnergyLevel.Text)
LogGF = CSng(txtLogGF.Text)
DampingFactor = CSng(txtDampingFactor.Text)
TypeOfTransition = CInt(txtTypeOfTransition.Text)
Catch ex As System.InvalidCastException
MsgBox("Please, check that all fields have proper values.", MsgBoxStyle.Exclamation, Me.Text)
Exit Sub
End Try
Source = txtSource.Text
Me.Close()
End Sub
End Class
|
oliveralatkovic/isaac
|
isaac/AddLine.vb
|
Visual Basic
|
bsd-3-clause
| 14,229
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class frmpasscookie
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmpasscookie))
Me.Label3 = New System.Windows.Forms.Label()
Me.Label2 = New System.Windows.Forms.Label()
Me.Label1 = New System.Windows.Forms.Label()
Me.TextBox1 = New System.Windows.Forms.TextBox()
Me.SuspendLayout()
'
'Label3
'
Me.Label3.AutoSize = True
Me.Label3.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label3.ForeColor = System.Drawing.Color.DimGray
Me.Label3.Location = New System.Drawing.Point(125, 26)
Me.Label3.Name = "Label3"
Me.Label3.Size = New System.Drawing.Size(199, 20)
Me.Label3.TabIndex = 7
Me.Label3.Text = "Just type in your password."
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.ForeColor = System.Drawing.Color.SlateGray
Me.Label2.Location = New System.Drawing.Point(24, 131)
Me.Label2.Name = "Label2"
Me.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label2.Size = New System.Drawing.Size(393, 26)
Me.Label2.TabIndex = 6
Me.Label2.Text = "Please use the password that you have setup in LockUp feature. LockUp feature " & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "h" & _
"elps you secure your major sections in browser application."
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 14.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label1.ForeColor = System.Drawing.Color.DimGray
Me.Label1.Location = New System.Drawing.Point(58, 70)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(97, 24)
Me.Label1.TabIndex = 5
Me.Label1.Text = "Password:"
'
'TextBox1
'
Me.TextBox1.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.TextBox1.Location = New System.Drawing.Point(161, 70)
Me.TextBox1.Name = "TextBox1"
Me.TextBox1.Size = New System.Drawing.Size(226, 26)
Me.TextBox1.TabIndex = 4
Me.TextBox1.UseSystemPasswordChar = True
'
'frmpasscookie
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.BackColor = System.Drawing.Color.White
Me.ClientSize = New System.Drawing.Size(443, 196)
Me.Controls.Add(Me.Label3)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.TextBox1)
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.MaximizeBox = False
Me.MinimizeBox = False
Me.Name = "frmpasscookie"
Me.ShowInTaskbar = False
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "Security Check"
Me.TopMost = True
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents Label3 As System.Windows.Forms.Label
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
End Class
|
sheikhimran01/xtravo
|
Xtravo/Forms/frmpasscookie.Designer.vb
|
Visual Basic
|
mit
| 4,547
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.VisualStudio.Text.Projection
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
Public Class CSharpCompletionCommandHandlerTests_Projections
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSimpleWithJustSubjectBuffer() As System.Threading.Tasks.Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
using System;
public class _Page_Default_cshtml : System.Web.WebPages.WebPage {
private static object @__o;
#line hidden
public override void Execute() {
#line 1 "Default.cshtml"
__o = AppDomain$$
#line default
#line hidden
}
}]]></Document>)
state.SendTypeChars(".Curr")
Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True)
state.AssertSelectedCompletionItem(displayText:="CurrentDomain")
state.SendTab()
Assert.Contains("__o = AppDomain.CurrentDomain", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestAfterDot() As System.Threading.Tasks.Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
{|S2:
class C
{
void Foo()
{
System$$
}
}
|}]]></Document>)
Dim subjectDocument = state.Workspace.Documents.First()
Dim firstProjection = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1: <html>@|}
{|S2:|}
</Document>.NormalizedValue, {subjectDocument}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1:|}
{|S2:</html>|}
</Document>.NormalizedValue, {firstProjection}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim view = topProjectionBuffer.GetTextView()
Dim buffer = subjectDocument.GetTextBuffer()
state.SendTypeCharsToSpecificViewAndBuffer(".", view, buffer)
Await state.AssertCompletionSession().ConfigureAwait(True)
state.SendTypeCharsToSpecificViewAndBuffer("Cons", view, buffer)
Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True)
state.AssertSelectedCompletionItem(displayText:="Console")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInObjectCreationExpression() As System.Threading.Tasks.Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
{|S2:
class C
{
void Foo()
{
string s = new$$
}
}
|}]]></Document>)
Dim subjectDocument = state.Workspace.Documents.First()
Dim firstProjection = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1: <html>@|}
{|S2:|}
</Document>.NormalizedValue, {subjectDocument}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1:|}
{|S2:</html>|}
</Document>.NormalizedValue, {firstProjection}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim view = topProjectionBuffer.GetTextView()
Dim buffer = subjectDocument.GetTextBuffer()
state.SendTypeCharsToSpecificViewAndBuffer(" ", view, buffer)
Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True)
state.AssertSelectedCompletionItem(displayText:="string", isHardSelected:=True)
End Using
End Function
<WorkItem(771761)>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestRegionCompletionCommitFormatting() As System.Threading.Tasks.Task
Using state = TestState.CreateCSharpTestState(
<Document><![CDATA[
{|S2:
class C
{
void Foo()
{
$$
}
}
|}]]></Document>)
Dim subjectDocument = state.Workspace.Documents.First()
Dim firstProjection = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1: <html>@|}
{|S2:|}
</Document>.NormalizedValue, {subjectDocument}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1:|}
{|S2:</html>|}
</Document>.NormalizedValue, {firstProjection}, LanguageNames.CSharp, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim view = topProjectionBuffer.GetTextView()
Dim buffer = subjectDocument.GetTextBuffer()
state.SendTypeCharsToSpecificViewAndBuffer("#reg", view, buffer)
Await state.WaitForAsynchronousOperationsAsync().ConfigureAwait(True)
state.AssertSelectedCompletionItem(displayText:="region", shouldFormatOnCommit:=True)
End Using
End Function
End Class
End Namespace
|
danielcweber/roslyn
|
src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_Projections.vb
|
Visual Basic
|
apache-2.0
| 5,824
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:2.0.50727.7905
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings),MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("")> _
Public Property User() As String
Get
Return CType(Me("User"),String)
End Get
Set
Me("User") = value
End Set
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.The_Leonic_Project.My.MySettings
Get
Return Global.The_Leonic_Project.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
TailsTeam/TheLeonicPrototype
|
TheLeonicProject/The Leonic Project/My Project/Settings.Designer.vb
|
Visual Basic
|
apache-2.0
| 3,362
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Partial Public Class RegisterExternalLogin
'''<summary>
'''email control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents email As Global.System.Web.UI.WebControls.TextBox
End Class
|
neozhu/WebFormsScaffolding
|
Samples.VB/Account/RegisterExternalLogin.aspx.designer.vb
|
Visual Basic
|
apache-2.0
| 722
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB
Public Class PDBCollectionInitializerTests
Inherits BasicTestBase
<Fact>
Public Sub CollectionInitializerAsCollTypeEquals()
Dim source =
<compilation>
<file>
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub Main()
Dim aList1 As List(Of String) = New List(Of String)() From {"Hello", " ", "World"}
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb("C1.Main",
<symbols>
<files>
<file id="1" name="" language="VB" />
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="Main">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" startLine="9" startColumn="5" endLine="9" endColumn="29" document="1"/>
<entry offset="0x1" startLine="10" startColumn="13" endLine="10" endColumn="91" document="1"/>
<entry offset="0x2b" startLine="11" startColumn="5" endLine="11" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x2c">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<local name="aList1" il_index="0" il_start="0x0" il_end="0x2c" attributes="0"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<Fact>
Public Sub CollectionInitializerAsNewCollType()
Dim source =
<compilation>
<file>
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub Main()
Dim aList2 As New List(Of String)() From {"Hello", " ", "World"}
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb("C1.Main",
<symbols>
<files>
<file id="1" name="" language="VB" />
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="Main">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" startLine="9" startColumn="5" endLine="9" endColumn="29" document="1"/>
<entry offset="0x1" startLine="10" startColumn="13" endLine="10" endColumn="73" document="1"/>
<entry offset="0x2b" startLine="11" startColumn="5" endLine="11" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x2c">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<local name="aList2" il_index="0" il_start="0x0" il_end="0x2c" attributes="0"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<Fact>
Public Sub CollectionInitializerNested()
Dim source =
<compilation>
<file>
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub Main()
Dim aList1 As New List(Of List(Of String))() From {new List(Of String)() From {"Hello", "World"} }
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb("C1.Main",
<symbols>
<files>
<file id="1" name="" language="VB" />
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="Main">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" startLine="9" startColumn="5" endLine="9" endColumn="29" document="1"/>
<entry offset="0x1" startLine="10" startColumn="13" endLine="10" endColumn="107" document="1"/>
<entry offset="0x2b" startLine="11" startColumn="5" endLine="11" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x2c">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<local name="aList1" il_index="0" il_start="0x0" il_end="0x2c" attributes="0"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<Fact>
Public Sub CollectionInitializerAsNewCollTypeMultipleVariables()
Dim source =
<compilation>
<file>
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub Main()
Dim aList1, aList2 As New List(Of String)() From {"Hello", " ", "World"}
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb("C1.Main",
<symbols>
<files>
<file id="1" name="" language="VB" />
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="Main">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
<slot kind="0" offset="12"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" startLine="9" startColumn="5" endLine="9" endColumn="29" document="1"/>
<entry offset="0x1" startLine="10" startColumn="13" endLine="10" endColumn="19" document="1"/>
<entry offset="0x2b" startLine="10" startColumn="21" endLine="10" endColumn="27" document="1"/>
<entry offset="0x55" startLine="11" startColumn="5" endLine="11" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x56">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<local name="aList1" il_index="0" il_start="0x0" il_end="0x56" attributes="0"/>
<local name="aList2" il_index="1" il_start="0x0" il_end="0x56" attributes="0"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
End Class
End Namespace
|
OmarTawfik/roslyn
|
src/Compilers/VisualBasic/Test/Emit/PDB/PDBCollectionInitializerTests.vb
|
Visual Basic
|
apache-2.0
| 7,606
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax
Imports InternalSyntaxFactory = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.SyntaxFactory
'
'============ Methods for parsing portions of executable statements ==
'
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Partial Friend Class Parser
' File: Parser.cpp
' Lines: 13261 - 13261
' Expression* .Parser::ParseXmlExpression( [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseXmlExpression() As XmlNodeSyntax
Debug.Assert(CurrentToken.Kind = SyntaxKind.LessThanToken OrElse
CurrentToken.Kind = SyntaxKind.LessThanGreaterThanToken OrElse
CurrentToken.Kind = SyntaxKind.LessThanSlashToken OrElse
CurrentToken.Kind = SyntaxKind.BeginCDataToken OrElse
CurrentToken.Kind = SyntaxKind.LessThanExclamationMinusMinusToken OrElse
CurrentToken.Kind = SyntaxKind.LessThanQuestionToken, "ParseXmlMarkup called on the wrong token.")
' The < token must be reset because a VB scanned < might following trivia attached to it.
ResetCurrentToken(ScannerState.Content)
Dim Result As XmlNodeSyntax = Nothing
If CurrentToken.Kind = SyntaxKind.LessThanQuestionToken Then
Result = ParseXmlDocument()
Else
Result = ParseXmlElement(ScannerState.VB)
End If
Result = AdjustTriviaForMissingTokens(Result)
Result = TransitionFromXmlToVB(Result)
Return Result
End Function
' File: Parser.cpp
' Lines: 13370 - 13370
' Expression* .Parser::ParseXmlDocument( [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseXmlDocument() As XmlNodeSyntax
Debug.Assert(CurrentToken.Kind = SyntaxKind.LessThanQuestionToken, "ParseXmlDocument called on wrong token")
Dim whitespaceChecker As New XmlWhitespaceChecker()
Dim nextToken = PeekNextToken(ScannerState.Element)
If nextToken.Kind = SyntaxKind.XmlNameToken AndAlso DirectCast(nextToken, XmlNameTokenSyntax).PossibleKeywordKind = SyntaxKind.XmlKeyword Then
' // Read the document version and encoding
Dim prologue = ParseXmlDeclaration()
prologue = DirectCast(whitespaceChecker.Visit(prologue), XmlDeclarationSyntax)
' // Read PI's and comments
Dim node As VisualBasicSyntaxNode = prologue
Dim precedingMisc = ParseXmlMisc(True, whitespaceChecker, node)
prologue = DirectCast(node, XmlDeclarationSyntax)
Dim body As XmlNodeSyntax
' // Get root element
' // This is either a single xml expression hole or an xml element
Select Case CurrentToken.Kind
Case SyntaxKind.LessThanToken
body = ParseXmlElement(ScannerState.Misc)
Case SyntaxKind.LessThanPercentEqualsToken
body = ParseXmlEmbedded(ScannerState.Misc)
Case Else
' Expected a root element or an embedded expression
body = SyntaxFactory.XmlEmptyElement(DirectCast(HandleUnexpectedToken(SyntaxKind.LessThanToken), PunctuationSyntax),
SyntaxFactory.XmlName(Nothing, DirectCast(InternalSyntaxFactory.MissingToken(SyntaxKind.XmlNameToken), XmlNameTokenSyntax)),
Nothing,
InternalSyntaxFactory.MissingPunctuation(SyntaxKind.SlashGreaterThanToken))
End Select
' // More PI's and comments
node = body
Dim followingMisc = ParseXmlMisc(False, whitespaceChecker, node)
body = DirectCast(node, XmlNodeSyntax)
Return SyntaxFactory.XmlDocument(prologue, precedingMisc, body, followingMisc)
Else
' // Parse Xml Processing Instruction
Return ParseXmlProcessingInstruction(ScannerState.VB, whitespaceChecker)
End If
End Function
' File: Parser.cpp
' Lines: 13425 - 13425
' XmlDocumentExpression* .Parser::ParseXmlDecl( [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseXmlDeclaration() As XmlDeclarationSyntax
Debug.Assert(CurrentToken.Kind = SyntaxKind.LessThanQuestionToken AndAlso
PeekNextToken(ScannerState.Element).Kind = SyntaxKind.XmlNameToken AndAlso
DirectCast(PeekNextToken(ScannerState.Element), XmlNameTokenSyntax).PossibleKeywordKind = SyntaxKind.XmlKeyword, "ParseXmlDecl called on the wrong token.")
Dim beginPrologue = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.Element)
Dim nameToken As XmlNameTokenSyntax = Nothing
VerifyExpectedToken(SyntaxKind.XmlNameToken, nameToken, ScannerState.Element)
Dim encodingIndex = 0
Dim standaloneIndex = 0
Dim foundVersion = False
Dim foundEncoding = False
Dim foundStandalone = False
Dim nodes(3) As VisualBasicSyntaxNode
Dim i As Integer = 0
nodes(i) = _scanner.MakeKeyword(nameToken)
i += 1
Do
Dim nextOption As XmlDeclarationOptionSyntax
Select Case CurrentToken.Kind
Case SyntaxKind.XmlNameToken
Dim optionName = DirectCast(CurrentToken, XmlNameTokenSyntax)
Select Case optionName.ToString
Case "version"
nextOption = ParseXmlDeclarationOption()
If foundVersion Then
nextOption = ReportSyntaxError(nextOption, ERRID.ERR_DuplicateXmlAttribute, optionName.ToString)
nodes(i - 1) = nodes(i - 1).AddTrailingSyntax(nextOption)
Exit Select
End If
foundVersion = True
Debug.Assert(i = 1)
If foundEncoding OrElse foundStandalone Then
nextOption = ReportSyntaxError(nextOption, ERRID.ERR_VersionMustBeFirstInXmlDecl, "", "", optionName.ToString)
End If
If nextOption.Value.TextTokens.Node Is Nothing OrElse nextOption.Value.TextTokens.Node.ToFullString <> "1.0" Then
nextOption = ReportSyntaxError(nextOption, ERRID.ERR_InvalidAttributeValue1, "1.0")
End If
nodes(i) = nextOption
i += 1
Case "encoding"
nextOption = ParseXmlDeclarationOption()
If foundEncoding Then
nextOption = ReportSyntaxError(nextOption, ERRID.ERR_DuplicateXmlAttribute, optionName.ToString)
nodes(i - 1) = nodes(i - 1).AddTrailingSyntax(nextOption)
Exit Select
End If
foundEncoding = True
If foundStandalone Then
nextOption = ReportSyntaxError(nextOption, ERRID.ERR_AttributeOrder, "encoding", "standalone")
nodes(i - 1) = nodes(i - 1).AddTrailingSyntax(nextOption)
Exit Select
ElseIf Not foundVersion Then
nodes(i - 1) = nodes(i - 1).AddTrailingSyntax(nextOption)
Exit Select
End If
Debug.Assert(i = 2)
encodingIndex = i
nodes(i) = nextOption
i += 1
Case "standalone"
nextOption = ParseXmlDeclarationOption()
If foundStandalone Then
nextOption = ReportSyntaxError(nextOption, ERRID.ERR_DuplicateXmlAttribute, optionName.ToString)
nodes(i - 1) = nodes(i - 1).AddTrailingSyntax(nextOption)
Exit Select
End If
foundStandalone = True
If Not foundVersion Then
nodes(i - 1) = nodes(i - 1).AddTrailingSyntax(nextOption)
Exit Select
End If
Dim stringValue = If(nextOption.Value.TextTokens.Node IsNot Nothing, nextOption.Value.TextTokens.Node.ToFullString, "")
If stringValue <> "yes" AndAlso stringValue <> "no" Then
nextOption = ReportSyntaxError(nextOption, ERRID.ERR_InvalidAttributeValue2, "yes", "no")
End If
Debug.Assert(i = 2 OrElse i = 3)
standaloneIndex = i
nodes(i) = nextOption
i += 1
Case Else
nextOption = ParseXmlDeclarationOption()
nextOption = ReportSyntaxError(nextOption, ERRID.ERR_IllegalAttributeInXmlDecl, "", "", nextOption.Name.ToString)
nodes(i - 1) = nodes(i - 1).AddTrailingSyntax(nextOption)
End Select
Case SyntaxKind.LessThanPercentEqualsToken
nextOption = ParseXmlDeclarationOption()
nodes(i - 1) = nodes(i - 1).AddTrailingSyntax(nextOption)
Case Else
Exit Do
End Select
Loop
Dim unexpected As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of SyntaxToken) = Nothing
If CurrentToken.Kind <> SyntaxKind.QuestionGreaterThanToken Then
unexpected = ResyncAt(ScannerState.Element, {SyntaxKind.EndOfXmlToken,
SyntaxKind.QuestionGreaterThanToken,
SyntaxKind.LessThanToken,
SyntaxKind.LessThanPercentEqualsToken,
SyntaxKind.LessThanExclamationMinusMinusToken})
End If
Dim endPrologue As PunctuationSyntax = Nothing
VerifyExpectedToken(SyntaxKind.QuestionGreaterThanToken, endPrologue, ScannerState.Content)
If unexpected.Node IsNot Nothing Then
endPrologue = endPrologue.AddLeadingSyntax(unexpected, ERRID.ERR_ExpectedXmlName)
End If
Debug.Assert(foundVersion = (nodes(1) IsNot Nothing))
If nodes(1) Is Nothing Then
Dim version = SyntaxFactory.XmlDeclarationOption(DirectCast(InternalSyntaxFactory.MissingToken(SyntaxKind.XmlNameToken), XmlNameTokenSyntax),
InternalSyntaxFactory.MissingPunctuation(SyntaxKind.EqualsToken),
CreateMissingXmlString())
nodes(1) = ReportSyntaxError(version, ERRID.ERR_MissingVersionInXmlDecl)
End If
Return SyntaxFactory.XmlDeclaration(beginPrologue,
TryCast(nodes(0), KeywordSyntax),
TryCast(nodes(1), XmlDeclarationOptionSyntax),
If(encodingIndex = 0, Nothing, TryCast(nodes(encodingIndex), XmlDeclarationOptionSyntax)),
If(standaloneIndex = 0, Nothing, TryCast(nodes(standaloneIndex), XmlDeclarationOptionSyntax)),
endPrologue)
End Function
' File: Parser.cpp
' Lines: 13813 - 13813
' Expression* .Parser::ParseXmlAttribute( [ bool AllowNameAsExpression ] [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseXmlDeclarationOption() As XmlDeclarationOptionSyntax
Debug.Assert(IsToken(CurrentToken,
SyntaxKind.XmlNameToken,
SyntaxKind.LessThanPercentEqualsToken,
SyntaxKind.EqualsToken,
SyntaxKind.SingleQuoteToken,
SyntaxKind.DoubleQuoteToken),
"ParseXmlPrologueOption called on wrong token.")
Dim result As XmlDeclarationOptionSyntax = Nothing
Dim name As XmlNameTokenSyntax = Nothing
Dim equals As PunctuationSyntax = Nothing
Dim value As XmlStringSyntax = Nothing
Dim hasPrecedingWhitespace = PrevToken.GetTrailingTrivia.ContainsWhitespaceTrivia() OrElse CurrentToken.GetLeadingTrivia.ContainsWhitespaceTrivia
VerifyExpectedToken(SyntaxKind.XmlNameToken, name, ScannerState.Element)
If Not hasPrecedingWhitespace Then
name = ReportSyntaxError(name, ERRID.ERR_ExpectedXmlWhiteSpace)
End If
If CurrentToken.Kind = SyntaxKind.LessThanPercentEqualsToken Then
' // <%= expr %>
Dim exp = ParseXmlEmbedded(ScannerState.Element)
name = name.AddTrailingSyntax(exp, ERRID.ERR_EmbeddedExpression)
End If
Dim skipped As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of SyntaxToken) = Nothing
If Not VerifyExpectedToken(SyntaxKind.EqualsToken, equals, ScannerState.Element) Then
skipped = ResyncAt(ScannerState.Element,
{SyntaxKind.SingleQuoteToken,
SyntaxKind.DoubleQuoteToken,
SyntaxKind.LessThanPercentEqualsToken,
SyntaxKind.QuestionGreaterThanToken,
SyntaxKind.EndOfXmlToken})
equals = equals.AddTrailingSyntax(skipped)
End If
Select Case CurrentToken.Kind
Case SyntaxKind.SingleQuoteToken,
SyntaxKind.DoubleQuoteToken
value = ParseXmlString(ScannerState.Element)
Case SyntaxKind.LessThanPercentEqualsToken
' // <%= expr %>
Dim exp = ParseXmlEmbedded(ScannerState.Element)
value = AddLeadingSyntax(CreateMissingXmlString(), exp, ERRID.ERR_EmbeddedExpression)
Case Else
value = CreateMissingXmlString()
End Select
result = SyntaxFactory.XmlDeclarationOption(name, equals, value)
Return result
End Function
' File: Parser.cpp
' Lines: 13452 - 13452
' ExpressionList** .Parser::ParseXmlMisc( [ _Inout_ ParseTree::ExpressionList** Prev ] [ bool IsProlog ] [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseXmlMisc(IsProlog As Boolean, whitespaceChecker As XmlWhitespaceChecker, ByRef outerNode As VisualBasicSyntaxNode) As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of XmlNodeSyntax)
Dim Content = Me._pool.Allocate(Of XmlNodeSyntax)()
While True
Dim result As XmlNodeSyntax = Nothing
Select Case (CurrentToken.Kind)
Case SyntaxKind.BadToken
Dim badToken = DirectCast(CurrentToken, BadTokenSyntax)
Dim skipped As GreenNode
If badToken.SubKind = SyntaxSubKind.BeginDocTypeToken Then
skipped = ParseXmlDocType(ScannerState.Misc)
Else
skipped = badToken
GetNextToken(ScannerState.Misc)
End If
Dim count = Content.Count
If count > 0 Then
Content(count - 1) = Content(count - 1).AddTrailingSyntax(skipped, ERRID.ERR_DTDNotSupported)
Else
outerNode = outerNode.AddTrailingSyntax(skipped, ERRID.ERR_DTDNotSupported)
End If
Case SyntaxKind.LessThanExclamationMinusMinusToken
result = ParseXmlComment(ScannerState.Misc)
Case SyntaxKind.LessThanQuestionToken
result = ParseXmlProcessingInstruction(ScannerState.Misc, whitespaceChecker)
Case Else
Exit While
End Select
If result IsNot Nothing Then
Content.Add(result)
End If
End While
Dim ContentList = Content.ToList
Me._pool.Free(Content)
Return ContentList
End Function
Private Function ParseXmlDocType(enclosingState As ScannerState) As GreenNode
Debug.Assert(CurrentToken.Kind = SyntaxKind.BadToken AndAlso
DirectCast(CurrentToken, BadTokenSyntax).SubKind = SyntaxSubKind.BeginDocTypeToken, "ParseDTD called on wrong token.")
Dim builder = SyntaxListBuilder(Of GreenNode).Create()
Dim beginDocType = DirectCast(CurrentToken, BadTokenSyntax)
builder.Add(beginDocType)
Dim name As XmlNameTokenSyntax = Nothing
GetNextToken(ScannerState.DocType)
VerifyExpectedToken(SyntaxKind.XmlNameToken, name, ScannerState.DocType)
builder.Add(name)
ParseExternalID(builder)
ParseInternalSubSet(builder)
Dim greaterThan As PunctuationSyntax = Nothing
VerifyExpectedToken(SyntaxKind.GreaterThanToken, greaterThan, enclosingState)
builder.Add(greaterThan)
Return builder.ToList().Node
End Function
Private Sub ParseExternalID(builder As SyntaxListBuilder(Of GreenNode))
If CurrentToken.Kind = SyntaxKind.XmlNameToken Then
Dim name = DirectCast(CurrentToken, XmlNameTokenSyntax)
Select Case name.ToString
Case "SYSTEM"
builder.Add(name)
GetNextToken(ScannerState.DocType)
Dim systemLiteral = ParseXmlString(ScannerState.DocType)
builder.Add(systemLiteral)
Case "PUBLIC"
builder.Add(name)
GetNextToken(ScannerState.DocType)
Dim publicLiteral = ParseXmlString(ScannerState.DocType)
builder.Add(publicLiteral)
Dim systemLiteral = ParseXmlString(ScannerState.DocType)
builder.Add(systemLiteral)
End Select
End If
End Sub
Private Sub ParseInternalSubSet(builder As SyntaxListBuilder(Of GreenNode))
Dim unexpected As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of SyntaxToken) = Nothing
If CurrentToken.Kind <> SyntaxKind.BadToken OrElse DirectCast(CurrentToken, BadTokenSyntax).SubKind <> SyntaxSubKind.OpenBracketToken Then
unexpected = ResyncAt(ScannerState.DocType, {SyntaxKind.BadToken,
SyntaxKind.GreaterThanToken,
SyntaxKind.LessThanToken,
SyntaxKind.LessThanExclamationMinusMinusToken,
SyntaxKind.BeginCDataToken,
SyntaxKind.LessThanPercentEqualsToken,
SyntaxKind.EndOfXmlToken})
If unexpected.Node IsNot Nothing Then
builder.Add(unexpected.Node)
End If
End If
If CurrentToken.Kind = SyntaxKind.BadToken AndAlso DirectCast(CurrentToken, BadTokenSyntax).SubKind = SyntaxSubKind.OpenBracketToken Then
'Assume we're on the '['
builder.Add(CurrentToken)
GetNextToken(ScannerState.DocType)
If CurrentToken.Kind = SyntaxKind.BadToken AndAlso DirectCast(CurrentToken, BadTokenSyntax).SubKind = SyntaxSubKind.LessThanExclamationToken Then
builder.Add(CurrentToken)
GetNextToken(ScannerState.DocType)
ParseXmlMarkupDecl(builder)
End If
If CurrentToken.Kind <> SyntaxKind.BadToken OrElse DirectCast(CurrentToken, BadTokenSyntax).SubKind <> SyntaxSubKind.CloseBracketToken Then
unexpected = ResyncAt(ScannerState.DocType, {SyntaxKind.BadToken,
SyntaxKind.GreaterThanToken,
SyntaxKind.LessThanToken,
SyntaxKind.LessThanExclamationMinusMinusToken,
SyntaxKind.BeginCDataToken,
SyntaxKind.LessThanPercentEqualsToken,
SyntaxKind.EndOfXmlToken})
If unexpected.Node IsNot Nothing Then
builder.Add(unexpected.Node)
End If
End If
'Assume we're on the ']'
builder.Add(CurrentToken)
GetNextToken(ScannerState.DocType)
End If
End Sub
Private Sub ParseXmlMarkupDecl(builder As SyntaxListBuilder(Of GreenNode))
Do
Select Case CurrentToken.Kind
Case SyntaxKind.BadToken
builder.Add(CurrentToken)
Dim badToken = DirectCast(CurrentToken, BadTokenSyntax)
GetNextToken(ScannerState.DocType)
If badToken.SubKind = SyntaxSubKind.LessThanExclamationToken Then
ParseXmlMarkupDecl(builder)
End If
Case SyntaxKind.LessThanQuestionToken
Dim xmlPI = ParseXmlProcessingInstruction(ScannerState.DocType, Nothing)
builder.Add(xmlPI)
Case SyntaxKind.LessThanExclamationMinusMinusToken
Dim xmlComment = ParseXmlComment(ScannerState.DocType)
builder.Add(xmlComment)
Case SyntaxKind.GreaterThanToken
builder.Add(CurrentToken)
GetNextToken(ScannerState.DocType)
Return
Case SyntaxKind.EndOfFileToken,
SyntaxKind.EndOfXmlToken
Return
Case Else
builder.Add(CurrentToken)
GetNextToken(ScannerState.DocType)
End Select
Loop
End Sub
' File: Parser.cpp
' Lines: 13624 - 13624
' XmlElementExpression* .Parser::ParseXmlElement( [ _In_opt_ ParseTree::XmlElementExpression* Parent ] [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseXmlElementStartTag(enclosingState As ScannerState) As XmlNodeSyntax
Debug.Assert(CurrentToken.Kind = SyntaxKind.LessThanToken, "ParseXmlElement call on wrong token.")
Dim lessThan As PunctuationSyntax = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.Element)
' /* AllowExpr */' /* IsBracketed */'
Dim Name = ParseXmlQualifiedName(False, True, ScannerState.Element, ScannerState.Element)
Dim nameIsFollowedByWhitespace = Name.HasTrailingTrivia
Dim Attributes = ParseXmlAttributes(Not nameIsFollowedByWhitespace, Name)
Dim greaterThan As PunctuationSyntax = Nothing
Dim endEmptyElementToken As PunctuationSyntax = Nothing
Select Case (CurrentToken.Kind)
Case SyntaxKind.GreaterThanToken
' Element with content
greaterThan = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.Content)
Return SyntaxFactory.XmlElementStartTag(lessThan, Name, Attributes, greaterThan)
Case SyntaxKind.SlashGreaterThanToken
' Empty element
endEmptyElementToken = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(enclosingState)
Return SyntaxFactory.XmlEmptyElement(lessThan, Name, Attributes, endEmptyElementToken)
Case SyntaxKind.SlashToken
' Looks like an empty element but / followed by '>' is an error when there is whitespace between the tokens.
If PeekNextToken(ScannerState.Element).Kind = SyntaxKind.GreaterThanToken Then
Dim divideToken As SyntaxToken = CurrentToken
GetNextToken(ScannerState.Element)
greaterThan = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(enclosingState)
Dim unexpectedSyntax = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of SyntaxToken)(SyntaxList.List(divideToken, greaterThan))
endEmptyElementToken = AddLeadingSyntax(New PunctuationSyntax(SyntaxKind.SlashGreaterThanToken, "", Nothing, Nothing),
unexpectedSyntax,
ERRID.ERR_IllegalXmlWhiteSpace)
Return SyntaxFactory.XmlEmptyElement(lessThan, Name, Attributes, endEmptyElementToken)
Else
' Try to resync to recovery from a bad parse
Return ResyncXmlElement(enclosingState, lessThan, Name, Attributes)
End If
Case Else
' Try to resync to recovery from a bad parse
Return ResyncXmlElement(enclosingState, lessThan, Name, Attributes)
End Select
End Function
' File: Parser.cpp
' Lines: 13624 - 13624
' XmlElementExpression* .Parser::ParseXmlElement( [ _In_opt_ ParseTree::XmlElementExpression* Parent ] [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseXmlElement(enclosingState As ScannerState) As XmlNodeSyntax
Debug.Assert(IsToken(CurrentToken,
SyntaxKind.LessThanToken,
SyntaxKind.LessThanGreaterThanToken,
SyntaxKind.LessThanSlashToken,
SyntaxKind.BeginCDataToken,
SyntaxKind.LessThanExclamationMinusMinusToken,
SyntaxKind.LessThanQuestionToken,
SyntaxKind.LessThanPercentEqualsToken,
SyntaxKind.XmlTextLiteralToken,
SyntaxKind.BadToken),
"ParseXmlElement call on wrong token.")
Dim xml As XmlNodeSyntax = Nothing
Dim contexts As New List(Of XmlContext)
Dim endElement As XmlElementEndTagSyntax
Dim nextState = enclosingState
Dim whitespaceChecker As New XmlWhitespaceChecker()
Do
Select Case CurrentToken.Kind
Case SyntaxKind.LessThanToken
Dim nextTokenIsSlash As Boolean = PeekNextToken(ScannerState.Element).Kind = SyntaxKind.SlashToken
If nextTokenIsSlash Then
' While </ is a single token, parse this as </ and report an error.
GoTo LessThanSlashTokenCase
End If
xml = ParseXmlElementStartTag(nextState)
xml = DirectCast(whitespaceChecker.Visit(xml), XmlNodeSyntax)
If xml.Kind = SyntaxKind.XmlElementStartTag Then
Dim startElement = DirectCast(xml, XmlElementStartTagSyntax)
contexts.Push(New XmlContext(_pool, startElement))
nextState = ScannerState.Content
Continue Do
End If
Case SyntaxKind.LessThanSlashToken
LessThanSlashTokenCase:
endElement = ParseXmlElementEndTag(nextState)
endElement = DirectCast(whitespaceChecker.Visit(endElement), XmlElementEndTagSyntax)
If contexts.Count > 0 Then
xml = CreateXmlElement(contexts, endElement)
Else
Dim missingLessThan = InternalSyntaxFactory.MissingPunctuation(SyntaxKind.LessThanToken)
Dim missingXmlNameToken = DirectCast(InternalSyntaxFactory.MissingToken(SyntaxKind.XmlNameToken), XmlNameTokenSyntax)
Dim missingName = SyntaxFactory.XmlName(Nothing, missingXmlNameToken)
Dim missingGreaterThan = InternalSyntaxFactory.MissingPunctuation(SyntaxKind.GreaterThanToken)
Dim startElement = SyntaxFactory.XmlElementStartTag(missingLessThan, missingName, Nothing, missingGreaterThan)
contexts.Push(New XmlContext(_pool, startElement))
xml = contexts.Peek.CreateElement(endElement)
xml = ReportSyntaxError(xml, ERRID.ERR_XmlEndElementNoMatchingStart)
contexts.Pop()
End If
Case SyntaxKind.LessThanExclamationMinusMinusToken
xml = ParseXmlComment(nextState)
Case SyntaxKind.LessThanQuestionToken
xml = ParseXmlProcessingInstruction(nextState, whitespaceChecker)
xml = DirectCast(whitespaceChecker.Visit(xml), XmlProcessingInstructionSyntax)
Case SyntaxKind.BeginCDataToken
xml = ParseXmlCData(nextState)
Case SyntaxKind.LessThanPercentEqualsToken
xml = ParseXmlEmbedded(nextState)
If contexts.Count = 0 Then
xml = ReportSyntaxError(xml, ERRID.ERR_EmbeddedExpression)
End If
Case SyntaxKind.XmlTextLiteralToken,
SyntaxKind.XmlEntityLiteralToken,
SyntaxKind.DocumentationCommentLineBreakToken
Dim newKind As SyntaxKind
Dim textTokens = _pool.Allocate(Of XmlTextTokenSyntax)()
Do
textTokens.Add(DirectCast(CurrentToken, XmlTextTokenSyntax))
GetNextToken(nextState)
newKind = CurrentToken.Kind
Loop While newKind = SyntaxKind.XmlTextLiteralToken OrElse
newKind = SyntaxKind.XmlEntityLiteralToken OrElse
newKind = SyntaxKind.DocumentationCommentLineBreakToken
Dim textResult = textTokens.ToList
_pool.Free(textTokens)
xml = SyntaxFactory.XmlText(textResult)
Case SyntaxKind.BadToken
Dim badToken = DirectCast(CurrentToken, BadTokenSyntax)
If badToken.SubKind = SyntaxSubKind.BeginDocTypeToken Then
Dim docTypeTrivia = ParseXmlDocType(ScannerState.Element)
xml = SyntaxFactory.XmlText(InternalSyntaxFactory.MissingToken(SyntaxKind.XmlTextLiteralToken))
xml = xml.AddLeadingSyntax(docTypeTrivia, ERRID.ERR_DTDNotSupported)
Else
' Let ParseXmlEndELement do the resync
Exit Do
End If
Case Else
' Let ParseXmlEndELement do the resync
Exit Do
End Select
If contexts.Count > 0 Then
contexts.Peek.Add(xml)
Else
Exit Do
End If
Loop
' Recover from improperly terminated element.
' Close all contexts and return
If contexts.Count > 0 Then
Do
endElement = ParseXmlElementEndTag(nextState)
xml = CreateXmlElement(contexts, endElement)
If contexts.Count > 0 Then
contexts.Peek().Add(xml)
Else
Exit Do
End If
Loop
End If
ResetCurrentToken(enclosingState)
Return xml
End Function
Private Function CreateXmlElement(contexts As List(Of XmlContext), endElement As XmlElementEndTagSyntax) As XmlNodeSyntax
Dim i = contexts.MatchEndElement(endElement.Name)
Dim element As XmlNodeSyntax
If i >= 0 Then
' Close any xml element that was not matched
Dim last = contexts.Count - 1
Do While last > i
Dim missingEndElement = SyntaxFactory.XmlElementEndTag(DirectCast(HandleUnexpectedToken(SyntaxKind.LessThanSlashToken), PunctuationSyntax),
ReportSyntaxError(InternalSyntaxFactory.XmlName(Nothing, SyntaxFactory.XmlNameToken("", SyntaxKind.XmlNameToken, Nothing, Nothing)), ERRID.ERR_ExpectedXmlName),
DirectCast(HandleUnexpectedToken(SyntaxKind.GreaterThanToken), PunctuationSyntax))
Dim xml = contexts.Peek.CreateElement(missingEndElement, ErrorFactory.ErrorInfo(ERRID.ERR_MissingXmlEndTag))
contexts.Pop()
If contexts.Count > 0 Then
contexts.Peek().Add(xml)
Else
Exit Do
End If
last -= 1
Loop
If endElement.IsMissing Then
element = contexts.Peek.CreateElement(endElement, ErrorFactory.ErrorInfo(ERRID.ERR_MissingXmlEndTag))
Else
element = contexts.Peek.CreateElement(endElement)
End If
Else
' Not match was found
' Just close the current xml element
'TODO - Consider whether the current element should be closed or create a missing start tag to match this dangling end tag.
Dim prefix = ""
Dim colon = ""
Dim localName = ""
Dim nameExpr = contexts.Peek().StartElement.Name
If nameExpr.Kind = SyntaxKind.XmlName Then
Dim name = DirectCast(nameExpr, XmlNameSyntax)
If name.Prefix IsNot Nothing Then
prefix = name.Prefix.Name.Text
colon = ":"
End If
localName = name.LocalName.Text
End If
endElement = ReportSyntaxError(endElement, ERRID.ERR_MismatchedXmlEndTag, prefix, colon, localName)
element = contexts.Peek.CreateElement(endElement, ErrorFactory.ErrorInfo(ERRID.ERR_MissingXmlEndTag))
End If
contexts.Pop()
Return element
End Function
Private Function ResyncXmlElement(state As ScannerState, lessThan As PunctuationSyntax, Name As XmlNodeSyntax, attributes As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of XmlNodeSyntax)) As XmlNodeSyntax
Dim unexpectedSyntax = ResyncAt(ScannerState.Element,
{SyntaxKind.SlashGreaterThanToken,
SyntaxKind.GreaterThanToken,
SyntaxKind.LessThanToken,
SyntaxKind.LessThanSlashToken,
SyntaxKind.LessThanPercentEqualsToken,
SyntaxKind.BeginCDataToken,
SyntaxKind.LessThanExclamationMinusMinusToken,
SyntaxKind.LessThanQuestionToken,
SyntaxKind.EndOfXmlToken})
Dim greaterThan As PunctuationSyntax
'TODO - Don't add an error if the unexpectedSyntax already has errors.
Select Case CurrentToken.Kind
Case SyntaxKind.SlashGreaterThanToken
Dim endEmptyElementToken = DirectCast(CurrentToken, PunctuationSyntax)
If unexpectedSyntax.Node IsNot Nothing Then
endEmptyElementToken = AddLeadingSyntax(endEmptyElementToken, unexpectedSyntax, ERRID.ERR_ExpectedGreater)
End If
GetNextToken(state)
Return SyntaxFactory.XmlEmptyElement(lessThan, Name, attributes, endEmptyElementToken)
Case SyntaxKind.GreaterThanToken
greaterThan = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.Content)
If unexpectedSyntax.Node IsNot Nothing Then
greaterThan = AddLeadingSyntax(greaterThan, unexpectedSyntax, ERRID.ERR_ExpectedGreater)
End If
Return SyntaxFactory.XmlElementStartTag(lessThan, Name, attributes, greaterThan)
Case Else
' Try to avoid spurious missing '>' error message. Only report error if no skipped text
' and attributes are error free.
greaterThan = InternalSyntaxFactory.MissingPunctuation(SyntaxKind.GreaterThanToken)
If unexpectedSyntax.Node Is Nothing Then
If Not (attributes.Node IsNot Nothing AndAlso attributes.Node.ContainsDiagnostics) Then
greaterThan = ReportSyntaxError(greaterThan, ERRID.ERR_ExpectedGreater)
End If
Else
greaterThan = AddLeadingSyntax(greaterThan, unexpectedSyntax, ERRID.ERR_Syntax)
End If
Return SyntaxFactory.XmlElementStartTag(lessThan, Name, attributes, greaterThan)
End Select
End Function
Private Function ResyncXmlContent() As XmlNodeSyntax
Dim result As XmlTextSyntax
Dim unexpectedSyntax = ResyncAt(ScannerState.Content,
{SyntaxKind.LessThanToken,
SyntaxKind.LessThanSlashToken,
SyntaxKind.LessThanPercentEqualsToken,
SyntaxKind.BeginCDataToken,
SyntaxKind.LessThanExclamationMinusMinusToken,
SyntaxKind.LessThanQuestionToken,
SyntaxKind.EndOfXmlToken,
SyntaxKind.XmlTextLiteralToken,
SyntaxKind.XmlEntityLiteralToken})
Dim currentKind = CurrentToken.Kind
If currentKind = SyntaxKind.XmlTextLiteralToken OrElse
currentKind = SyntaxKind.DocumentationCommentLineBreakToken OrElse
currentKind = SyntaxKind.XmlEntityLiteralToken Then
result = SyntaxFactory.XmlText(CurrentToken)
GetNextToken(ScannerState.Content)
Else
result = SyntaxFactory.XmlText(HandleUnexpectedToken(SyntaxKind.XmlTextLiteralToken))
End If
If result.ContainsDiagnostics Then
result = AddLeadingSyntax(result, unexpectedSyntax)
Else
result = AddLeadingSyntax(result, unexpectedSyntax, ERRID.ERR_Syntax)
End If
Return result
End Function
' File: Parser.cpp
' Lines: 13695 - 13695
' XmlElementExpression* .Parser::ParseXmlEndElement( [ _Inout_ ParseTree::XmlElementExpression* Result ] [ Token* StartToken ] [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseXmlElementEndTag(nextState As ScannerState) As XmlElementEndTagSyntax
Dim beginEndElement As PunctuationSyntax = Nothing
Dim name As XmlNameSyntax = Nothing
Dim greaterToken As PunctuationSyntax = Nothing
Dim unexpected As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of SyntaxToken) = Nothing
If CurrentToken.Kind <> SyntaxKind.LessThanSlashToken Then
unexpected = ResyncAt(ScannerState.Content,
{SyntaxKind.LessThanToken,
SyntaxKind.LessThanSlashToken,
SyntaxKind.EndOfXmlToken})
End If
If Not VerifyExpectedToken(SyntaxKind.LessThanSlashToken, beginEndElement, ScannerState.EndElement) Then
' Check for '<' followed by '/'. This is an error because whitespace is not allowed between the tokens.
If CurrentToken.Kind = SyntaxKind.LessThanToken Then
Dim lessThan = DirectCast(CurrentToken, PunctuationSyntax)
Dim slashToken As SyntaxToken = PeekNextToken(ScannerState.EndElement)
If slashToken.Kind = SyntaxKind.SlashToken Then
If lessThan.HasTrailingTrivia Or slashToken.HasLeadingTrivia Then
beginEndElement = AddLeadingSyntax(beginEndElement,
SyntaxList.List(lessThan, slashToken),
ERRID.ERR_IllegalXmlWhiteSpace)
Else
beginEndElement = DirectCast(InternalSyntaxFactory.Token(lessThan.GetLeadingTrivia,
SyntaxKind.LessThanSlashToken,
slashToken.GetTrailingTrivia,
lessThan.Text & slashToken.Text),
PunctuationSyntax)
End If
GetNextToken(ScannerState.EndElement)
GetNextToken(ScannerState.EndElement)
End If
End If
End If
If unexpected.Node IsNot Nothing Then
If unexpected.Node.ContainsDiagnostics Then
beginEndElement = beginEndElement.AddLeadingSyntax(unexpected)
Else
beginEndElement = AddLeadingSyntax(beginEndElement, unexpected, ERRID.ERR_ExpectedLT)
End If
End If
If CurrentToken.Kind = SyntaxKind.XmlNameToken Then
' /* AllowExpr */' /* IsBracketed */'
name = DirectCast(ParseXmlQualifiedName(False, False, ScannerState.EndElement, ScannerState.EndElement), XmlNameSyntax)
End If
VerifyExpectedToken(SyntaxKind.GreaterThanToken, greaterToken, nextState)
Return SyntaxFactory.XmlElementEndTag(beginEndElement, name, greaterToken)
End Function
' File: Parser.cpp
' Lines: 13770 - 13770
' ExpressionList* .Parser::ParseXmlAttributes( [ bool AllowNameAsExpression ] [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseXmlAttributes(requireLeadingWhitespace As Boolean, xmlElementName As XmlNodeSyntax) As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of XmlNodeSyntax)
Dim Attributes = Me._pool.Allocate(Of XmlNodeSyntax)()
Do
Select Case CurrentToken.Kind
Case SyntaxKind.XmlNameToken,
SyntaxKind.LessThanPercentEqualsToken,
SyntaxKind.EqualsToken,
SyntaxKind.SingleQuoteToken,
SyntaxKind.DoubleQuoteToken
Dim attribute = ParseXmlAttribute(requireLeadingWhitespace, AllowNameAsExpression:=True, xmlElementName:=xmlElementName)
Debug.Assert(attribute IsNot Nothing)
requireLeadingWhitespace = Not attribute.HasTrailingTrivia
Attributes.Add(attribute)
Case Else
Exit Do
End Select
Loop
Dim result = Attributes.ToList
Me._pool.Free(Attributes)
Return result
End Function
' File: Parser.cpp
' Lines: 13813 - 13813
' Expression* .Parser::ParseXmlAttribute( [ bool AllowNameAsExpression ] [ _Inout_ bool& ErrorInConstruct ] )
Friend Function ParseXmlAttribute(requireLeadingWhitespace As Boolean, AllowNameAsExpression As Boolean, xmlElementName As XmlNodeSyntax) As XmlNodeSyntax
Debug.Assert(IsToken(CurrentToken,
SyntaxKind.XmlNameToken,
SyntaxKind.LessThanPercentEqualsToken,
SyntaxKind.EqualsToken,
SyntaxKind.SingleQuoteToken,
SyntaxKind.DoubleQuoteToken),
"ParseXmlAttribute called on wrong token.")
Dim Result As XmlNodeSyntax = Nothing
If CurrentToken.Kind = SyntaxKind.XmlNameToken OrElse
(AllowNameAsExpression AndAlso CurrentToken.Kind = SyntaxKind.LessThanPercentEqualsToken) OrElse
CurrentToken.Kind = SyntaxKind.EqualsToken OrElse
CurrentToken.Kind = SyntaxKind.SingleQuoteToken OrElse
CurrentToken.Kind = SyntaxKind.DoubleQuoteToken Then
' /* AllowExpr */' /* IsBracketed */'
Dim Name = ParseXmlQualifiedName(requireLeadingWhitespace, True, ScannerState.Element, ScannerState.Element)
If CurrentToken.Kind = SyntaxKind.EqualsToken Then
Dim equals = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.Element)
Dim value As XmlNodeSyntax = Nothing
If CurrentToken.Kind = SyntaxKind.LessThanPercentEqualsToken Then
' // <%= expr %>
value = ParseXmlEmbedded(ScannerState.Element)
Result = SyntaxFactory.XmlAttribute(Name, equals, value)
ElseIf Not Me._scanner.IsScanningXmlDoc OrElse
Not TryParseXmlCrefAttributeValue(Name, equals, Result) AndAlso
Not TryParseXmlNameAttributeValue(Name, equals, Result, xmlElementName) Then
' Try parsing as a string (quoted or unquoted)
value = ParseXmlString(ScannerState.Element)
Result = SyntaxFactory.XmlAttribute(Name, equals, value)
End If
ElseIf Name.Kind = SyntaxKind.XmlEmbeddedExpression Then
' // In this case, the Name is some expression which may evaluate to an attribute
Result = Name
Else
' // Names must be followed by an "="
Dim value As XmlNodeSyntax
If CurrentToken.Kind <> SyntaxKind.SingleQuoteToken AndAlso
CurrentToken.Kind <> SyntaxKind.DoubleQuoteToken Then
Dim missingQuote = DirectCast(InternalSyntaxFactory.MissingToken(SyntaxKind.SingleQuoteToken), PunctuationSyntax)
value = SyntaxFactory.XmlString(missingQuote, Nothing, missingQuote)
Else
' Case of quoted string without attribute name
' Try parsing as a string (quoted or unquoted)
value = ParseXmlString(ScannerState.Element)
End If
Result = SyntaxFactory.XmlAttribute(Name, DirectCast(HandleUnexpectedToken(SyntaxKind.EqualsToken), PunctuationSyntax), value)
End If
End If
Return Result
End Function
Private Function ElementNameIsOneFromTheList(xmlElementName As XmlNodeSyntax, ParamArray names() As String) As Boolean
If xmlElementName Is Nothing OrElse xmlElementName.Kind <> SyntaxKind.XmlName Then
Return False
End If
Dim xmlName = DirectCast(xmlElementName, XmlNameSyntax)
If xmlName.Prefix IsNot Nothing Then
Return False
End If
For Each name In names
If DocumentationCommentXmlNames.ElementEquals(xmlName.LocalName.Text, name, True) Then
Return True
End If
Next
Return False
End Function
Private Function TryParseXmlCrefAttributeValue(name As XmlNodeSyntax, equals As PunctuationSyntax, <Out> ByRef crefAttribute As XmlNodeSyntax) As Boolean
Debug.Assert(Me._scanner.IsScanningXmlDoc)
If name.Kind <> SyntaxKind.XmlName Then
Return False
End If
Dim xmlName = DirectCast(name, XmlNameSyntax)
If xmlName.Prefix IsNot Nothing OrElse
Not DocumentationCommentXmlNames.AttributeEquals(xmlName.LocalName.Text,
DocumentationCommentXmlNames.CrefAttributeName) Then
Return False
End If
' NOTE: we don't check the parent, seems 'cref' attribute is supported
' NOTE: for any nodes even user-defined ones
Dim state As ScannerState
Dim startQuote As PunctuationSyntax
If CurrentToken.Kind = SyntaxKind.SingleQuoteToken Then
state = If(CurrentToken.Text = "'"c, ScannerState.SingleQuotedString, ScannerState.SmartSingleQuotedString)
startQuote = DirectCast(CurrentToken, PunctuationSyntax)
ElseIf CurrentToken.Kind = SyntaxKind.DoubleQuoteToken Then
state = If(CurrentToken.Text = """"c, ScannerState.QuotedString, ScannerState.SmartQuotedString)
startQuote = DirectCast(CurrentToken, PunctuationSyntax)
Else
Return False
End If
' If we have any problems with parsing the name we want to restore the scanner and
' fall back to a regular attribute scenario
Dim restorePoint As Scanner.RestorePoint = Me._scanner.CreateRestorePoint()
Dim nextToken = Me.PeekNextToken(state)
If Not (nextToken.Kind = SyntaxKind.XmlTextLiteralToken OrElse nextToken.Kind = SyntaxKind.XmlEntityLiteralToken) Then
GoTo lFailed
End If
Dim text As String = nextToken.Text.Trim()
If text.Length >= 2 AndAlso text(0) <> ":" AndAlso text(1) = ":" Then
GoTo lFailed
End If
' The code above is supposed to reflect how Dev11 detects and verifies 'cref' attribute on the node
' See also: XmlDocFile.cpp, XMLDocNode::VerifyCRefAttributeOnNode(...)
' Eat the quotation mark, note that default context is being used here...
GetNextToken()
' The next portion of attribute value should be parsed as Name
Dim crefReference As CrefReferenceSyntax
' If can be either a VB intrinsic type or a proper optionally qualified name
' See also: XmlDocFile.cpp, XMLDocNode::PerformActualBinding
If SyntaxFacts.IsPredefinedTypeKeyword(Me.CurrentToken.Kind) Then
Dim type As PredefinedTypeSyntax = SyntaxFactory.PredefinedType(DirectCast(CurrentToken, KeywordSyntax))
' We need to move to the next token as ParseName(...) does
GetNextToken()
crefReference = SyntaxFactory.CrefReference(type, Nothing, Nothing)
Else
crefReference = Me.TryParseCrefReference()
End If
If crefReference Is Nothing Then
GoTo lFailed
End If
' We need to reset the current token and possibly peeked tokens because those
' were created using default scanner state, but we want to see from this
' point tokens received using custom scanner state saved in 'state'
Me.ResetCurrentToken(state)
Do
Select Case Me.CurrentToken.Kind
Case SyntaxKind.SingleQuoteToken,
SyntaxKind.DoubleQuoteToken
Dim endQuote = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.Element)
crefAttribute = SyntaxFactory.XmlCrefAttribute(xmlName, equals, startQuote, crefReference, endQuote)
Return True
Case SyntaxKind.XmlTextLiteralToken,
SyntaxKind.XmlEntityLiteralToken
Dim token As SyntaxToken = CurrentToken
If TriviaChecker.HasInvalidTrivia(token) Then
GoTo lFailed
End If
crefReference = crefReference.AddTrailingSyntax(token)
crefReference.ClearFlags(GreenNode.NodeFlags.ContainsDiagnostics)
GetNextToken(state)
Continue Do
Case SyntaxKind.EndOfXmlToken,
SyntaxKind.EndOfFileToken
Dim endQuote = DirectCast(InternalSyntaxFactory.MissingToken(startQuote.Kind), PunctuationSyntax)
crefAttribute = SyntaxFactory.XmlCrefAttribute(xmlName, equals, startQuote, crefReference, endQuote)
Return True
End Select
Exit Do
Loop
lFailed:
restorePoint.Restore()
Me.ResetCurrentToken(ScannerState.Element)
Return False
End Function
Friend Function TryParseCrefReference() As CrefReferenceSyntax
' Mandatory name part
Dim name As TypeSyntax = TryParseCrefOptionallyQualifiedName()
Debug.Assert(name IsNot Nothing)
Dim signature As CrefSignatureSyntax = Nothing
Dim asClause As SimpleAsClauseSyntax = Nothing
If CurrentToken.Kind = SyntaxKind.OpenParenToken AndAlso name.Kind <> SyntaxKind.PredefinedType Then
' Optional signature and As clause
signature = TryParseCrefReferenceSignature()
Debug.Assert(signature IsNot Nothing)
' NOTE: 'As' clause is only allowed if signature specified
If CurrentToken.Kind = SyntaxKind.AsKeyword Then
Dim asKeyword As KeywordSyntax = DirectCast(CurrentToken, KeywordSyntax)
GetNextToken()
Dim returnType As TypeSyntax = ParseGeneralType()
Debug.Assert(returnType IsNot Nothing)
asClause = SyntaxFactory.SimpleAsClause(asKeyword, Nothing, returnType)
End If
End If
Dim result As CrefReferenceSyntax = SyntaxFactory.CrefReference(name, signature, asClause)
' Even if there are diagnostics in name we don't report them, they will be
' reported later in Documentation comment binding
If result.ContainsDiagnostics Then
result.ClearFlags(GreenNode.NodeFlags.ContainsDiagnostics)
End If
Return result
End Function
Friend Function TryParseCrefReferenceSignature() As CrefSignatureSyntax
'('
Debug.Assert(CurrentToken.Kind = SyntaxKind.OpenParenToken)
Dim openParen As PunctuationSyntax = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken()
Dim signatureTypes = _pool.AllocateSeparated(Of CrefSignaturePartSyntax)()
Dim firstType As Boolean = True
Do
Dim currToken As SyntaxToken = Me.CurrentToken
If currToken.Kind <> SyntaxKind.CloseParenToken AndAlso currToken.Kind <> SyntaxKind.CommaToken AndAlso Not firstType Then
' In case we expect ')' or ',' but don't find one, we consider this an end of
' the signature, add a missing '(' and exit parsing
currToken = InternalSyntaxFactory.MissingToken(SyntaxKind.CloseParenToken)
End If
If currToken.Kind = SyntaxKind.CloseParenToken Then
' ')', we are done
Dim closeParen As PunctuationSyntax = DirectCast(currToken, PunctuationSyntax)
If Not currToken.IsMissing Then
' Only move to the next token if this is a non-missing one
GetNextToken()
End If
Dim typeArguments As CodeAnalysis.Syntax.InternalSyntax.SeparatedSyntaxList(Of CrefSignaturePartSyntax) = signatureTypes.ToList
_pool.Free(signatureTypes)
Return SyntaxFactory.CrefSignature(openParen, typeArguments, closeParen)
End If
If firstType Then
firstType = False
Else
Debug.Assert(CurrentToken.Kind = SyntaxKind.CommaToken)
signatureTypes.AddSeparator(CurrentToken)
GetNextToken()
End If
Dim modifier As KeywordSyntax = Nothing
While CurrentToken.Kind = SyntaxKind.ByValKeyword OrElse CurrentToken.Kind = SyntaxKind.ByRefKeyword
If modifier Is Nothing Then
' The first one
modifier = DirectCast(CurrentToken, KeywordSyntax)
Else
' Add diagnostics for all other modifiers
modifier = modifier.AddTrailingSyntax(CurrentToken, ERRID.ERR_InvalidParameterSyntax)
End If
GetNextToken()
End While
Dim typeName As TypeSyntax = ParseGeneralType(allowEmptyGenericArguments:=False)
Debug.Assert(typeName IsNot Nothing)
signatureTypes.Add(SyntaxFactory.CrefSignaturePart(modifier, typeName))
Loop
Throw ExceptionUtilities.Unreachable
End Function
Friend Function TryParseCrefOperatorName() As CrefOperatorReferenceSyntax
Dim operatorKeyword As KeywordSyntax = DirectCast(CurrentToken, KeywordSyntax)
Debug.Assert(operatorKeyword.Kind = SyntaxKind.OperatorKeyword)
GetNextToken()
Dim keyword As KeywordSyntax = Nothing
Dim operatorToken As SyntaxToken
If TryTokenAsContextualKeyword(CurrentToken, keyword) Then
operatorToken = keyword
Else
operatorToken = CurrentToken
End If
Dim operatorKind As SyntaxKind = operatorToken.Kind
If SyntaxFacts.IsOperatorStatementOperatorToken(operatorKind) Then
GetNextToken()
Else
operatorToken = ReportSyntaxError(InternalSyntaxFactory.MissingToken(SyntaxKind.PlusToken), ERRID.ERR_UnknownOperator)
End If
Return SyntaxFactory.CrefOperatorReference(operatorKeyword, operatorToken)
End Function
Friend Function TryParseCrefOptionallyQualifiedName() As TypeSyntax
Dim result As NameSyntax = Nothing
' Parse head: Either a GlobalName or a SimpleName.
If CurrentToken.Kind = SyntaxKind.GlobalKeyword Then
result = SyntaxFactory.GlobalName(DirectCast(CurrentToken, KeywordSyntax))
GetNextToken()
ElseIf CurrentToken.Kind = SyntaxKind.ObjectKeyword Then
' Dev11 treats type 'object' quite in a weird way, thus [cref="object"] and
' [cref="system.object"] will both be resolved into "T:System.Object", but
' while [cref="system.object.tostring"] is resolved into "M:System.Object.ToString",
' [cref="object.tostring"] produces an error. We fix this in Roslyn
result = SyntaxFactory.IdentifierName(
Me._scanner.MakeIdentifier(
DirectCast(Me.CurrentToken, KeywordSyntax)))
GetNextToken()
ElseIf CurrentToken.Kind = SyntaxKind.OperatorKeyword Then
' Operator reference like 'Operator+(...)' cannot be followed by 'dot'
Return TryParseCrefOperatorName()
ElseIf CurrentToken.Kind = SyntaxKind.NewKeyword Then
' Constructor reference like 'New(...)' cannot be followed by 'dot'
Return ParseSimpleName(
allowGenericArguments:=False,
allowGenericsWithoutOf:=False,
disallowGenericArgumentsOnLastQualifiedName:=True,
allowKeyword:=True,
nonArrayName:=False,
allowEmptyGenericArguments:=False,
allowNonEmptyGenericArguments:=True)
Else
Debug.Assert(Not SyntaxFacts.IsPredefinedTypeKeyword(CurrentToken.Kind))
result = ParseSimpleName(
allowGenericArguments:=True,
allowGenericsWithoutOf:=False,
disallowGenericArgumentsOnLastQualifiedName:=False,
allowKeyword:=False,
nonArrayName:=False,
allowEmptyGenericArguments:=False,
allowNonEmptyGenericArguments:=True)
End If
Debug.Assert(result IsNot Nothing)
' Parse tail: A sequence of zero or more [dot SimpleName].
While CurrentToken.Kind = SyntaxKind.DotToken
Dim dotToken As PunctuationSyntax = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken()
If CurrentToken.Kind = SyntaxKind.OperatorKeyword Then
' Operator reference like 'Clazz.Operator+(...)' cannot be followed by 'dot'
Dim operatorReference As CrefOperatorReferenceSyntax = TryParseCrefOperatorName()
Debug.Assert(operatorReference IsNot Nothing)
Return SyntaxFactory.QualifiedCrefOperatorReference(result, dotToken, operatorReference)
Else
Dim simpleName As SimpleNameSyntax =
ParseSimpleName(
allowGenericArguments:=True,
allowGenericsWithoutOf:=False,
disallowGenericArgumentsOnLastQualifiedName:=False,
allowKeyword:=True,
nonArrayName:=False,
allowEmptyGenericArguments:=False,
allowNonEmptyGenericArguments:=True)
result = SyntaxFactory.QualifiedName(result, dotToken, simpleName)
End If
End While
Return result
End Function
Private Function TryParseXmlNameAttributeValue(name As XmlNodeSyntax, equals As PunctuationSyntax, <Out> ByRef nameAttribute As XmlNodeSyntax, xmlElementName As XmlNodeSyntax) As Boolean
Debug.Assert(Me._scanner.IsScanningXmlDoc)
If name.Kind <> SyntaxKind.XmlName Then
Return False
End If
Dim xmlName = DirectCast(name, XmlNameSyntax)
If xmlName.Prefix IsNot Nothing OrElse
Not DocumentationCommentXmlNames.AttributeEquals(xmlName.LocalName.Text,
DocumentationCommentXmlNames.NameAttributeName) Then
Return False
End If
If Not ElementNameIsOneFromTheList(xmlElementName,
DocumentationCommentXmlNames.ParameterElementName,
DocumentationCommentXmlNames.ParameterReferenceElementName,
DocumentationCommentXmlNames.TypeParameterElementName,
DocumentationCommentXmlNames.TypeParameterReferenceElementName) Then
Return False
End If
Dim state As ScannerState
Dim startQuote As PunctuationSyntax
If CurrentToken.Kind = SyntaxKind.SingleQuoteToken Then
state = If(CurrentToken.Text = "'"c, ScannerState.SingleQuotedString, ScannerState.SmartSingleQuotedString)
startQuote = DirectCast(CurrentToken, PunctuationSyntax)
ElseIf CurrentToken.Kind = SyntaxKind.DoubleQuoteToken Then
state = If(CurrentToken.Text = """"c, ScannerState.QuotedString, ScannerState.SmartQuotedString)
startQuote = DirectCast(CurrentToken, PunctuationSyntax)
Else
Return False
End If
' If we have any problems with parsing the name we want to restore the scanner and
' fall back to a regular attribute scenario
Dim restorePoint As Scanner.RestorePoint = Me._scanner.CreateRestorePoint()
' Eat the quotation mark, note that default context is being used here...
GetNextToken()
Dim identToken As SyntaxToken = CurrentToken
If identToken.Kind <> SyntaxKind.IdentifierToken Then
If identToken.IsKeyword Then
identToken = Me._scanner.MakeIdentifier(DirectCast(Me.CurrentToken, KeywordSyntax))
Else
GoTo lFailed
End If
End If
If identToken.ContainsDiagnostics() Then
GoTo lFailed
End If
If TriviaChecker.HasInvalidTrivia(identToken) Then
GoTo lFailed
End If
' Move to the next token which is supposed to be a closing quote
GetNextToken(state)
Dim closingToken As SyntaxToken = Me.CurrentToken
If closingToken.Kind = SyntaxKind.SingleQuoteToken OrElse closingToken.Kind = SyntaxKind.DoubleQuoteToken Then
Dim endQuote = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.Element)
nameAttribute = SyntaxFactory.XmlNameAttribute(xmlName,
equals,
startQuote,
SyntaxFactory.IdentifierName(DirectCast(identToken, IdentifierTokenSyntax)),
endQuote)
Return True
End If
lFailed:
restorePoint.Restore()
Me.ResetCurrentToken(ScannerState.Element)
Return False
End Function
''' <summary>
''' Checks if the resulting Cref or Name attribute value has valid trivia
''' Note, this may be applicable not only to regular trivia, but also to syntax
''' nodes added to trivia when the parser was recovering from errors
''' </summary>
Private Class TriviaChecker
Private Sub New()
End Sub
Public Shared Function HasInvalidTrivia(node As GreenNode) As Boolean
Return SyntaxNodeOrTokenHasInvalidTrivia(node)
End Function
Private Shared Function SyntaxNodeOrTokenHasInvalidTrivia(node As GreenNode) As Boolean
If node IsNot Nothing Then
Dim token As SyntaxToken = TryCast(node, SyntaxToken)
If token IsNot Nothing Then
If IsInvalidTrivia(token.GetLeadingTrivia) OrElse IsInvalidTrivia(token.GetTrailingTrivia) Then
Return True
End If
ElseIf SyntaxNodeHasInvalidTrivia(node) Then
Return True
End If
End If
Return False
End Function
Private Shared Function SyntaxNodeHasInvalidTrivia(node As GreenNode) As Boolean
For index = 0 To node.SlotCount - 1
If SyntaxNodeOrTokenHasInvalidTrivia(node.GetSlot(index)) Then
Return True
End If
Next
Return False
End Function
Private Shared Function IsInvalidTrivia(node As GreenNode) As Boolean
If node IsNot Nothing Then
Select Case node.RawKind
Case SyntaxKind.List
For index = 0 To node.SlotCount - 1
If IsInvalidTrivia(node.GetSlot(index)) Then
Return True
End If
Next
Case SyntaxKind.WhitespaceTrivia
' TODO: The following is simplified, need to be revised
Dim whitespace As String = DirectCast(node, SyntaxTrivia).Text
For Each ch In whitespace
If ch <> " "c AndAlso ch <> ChrW(9) Then
Return True
End If
Next
Case SyntaxKind.SkippedTokensTrivia
If SyntaxNodeOrTokenHasInvalidTrivia(DirectCast(node, SkippedTokensTriviaSyntax).Tokens.Node) Then
Return True
End If
Case Else
Return True
End Select
End If
Return False
End Function
End Class
' File: Parser.cpp
' Lines: 13931 - 13931
' Expression* .Parser::ParseXmlQualifiedName( [ bool AllowExpr ] [ bool IsBracketed ] [ bool IsElementName ] [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseXmlQualifiedName(
requireLeadingWhitespace As Boolean,
allowExpr As Boolean,
stateForName As ScannerState,
nextState As ScannerState
) As XmlNodeSyntax
Select Case (CurrentToken.Kind)
Case SyntaxKind.XmlNameToken
Return ParseXmlQualifiedName(requireLeadingWhitespace, stateForName, nextState)
Case SyntaxKind.LessThanPercentEqualsToken
If allowExpr Then
' // <%= expr %>
Return ParseXmlEmbedded(nextState)
End If
End Select
ResetCurrentToken(nextState)
Return ReportExpectedXmlName()
End Function
Private Function ParseXmlQualifiedName(requireLeadingWhitespace As Boolean, stateForName As ScannerState, nextState As ScannerState) As XmlNodeSyntax
Dim hasPrecedingWhitespace = requireLeadingWhitespace AndAlso
(PrevToken.GetTrailingTrivia.ContainsWhitespaceTrivia() OrElse CurrentToken.GetLeadingTrivia.ContainsWhitespaceTrivia)
Dim localName = DirectCast(CurrentToken, XmlNameTokenSyntax)
GetNextToken(stateForName)
If requireLeadingWhitespace AndAlso Not hasPrecedingWhitespace Then
localName = ReportSyntaxError(localName, ERRID.ERR_ExpectedXmlWhiteSpace)
End If
Dim prefix As XmlPrefixSyntax = Nothing
If CurrentToken.Kind = SyntaxKind.ColonToken Then
Dim colon As PunctuationSyntax = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(stateForName)
prefix = SyntaxFactory.XmlPrefix(localName, colon)
If CurrentToken.Kind = SyntaxKind.XmlNameToken Then
localName = DirectCast(CurrentToken, XmlNameTokenSyntax)
GetNextToken(stateForName)
If colon.HasTrailingTrivia OrElse
localName.HasLeadingTrivia Then
localName = ReportSyntaxError(localName, ERRID.ERR_ExpectedXmlName)
End If
Else
localName = ReportSyntaxError(InternalSyntaxFactory.XmlNameToken("", SyntaxKind.XmlNameToken, Nothing, Nothing), ERRID.ERR_ExpectedXmlName)
End If
End If
Dim name = SyntaxFactory.XmlName(prefix, localName)
ResetCurrentToken(nextState)
Return name
End Function
''' <summary>
''' Checks if the given <paramref name="node"/> is a colon trivia whose string representation is the COLON (U+003A) character from ASCII range
''' (specifically excluding cases when it is the FULLWIDTH COLON (U+FF1A) character).
''' See also: http://fileformat.info/info/unicode/char/FF1A
''' </summary>
''' <param name="node">A VB syntax node to check.</param>
Private Shared Function IsAsciiColonTrivia(node As VisualBasicSyntaxNode) As Boolean
Return node.Kind = SyntaxKind.ColonTrivia AndAlso node.ToString() = ":"
End Function
Private Function ParseXmlQualifiedNameVB() As XmlNameSyntax
If Not IsValidXmlQualifiedNameToken(CurrentToken) Then
Return ReportExpectedXmlName()
End If
Dim localName = ToXmlNameToken(CurrentToken)
GetNextToken(ScannerState.VB)
Dim prefix As XmlPrefixSyntax = Nothing
' Because this token was scanned in VB mode, it may have colon token trivia on the end. Because the colon may
' be part of an Xml name remove the colon from the trivia if it exists. Also, get the next token in Element state
' so that the colon appears as a normal token. A colon may come after the identifier if and only if it is the only
' trivia following the identifier. If there is any trivia before the colon then the colon should stay as trivia
' and be interpreted as a colon token terminator. If there is any trivia following the colon, this is an error.
' Note that only the COLON (U+003A) character, but not the FULLWIDTH COLON (U+FF1A), may be a part of an XML name,
' although they both may be represented by a node with kind SyntaxKind.ColonTrivia.
Dim trailingTrivia = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(localName.GetTrailingTrivia())
If trailingTrivia.Count > 0 AndAlso IsAsciiColonTrivia(trailingTrivia(0)) Then
Debug.Assert(trailingTrivia.Last.Kind = SyntaxKind.ColonTrivia)
Debug.Assert(CurrentToken.FullWidth = 0)
' Remove trailing colon trivia from the identifier
trailingTrivia = trailingTrivia.GetStartOfTrivia(trailingTrivia.Count - 1)
localName = SyntaxFactory.XmlNameToken(localName.Text, localName.PossibleKeywordKind, localName.GetLeadingTrivia(), trailingTrivia.Node).WithDiagnostics(localName.GetDiagnostics())
' Get the colon as an Xml colon token, then transition back to VB.
ResetCurrentToken(ScannerState.Element)
Dim colon = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.Element)
colon = TransitionFromXmlToVB(colon)
prefix = SyntaxFactory.XmlPrefix(localName, colon)
localName = Nothing
If trailingTrivia.Count = 0 AndAlso Not colon.HasTrailingTrivia() AndAlso
IsValidXmlQualifiedNameToken(CurrentToken) Then
localName = ToXmlNameToken(CurrentToken)
GetNextToken(ScannerState.VB)
End If
If localName Is Nothing Then
localName = ReportSyntaxError(InternalSyntaxFactory.XmlNameToken("", SyntaxKind.XmlNameToken, Nothing, Nothing), ERRID.ERR_ExpectedXmlName)
End If
End If
Return SyntaxFactory.XmlName(prefix, localName)
End Function
Private Shared Function IsValidXmlQualifiedNameToken(token As SyntaxToken) As Boolean
Return token.Kind = SyntaxKind.IdentifierToken OrElse TryCast(token, KeywordSyntax) IsNot Nothing
End Function
Private Function ToXmlNameToken(token As SyntaxToken) As XmlNameTokenSyntax
If token.Kind = SyntaxKind.IdentifierToken Then
Dim id = DirectCast(token, IdentifierTokenSyntax)
Dim name = SyntaxFactory.XmlNameToken(id.Text, id.PossibleKeywordKind, token.GetLeadingTrivia(), token.GetTrailingTrivia())
' Xml names should not be escaped
If id.IsBracketed Then
name = ReportSyntaxError(name, ERRID.ERR_ExpectedXmlName)
Else
name = VerifyXmlNameToken(name)
End If
Return name
Else
' This is the keyword case
Debug.Assert(TryCast(token, KeywordSyntax) IsNot Nothing)
Return SyntaxFactory.XmlNameToken(token.Text, token.Kind, token.GetLeadingTrivia(), token.GetTrailingTrivia())
End If
End Function
Private Shared Function VerifyXmlNameToken(tk As XmlNameTokenSyntax) As XmlNameTokenSyntax
Dim text = tk.ValueText
If Not String.IsNullOrEmpty(text) Then
If Not isStartNameChar(text(0)) Then
Dim ch = text(0)
Return ReportSyntaxError(tk,
ERRID.ERR_IllegalXmlStartNameChar,
ch,
"0x" & Convert.ToInt32(ch).ToString("X4"))
End If
For Each ch In text
If Not isNameChar(ch) Then
Return ReportSyntaxError(tk,
ERRID.ERR_IllegalXmlNameChar,
ch,
"0x" & Convert.ToInt32(ch).ToString("X4"))
End If
Next
End If
Return tk
End Function
Friend Function ParseRestOfDocCommentContent(nodesSoFar As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of GreenNode)) As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of XmlNodeSyntax)
Dim content = Me._pool.Allocate(Of XmlNodeSyntax)()
For Each node In nodesSoFar.Nodes
content.Add(DirectCast(node, XmlNodeSyntax))
Next
If CurrentToken.Kind = SyntaxKind.EndOfXmlToken Then
GetNextToken(ScannerState.Content)
If CurrentToken.Kind = SyntaxKind.DocumentationCommentLineBreakToken Then
Dim tempNodes = ParseXmlContent(ScannerState.Content)
Debug.Assert(tempNodes.Nodes.Length = 1)
For Each node In tempNodes.Nodes
content.Add(node)
Next
End If
End If
Dim result = content.ToList
Me._pool.Free(content)
Return result
End Function
' File: Parser.cpp
' Lines: 14004 - 14004
' ExpressionList* .Parser::ParseXmlContent( [ _Inout_ ParseTree::XmlElementExpression* Parent ] [ _Inout_ bool& ErrorInConstruct ] )
Friend Function ParseXmlContent(state As ScannerState) As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of XmlNodeSyntax)
Debug.Assert(IsToken(CurrentToken,
SyntaxKind.XmlTextLiteralToken,
SyntaxKind.DocumentationCommentLineBreakToken,
SyntaxKind.XmlEntityLiteralToken,
SyntaxKind.LessThanToken,
SyntaxKind.LessThanSlashToken,
SyntaxKind.LessThanExclamationMinusMinusToken,
SyntaxKind.LessThanQuestionToken,
SyntaxKind.LessThanPercentEqualsToken,
SyntaxKind.BeginCDataToken,
SyntaxKind.EndCDataToken,
SyntaxKind.EndOfFileToken,
SyntaxKind.EndOfXmlToken,
SyntaxKind.BadToken),
"ParseXmlContent called on wrong token.")
Dim Content = Me._pool.Allocate(Of XmlNodeSyntax)()
Dim whitespaceChecker As New XmlWhitespaceChecker()
Dim xml As XmlNodeSyntax
Do
Select Case (CurrentToken.Kind)
Case SyntaxKind.LessThanToken
xml = ParseXmlElement(ScannerState.Content)
Case SyntaxKind.LessThanSlashToken
xml = ReportSyntaxError(ParseXmlElementEndTag(ScannerState.Content), ERRID.ERR_XmlEndElementNoMatchingStart)
Case SyntaxKind.LessThanExclamationMinusMinusToken
xml = ParseXmlComment(ScannerState.Content)
Case SyntaxKind.LessThanQuestionToken
xml = ParseXmlProcessingInstruction(ScannerState.Content, whitespaceChecker)
Case SyntaxKind.BeginCDataToken
xml = ParseXmlCData(ScannerState.Content)
Case SyntaxKind.LessThanPercentEqualsToken
xml = ParseXmlEmbedded(ScannerState.Content)
Case SyntaxKind.XmlTextLiteralToken,
SyntaxKind.XmlEntityLiteralToken,
SyntaxKind.DocumentationCommentLineBreakToken
Dim newKind As SyntaxKind
Dim textTokens = _pool.Allocate(Of XmlTextTokenSyntax)()
Do
textTokens.Add(DirectCast(CurrentToken, XmlTextTokenSyntax))
GetNextToken(ScannerState.Content)
newKind = CurrentToken.Kind
Loop While newKind = SyntaxKind.XmlTextLiteralToken OrElse
newKind = SyntaxKind.XmlEntityLiteralToken OrElse
newKind = SyntaxKind.DocumentationCommentLineBreakToken
Dim textResult = textTokens.ToList
_pool.Free(textTokens)
xml = SyntaxFactory.XmlText(textResult)
Case SyntaxKind.EndOfFileToken,
SyntaxKind.EndOfXmlToken
Exit Do
Case SyntaxKind.BadToken
Dim badToken = DirectCast(CurrentToken, BadTokenSyntax)
If badToken.SubKind = SyntaxSubKind.BeginDocTypeToken Then
Dim docTypeTrivia = ParseXmlDocType(ScannerState.Element)
xml = SyntaxFactory.XmlText(InternalSyntaxFactory.MissingToken(SyntaxKind.XmlTextLiteralToken))
xml = xml.AddLeadingSyntax(docTypeTrivia, ERRID.ERR_DTDNotSupported)
Else
' Let resync handle it
GoTo TryResync
End If
Case Else
TryResync:
' when parsing XmlDoc there may not be outer context to take care of garbage
If state = ScannerState.Content Then
xml = ResyncXmlContent()
Else
Exit Do
End If
End Select
Content.Add(xml)
Loop
Dim result = Content.ToList
Me._pool.Free(Content)
Return result
End Function
' File: Parser.cpp
' Lines: 14078 - 14078
' Expression* .Parser::ParseXmlPI( [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseXmlProcessingInstruction(nextState As ScannerState, whitespaceChecker As XmlWhitespaceChecker) As XmlProcessingInstructionSyntax
Debug.Assert(CurrentToken.Kind = SyntaxKind.LessThanQuestionToken, "ParseXmlPI called on the wrong token.")
Dim beginProcessingInstruction = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.Element)
'TODO - handle whitespace between begin and name. This check is also needed for xml document declaration
' Consider adding a special state for the xml document/pi that does not add trivia to tokens.
Dim name As XmlNameTokenSyntax = Nothing
'TODO - name has to allow :. Dev10 puts a fully qualified name here.
If Not VerifyExpectedToken(SyntaxKind.XmlNameToken, name, ScannerState.StartProcessingInstruction) Then
' In case there wasn't a name in the PI and the scanner returned another token from the element state,
' the current token must be reset to a processing instruction token.
ResetCurrentToken(ScannerState.StartProcessingInstruction)
End If
If name.Text.Length = 3 AndAlso String.Equals(name.Text, "xml", StringComparison.OrdinalIgnoreCase) Then
name = ReportSyntaxError(name, ERRID.ERR_IllegalProcessingInstructionName, name.Text)
End If
Dim textToken As XmlTextTokenSyntax = Nothing
Dim values = _pool.Allocate(Of XmlTextTokenSyntax)()
If CurrentToken.Kind = SyntaxKind.XmlTextLiteralToken OrElse CurrentToken.Kind = SyntaxKind.DocumentationCommentLineBreakToken Then
textToken = DirectCast(CurrentToken, XmlTextTokenSyntax)
If Not name.IsMissing AndAlso
Not name.GetTrailingTrivia.ContainsWhitespaceTrivia() AndAlso
Not textToken.GetLeadingTrivia.ContainsWhitespaceTrivia() Then
textToken = ReportSyntaxError(textToken, ERRID.ERR_ExpectedXmlWhiteSpace)
End If
Do
values.Add(textToken)
GetNextToken(ScannerState.ProcessingInstruction)
If CurrentToken.Kind <> SyntaxKind.XmlTextLiteralToken AndAlso CurrentToken.Kind <> SyntaxKind.DocumentationCommentLineBreakToken Then
Exit Do
End If
textToken = DirectCast(CurrentToken, XmlTextTokenSyntax)
Loop
End If
Dim endProcessingInstruction As PunctuationSyntax = Nothing
VerifyExpectedToken(SyntaxKind.QuestionGreaterThanToken, endProcessingInstruction, nextState)
Dim result = SyntaxFactory.XmlProcessingInstruction(beginProcessingInstruction, name, values.ToList, endProcessingInstruction)
result = DirectCast(whitespaceChecker.Visit(result), XmlProcessingInstructionSyntax)
_pool.Free(values)
Return result
End Function
' File: Parser.cpp
' Lines: 14119 - 14119
' Expression* .Parser::ParseXmlCData( [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseXmlCData(nextState As ScannerState) As XmlCDataSectionSyntax
Debug.Assert(CurrentToken.Kind = SyntaxKind.BeginCDataToken, "ParseXmlCData called on the wrong token.")
Dim beginCData = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.CData)
Dim values = _pool.Allocate(Of XmlTextTokenSyntax)()
Do While CurrentToken.Kind = SyntaxKind.XmlTextLiteralToken OrElse CurrentToken.Kind = SyntaxKind.DocumentationCommentLineBreakToken
values.Add(DirectCast(CurrentToken, XmlTextTokenSyntax))
GetNextToken(ScannerState.CData)
Loop
Dim endCData As PunctuationSyntax = Nothing
VerifyExpectedToken(SyntaxKind.EndCDataToken, endCData, nextState)
Dim result = values.ToList
_pool.Free(values)
Return SyntaxFactory.XmlCDataSection(beginCData, result, endCData)
End Function
' File: Parser.cpp
' Lines: 14134 - 14134
' Expression* .Parser::ParseXmlComment( [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseXmlComment(nextState As ScannerState) As XmlNodeSyntax
Debug.Assert(CurrentToken.Kind = SyntaxKind.LessThanExclamationMinusMinusToken, "ParseXmlComment called on wrong token.")
Dim beginComment As PunctuationSyntax = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.Comment)
Dim values = _pool.Allocate(Of XmlTextTokenSyntax)()
Do While CurrentToken.Kind = SyntaxKind.XmlTextLiteralToken OrElse CurrentToken.Kind = SyntaxKind.DocumentationCommentLineBreakToken
Dim textToken = DirectCast(CurrentToken, XmlTextTokenSyntax)
If textToken.Text.Length = 2 AndAlso textToken.Text = "--" Then
textToken = ReportSyntaxError(textToken, ERRID.ERR_IllegalXmlCommentChar)
End If
values.Add(textToken)
GetNextToken(ScannerState.Comment)
Loop
Dim endComment As PunctuationSyntax = Nothing
VerifyExpectedToken(SyntaxKind.MinusMinusGreaterThanToken, endComment, nextState)
Dim result = values.ToList
_pool.Free(values)
Return SyntaxFactory.XmlComment(beginComment, result, endComment)
End Function
' File: Parser.cpp
' Lines: 14209 - 14209
' Expression* .Parser::ParseXmlString( [ _Out_ ParseTree::XmlAttributeExpression* Attribute ] [ _Inout_ bool& ErrorInConstruct ] )
Friend Function ParseXmlString(nextState As ScannerState) As XmlStringSyntax
Dim state As ScannerState
Dim startQuote As PunctuationSyntax
If CurrentToken.Kind = SyntaxKind.SingleQuoteToken Then
state = If(CurrentToken.Text = "'"c, ScannerState.SingleQuotedString, ScannerState.SmartSingleQuotedString)
startQuote = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(state)
ElseIf CurrentToken.Kind = SyntaxKind.DoubleQuoteToken Then
state = If(CurrentToken.Text = """"c, ScannerState.QuotedString, ScannerState.SmartQuotedString)
startQuote = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(state)
Else
' this is not a quote.
' Let's parse the stuff as if it is quoted, but complain that quote is missing
state = ScannerState.UnQuotedString
startQuote = DirectCast(InternalSyntaxFactory.MissingToken(SyntaxKind.SingleQuoteToken), PunctuationSyntax)
startQuote = ReportSyntaxError(startQuote, ERRID.ERR_StartAttributeValue)
ResetCurrentToken(state)
End If
Dim list = _pool.Allocate(Of XmlTextTokenSyntax)()
Do
Dim kind = CurrentToken.Kind
Select Case kind
Case SyntaxKind.SingleQuoteToken,
SyntaxKind.DoubleQuoteToken
Dim endQuote = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(nextState)
Dim result = SyntaxFactory.XmlString(startQuote, list.ToList, endQuote)
_pool.Free(list)
Return result
Case SyntaxKind.XmlTextLiteralToken,
SyntaxKind.XmlEntityLiteralToken,
SyntaxKind.DocumentationCommentLineBreakToken
list.Add(DirectCast(CurrentToken, XmlTextTokenSyntax))
Case Else
' error. This happens on EndOfText and BadChar. Let the caller deal with this.
' TODO: is this ok?
Dim endQuote = HandleUnexpectedToken(startQuote.Kind)
Dim result = SyntaxFactory.XmlString(startQuote, list.ToList, DirectCast(endQuote, PunctuationSyntax))
_pool.Free(list)
Return result
End Select
GetNextToken(state)
Loop
End Function
' File: Parser.cpp
' Lines: 14379 - 14379
' Expression* .Parser::ParseXmlEmbedded( [ bool AllowEmbedded ] [ _Inout_ bool& ErrorInConstruct ] )
Private Function ParseXmlEmbedded(enclosingState As ScannerState) As XmlEmbeddedExpressionSyntax
Debug.Assert(CurrentToken.Kind = SyntaxKind.LessThanPercentEqualsToken, "ParseXmlEmbedded called on wrong token")
Dim beginXmlEmbedded As PunctuationSyntax = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(enclosingState)
beginXmlEmbedded = TransitionFromXmlToVB(beginXmlEmbedded)
TryEatNewLine(ScannerState.VB)
Dim value = ParseExpressionCore()
Dim endXmlEmbedded As PunctuationSyntax = Nothing
If Not TryEatNewLineAndGetToken(SyntaxKind.PercentGreaterThanToken, endXmlEmbedded, createIfMissing:=False, state:=enclosingState) Then
Dim skippedTokens = Me._pool.Allocate(Of SyntaxToken)()
ResyncAt(skippedTokens, ScannerState.VB, {SyntaxKind.PercentGreaterThanToken,
SyntaxKind.GreaterThanToken,
SyntaxKind.LessThanToken,
SyntaxKind.LessThanPercentEqualsToken,
SyntaxKind.LessThanQuestionToken,
SyntaxKind.BeginCDataToken,
SyntaxKind.LessThanExclamationMinusMinusToken,
SyntaxKind.LessThanSlashToken})
If CurrentToken.Kind = SyntaxKind.PercentGreaterThanToken Then
endXmlEmbedded = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(enclosingState)
Else
endXmlEmbedded = DirectCast(HandleUnexpectedToken(SyntaxKind.PercentGreaterThanToken), PunctuationSyntax)
End If
Dim unexpectedSyntax = skippedTokens.ToList()
Me._pool.Free(skippedTokens)
If unexpectedSyntax.Node IsNot Nothing Then
endXmlEmbedded = AddLeadingSyntax(endXmlEmbedded, unexpectedSyntax, ERRID.ERR_Syntax)
End If
End If
Dim result = SyntaxFactory.XmlEmbeddedExpression(beginXmlEmbedded, value, endXmlEmbedded)
result = AdjustTriviaForMissingTokens(result)
result = TransitionFromVBToXml(enclosingState, result)
Return result
End Function
End Class
Friend Class XmlWhitespaceChecker
Inherits VisualBasicSyntaxRewriter
<Flags()>
Friend Enum TriviaCheck
None = 0
ProhibitLeadingTrivia = 1
ProhibitTrailingTrivia = 2
End Enum
Friend Structure WhiteSpaceOptions
Friend _parentKind As SyntaxKind
Friend _triviaCheck As TriviaCheck
End Structure
Private _options As WhiteSpaceOptions
Public Sub New()
End Sub
Public Overrides Function VisitXmlDeclaration(node As XmlDeclarationSyntax) As VisualBasicSyntaxNode
Dim anyChanges As Boolean = False
Dim saveOptions = _options
_options._triviaCheck = TriviaCheck.ProhibitTrailingTrivia
Dim lessThanQuestionToken = DirectCast(Visit(node.LessThanQuestionToken), PunctuationSyntax)
If node._lessThanQuestionToken IsNot lessThanQuestionToken Then anyChanges = True
_options._triviaCheck = TriviaCheck.ProhibitLeadingTrivia
Dim xmlKeyword = DirectCast(Visit(node.XmlKeyword), KeywordSyntax)
If node._xmlKeyword IsNot xmlKeyword Then anyChanges = True
_options = saveOptions
If anyChanges Then
Return New XmlDeclarationSyntax(node.Kind, node.GetDiagnostics, node.GetAnnotations, lessThanQuestionToken, xmlKeyword, node.Version, node.Encoding, node.Standalone, node.QuestionGreaterThanToken)
Else
Return node
End If
End Function
Public Overrides Function VisitXmlElementStartTag(node As XmlElementStartTagSyntax) As VisualBasicSyntaxNode
Dim anyChanges As Boolean = False
Dim saveOptions = _options
_options._parentKind = SyntaxKind.XmlElementStartTag
_options._triviaCheck = TriviaCheck.ProhibitTrailingTrivia
Dim lessThanToken = DirectCast(VisitSyntaxToken(node.LessThanToken), PunctuationSyntax)
If node.LessThanToken IsNot lessThanToken Then anyChanges = True
_options._triviaCheck = TriviaCheck.ProhibitLeadingTrivia
Dim name As XmlNodeSyntax = DirectCast(Visit(node.Name), XmlNodeSyntax)
If node.Name IsNot name Then anyChanges = True
_options._triviaCheck = TriviaCheck.None
Dim attributes = VisitList(node.Attributes)
If node.Attributes.Node IsNot attributes.Node Then anyChanges = True
_options = saveOptions
If anyChanges Then
Return InternalSyntaxFactory.XmlElementStartTag(lessThanToken, name, attributes, node.GreaterThanToken)
End If
Return node
End Function
Public Overrides Function VisitXmlEmptyElement(node As XmlEmptyElementSyntax) As VisualBasicSyntaxNode
Dim anyChanges As Boolean = False
Dim saveOptions = _options
_options._parentKind = SyntaxKind.XmlElementStartTag
_options._triviaCheck = TriviaCheck.ProhibitTrailingTrivia
Dim lessThanToken = DirectCast(VisitSyntaxToken(node.LessThanToken), PunctuationSyntax)
If node.LessThanToken IsNot lessThanToken Then anyChanges = True
_options._triviaCheck = TriviaCheck.ProhibitLeadingTrivia
Dim name As XmlNodeSyntax = DirectCast(Visit(node.Name), XmlNodeSyntax)
If node.Name IsNot name Then anyChanges = True
_options._triviaCheck = TriviaCheck.None
Dim attributes = VisitList(node.Attributes)
If node.Attributes.Node IsNot attributes.Node Then anyChanges = True
_options = saveOptions
If anyChanges Then
Return InternalSyntaxFactory.XmlEmptyElement(lessThanToken, name, attributes, node.SlashGreaterThanToken)
End If
Return node
End Function
Public Overrides Function VisitXmlElementEndTag(node As XmlElementEndTagSyntax) As VisualBasicSyntaxNode
Dim anyChanges As Boolean = False
Dim saveOptions = _options
_options._parentKind = SyntaxKind.XmlElementStartTag
_options._triviaCheck = TriviaCheck.ProhibitTrailingTrivia
Dim LessThanSlashToken = DirectCast(VisitSyntaxToken(node.LessThanSlashToken), PunctuationSyntax)
If node.LessThanSlashToken IsNot LessThanSlashToken Then anyChanges = True
Dim name As XmlNameSyntax = DirectCast(Visit(node.Name), XmlNameSyntax)
If node.Name IsNot name Then anyChanges = True
_options = saveOptions
If anyChanges Then
Return InternalSyntaxFactory.XmlElementEndTag(LessThanSlashToken, name, node.GreaterThanToken)
End If
Return node
End Function
Public Overrides Function VisitXmlProcessingInstruction(node As XmlProcessingInstructionSyntax) As VisualBasicSyntaxNode
Dim anyChanges As Boolean = False
Dim saveOptions = _options
_options._triviaCheck = TriviaCheck.ProhibitTrailingTrivia
Dim lessThanQuestionToken = DirectCast(VisitSyntaxToken(node.LessThanQuestionToken), PunctuationSyntax)
If node.LessThanQuestionToken IsNot lessThanQuestionToken Then anyChanges = True
'Prohibit trivia before pi name
_options._triviaCheck = TriviaCheck.ProhibitLeadingTrivia
Dim nameNew As XmlNameTokenSyntax = DirectCast(VisitSyntaxToken(node.Name), XmlNameTokenSyntax)
If node.Name IsNot nameNew Then anyChanges = True
_options = saveOptions
If anyChanges Then
Return New XmlProcessingInstructionSyntax(node.Kind,
node.GetDiagnostics,
node.GetAnnotations,
lessThanQuestionToken,
nameNew,
node.TextTokens.Node,
node.QuestionGreaterThanToken)
Else
Return node
End If
End Function
Public Overrides Function VisitXmlNameAttribute(node As XmlNameAttributeSyntax) As VisualBasicSyntaxNode
Dim anyChanges As Boolean = False
' Only check the name for trivia.
Dim saveOptions = _options
_options._parentKind = SyntaxKind.XmlNameAttribute
Dim nameNew As XmlNameSyntax = DirectCast(Visit(node.Name), XmlNameSyntax)
If node.Name IsNot nameNew Then anyChanges = True
_options = saveOptions
If anyChanges Then
Return New XmlNameAttributeSyntax(node.Kind, node.GetDiagnostics, node.GetAnnotations, nameNew, node.EqualsToken, node.StartQuoteToken, node.Reference, node.EndQuoteToken)
Else
Return node
End If
End Function
Public Overrides Function VisitXmlCrefAttribute(node As XmlCrefAttributeSyntax) As VisualBasicSyntaxNode
Dim anyChanges As Boolean = False
' Only check the name for trivia.
Dim saveOptions = _options
_options._parentKind = SyntaxKind.XmlCrefAttribute
Dim nameNew As XmlNameSyntax = DirectCast(Visit(node.Name), XmlNameSyntax)
If node.Name IsNot nameNew Then anyChanges = True
_options = saveOptions
If anyChanges Then
Return New XmlCrefAttributeSyntax(node.Kind, node.GetDiagnostics, node.GetAnnotations, nameNew, node.EqualsToken, node.StartQuoteToken, node.Reference, node.EndQuoteToken)
Else
Return node
End If
End Function
Public Overrides Function VisitXmlAttribute(node As XmlAttributeSyntax) As VisualBasicSyntaxNode
Dim anyChanges As Boolean = False
' Only check the name for trivia.
Dim saveOptions = _options
_options._parentKind = SyntaxKind.XmlAttribute
Dim nameNew As XmlNodeSyntax = DirectCast(Visit(node.Name), XmlNodeSyntax)
If node.Name IsNot nameNew Then anyChanges = True
_options = saveOptions
If anyChanges Then
Return New XmlAttributeSyntax(node.Kind, node.GetDiagnostics, node.GetAnnotations, nameNew, node.EqualsToken, node.Value)
Else
Return node
End If
End Function
Public Overrides Function VisitXmlBracketedName(node As XmlBracketedNameSyntax) As VisualBasicSyntaxNode
Dim anyChanges As Boolean = False
Dim saveOptions = _options
_options._parentKind = SyntaxKind.XmlBracketedName
_options._triviaCheck = TriviaCheck.ProhibitTrailingTrivia
Dim lessThanToken = DirectCast(VisitSyntaxToken(node.LessThanToken), PunctuationSyntax)
If node.LessThanToken IsNot lessThanToken Then anyChanges = True
Dim name As XmlNodeSyntax = DirectCast(Visit(node.Name), XmlNodeSyntax)
If node.Name IsNot name Then anyChanges = True
_options._triviaCheck = TriviaCheck.ProhibitLeadingTrivia
Dim greaterThanToken = DirectCast(VisitSyntaxToken(node.GreaterThanToken), PunctuationSyntax)
If node.GreaterThanToken IsNot greaterThanToken Then anyChanges = True
_options = saveOptions
If anyChanges Then
Return InternalSyntaxFactory.XmlBracketedName(lessThanToken, DirectCast(name, XmlNameSyntax), greaterThanToken)
Else
Return node
End If
End Function
Public Overrides Function VisitXmlName(node As XmlNameSyntax) As VisualBasicSyntaxNode
Dim anyChanges As Boolean = False
Dim prefix As XmlPrefixSyntax = DirectCast(Visit(node.Prefix), XmlPrefixSyntax)
If node.Prefix IsNot prefix Then anyChanges = True
Dim localName As XmlNameTokenSyntax
Dim saveOptions = _options
' Prohibit trivia depending on parent context
Select Case _options._parentKind
Case SyntaxKind.XmlAttribute,
SyntaxKind.XmlCrefAttribute,
SyntaxKind.XmlNameAttribute
If node.Prefix IsNot Nothing Then
_options._triviaCheck = TriviaCheck.ProhibitLeadingTrivia
Else
_options._triviaCheck = TriviaCheck.None
End If
Case SyntaxKind.XmlBracketedName
_options._triviaCheck = TriviaCheck.ProhibitLeadingTrivia Or TriviaCheck.ProhibitTrailingTrivia
Case Else
_options._triviaCheck = TriviaCheck.ProhibitLeadingTrivia
End Select
If _options._triviaCheck <> TriviaCheck.None Then
localName = DirectCast(VisitSyntaxToken(node.LocalName), XmlNameTokenSyntax)
If node.LocalName IsNot localName Then anyChanges = True
Else
localName = node.LocalName
End If
_options = saveOptions
If anyChanges Then
Return New XmlNameSyntax(node.Kind, node.GetDiagnostics, node.GetAnnotations, prefix, localName)
Else
Return node
End If
End Function
Public Overrides Function VisitXmlPrefix(node As XmlPrefixSyntax) As VisualBasicSyntaxNode
Dim anyChanges As Boolean = False
' Prohibit trailing trivia if prefix is an attribute name and both leading and trailing trivia if prefix is an element name
Dim saveOptions = _options
_options._triviaCheck = If(_options._parentKind = SyntaxKind.XmlAttribute, TriviaCheck.ProhibitTrailingTrivia, TriviaCheck.ProhibitLeadingTrivia Or TriviaCheck.ProhibitTrailingTrivia)
Dim name = DirectCast(VisitSyntaxToken(node.Name), XmlNameTokenSyntax)
If node.Name IsNot name Then anyChanges = True
' Prohibit both leading and trailing trivia around the ':'
_options._triviaCheck = TriviaCheck.ProhibitLeadingTrivia Or TriviaCheck.ProhibitTrailingTrivia
Dim colon As PunctuationSyntax = DirectCast(VisitSyntaxToken(node.ColonToken), PunctuationSyntax)
If node.ColonToken IsNot colon Then anyChanges = True
_options = saveOptions
If anyChanges Then
Return New XmlPrefixSyntax(node.Kind, node.GetDiagnostics, node.GetAnnotations, name, colon)
Else
Return node
End If
End Function
Public Overrides Function VisitSyntaxToken(token As SyntaxToken) As SyntaxToken
If token Is Nothing Then
Return Nothing
End If
Dim anyChanges As Boolean = False
Dim leadingTrivia As GreenNode = Nothing
Dim trailingTrivia As GreenNode = Nothing
' For whitespace checking, only look at '<', '</', <%= and ':' tokens.
' i.e.
' < a >
' <a :b>
' <a: b>
' </ a>
' <<%=
Select Case token.Kind
Case SyntaxKind.XmlNameToken,
SyntaxKind.XmlKeyword,
SyntaxKind.LessThanToken,
SyntaxKind.LessThanSlashToken,
SyntaxKind.LessThanQuestionToken,
SyntaxKind.LessThanPercentEqualsToken,
SyntaxKind.ColonToken
leadingTrivia = token.GetLeadingTrivia
If (_options._triviaCheck And TriviaCheck.ProhibitLeadingTrivia) = TriviaCheck.ProhibitLeadingTrivia Then
Dim newleadingTrivia = VisitList(New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(leadingTrivia)).Node
If newleadingTrivia IsNot leadingTrivia Then
anyChanges = True
leadingTrivia = newleadingTrivia
End If
End If
trailingTrivia = token.GetTrailingTrivia
If (_options._triviaCheck And TriviaCheck.ProhibitTrailingTrivia) = TriviaCheck.ProhibitTrailingTrivia Then
Dim newTrailingTrivia = VisitList(New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(trailingTrivia)).Node
If newTrailingTrivia IsNot trailingTrivia Then
anyChanges = True
trailingTrivia = newTrailingTrivia
End If
End If
End Select
If anyChanges Then
Select Case token.Kind
Case SyntaxKind.XmlNameToken
Dim node = DirectCast(token, XmlNameTokenSyntax)
Return New XmlNameTokenSyntax(node.Kind, node.GetDiagnostics, node.GetAnnotations, node.Text, leadingTrivia, trailingTrivia, node.PossibleKeywordKind)
Case SyntaxKind.XmlKeyword
Dim node = DirectCast(token, KeywordSyntax)
Return New KeywordSyntax(node.Kind, node.GetDiagnostics, node.GetAnnotations, node.Text, leadingTrivia, trailingTrivia)
Case SyntaxKind.LessThanToken,
SyntaxKind.LessThanSlashToken,
SyntaxKind.LessThanQuestionToken,
SyntaxKind.LessThanPercentEqualsToken,
SyntaxKind.ColonToken
Dim node = DirectCast(token, PunctuationSyntax)
Return New PunctuationSyntax(node.Kind, node.GetDiagnostics, node.GetAnnotations, node.Text, leadingTrivia, trailingTrivia)
End Select
End If
Return token
End Function
Public Overrides Function VisitSyntaxTrivia(trivia As SyntaxTrivia) As SyntaxTrivia
If trivia.Kind = SyntaxKind.WhitespaceTrivia OrElse trivia.Kind = SyntaxKind.EndOfLineTrivia Then
Return DirectCast(trivia.AddError(ErrorFactory.ErrorInfo(ERRID.ERR_IllegalXmlWhiteSpace)), SyntaxTrivia)
End If
Return trivia
End Function
End Class
Friend Structure XmlContext
Private ReadOnly _start As XmlElementStartTagSyntax
Private ReadOnly _content As SyntaxListBuilder(Of XmlNodeSyntax)
Private ReadOnly _pool As SyntaxListPool
Public Sub New(pool As SyntaxListPool, start As XmlElementStartTagSyntax)
_pool = pool
_start = start
_content = _pool.Allocate(Of XmlNodeSyntax)()
End Sub
Public Sub Add(xml As XmlNodeSyntax)
_content.Add(xml)
End Sub
Public ReadOnly Property StartElement As XmlElementStartTagSyntax
Get
Return _start
End Get
End Property
Public Function CreateElement(endElement As XmlElementEndTagSyntax) As XmlNodeSyntax
Debug.Assert(endElement IsNot Nothing)
Dim contentList = _content.ToList
_pool.Free(_content)
Return InternalSyntaxFactory.XmlElement(_start, contentList, endElement)
End Function
Public Function CreateElement(endElement As XmlElementEndTagSyntax, diagnostic As DiagnosticInfo) As XmlNodeSyntax
Debug.Assert(endElement IsNot Nothing)
Dim contentList = _content.ToList
_pool.Free(_content)
Return InternalSyntaxFactory.XmlElement(DirectCast(_start.AddError(diagnostic), XmlElementStartTagSyntax), contentList, endElement)
End Function
End Structure
Friend Module XmlContextExtensions
<Extension()>
Friend Sub Push(this As List(Of XmlContext), context As XmlContext)
this.Add(context)
End Sub
<Extension()>
Friend Function Pop(this As List(Of XmlContext)) As XmlContext
Dim last = this.Count - 1
Dim context = this(last)
this.RemoveAt(last)
Return context
End Function
<Extension()>
Friend Function Peek(this As List(Of XmlContext), Optional i As Integer = 0) As XmlContext
Dim last = this.Count - 1
Return this(last - i)
End Function
<Extension()>
Friend Function MatchEndElement(this As List(Of XmlContext), name As XmlNameSyntax) As Integer
Debug.Assert(name Is Nothing OrElse name.Kind = SyntaxKind.XmlName)
Dim last = this.Count - 1
If name Is Nothing Then
' An empty name matches anything
Return last
End If
Dim i = last
Do While i >= 0
Dim context = this(i)
Dim nameExpr = context.StartElement.Name
If nameExpr.Kind = SyntaxKind.XmlName Then
Dim startName = DirectCast(nameExpr, XmlNameSyntax)
If startName.LocalName.Text = name.LocalName.Text Then
Dim startPrefix = startName.Prefix
Dim endPrefix = name.Prefix
If startPrefix Is endPrefix Then
Exit Do
End If
If startPrefix IsNot Nothing AndAlso endPrefix IsNot Nothing Then
If startPrefix.Name.Text = endPrefix.Name.Text Then
Exit Do
End If
End If
End If
End If
i -= 1
Loop
Return i
End Function
End Module
End Namespace
|
AmadeusW/roslyn
|
src/Compilers/VisualBasic/Portable/Parser/ParseXml.vb
|
Visual Basic
|
apache-2.0
| 118,406
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Option Strict On
Option Explicit On
Imports System
Imports System.Collections
Imports System.Collections.Specialized
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Globalization
Imports System.Security
Imports System.Text
Imports Microsoft.VisualBasic.CompilerServices
#If PLATFORM_WINDOWS Then
Imports Microsoft.VisualBasic.CompilerServices.NativeMethods
Imports Microsoft.VisualBasic.CompilerServices.NativeTypes
#End If
Imports ExUtils = Microsoft.VisualBasic.CompilerServices.ExceptionUtils
Namespace Microsoft.VisualBasic.FileIO
''' <summary>
''' This class represents the file system on a computer. It allows browsing the existing drives, special directories;
''' and also contains some commonly use methods for IO tasks.
''' </summary>
Public Class FileSystem
''' <summary>
''' Return the names of all available drives on the computer.
''' </summary>
''' <value>A ReadOnlyCollection(Of DriveInfo) containing all the current drives' names.</value>
Public Shared ReadOnly Property Drives() As ObjectModel.ReadOnlyCollection(Of System.IO.DriveInfo)
Get
' NOTE: Don't cache the collection since it may change without us knowing.
' The performance hit will be small since it's a small collection.
Dim DriveInfoCollection As New ObjectModel.Collection(Of System.IO.DriveInfo)
For Each DriveInfo As System.IO.DriveInfo In IO.DriveInfo.GetDrives()
DriveInfoCollection.Add(DriveInfo)
Next
Return New ObjectModel.ReadOnlyCollection(Of System.IO.DriveInfo)(DriveInfoCollection)
End Get
End Property
''' <summary>
''' Get or set the current working directory.
''' </summary>
''' <value>A String containing the path to the directory.</value>
Public Shared Property CurrentDirectory() As String
Get
Return NormalizePath(IO.Directory.GetCurrentDirectory())
End Get
Set(ByVal value As String)
IO.Directory.SetCurrentDirectory(value)
End Set
End Property
''' <summary>
''' Combines two path strings by adding a path separator.
''' </summary>
''' <param name="baseDirectory">The first part of the path.</param>
''' <param name="relativePath">The second part of the path, must be a relative path.</param>
''' <returns>A String contains the combined path.</returns>
Public Shared Function CombinePath(ByVal baseDirectory As String, ByVal relativePath As String) As String
If baseDirectory = "" Then
Throw ExUtils.GetArgumentNullException("baseDirectory", SR.General_ArgumentEmptyOrNothing_Name, "baseDirectory")
End If
If relativePath = "" Then
Return baseDirectory
End If
baseDirectory = IO.Path.GetFullPath(baseDirectory) ' Throw exceptions if BaseDirectoryPath is invalid.
Return NormalizePath(IO.Path.Combine(baseDirectory, relativePath))
End Function
''' <summary>
''' Determines whether the given path refers to an existing directory on disk.
''' </summary>
''' <param name="directory">The path to verify.</param>
''' <returns>True if DirectoryPath refers to an existing directory. Otherwise, False.</returns>
Public Shared Function DirectoryExists(ByVal directory As String) As Boolean
Return IO.Directory.Exists(directory)
End Function
''' <summary>
''' Determines whether the given path refers to an existing file on disk.
''' </summary>
''' <param name="file">The path to verify.</param>
''' <returns>True if FilePath refers to an existing file on disk. Otherwise, False.</returns>
Public Shared Function FileExists(ByVal file As String) As Boolean
If Not String.IsNullOrEmpty(file) AndAlso
(file.EndsWith(IO.Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) Or
file.EndsWith(IO.Path.AltDirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) Then
Return False
End If
Return IO.File.Exists(file)
End Function
''' <summary>
''' Find files in the given folder that contain the given text.
''' </summary>
''' <param name="directory">The folder path to start from.</param>
''' <param name="containsText">The text to be found in file.</param>
''' <param name="ignoreCase">True to ignore case. Otherwise, False.</param>
''' <param name="searchType">SearchAllSubDirectories to find recursively. Otherwise, SearchTopLevelOnly.</param>
''' <returns>A string array containing the files that match the search condition.</returns>
Public Shared Function FindInFiles(ByVal directory As String,
ByVal containsText As String, ByVal ignoreCase As Boolean, ByVal searchType As SearchOption) As ObjectModel.ReadOnlyCollection(Of String)
Return FindInFiles(directory, containsText, ignoreCase, searchType, Nothing)
End Function
''' <summary>
''' Find files in the given folder that contain the given text.
''' </summary>
''' <param name="directory">The folder path to start from.</param>
''' <param name="containsText">The text to be found in file.</param>
''' <param name="ignoreCase">True to ignore case. Otherwise, False.</param>
''' <param name="searchType">SearchAllSubDirectories to find recursively. Otherwise, SearchTopLevelOnly.</param>
''' <param name="fileWildcards">The search patterns to use for the file name ("*.*")</param>
''' <returns>A string array containing the files that match the search condition.</returns>
''' <exception cref="System.ArgumentNullException">If one of the pattern is Null, Empty or all-spaces string.</exception>
Public Shared Function FindInFiles(ByVal directory As String, ByVal containsText As String, ByVal ignoreCase As Boolean,
ByVal searchType As SearchOption, ByVal ParamArray fileWildcards() As String) As ObjectModel.ReadOnlyCollection(Of String)
' Find the files with matching name.
Dim NameMatchFiles As ObjectModel.ReadOnlyCollection(Of String) = FindFilesOrDirectories(
FileOrDirectory.File, directory, searchType, fileWildcards)
' Find the files containing the given text.
If containsText <> "" Then
Dim ContainTextFiles As New ObjectModel.Collection(Of String)
For Each FilePath As String In NameMatchFiles
If (FileContainsText(FilePath, containsText, ignoreCase)) Then
ContainTextFiles.Add(FilePath)
End If
Next
Return New ObjectModel.ReadOnlyCollection(Of String)(ContainTextFiles)
Else
Return NameMatchFiles
End If
End Function
''' <summary>
''' Return the paths of sub directories found directly under a directory.
''' </summary>
''' <param name="directory">The directory to find the sub directories inside.</param>
''' <returns>A ReadOnlyCollection(Of String) containing the matched directories' paths.</returns>
Public Shared Function GetDirectories(ByVal directory As String) As ObjectModel.ReadOnlyCollection(Of String)
Return FindFilesOrDirectories(FileOrDirectory.Directory, directory, SearchOption.SearchTopLevelOnly, Nothing)
End Function
''' <summary>
''' Return the paths of sub directories found under a directory with the specified name patterns.
''' </summary>
''' <param name="directory">The directory to find the sub directories inside.</param>
''' <param name="searchType">SearchAllSubDirectories to find recursively. Otherwise, SearchTopLevelOnly.</param>
''' <param name="wildcards">The wildcards for the file name, for example "*.bmp", "*.txt"</param>
''' <returns>A ReadOnlyCollection(Of String) containing the matched directories' paths.</returns>
Public Shared Function GetDirectories(ByVal directory As String, ByVal searchType As SearchOption,
ByVal ParamArray wildcards() As String) As ObjectModel.ReadOnlyCollection(Of String)
Return FindFilesOrDirectories(FileOrDirectory.Directory, directory, searchType, wildcards)
End Function
''' <summary>
''' Returns the information object about the specified directory.
''' </summary>
''' <param name="directory">The path to the directory.</param>
''' <returns>A DirectoryInfo object containing the information about the specified directory.</returns>
Public Shared Function GetDirectoryInfo(ByVal directory As String) As System.IO.DirectoryInfo
Return New System.IO.DirectoryInfo(directory)
End Function
''' <summary>
''' Return the information about the specified drive.
''' </summary>
''' <param name="drive">The path to the drive.</param>
''' <returns>A DriveInfo object containing the information about the specified drive.</returns>
Public Shared Function GetDriveInfo(ByVal drive As String) As System.IO.DriveInfo
Return New System.IO.DriveInfo(drive)
End Function
''' <summary>
''' Returns the information about the specified file.
''' </summary>
''' <param name="file">The path to the file.</param>
''' <returns>A FileInfo object containing the information about the specified file.</returns>
Public Shared Function GetFileInfo(ByVal file As String) As System.IO.FileInfo
file = NormalizeFilePath(file, "file")
Return New System.IO.FileInfo(file)
End Function
''' <summary>
''' Return an unordered collection of file paths found directly under a directory.
''' </summary>
''' <param name="directory">The directory to find the files inside.</param>
''' <returns>A ReadOnlyCollection(Of String) containing the matched files' paths.</returns>
Public Shared Function GetFiles(ByVal directory As String) As ObjectModel.ReadOnlyCollection(Of String)
Return FindFilesOrDirectories(FileOrDirectory.File, directory, SearchOption.SearchTopLevelOnly, Nothing)
End Function
''' <summary>
''' Return an unordered collection of file paths found under a directory with the specified name patterns and containing the specified text.
''' </summary>
''' <param name="directory">The directory to find the files inside.</param>
''' <param name="searchType">SearchAllSubDirectories to find recursively. Otherwise, SearchTopLevelOnly.</param>
''' <param name="wildcards">The wildcards for the file name, for example "*.bmp", "*.txt"</param>
''' <returns>A ReadOnlyCollection(Of String) containing the matched files' paths.</returns>
Public Shared Function GetFiles(ByVal directory As String, ByVal searchType As SearchOption,
ByVal ParamArray wildcards() As String) As ObjectModel.ReadOnlyCollection(Of String)
Return FindFilesOrDirectories(FileOrDirectory.File, directory, searchType, wildcards)
End Function
''' <summary>
''' Return the name (and extension) from the given path string.
''' </summary>
''' <param name="path">The path string from which to obtain the file name (and extension).</param>
''' <returns>A String containing the name of the file or directory.</returns>
''' <exception cref="ArgumentException">path contains one or more of the invalid characters defined in InvalidPathChars.</exception>
Public Shared Function GetName(ByVal path As String) As String
Return IO.Path.GetFileName(path)
End Function
''' <summary>
''' Returns the parent directory's path from a specified path.
''' </summary>
''' <param name="path">The path to a file or directory, this can be absolute or relative.</param>
''' <returns>
''' The path to the parent directory of that file or directory (whether absolute or relative depends on the input),
''' or an empty string if Path is a root directory.
''' </returns>
''' <exception cref="IO.Path.GetFullPath">See IO.Path.GetFullPath: If path is an invalid path.</exception>
''' <remarks>
''' The path will be normalized (for example: C:\Dir1////\\\Dir2 will become C:\Dir1\Dir2)
''' but will not be resolved (for example: C:\Dir1\Dir2\..\Dir3 WILL NOT become C:\Dir1\Dir3). Use CombinePath.
''' </remarks>
Public Shared Function GetParentPath(ByVal path As String) As String
' Call IO.Path.GetFullPath to handle exception cases. Don't use the full path returned.
IO.Path.GetFullPath(path)
If IsRoot(path) Then
Throw ExUtils.GetArgumentExceptionWithArgName("path", SR.IO_GetParentPathIsRoot_Path, path)
Else
Return IO.Path.GetDirectoryName(path.TrimEnd(
IO.Path.DirectorySeparatorChar, IO.Path.AltDirectorySeparatorChar))
End If
End Function
''' <summary>
''' Create a uniquely named zero-byte temporary file on disk and return the full path to that file.
''' </summary>
''' <returns>A String containing the name of the temporary file.</returns>
Public Shared Function GetTempFileName() As String
Return System.IO.Path.GetTempFileName()
End Function
''' <summary>
''' Return an instance of a TextFieldParser for the given file.
''' </summary>
''' <param name="file">The path to the file to parse.</param>
''' <returns>An instance of a TextFieldParser.</returns>
Public Shared Function OpenTextFieldParser(ByVal file As String) As TextFieldParser
Return New TextFieldParser(file)
End Function
''' <summary>
''' Return an instance of a TextFieldParser for the given file using the given delimiters.
''' </summary>
''' <param name="file">The path to the file to parse.</param>
''' <param name="delimiters">A list of delimiters.</param>
''' <returns>An instance of a TextFieldParser</returns>
Public Shared Function OpenTextFieldParser(ByVal file As String, ByVal ParamArray delimiters As String()) As TextFieldParser
Dim Result As New TextFieldParser(file)
Result.SetDelimiters(delimiters)
Result.TextFieldType = FieldType.Delimited
Return Result
End Function
''' <summary>
''' Return an instance of a TextFieldParser for the given file using the given field widths.
''' </summary>
''' <param name="file">The path to the file to parse.</param>
''' <param name="fieldWidths">A list of field widths.</param>
''' <returns>An instance of a TextFieldParser</returns>
Public Shared Function OpenTextFieldParser(ByVal file As String, ByVal ParamArray fieldWidths As Integer()) As TextFieldParser
Dim Result As New TextFieldParser(file)
Result.SetFieldWidths(fieldWidths)
Result.TextFieldType = FieldType.FixedWidth
Return Result
End Function
''' <summary>
''' Return a StreamReader for reading the given file using UTF-8 as preferred encoding.
''' </summary>
''' <param name="file">The file to open the StreamReader on.</param>
''' <returns>An instance of System.IO.StreamReader opened on the file (with FileShare.Read).</returns>
Public Shared Function OpenTextFileReader(ByVal file As String) As IO.StreamReader
Return OpenTextFileReader(file, Encoding.UTF8)
End Function
''' <summary>
''' Return a StreamReader for reading the given file using the given encoding as preferred encoding.
''' </summary>
''' <param name="file">The file to open the StreamReader on.</param>
''' <param name="Encoding">The preferred encoding that will be used if the encoding of the file could not be detected.</param>
''' <returns>An instance of System.IO.StreamReader opened on the file (with FileShare.Read).</returns>
Public Shared Function OpenTextFileReader(ByVal file As String, ByVal encoding As Encoding) As IO.StreamReader
file = NormalizeFilePath(file, "file")
Return New IO.StreamReader(file, encoding, detectEncodingFromByteOrderMarks:=True)
End Function
''' <summary>
''' Return a StreamWriter for writing to the given file using UTF-8 encoding.
''' </summary>
''' <param name="file">The file to write to.</param>
''' <param name="Append">True to append to the content of the file. False to overwrite the content of the file.</param>
''' <returns>An instance of StreamWriter opened on the file (with FileShare.Read).</returns>
Public Shared Function OpenTextFileWriter(ByVal file As String, ByVal append As Boolean) As IO.StreamWriter
Return OpenTextFileWriter(file, append, Encoding.UTF8)
End Function
''' <summary>
''' Return a StreamWriter for writing to the given file using the given encoding.
''' </summary>
''' <param name="file">The file to write to.</param>
''' <param name="Append">True to append to the content of the file. False to overwrite the content of the file.</param>
''' <param name="Encoding">The encoding to use to write to the file.</param>
''' <returns>An instance of StreamWriter opened on the file (with FileShare.Read).</returns>
Public Shared Function OpenTextFileWriter(ByVal file As String, ByVal append As Boolean,
ByVal encoding As Encoding) As IO.StreamWriter
file = NormalizeFilePath(file, "file")
Return New IO.StreamWriter(file, append, encoding)
End Function
''' <summary>
''' Read the whole content of a file into a byte array.
''' </summary>
''' <param name="file">The path to the file.</param>
''' <returns>A byte array contains the content of the file.</returns>
''' <exception cref="IO.IOException">If the length of the file is larger than Integer.MaxValue (~2GB).</exception>
''' <exception cref="IO.FileStream">See FileStream constructor and Read: for other exceptions.</exception>
Public Shared Function ReadAllBytes(ByVal file As String) As Byte()
Return IO.File.ReadAllBytes(file)
End Function
''' <summary>
''' Read the whole content of a text file into a string using UTF-8 encoding.
''' </summary>
''' <param name="file">The path to the text file.</param>
''' <returns>A String contains the content of the given file.</returns>
''' <exception cref="IO.StreamReader">See StreamReader constructor and ReadToEnd.</exception>
Public Shared Function ReadAllText(ByVal file As String) As String
Return IO.File.ReadAllText(file)
End Function
''' <summary>
''' Read the whole content of a text file into a string using the given encoding.
''' </summary>
''' <param name="file">The path to the text file.</param>
''' <param name="encoding">The character encoding to use if the encoding was not detected.</param>
''' <returns>A String contains the content of the given file.</returns>
''' <exception cref="IO.StreamReader">See StreamReader constructor and ReadToEnd.</exception>
Public Shared Function ReadAllText(ByVal file As String, ByVal encoding As Encoding) As String
Return IO.File.ReadAllText(file, encoding)
End Function
''' <summary>
''' Copy an existing directory to a new directory,
''' throwing exception if there are existing files with the same name.
''' </summary>
''' <param name="sourceDirectoryName">The path to the source directory, can be relative or absolute.</param>
''' <param name="destinationDirectoryName">The path to the target directory, can be relative or absolute. Parent directory will always be created.</param>
Public Shared Sub CopyDirectory(ByVal sourceDirectoryName As String, ByVal destinationDirectoryName As String)
CopyOrMoveDirectory(CopyOrMove.Copy, sourceDirectoryName, destinationDirectoryName,
overwrite:=False, UIOptionInternal.NoUI, UICancelOption.ThrowException)
End Sub
''' <summary>
''' Copy an existing directory to a new directory,
''' overwriting existing files with the same name if specified.
''' </summary>
''' <param name="sourceDirectoryName">The path to the source directory, can be relative or absolute.</param>
''' <param name="destinationDirectoryName">The path to the target directory, can be relative or absolute. Parent directory will always be created.</param>
''' <param name="overwrite">True to overwrite existing files with the same name. Otherwise False.</param>
Public Shared Sub CopyDirectory(ByVal sourceDirectoryName As String, ByVal destinationDirectoryName As String, ByVal overwrite As Boolean)
CopyOrMoveDirectory(CopyOrMove.Copy, sourceDirectoryName, destinationDirectoryName,
overwrite, UIOptionInternal.NoUI, UICancelOption.ThrowException)
End Sub
''' <summary>
''' Copy an existing directory to a new directory,
''' displaying progress dialog and confirmation dialogs if specified,
''' throwing exception if user cancels the operation (only applies if displaying progress dialog and confirmation dialogs).
''' </summary>
''' <param name="sourceDirectoryName">The path to the source directory, can be relative or absolute.</param>
''' <param name="destinationDirectoryName">The path to the target directory, can be relative or absolute. Parent directory will always be created.</param>
''' <param name="showUI">ShowDialogs to display progress and confirmation dialogs. Otherwise HideDialogs.</param>
Public Shared Sub CopyDirectory(ByVal sourceDirectoryName As String, ByVal destinationDirectoryName As String, ByVal showUI As UIOption)
CopyOrMoveDirectory(CopyOrMove.Copy, sourceDirectoryName, destinationDirectoryName,
overwrite:=False, ToUIOptionInternal(showUI), UICancelOption.ThrowException)
End Sub
''' <summary>
''' Copy an existing directory to a new directory,
''' displaying progress dialog and confirmation dialogs if specified,
''' throwing exception if user cancels the operation if specified. (only applies if displaying progress dialog and confirmation dialogs).
''' </summary>
''' <param name="sourceDirectoryName">The path to the source directory, can be relative or absolute.</param>
''' <param name="destinationDirectoryName">The path to the target directory, can be relative or absolute. Parent directory will always be created.</param>
''' <param name="showUI">ShowDialogs to display progress and confirmation dialogs. Otherwise HideDialogs.</param>
''' <param name="onUserCancel">ThrowException to throw exception if user cancels the operation. Otherwise DoNothing.</param>
Public Shared Sub CopyDirectory(ByVal sourceDirectoryName As String, ByVal destinationDirectoryName As String, ByVal showUI As UIOption, ByVal onUserCancel As UICancelOption)
CopyOrMoveDirectory(CopyOrMove.Copy, sourceDirectoryName, destinationDirectoryName,
overwrite:=False, ToUIOptionInternal(showUI), onUserCancel)
End Sub
''' <summary>
''' Copy an existing file to a new file. Overwriting a file of the same name is not allowed.
''' </summary>
''' <param name="sourceFileName">The path to the source file, can be relative or absolute.</param>
''' <param name="destinationFileName">The path to the destination file, can be relative or absolute. Parent directory will always be created.</param>
Public Shared Sub CopyFile(ByVal sourceFileName As String, ByVal destinationFileName As String)
CopyOrMoveFile(CopyOrMove.Copy, sourceFileName, destinationFileName,
overwrite:=False, UIOptionInternal.NoUI, UICancelOption.ThrowException)
End Sub
''' <summary>
''' Copy an existing file to a new file. Overwriting a file of the same name if specified.
''' </summary>
''' <param name="sourceFileName">The path to the source file, can be relative or absolute.</param>
''' <param name="destinationFileName">The path to the destination file, can be relative or absolute. Parent directory will always be created.</param>
''' <param name="overwrite">True to overwrite existing file with the same name. Otherwise False.</param>
Public Shared Sub CopyFile(ByVal sourceFileName As String, ByVal destinationFileName As String, ByVal overwrite As Boolean)
CopyOrMoveFile(CopyOrMove.Copy, sourceFileName, destinationFileName,
overwrite, UIOptionInternal.NoUI, UICancelOption.ThrowException)
End Sub
''' <summary>
''' Copy an existing file to a new file,
''' displaying progress dialog and confirmation dialogs if specified,
''' will throw exception if user cancels the operation.
''' </summary>
''' <param name="sourceFileName">The path to the source file, can be relative or absolute.</param>
''' <param name="destinationFileName">The path to the destination file, can be relative or absolute. Parent directory will always be created.</param>
''' <param name="showUI">ShowDialogs to display progress and confirmation dialogs. Otherwise HideDialogs.</param>
Public Shared Sub CopyFile(ByVal sourceFileName As String, ByVal destinationFileName As String, ByVal showUI As UIOption)
CopyOrMoveFile(CopyOrMove.Copy, sourceFileName, destinationFileName,
overwrite:=False, ToUIOptionInternal(showUI), UICancelOption.ThrowException)
End Sub
''' <summary>
''' Copy an existing file to a new file,
''' displaying progress dialog and confirmation dialogs if specified,
''' will throw exception if user cancels the operation if specified.
''' </summary>
''' <param name="sourceFileName">The path to the source file, can be relative or absolute.</param>
''' <param name="destinationFileName">The path to the destination file, can be relative or absolute. Parent directory will always be created.</param>
''' <param name="showUI">ShowDialogs to display progress and confirmation dialogs. Otherwise HideDialogs.</param>
''' <param name="onUserCancel">ThrowException to throw exception if user cancels the operation. Otherwise DoNothing.</param>
''' <remarks>onUserCancel will be ignored if showUI = HideDialogs.</remarks>
Public Shared Sub CopyFile(ByVal sourceFileName As String, ByVal destinationFileName As String, ByVal showUI As UIOption, ByVal onUserCancel As UICancelOption)
CopyOrMoveFile(CopyOrMove.Copy, sourceFileName, destinationFileName,
overwrite:=False, ToUIOptionInternal(showUI), onUserCancel)
End Sub
''' <summary>
''' Creates a directory from the given path (including all parent directories).
''' </summary>
''' <param name="directory">The path to create the directory at.</param>
Public Shared Sub CreateDirectory(ByVal directory As String)
' Get the full path. GetFullPath will throw if invalid path.
directory = IO.Path.GetFullPath(directory)
If IO.File.Exists(directory) Then
Throw ExUtils.GetIOException(SR.IO_FileExists_Path, directory)
End If
' CreateDirectory will create the full structure and not throw if directory exists.
System.IO.Directory.CreateDirectory(directory)
End Sub
''' <summary>
''' Delete the given directory, with options to recursively delete.
''' </summary>
''' <param name="directory">The path to the directory.</param>
''' <param name="onDirectoryNotEmpty">DeleteAllContents to delete everything. ThrowIfDirectoryNonEmpty to throw exception if the directory is not empty.</param>
Public Shared Sub DeleteDirectory(ByVal directory As String, ByVal onDirectoryNotEmpty As DeleteDirectoryOption)
DeleteDirectoryInternal(directory, onDirectoryNotEmpty,
UIOptionInternal.NoUI, RecycleOption.DeletePermanently, UICancelOption.ThrowException)
End Sub
''' <summary>
''' Delete the given directory, with options to recursively delete, show progress UI, send file to Recycle Bin; throwing exception if user cancels.
''' </summary>
''' <param name="directory">The path to the directory.</param>
''' <param name="showUI">True to shows progress window. Otherwise, False.</param>
''' <param name="recycle">SendToRecycleBin to delete to Recycle Bin. Otherwise DeletePermanently.</param>
Public Shared Sub DeleteDirectory(ByVal directory As String, ByVal showUI As UIOption, ByVal recycle As RecycleOption)
DeleteDirectoryInternal(directory, DeleteDirectoryOption.DeleteAllContents,
ToUIOptionInternal(showUI), recycle, UICancelOption.ThrowException)
End Sub
''' <summary>
''' Delete the given directory, with options to recursively delete, show progress UI, send file to Recycle Bin, and whether to throw exception if user cancels.
''' </summary>
''' <param name="directory">The path to the directory.</param>
''' <param name="showUI">ShowDialogs to display progress and confirmation dialogs. Otherwise HideDialogs.</param>
''' <param name="recycle">SendToRecycleBin to delete to Recycle Bin. Otherwise DeletePermanently.</param>
''' <param name="onUserCancel">Throw exception when user cancel the UI operation or not.</param>
Public Shared Sub DeleteDirectory(ByVal directory As String,
ByVal showUI As UIOption, ByVal recycle As RecycleOption, ByVal onUserCancel As UICancelOption)
DeleteDirectoryInternal(directory, DeleteDirectoryOption.DeleteAllContents,
ToUIOptionInternal(showUI), recycle, onUserCancel)
End Sub
''' <summary>
''' Delete the given file.
''' </summary>
''' <param name="file">The path to the file.</param>
Public Shared Sub DeleteFile(ByVal file As String)
DeleteFileInternal(file, UIOptionInternal.NoUI, RecycleOption.DeletePermanently, UICancelOption.ThrowException)
End Sub
''' <summary>
''' Delete the given file, with options to show progress UI, delete to recycle bin.
''' </summary>
''' <param name="file">The path to the file.</param>
''' <param name="showUI">ShowDialogs to display progress and confirmation dialogs. Otherwise HideDialogs.</param>
''' <param name="recycle">SendToRecycleBin to delete to Recycle Bin. Otherwise DeletePermanently.</param>
Public Shared Sub DeleteFile(ByVal file As String, ByVal showUI As UIOption, ByVal recycle As RecycleOption)
DeleteFileInternal(file, ToUIOptionInternal(showUI), recycle, UICancelOption.ThrowException)
End Sub
''' <summary>
''' Delete the given file, with options to show progress UI, delete to recycle bin, and whether to throw exception if user cancels.
''' </summary>
''' <param name="file">The path to the file.</param>
''' <param name="showUI">ShowDialogs to display progress and confirmation dialogs. Otherwise HideDialogs.</param>
''' <param name="recycle">SendToRecycleBin to delete to Recycle Bin. Otherwise DeletePermanently.</param>
''' <param name="onUserCancel">Throw exception when user cancel the UI operation or not.</param>
''' <exception cref="IO.Path.GetFullPath">IO.Path.GetFullPath() exceptions: if FilePath is invalid.</exception>
''' <exception cref="IO.FileNotFoundException">if a file does not exist at FilePath</exception>
Public Shared Sub DeleteFile(ByVal file As String, ByVal showUI As UIOption, ByVal recycle As RecycleOption,
ByVal onUserCancel As UICancelOption)
DeleteFileInternal(file, ToUIOptionInternal(showUI), recycle, onUserCancel)
End Sub
''' <summary>
''' Move an existing directory to a new directory,
''' throwing exception if there are existing files with the same name.
''' </summary>
''' <param name="sourceDirectoryName">The path to the source directory, can be relative or absolute.</param>
''' <param name="destinationDirectoryName">The path to the target directory, can be relative or absolute. Parent directory will always be created.</param>
Public Shared Sub MoveDirectory(ByVal sourceDirectoryName As String, ByVal destinationDirectoryName As String)
CopyOrMoveDirectory(CopyOrMove.Move, sourceDirectoryName, destinationDirectoryName,
overwrite:=False, UIOptionInternal.NoUI, UICancelOption.ThrowException)
End Sub
''' <summary>
''' Move an existing directory to a new directory,
''' overwriting existing files with the same name if specified.
''' </summary>
''' <param name="sourceDirectoryName">The path to the source directory, can be relative or absolute.</param>
''' <param name="destinationDirectoryName">The path to the target directory, can be relative or absolute. Parent directory will always be created.</param> ''' <param name="overwrite">True to overwrite existing files with the same name. Otherwise False.</param>
Public Shared Sub MoveDirectory(ByVal sourceDirectoryName As String, ByVal destinationDirectoryName As String, ByVal overwrite As Boolean)
CopyOrMoveDirectory(CopyOrMove.Move, sourceDirectoryName, destinationDirectoryName,
overwrite, UIOptionInternal.NoUI, UICancelOption.ThrowException)
End Sub
''' <summary>
''' Move an existing directory to a new directory,
''' displaying progress dialog and confirmation dialogs if specified,
''' throwing exception if user cancels the operation (only applies if displaying progress dialog and confirmation dialogs).
''' </summary>
''' <param name="sourceDirectoryName">The path to the source directory, can be relative or absolute.</param>
''' <param name="destinationDirectoryName">The path to the target directory, can be relative or absolute. Parent directory will always be created.</param>
''' <param name="showUI">ShowDialogs to display progress and confirmation dialogs. Otherwise HideDialogs.</param>
Public Shared Sub MoveDirectory(ByVal sourceDirectoryName As String, ByVal destinationDirectoryName As String, ByVal showUI As UIOption)
CopyOrMoveDirectory(CopyOrMove.Move, sourceDirectoryName, destinationDirectoryName,
overwrite:=False, ToUIOptionInternal(showUI), UICancelOption.ThrowException)
End Sub
''' <summary>
''' Move an existing directory to a new directory,
''' displaying progress dialog and confirmation dialogs if specified,
''' throwing exception if user cancels the operation if specified. (only applies if displaying progress dialog and confirmation dialogs).
''' </summary>
''' <param name="sourceDirectoryName">The path to the source directory, can be relative or absolute.</param>
''' <param name="destinationDirectoryName">The path to the target directory, can be relative or absolute. Parent directory will always be created.</param>
''' <param name="showUI">ShowDialogs to display progress and confirmation dialogs. Otherwise HideDialogs.</param>
''' <param name="onUserCancel">ThrowException to throw exception if user cancels the operation. Otherwise DoNothing.</param>
Public Shared Sub MoveDirectory(ByVal sourceDirectoryName As String, ByVal destinationDirectoryName As String, ByVal showUI As UIOption, ByVal onUserCancel As UICancelOption)
CopyOrMoveDirectory(CopyOrMove.Move, sourceDirectoryName, destinationDirectoryName,
overwrite:=False, ToUIOptionInternal(showUI), onUserCancel)
End Sub
''' <summary>
''' Move an existing file to a new file. Overwriting a file of the same name is not allowed.
''' </summary>
''' <param name="sourceFileName">The path to the source file, can be relative or absolute.</param>
''' <param name="destinationFileName">The path to the destination file, can be relative or absolute. Parent directory will always be created.</param>
Public Shared Sub MoveFile(ByVal sourceFileName As String, ByVal destinationFileName As String)
CopyOrMoveFile(CopyOrMove.Move, sourceFileName, destinationFileName,
overwrite:=False, UIOptionInternal.NoUI, UICancelOption.ThrowException)
End Sub
''' <summary>
''' Move an existing file to a new file. Overwriting a file of the same name if specified.
''' </summary>
''' <param name="sourceFileName">The path to the source file, can be relative or absolute.</param>
''' <param name="destinationFileName">The path to the destination file, can be relative or absolute. Parent directory will always be created.</param>
''' <param name="overwrite">True to overwrite existing file with the same name. Otherwise False.</param>
Public Shared Sub MoveFile(ByVal sourceFileName As String, ByVal destinationFileName As String, ByVal overwrite As Boolean)
CopyOrMoveFile(CopyOrMove.Move, sourceFileName, destinationFileName,
overwrite, UIOptionInternal.NoUI, UICancelOption.ThrowException)
End Sub
''' <summary>
''' Move an existing file to a new file,
''' displaying progress dialog and confirmation dialogs if specified,
''' will throw exception if user cancels the operation.
''' </summary>
''' <param name="sourceFileName">The path to the source file, can be relative or absolute.</param>
''' <param name="destinationFileName">The path to the destination file, can be relative or absolute. Parent directory will always be created.</param>
''' <param name="showUI">ShowDialogs to display progress and confirmation dialogs. Otherwise HideDialogs.</param>
Public Shared Sub MoveFile(ByVal sourceFileName As String, ByVal destinationFileName As String, ByVal showUI As UIOption)
CopyOrMoveFile(CopyOrMove.Move, sourceFileName, destinationFileName,
overwrite:=False, ToUIOptionInternal(showUI), UICancelOption.ThrowException)
End Sub
''' <summary>
''' Move an existing file to a new file,
''' displaying progress dialog and confirmation dialogs if specified,
''' will throw exception if user cancels the operation if specified.
''' </summary>
''' <param name="sourceFileName">The path to the source file, can be relative or absolute.</param>
''' <param name="destinationFileName">The path to the destination file, can be relative or absolute. Parent directory will always be created.</param>
''' <param name="showUI">ShowDialogs to display progress and confirmation dialogs. Otherwise HideDialogs.</param>
''' <param name="onUserCancel">ThrowException to throw exception if user cancels the operation. Otherwise DoNothing.</param>
''' <remarks>onUserCancel will be ignored if showUI = HideDialogs.</remarks>
Public Shared Sub MoveFile(ByVal sourceFileName As String, ByVal destinationFileName As String, ByVal showUI As UIOption, ByVal onUserCancel As UICancelOption)
CopyOrMoveFile(CopyOrMove.Move, sourceFileName, destinationFileName,
overwrite:=False, ToUIOptionInternal(showUI), onUserCancel)
End Sub
''' <summary>
''' Rename a directory, does not act like a move.
''' </summary>
''' <param name="directory">The path of the directory to be renamed.</param>
''' <param name="newName">The new name to change to. This must not contain path information.</param>
''' <exception cref="IO.Path.GetFullPath">IO.Path.GetFullPath exceptions: If directory is invalid.</exception>
''' <exception cref="System.ArgumentException">If newName is Nothing or Empty String or contains path information.</exception>
''' <exception cref="IO.FileNotFoundException">If directory does not point to an existing directory.</exception>
''' <exception cref="IO.IOException">If directory points to a root directory.
''' Or if there's an existing directory or an existing file with the same name.</exception>
Public Shared Sub RenameDirectory(ByVal directory As String, ByVal newName As String)
' Get the full path. This will handle invalid path exceptions.
directory = IO.Path.GetFullPath(directory)
' Throw if device path.
ThrowIfDevicePath(directory)
' Directory is a root directory. This does not require IO access so it's cheaper up front.
If IsRoot(directory) Then
Throw ExUtils.GetIOException(SR.IO_DirectoryIsRoot_Path, directory)
End If
' Throw if directory does not exist.
If Not IO.Directory.Exists(directory) Then
Throw ExUtils.GetDirectoryNotFoundException(SR.IO_DirectoryNotFound_Path, directory)
End If
' Verify newName is not null.
If newName = "" Then
Throw ExUtils.GetArgumentNullException(
"newName", SR.General_ArgumentEmptyOrNothing_Name, "newName")
End If
' Calculate new path. GetFullPathFromNewName will verify newName is only a name.
Dim FullNewPath As String = GetFullPathFromNewName(GetParentPath(directory), newName, "newName")
Debug.Assert(GetParentPath(FullNewPath).Equals(GetParentPath(directory),
StringComparison.OrdinalIgnoreCase), "Invalid FullNewPath")
' Verify that the new path does not conflict.
EnsurePathNotExist(FullNewPath)
IO.Directory.Move(directory, FullNewPath)
End Sub
''' <summary>
''' Renames a file, does not change the file location.
''' </summary>
''' <param name="file">The path to the file.</param>
''' <param name="newName">The new name to change to. This must not contain path information.</param>
''' <exception cref="IO.Path.GetFullPath">IO.Path.GetFullPath exceptions: If file is invalid.</exception>
''' <exception cref="System.ArgumentException">If newName is Nothing or Empty String or contains path information.</exception>
''' <exception cref="IO.FileNotFoundException">If file does not point to an existing file.</exception>
''' <exception cref="IO.IOException">If there's an existing directory or an existing file with the same name.</exception>
Public Shared Sub RenameFile(ByVal file As String, ByVal newName As String)
' Get the full path. This will handle invalid path exceptions.
file = NormalizeFilePath(file, "file")
' Throw if device path.
ThrowIfDevicePath(file)
' Throw if file does not exist.
If Not IO.File.Exists(file) Then
Throw ExUtils.GetFileNotFoundException(file, SR.IO_FileNotFound_Path, file)
End If
' Verify newName is not null.
If newName = "" Then
Throw ExUtils.GetArgumentNullException(
"newName", SR.General_ArgumentEmptyOrNothing_Name, "newName")
End If
' Calculate new path. GetFullPathFromNewName will verify that newName is only a name.
Dim FullNewPath As String = GetFullPathFromNewName(GetParentPath(file), newName, "newName")
Debug.Assert(GetParentPath(FullNewPath).Equals(GetParentPath(file),
StringComparison.OrdinalIgnoreCase), "Invalid FullNewPath")
' Verify that the new path does not conflict.
EnsurePathNotExist(FullNewPath)
IO.File.Move(file, FullNewPath)
End Sub
''' <summary>
''' Overwrites or appends the specified byte array to the specified file,
''' creating the file if it does not exist.
''' </summary>
''' <param name="file">The path to the file.</param>
''' <param name="data">The byte array to write to the file.</param>
''' <param name="append">True to append the text to the existing content. False to overwrite the existing content.</param>
''' <exception cref="IO.FileStream">See FileStream constructor and Write: For other exceptions.</exception>
Public Shared Sub WriteAllBytes(ByVal file As String, ByVal data() As Byte, ByVal append As Boolean)
' Cannot call through IO.File.WriteAllBytes (since they don't support append)
' so only check for trailing separator
CheckFilePathTrailingSeparator(file, "file")
Dim FileStream As IO.FileStream = Nothing
Try
Dim IOFileMode As IO.FileMode
If append Then
IOFileMode = IO.FileMode.Append
Else
IOFileMode = IO.FileMode.Create ' CreateNew or Truncate.
End If
FileStream = New IO.FileStream(file,
mode:=IOFileMode, access:=IO.FileAccess.Write, share:=IO.FileShare.Read)
FileStream.Write(data, 0, data.Length)
Finally
If Not FileStream Is Nothing Then
FileStream.Close()
End If
End Try
End Sub
''' <summary>
''' Overwrites or appends the given text using UTF-8 encoding to the given file,
''' creating the file if it does not exist.
''' </summary>
''' <param name="file">The path to the file.</param>
''' <param name="text">The text to write to the file.</param>
''' <param name="append">True to append the text to the existing content. False to overwrite the existing content.</param>
''' <exception cref="IO.StreamWriter">See StreamWriter constructor and Write: For other exceptions.</exception>
Public Shared Sub WriteAllText(ByVal file As String, ByVal text As String, ByVal append As Boolean)
WriteAllText(file, text, append, Encoding.UTF8)
End Sub
''' <summary>
''' Overwrites or appends the given text using the given encoding to the given file,
''' creating the file if it does not exist.
''' </summary>
''' <param name="file">The path to the file.</param>
''' <param name="text">The text to write to the file.</param>
''' <param name="append">True to append the text to the existing content. False to overwrite the existing content.</param>
''' <param name="encoding">The encoding to use.</param>
''' <exception cref="IO.StreamWriter">See StreamWriter constructor and Write: For other exceptions.</exception>
Public Shared Sub WriteAllText(ByVal file As String, ByVal text As String, ByVal append As Boolean,
ByVal encoding As Encoding)
'Cannot call through IO.File.WriteAllText (since they don't support: append, prefer current encoding than specified one)
' so only check for trailing separator.
CheckFilePathTrailingSeparator(file, "file")
Dim StreamWriter As IO.StreamWriter = Nothing
Try
' If appending to a file and it exists, attempt to detect the current encoding and use it.
If append AndAlso IO.File.Exists(file) Then
Dim StreamReader As IO.StreamReader = Nothing
Try
StreamReader = New IO.StreamReader(file, encoding, detectEncodingFromByteOrderMarks:=True)
Dim Chars(10 - 1) As Char
StreamReader.Read(Chars, 0, 10) ' Read the next 10 characters to activate auto detect encoding.
encoding = StreamReader.CurrentEncoding ' Set encoding to the detected encoding.
Catch ex As IO.IOException
' Ignore IOException.
Finally
If StreamReader IsNot Nothing Then
StreamReader.Close()
End If
End Try
End If
' StreamWriter uses FileShare.Read by default.
StreamWriter = New IO.StreamWriter(file, append, encoding)
StreamWriter.Write(text)
Finally
If Not StreamWriter Is Nothing Then
StreamWriter.Close()
End If
End Try
End Sub
''' <summary>
''' Normalize the path, but throw exception if the path ends with separator.
''' </summary>
''' <param name="Path">The input path.</param>
''' <param name="ParamName">The parameter name to include in the exception if one is raised.</param>
''' <returns>The normalized path.</returns>
Friend Shared Function NormalizeFilePath(ByVal Path As String, ByVal ParamName As String) As String
CheckFilePathTrailingSeparator(Path, ParamName)
Return NormalizePath(Path)
End Function
''' <summary>
''' Get full path, get long format, and remove any pending separator.
''' </summary>
''' <param name="Path">The path to be normalized.</param>
''' <returns>The normalized path.</returns>
''' <exception cref="IO.Path.GetFullPath">See IO.Path.GetFullPath for possible exceptions.</exception>
''' <remarks>Keep this function since we might change the implementation / behavior later.</remarks>
Friend Shared Function NormalizePath(ByVal Path As String) As String
Return GetLongPath(RemoveEndingSeparator(IO.Path.GetFullPath(Path)))
End Function
''' <summary>
''' Throw ArgumentException if the file path ends with a separator.
''' </summary>
''' <param name="path">The file path.</param>
''' <param name="paramName">The parameter name to include in ArgumentException.</param>
Friend Shared Sub CheckFilePathTrailingSeparator(ByVal path As String, ByVal paramName As String)
If path = "" Then ' Check for argument null
Throw ExUtils.GetArgumentNullException(paramName)
End If
If path.EndsWith(IO.Path.DirectorySeparatorChar, StringComparison.Ordinal) Or
path.EndsWith(IO.Path.AltDirectorySeparatorChar, StringComparison.Ordinal) Then
Throw ExUtils.GetArgumentExceptionWithArgName(paramName, SR.IO_FilePathException)
End If
End Sub
''' <summary>
''' Add an array of string into a Generic Collection of String.
''' </summary>
Private Shared Sub AddToStringCollection(ByVal StrCollection As ObjectModel.Collection(Of String), ByVal StrArray() As String)
' CONSIDER: : BCL to support adding an array of string directly into a generic string collection?
Debug.Assert(StrCollection IsNot Nothing, "StrCollection is NULL")
If StrArray IsNot Nothing Then
For Each Str As String In StrArray
If Not StrCollection.Contains(Str) Then
StrCollection.Add(Str)
End If
Next
End If
End Sub
''' <summary>
''' Handles exception cases and calls shell or framework to copy / move directory.
''' </summary>
''' <param name="operation">select Copy or Move operation.</param>
''' <param name="sourceDirectoryName">the source directory</param>
''' <param name="destinationDirectoryName">the target directory</param>
''' <param name="overwrite">overwrite files</param>
''' <param name="showUI">calls into shell to copy / move directory</param>
''' <param name="onUserCancel">throw exception if user cancels the operation or not.</param>
''' <exception cref="IO.Path.GetFullPath">IO.Path.GetFullPath exceptions: If SourceDirectoryPath or TargetDirectoryPath is invalid.
''' Or if NewName contains path information.</exception>
''' <exception cref="System.ArgumentException">If Source or Target is device path (\\.\).</exception>
''' <exception cref="IO.DirectoryNotFoundException">Source directory does not exist as a directory.</exception>
''' <exception cref="System.ArgumentNullException">If NewName = "".</exception>
''' <exception cref="IO.IOException">SourceDirectoryPath and TargetDirectoryPath are the same.
''' IOException: Target directory is under source directory - cyclic operation.
''' IOException: TargetDirectoryPath points to an existing file.
''' IOException: Some files and directories can not be copied.</exception>
Private Shared Sub CopyOrMoveDirectory(ByVal operation As CopyOrMove,
ByVal sourceDirectoryName As String, ByVal destinationDirectoryName As String,
ByVal overwrite As Boolean, ByVal showUI As UIOptionInternal, ByVal onUserCancel As UICancelOption)
Debug.Assert(System.Enum.IsDefined(GetType(CopyOrMove), operation), "Invalid Operation")
' Verify enums.
VerifyUICancelOption("onUserCancel", onUserCancel)
' Get the full path and remove any separators at the end. This will handle invalid path exceptions.
' IMPORTANT: sourceDirectoryName and destinationDirectoryName should be used for exception throwing ONLY.
Dim SourceDirectoryFullPath As String = NormalizePath(sourceDirectoryName)
Dim TargetDirectoryFullPath As String = NormalizePath(destinationDirectoryName)
' Throw if device path.
ThrowIfDevicePath(SourceDirectoryFullPath)
ThrowIfDevicePath(TargetDirectoryFullPath)
' Throw if source directory does not exist.
If Not IO.Directory.Exists(SourceDirectoryFullPath) Then
Throw ExUtils.GetDirectoryNotFoundException(SR.IO_DirectoryNotFound_Path, sourceDirectoryName)
End If
' Throw if source directory is a root directory.
If IsRoot(SourceDirectoryFullPath) Then
Throw ExUtils.GetIOException(SR.IO_DirectoryIsRoot_Path, sourceDirectoryName)
End If
' Throw if there's a file at TargetDirectoryFullPath.
If IO.File.Exists(TargetDirectoryFullPath) Then
Throw ExUtils.GetIOException(SR.IO_FileExists_Path, destinationDirectoryName)
End If
' Throw if source and target are the same.
If TargetDirectoryFullPath.Equals(SourceDirectoryFullPath, StringComparison.OrdinalIgnoreCase) Then
Throw ExUtils.GetIOException(SR.IO_SourceEqualsTargetDirectory)
End If
' Throw if cyclic operation (target is under source). A sample case is
' Source = C:\Dir1\Dir2
' Target = C:\Dir1\Dir2\Dir3\Dir4.
' NOTE: Do not use StartWith since it does not allow specifying InvariantCultureIgnoreCase.
If TargetDirectoryFullPath.Length > SourceDirectoryFullPath.Length AndAlso
TargetDirectoryFullPath.Substring(0, SourceDirectoryFullPath.Length).Equals(
SourceDirectoryFullPath, StringComparison.OrdinalIgnoreCase) Then
Debug.Assert(TargetDirectoryFullPath.Length > SourceDirectoryFullPath.Length, "Target path should be longer")
If TargetDirectoryFullPath.Chars(SourceDirectoryFullPath.Length) = IO.Path.DirectorySeparatorChar Then
Throw ExUtils.GetInvalidOperationException(SR.IO_CyclicOperation)
End If
End If
' NOTE: Decision to create target directory is different for Shell and Framework call.
If showUI <> UIOptionInternal.NoUI AndAlso Environment.UserInteractive Then
ShellCopyOrMove(operation, FileOrDirectory.Directory, SourceDirectoryFullPath, TargetDirectoryFullPath, showUI, onUserCancel)
Else
' Otherwise, copy the directory using System.IO.
FxCopyOrMoveDirectory(operation, SourceDirectoryFullPath, TargetDirectoryFullPath, overwrite)
End If
End Sub
''' <summary>
''' Copies or moves the directory using Framework.
''' </summary>
''' <param name="operation">Copy or Move.</param>
''' <param name="sourceDirectoryPath">Source path - must be full path.</param>
''' <param name="targetDirectoryPath">Target path - must be full path.</param>
''' <param name="Overwrite">True to overwrite the files. Otherwise, False.</param>
''' <exception cref="IO.IOException">Some files or directories cannot be copied or moved.</exception>
Private Shared Sub FxCopyOrMoveDirectory(ByVal operation As CopyOrMove,
ByVal sourceDirectoryPath As String, ByVal targetDirectoryPath As String, ByVal overwrite As Boolean)
Debug.Assert(System.Enum.IsDefined(GetType(CopyOrMove), operation), "Invalid Operation")
Debug.Assert(sourceDirectoryPath <> "" And IO.Path.IsPathRooted(sourceDirectoryPath), "Invalid Source")
Debug.Assert(targetDirectoryPath <> "" And IO.Path.IsPathRooted(targetDirectoryPath), "Invalid Target")
' Special case for moving: If target directory does not exist, AND both directories are on same drive,
' use IO.Directory.Move for performance gain (not copying).
If operation = CopyOrMove.Move And Not IO.Directory.Exists(targetDirectoryPath) And
IsOnSameDrive(sourceDirectoryPath, targetDirectoryPath) Then
' Create the target's parent. IO.Directory.CreateDirectory won't throw if it exists.
IO.Directory.CreateDirectory(GetParentPath(targetDirectoryPath))
Try
IO.Directory.Move(sourceDirectoryPath, targetDirectoryPath)
Exit Sub
Catch ex As IO.IOException
Catch ex As UnauthorizedAccessException
' Ignore IO.Directory.Move specific exceptions here. Try to do as much as possible later.
End Try
End If
' Create the target, create the root node, and call the recursive function.
System.IO.Directory.CreateDirectory(targetDirectoryPath)
Debug.Assert(IO.Directory.Exists(targetDirectoryPath), "Should be able to create Target Directory")
Dim SourceDirectoryNode As New DirectoryNode(sourceDirectoryPath, targetDirectoryPath)
Dim Exceptions As New ListDictionary
CopyOrMoveDirectoryNode(operation, SourceDirectoryNode, overwrite, Exceptions)
' Throw the final exception if there were exceptions during copy / move.
If Exceptions.Count > 0 Then
Dim IOException As New IO.IOException(Utils.GetResourceString(SR.IO_CopyMoveRecursive))
For Each Entry As DictionaryEntry In Exceptions
IOException.Data.Add(Entry.Key, Entry.Value)
Next
Throw IOException
End If
End Sub
''' <summary>
''' Given a directory node, copy or move that directory tree.
''' </summary>
''' <param name="Operation">Specify whether to move or copy the directories.</param>
''' <param name="SourceDirectoryNode">The source node. Only copy / move directories contained in the source node.</param>
''' <param name="Overwrite">True to overwrite sub-files. Otherwise False.</param>
''' <param name="Exceptions">The list of accumulated exceptions while doing the copy / move</param>
Private Shared Sub CopyOrMoveDirectoryNode(ByVal Operation As CopyOrMove,
ByVal SourceDirectoryNode As DirectoryNode, ByVal Overwrite As Boolean, ByVal Exceptions As ListDictionary)
Debug.Assert(System.Enum.IsDefined(GetType(CopyOrMove), Operation), "Invalid Operation")
Debug.Assert(Exceptions IsNot Nothing, "Null exception list")
Debug.Assert(SourceDirectoryNode IsNot Nothing, "Null source node")
' Create the target directory. If we encounter known exceptions, add the exception to the exception list and quit.
Try
If Not IO.Directory.Exists(SourceDirectoryNode.TargetPath) Then
IO.Directory.CreateDirectory(SourceDirectoryNode.TargetPath)
End If
Catch ex As Exception
If (TypeOf ex Is IO.IOException OrElse TypeOf ex Is UnauthorizedAccessException OrElse
TypeOf ex Is IO.DirectoryNotFoundException OrElse TypeOf ex Is NotSupportedException OrElse
TypeOf ex Is SecurityException) Then
Exceptions.Add(SourceDirectoryNode.Path, ex.Message)
Exit Sub
Else
Throw
End If
End Try
Debug.Assert(IO.Directory.Exists(SourceDirectoryNode.TargetPath), "TargetPath should have existed or exception should be thrown")
If Not IO.Directory.Exists(SourceDirectoryNode.TargetPath) Then
Exceptions.Add(SourceDirectoryNode.TargetPath, ExUtils.GetDirectoryNotFoundException(SR.IO_DirectoryNotFound_Path, SourceDirectoryNode.TargetPath))
Exit Sub
End If
' Copy / move all the files under this directory to target directory.
For Each SubFilePath As String In IO.Directory.GetFiles(SourceDirectoryNode.Path)
Try
CopyOrMoveFile(Operation, SubFilePath, IO.Path.Combine(SourceDirectoryNode.TargetPath, IO.Path.GetFileName(SubFilePath)),
Overwrite, UIOptionInternal.NoUI, UICancelOption.ThrowException)
Catch ex As Exception
If (TypeOf ex Is IO.IOException OrElse TypeOf ex Is UnauthorizedAccessException OrElse
TypeOf ex Is SecurityException OrElse TypeOf ex Is NotSupportedException) Then
Exceptions.Add(SubFilePath, ex.Message)
Else
Throw
End If
End Try
Next
' Copy / move all the sub directories under this directory to target directory.
For Each SubDirectoryNode As DirectoryNode In SourceDirectoryNode.SubDirs
CopyOrMoveDirectoryNode(Operation, SubDirectoryNode, Overwrite, Exceptions)
Next
' If this is a move, try to delete the current directory.
' Using recursive:=False since we expect the content should be emptied by now.
If Operation = CopyOrMove.Move Then
Try
IO.Directory.Delete(SourceDirectoryNode.Path, recursive:=False)
Catch ex As Exception
If (TypeOf ex Is IO.IOException OrElse TypeOf ex Is UnauthorizedAccessException OrElse
TypeOf ex Is SecurityException OrElse TypeOf ex Is IO.DirectoryNotFoundException) Then
Exceptions.Add(SourceDirectoryNode.Path, ex.Message)
Else
Throw
End If
End Try
End If
End Sub
''' <summary>
''' Copies or move files. This will be called from CopyFile and MoveFile.
''' </summary>
''' <param name="Operation">Copy or Move.</param>
''' <param name="sourceFileName">Path to source file.</param>
''' <param name="destinationFileName">Path to target file.</param>
''' <param name="Overwrite">True = Overwrite. This flag will be ignored if ShowUI.</param>
''' <param name="ShowUI">Hide or show the UIDialogs.</param>
''' <param name="OnUserCancel">Throw exception in case user cancel using UI or not.</param>
''' <exception cref="IO.Path.GetFullPath">
''' IO.Path.GetFullPath exceptions: If SourceFilePath or TargetFilePath is invalid.
''' ArgumentException: If Source or Target is device path (\\.\).
''' FileNotFoundException: If SourceFilePath does not exist (including pointing to an existing directory).
''' IOException: If TargetFilePath points to an existing directory.
''' ArgumentNullException: If NewName = "".
''' ArgumentException: If NewName contains path information.
''' </exception>
Private Shared Sub CopyOrMoveFile(ByVal operation As CopyOrMove,
ByVal sourceFileName As String, ByVal destinationFileName As String,
ByVal overwrite As Boolean, ByVal showUI As UIOptionInternal, ByVal onUserCancel As UICancelOption
)
Debug.Assert(System.Enum.IsDefined(GetType(CopyOrMove), operation), "Invalid Operation")
' Verify enums.
VerifyUICancelOption("onUserCancel", onUserCancel)
' Get the full path and remove any separator at the end. This will handle invalid path exceptions.
' IMPORTANT: sourceFileName and destinationFileName should be used for throwing user exceptions ONLY.
Dim sourceFileFullPath As String = NormalizeFilePath(sourceFileName, "sourceFileName")
Dim destinationFileFullPath As String = NormalizeFilePath(destinationFileName, "destinationFileName")
' Throw if device path.
ThrowIfDevicePath(sourceFileFullPath)
ThrowIfDevicePath(destinationFileFullPath)
' Throw exception if SourceFilePath does not exist.
If Not IO.File.Exists(sourceFileFullPath) Then
Throw ExUtils.GetFileNotFoundException(sourceFileName, SR.IO_FileNotFound_Path, sourceFileName)
End If
' Throw exception if TargetFilePath is an existing directory.
If IO.Directory.Exists(destinationFileFullPath) Then
Throw ExUtils.GetIOException(SR.IO_DirectoryExists_Path, destinationFileName)
End If
' Always create the target's parent directory(s).
IO.Directory.CreateDirectory(GetParentPath(destinationFileFullPath))
' If ShowUI, attempt to call Shell function.
If showUI <> UIOptionInternal.NoUI AndAlso System.Environment.UserInteractive Then
ShellCopyOrMove(operation, FileOrDirectory.File, sourceFileFullPath, destinationFileFullPath, showUI, onUserCancel)
Exit Sub
End If
' Use Framework.
If operation = CopyOrMove.Copy OrElse
sourceFileFullPath.Equals(destinationFileFullPath, StringComparison.OrdinalIgnoreCase) Then
' Call IO.File.Copy if this is a copy operation.
' In addition, if sourceFileFullPath is the same as destinationFileFullPath,
' IO.File.Copy will throw, IO.File.Move will not.
' Whatever overwrite flag is passed in, IO.File.Move should throw exception,
' so call IO.File.Copy to get the exception as well.
IO.File.Copy(sourceFileFullPath, destinationFileFullPath, overwrite)
Else ' MoveFile with support for overwrite flag.
If overwrite Then ' User wants to overwrite destination.
' Why not checking for destination existence: user may not have read permission / ACL,
' but have write permission / ACL thus cannot see but can delete / overwrite destination.
If Environment.OSVersion.Platform = PlatformID.Win32NT Then ' Platforms supporting MoveFileEx.
#If PLATFORM_WINDOWS Then
Try
Dim succeed As Boolean = NativeMethods.MoveFileEx(
sourceFileFullPath, destinationFileFullPath, m_MOVEFILEEX_FLAGS)
' GetLastWin32Error has to be close to PInvoke call. FxCop rule.
If Not succeed Then
ThrowWinIOError(System.Runtime.InteropServices.Marshal.GetLastWin32Error())
End If
Catch
Throw
End Try
#End If
Else ' Non Windows
' IO.File.Delete will not throw if destinationFileFullPath does not exist
' (user may not have permission to discover this, but have permission to overwrite),
' so always delete the destination.
IO.File.Delete(destinationFileFullPath)
IO.File.Move(sourceFileFullPath, destinationFileFullPath)
End If
Else ' Overwrite = False, call Framework.
IO.File.Move(sourceFileFullPath, destinationFileFullPath)
End If ' Overwrite
End If
End Sub
''' <summary>
''' Delete the given directory, with options to recursively delete, show progress UI, send file to Recycle Bin, and whether to throw exception if user cancels.
''' </summary>
''' <param name="directory">The path to the directory.</param>
''' <param name="onDirectoryNotEmpty">DeleteAllContents to delete everything. ThrowIfDirectoryNonEmpty to throw exception if the directory is not empty.</param>
''' <param name="showUI">ShowDialogs to display progress and confirmation dialogs. Otherwise HideDialogs.</param>
''' <param name="recycle">SendToRecycleBin to delete to Recycle Bin. Otherwise DeletePermanently.</param>
''' <param name="onUserCancel">Throw exception when user cancel the UI operation or not.</param>
''' <remarks>If user wants shell features, onDirectoryNotEmpty is ignored.</remarks>
Private Shared Sub DeleteDirectoryInternal(ByVal directory As String, ByVal onDirectoryNotEmpty As DeleteDirectoryOption,
ByVal showUI As UIOptionInternal, ByVal recycle As RecycleOption, ByVal onUserCancel As UICancelOption)
VerifyDeleteDirectoryOption("onDirectoryNotEmpty", onDirectoryNotEmpty)
VerifyRecycleOption("recycle", recycle)
VerifyUICancelOption("onUserCancel", onUserCancel)
' Get the full path. This will handle invalid paths exceptions.
Dim directoryFullPath As String = IO.Path.GetFullPath(directory)
' Throw if device path.
ThrowIfDevicePath(directoryFullPath)
If Not IO.Directory.Exists(directoryFullPath) Then
Throw ExUtils.GetDirectoryNotFoundException(SR.IO_DirectoryNotFound_Path, directory)
End If
If IsRoot(directoryFullPath) Then
Throw ExUtils.GetIOException(SR.IO_DirectoryIsRoot_Path, directory)
End If
' If user want shell features (Progress, Recycle Bin), call shell operation.
' We don't need to consider onDirectoryNotEmpty here.
If (showUI <> UIOptionInternal.NoUI) AndAlso Environment.UserInteractive Then
ShellDelete(directoryFullPath, showUI, recycle, onUserCancel, FileOrDirectory.Directory)
Exit Sub
End If
' Otherwise, call Framework's method.
IO.Directory.Delete(directoryFullPath, onDirectoryNotEmpty = DeleteDirectoryOption.DeleteAllContents)
End Sub
''' <summary>
''' Delete the given file, with options to show progress UI, send file to Recycle Bin, throw exception if user cancels.
''' </summary>
''' <param name="file">the path to the file</param>
''' <param name="showUI">AllDialogs, OnlyErrorDialogs, or NoUI</param>
''' <param name="recycle">DeletePermanently or SendToRecycleBin</param>
''' <param name="onUserCancel">DoNothing or ThrowException</param>
''' <remarks></remarks>
Private Shared Sub DeleteFileInternal(ByVal file As String, ByVal showUI As UIOptionInternal, ByVal recycle As RecycleOption,
ByVal onUserCancel As UICancelOption)
' Verify enums
VerifyRecycleOption("recycle", recycle)
VerifyUICancelOption("onUserCancel", onUserCancel)
' Get the full path. This will handle invalid path exceptions.
Dim fileFullPath As String = NormalizeFilePath(file, "file")
' Throw if device path.
ThrowIfDevicePath(fileFullPath)
If Not IO.File.Exists(fileFullPath) Then
Throw ExUtils.GetFileNotFoundException(file, SR.IO_FileNotFound_Path, file)
End If
' If user want shell features (Progress, Recycle Bin), call shell operation.
If (showUI <> UIOptionInternal.NoUI) AndAlso Environment.UserInteractive Then
ShellDelete(fileFullPath, showUI, recycle, onUserCancel, FileOrDirectory.File)
Exit Sub
End If
IO.File.Delete(fileFullPath)
End Sub
''' <summary>
''' Verify that a path does not refer to an existing directory or file. Throw exception otherwise.
''' </summary>
''' <param name="Path">The path to verify.</param>
''' <remarks>This is used for RenameFile and RenameDirectory.</remarks>
Private Shared Sub EnsurePathNotExist(ByVal Path As String)
If IO.File.Exists(Path) Then
Throw ExUtils.GetIOException(SR.IO_FileExists_Path, Path)
End If
If IO.Directory.Exists(Path) Then
Throw ExUtils.GetIOException(SR.IO_DirectoryExists_Path, Path)
End If
End Sub
''' <summary>
''' Determines if the given file in the path contains the given text.
''' </summary>
''' <param name="FilePath">The file to check for.</param>
''' <param name="Text">The text to search for.</param>
''' <returns>True if the file contains the text. Otherwise False.</returns>
Private Shared Function FileContainsText(ByVal FilePath As String, ByVal Text As String, ByVal IgnoreCase As Boolean) _
As Boolean
Debug.Assert(FilePath <> "" AndAlso IO.Path.IsPathRooted(FilePath), FilePath)
Debug.Assert(Text <> "", "Empty text")
' To support different encoding (UTF-8, ASCII).
' Read the file in byte, then use Decoder classes to get a string from those bytes and compare.
' Decoder class maintains state between the conversion, allowing it to correctly decode
' byte sequences that span adjacent blocks. (sources\ndp\clr\src\BCL\System\Text\Decoder.cs).
Dim DEFAULT_BUFFER_SIZE As Integer = 1024 ' default buffer size to read each time.
Dim FileStream As IO.FileStream = Nothing
Try
' Open the file with ReadWrite share, least possibility to fail.
FileStream = New IO.FileStream(FilePath, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.ReadWrite)
' Read in a byte buffer with default size, then open a StreamReader to detect the encoding of the file.
Dim DetectedEncoding As System.Text.Encoding = System.Text.Encoding.Default ' Use Default encoding as the fall back.
Dim ByteBuffer(DEFAULT_BUFFER_SIZE - 1) As Byte
Dim ByteCount As Integer = 0
ByteCount = FileStream.Read(ByteBuffer, 0, ByteBuffer.Length)
If ByteCount > 0 Then
' Only take the number of bytes returned to avoid false detection.
Dim MemoryStream As New IO.MemoryStream(ByteBuffer, 0, ByteCount)
Dim StreamReader As New IO.StreamReader(MemoryStream, DetectedEncoding, detectEncodingFromByteOrderMarks:=True)
StreamReader.ReadLine()
DetectedEncoding = StreamReader.CurrentEncoding
End If
' Calculate the real buffer size to read in each time to ensure read in at least a character array
' as long as or longer than the given text.
' 1. Calculate the maximum number of bytes required to encode the given text in the detected encoding.
' 2. If it's larger than DEFAULT_BUFFER_SIZE, use it. Otherwise, use DEFAULT_BUFFER_SIZE.
Dim MaxByteDetectedEncoding As Integer = DetectedEncoding.GetMaxByteCount(Text.Length)
Dim BufferSize As Integer = Math.Max(MaxByteDetectedEncoding, DEFAULT_BUFFER_SIZE)
' Dim up the byte buffer and the search helpers (See TextSearchHelper).
Dim SearchHelper As New TextSearchHelper(DetectedEncoding, Text, IgnoreCase)
' If the buffer size is larger than DEFAULT_BUFFER_SIZE, read more from the file stream
' to fill up the byte buffer.
If BufferSize > DEFAULT_BUFFER_SIZE Then
ReDim Preserve ByteBuffer(BufferSize - 1)
' Read maximum ByteBuffer.Length - ByteCount (from the initial read) bytes from the stream
' into the ByteBuffer, starting at ByteCount position.
Dim AdditionalByteCount As Integer = FileStream.Read(ByteBuffer, ByteCount, ByteBuffer.Length - ByteCount)
ByteCount += AdditionalByteCount ' The total byte count now is ByteCount + AdditionalByteCount
Debug.Assert(ByteCount <= ByteBuffer.Length)
End If
' Start the search and read until end of file.
Do
If ByteCount > 0 Then
If SearchHelper.IsTextFound(ByteBuffer, ByteCount) Then
Return True
End If
End If
ByteCount = FileStream.Read(ByteBuffer, 0, ByteBuffer.Length)
Loop While (ByteCount > 0)
Return False
Catch ex As Exception
' We don't expect the following types of exceptions, so we'll re-throw it together with Yukon's exceptions.
Debug.Assert(Not (TypeOf ex Is ArgumentException Or TypeOf ex Is ArgumentOutOfRangeException Or
TypeOf ex Is ArgumentNullException Or TypeOf ex Is IO.DirectoryNotFoundException Or
TypeOf ex Is IO.FileNotFoundException Or TypeOf ex Is ObjectDisposedException Or
TypeOf ex Is RankException Or TypeOf ex Is ArrayTypeMismatchException Or
TypeOf ex Is InvalidCastException), "Unexpected exception: " & ex.ToString())
' These exceptions may happen and we'll return False here.
If TypeOf ex Is IO.IOException Or
TypeOf ex Is NotSupportedException Or
TypeOf ex Is SecurityException Or
TypeOf ex Is UnauthorizedAccessException Then
Return False
Else
' Re-throw Yukon's exceptions, PathTooLong exception (linked directory) and others.
Throw
End If
Finally
If FileStream IsNot Nothing Then
FileStream.Close()
End If
End Try
End Function
''' <summary>
''' Find files or directories in a directory and return them in a string collection.
''' </summary>
''' <param name="FileOrDirectory">Specify to search for file or directory.</param>
''' <param name="directory">The directory path to start from.</param>
''' <param name="searchType">SearchAllSubDirectories to find recursively. Otherwise, SearchTopLevelOnly.</param>
''' <param name="wildcards">The search patterns to use for the file name ("*.*")</param>
''' <returns>A ReadOnlyCollection(Of String) containing the files that match the search condition.</returns>
''' <exception cref="System.ArgumentException">ArgumentNullException: If one of the pattern is Null, Empty or all-spaces string.</exception>
Private Shared Function FindFilesOrDirectories(ByVal FileOrDirectory As FileOrDirectory, ByVal directory As String,
ByVal searchType As SearchOption, ByVal wildcards() As String) As ObjectModel.ReadOnlyCollection(Of String)
Dim Results As New ObjectModel.Collection(Of String)
FindFilesOrDirectories(FileOrDirectory, directory, searchType, wildcards, Results)
Return New ObjectModel.ReadOnlyCollection(Of String)(Results)
End Function
''' <summary>
''' Find files or directories in a directory and return them in a string collection.
''' </summary>
''' <param name="FileOrDirectory">Specify to search for file or directory.</param>
''' <param name="directory">The directory path to start from.</param>
''' <param name="searchType">SearchAllSubDirectories to find recursively. Otherwise, SearchTopLevelOnly.</param>
''' <param name="wildcards">The search patterns to use for the file name ("*.*")</param>
''' <param name="Results">A ReadOnlyCollection(Of String) containing the files that match the search condition.</param>
Private Shared Sub FindFilesOrDirectories(ByVal FileOrDirectory As FileOrDirectory, ByVal directory As String,
ByVal searchType As SearchOption, ByVal wildcards() As String, ByVal Results As ObjectModel.Collection(Of String))
Debug.Assert(Results IsNot Nothing, "Results is NULL")
' Verify enums.
VerifySearchOption("searchType", searchType)
directory = NormalizePath(directory)
' Verify wild cards. Only TrimEnd since empty space is allowed at the start of file / directory name.
If wildcards IsNot Nothing Then
For Each wildcard As String In wildcards
' Throw if empty string or Nothing.
If wildcard.TrimEnd() = "" Then
Throw ExUtils.GetArgumentNullException("wildcards", SR.IO_GetFiles_NullPattern)
End If
Next
End If
' Search for files / directories directly under given directory (based on wildcards).
If wildcards Is Nothing OrElse wildcards.Length = 0 Then
AddToStringCollection(Results, FindPaths(FileOrDirectory, directory, Nothing))
Else
For Each wildcard As String In wildcards
AddToStringCollection(Results, FindPaths(FileOrDirectory, directory, wildcard))
Next
End If
' Search in sub directories if specified.
If searchType = SearchOption.SearchAllSubDirectories Then
For Each SubDirectoryPath As String In IO.Directory.GetDirectories(directory)
FindFilesOrDirectories(FileOrDirectory, SubDirectoryPath, searchType, wildcards, Results)
Next
End If
End Sub
''' <summary>
''' Given a directory, a pattern, find the files or directories directly under the given directory that match the pattern.
''' </summary>
''' <param name="FileOrDirectory">Specify whether to find files or directories.</param>
''' <param name="directory">The directory to look under.</param>
''' <param name="wildCard">*.bmp, *.txt, ... Nothing to search for every thing.</param>
''' <returns>An array of String containing the paths found.</returns>
Private Shared Function FindPaths(ByVal FileOrDirectory As FileOrDirectory, ByVal directory As String, ByVal wildCard As String) As String()
If FileOrDirectory = FileSystem.FileOrDirectory.Directory Then
If wildCard = "" Then
Return IO.Directory.GetDirectories(directory)
Else
Return IO.Directory.GetDirectories(directory, wildCard)
End If
Else
If wildCard = "" Then
Return IO.Directory.GetFiles(directory)
Else
Return IO.Directory.GetFiles(directory, wildCard)
End If
End If
End Function
''' <summary>
''' Returns the fullpath from a directory path and a new name. Throws exception if the new name contains path information.
''' </summary>
''' <param name="Path">The directory path.</param>
''' <param name="NewName">The new name to combine to the directory path.</param>
''' <param name="ArgumentName">The argument name to throw in the exception.</param>
''' <returns>A String contains the full path.</returns>
''' <remarks>This function is used for CopyFile, RenameFile and RenameDirectory.</remarks>
Private Shared Function GetFullPathFromNewName(ByVal Path As String,
ByVal NewName As String, ByVal ArgumentName As String) As String
Debug.Assert(Path <> "" AndAlso IO.Path.IsPathRooted(Path), Path)
Debug.Assert(Path.Equals(IO.Path.GetFullPath(Path)), Path)
Debug.Assert(NewName <> "", "Null NewName")
Debug.Assert(ArgumentName <> "", "Null argument name")
' In copy file, rename file and rename directory, the new name must be a name only.
' Enforce that by combine the path, normalize it, then compare the new parent directory with the old parent directory.
' These two directories must be the same.
' Throw exception if NewName contains any separator characters.
If NewName.IndexOfAny(m_SeparatorChars) >= 0 Then
Throw ExUtils.GetArgumentExceptionWithArgName(ArgumentName, SR.IO_ArgumentIsPath_Name_Path, ArgumentName, NewName)
End If
' Call GetFullPath again to catch invalid characters in NewName.
Dim FullPath As String = RemoveEndingSeparator(IO.Path.GetFullPath(IO.Path.Combine(Path, NewName)))
' If the new parent directory path does not equal the parent directory passed in, throw exception.
' Use this to check for cases like "..", checking for separators will not block this case.
If Not GetParentPath(FullPath).Equals(Path, StringComparison.OrdinalIgnoreCase) Then
Throw ExUtils.GetArgumentExceptionWithArgName(ArgumentName, SR.IO_ArgumentIsPath_Name_Path, ArgumentName, NewName)
End If
Return FullPath
End Function
''' <summary>
''' Returns the given path in long format (v.s 8.3 format) if the path exists.
''' </summary>
''' <param name="FullPath">The path to resolve to long format.</param>
''' <returns>The given path in long format if the path exists.</returns>
''' <remarks>
''' GetLongPathName is a PInvoke call and requires unmanaged code permission.
''' Use DirectoryInfo.GetFiles and GetDirectories (which call FindFirstFile) so that we always have permission.
'''</remarks>
Private Shared Function GetLongPath(ByVal FullPath As String) As String
Debug.Assert(Not FullPath = "" AndAlso IO.Path.IsPathRooted(FullPath), "Must be full path")
Try
' If root path, return itself. UNC path do not recognize 8.3 format in root path, so this is fine.
If IsRoot(FullPath) Then
Return FullPath
End If
' DirectoryInfo.GetFiles and GetDirectories call FindFirstFile which resolves 8.3 path.
' Get the DirectoryInfo (user must have code permission or access permission).
Dim DInfo As New IO.DirectoryInfo(GetParentPath(FullPath))
If IO.File.Exists(FullPath) Then
Debug.Assert(DInfo.GetFiles(IO.Path.GetFileName(FullPath)).Length = 1, "Must found exactly 1")
Return DInfo.GetFiles(IO.Path.GetFileName(FullPath))(0).FullName
ElseIf IO.Directory.Exists(FullPath) Then
Debug.Assert(DInfo.GetDirectories(IO.Path.GetFileName(FullPath)).Length = 1,
"Must found exactly 1")
Return DInfo.GetDirectories(IO.Path.GetFileName(FullPath))(0).FullName
Else
Return FullPath ' Path does not exist, cannot resolve.
End If
Catch ex As Exception
' Ignore these type of exceptions and return FullPath. These type of exceptions should either be caught by calling functions
' or indicate that caller does not have enough permission and should get back the 8.3 path.
If TypeOf ex Is ArgumentException OrElse
TypeOf ex Is ArgumentNullException OrElse
TypeOf ex Is IO.PathTooLongException OrElse
TypeOf ex Is NotSupportedException OrElse
TypeOf ex Is IO.DirectoryNotFoundException OrElse
TypeOf ex Is SecurityException OrElse
TypeOf ex Is UnauthorizedAccessException Then
Debug.Assert(Not (TypeOf ex Is ArgumentException OrElse
TypeOf ex Is ArgumentNullException OrElse
TypeOf ex Is IO.PathTooLongException OrElse
TypeOf ex Is NotSupportedException), "These exceptions should be caught above")
Return FullPath
Else
Throw
End If
End Try
End Function
''' <summary>
''' Checks to see if the two paths is on the same drive.
''' </summary>
''' <param name="Path1"></param>
''' <param name="Path2"></param>
''' <returns>True if the 2 paths is on the same drive. False otherwise.</returns>
''' <remarks>Just a string comparison.</remarks>
Private Shared Function IsOnSameDrive(ByVal Path1 As String, ByVal Path2 As String) As Boolean
' Remove any separators at the end for the same reason in IsRoot.
Path1 = Path1.TrimEnd(IO.Path.DirectorySeparatorChar, IO.Path.AltDirectorySeparatorChar)
Path2 = Path2.TrimEnd(IO.Path.DirectorySeparatorChar, IO.Path.AltDirectorySeparatorChar)
Return String.Compare(IO.Path.GetPathRoot(Path1), IO.Path.GetPathRoot(Path2),
StringComparison.OrdinalIgnoreCase) = 0
End Function
''' <summary>
''' Checks if the full path is a root path.
''' </summary>
''' <param name="Path">The path to check.</param>
''' <returns>True if FullPath is a root path, False otherwise.</returns>
''' <remarks>
''' IO.Path.GetPathRoot: C: -> C:, C:\ -> C:\, \\machine\share -> \\machine\share,
''' BUT \\machine\share\ -> \\machine\share (No separator here).
''' Therefore, remove any separators at the end to have correct result.
''' </remarks>
Private Shared Function IsRoot(ByVal Path As String) As Boolean
' This function accepts a relative path since GetParentPath will call this,
' and GetParentPath accept relative paths.
If Not IO.Path.IsPathRooted(Path) Then
Return False
End If
Path = Path.TrimEnd(IO.Path.DirectorySeparatorChar, IO.Path.AltDirectorySeparatorChar)
Return String.Compare(Path, IO.Path.GetPathRoot(Path),
StringComparison.OrdinalIgnoreCase) = 0
End Function
''' <summary>
''' Removes all directory separators at the end of a path.
''' </summary>
''' <param name="Path">a full or relative path.</param>
''' <returns>If Path is a root path, the same value. Otherwise, removes any directory separators at the end.</returns>
''' <remarks>We decided not to return path with separators at the end.</remarks>
Private Shared Function RemoveEndingSeparator(ByVal Path As String) As String
If IO.Path.IsPathRooted(Path) Then
' If the path is rooted, attempt to check if it is a root path.
' Note: IO.Path.GetPathRoot: C: -> C:, C:\ -> C:\, \\myshare\mydir -> \\myshare\mydir
' BUT \\myshare\mydir\ -> \\myshare\mydir!!! This function will remove the ending separator of
' \\myshare\mydir\ as well. Do not use IsRoot here.
If Path.Equals(IO.Path.GetPathRoot(Path), StringComparison.OrdinalIgnoreCase) Then
Return Path
End If
End If
' Otherwise, remove all separators at the end.
Return Path.TrimEnd(IO.Path.DirectorySeparatorChar, IO.Path.AltDirectorySeparatorChar)
End Function
''' <summary>
''' Sets relevant flags on the SHFILEOPSTRUCT and calls SHFileOperation to copy move file / directory.
''' </summary>
''' <param name="Operation">Copy or move.</param>
''' <param name="TargetType">The target is a file or directory?</param>
''' <param name="FullSourcePath">Full path to source directory / file.</param>
''' <param name="FullTargetPath">Full path to target directory / file.</param>
''' <param name="ShowUI">Show all dialogs or just the error dialogs.</param>
''' <param name="OnUserCancel">Throw exception or ignore if user cancels the operation.</param>
''' <remarks>
''' Copy/MoveFile will call this directly. Copy/MoveDirectory will call ShellCopyOrMoveDirectory first
''' to change the path if needed.
''' </remarks>
Private Shared Sub ShellCopyOrMove(ByVal Operation As CopyOrMove, ByVal TargetType As FileOrDirectory,
ByVal FullSourcePath As String, ByVal FullTargetPath As String, ByVal ShowUI As UIOptionInternal, ByVal OnUserCancel As UICancelOption)
Debug.Assert(System.Enum.IsDefined(GetType(CopyOrMove), Operation))
Debug.Assert(System.Enum.IsDefined(GetType(FileOrDirectory), TargetType))
Debug.Assert(FullSourcePath <> "" And IO.Path.IsPathRooted(FullSourcePath), "Invalid FullSourcePath")
Debug.Assert(FullTargetPath <> "" And IO.Path.IsPathRooted(FullTargetPath), "Invalid FullTargetPath")
Debug.Assert(ShowUI <> UIOptionInternal.NoUI, "Why call ShellDelete if ShowUI is NoUI???")
#If PLATFORM_WINDOWS Then
' Set operation type.
Dim OperationType As SHFileOperationType
If Operation = CopyOrMove.Copy Then
OperationType = SHFileOperationType.FO_COPY
Else
OperationType = SHFileOperationType.FO_MOVE
End If
' Set operation details.
Dim OperationFlags As ShFileOperationFlags = GetOperationFlags(ShowUI)
' *** Special action for Directory only. ***
Dim FinalSourcePath As String = FullSourcePath
If TargetType = FileOrDirectory.Directory Then
' Shell behavior: If target does not exist, create target and copy / move source CONTENT into target.
' If target exists, copy / move source into target.
' To have our behavior:
' If target does not exist, create target parent (or shell will throw) and call ShellCopyOrMove.
' If target exists, attach "\*" to FullSourcePath and call ShellCopyOrMove.
' In case of Move, since moving the directory, just create the target parent.
If IO.Directory.Exists(FullTargetPath) Then
FinalSourcePath = IO.Path.Combine(FullSourcePath, "*")
Else
IO.Directory.CreateDirectory(GetParentPath(FullTargetPath))
End If
End If
' Call into ShellFileOperation.
ShellFileOperation(OperationType, OperationFlags, FinalSourcePath, FullTargetPath, OnUserCancel, TargetType)
' *** Special action for Directory only. ***
' In case target does exist, and it's a move, we actually move content and leave the source directory.
' Clean up here.
If Operation = CopyOrMove.Move And TargetType = FileOrDirectory.Directory Then
If IO.Directory.Exists(FullSourcePath) Then
If IO.Directory.GetDirectories(FullSourcePath).Length = 0 _
AndAlso IO.Directory.GetFiles(FullSourcePath).Length = 0 Then
IO.Directory.Delete(FullSourcePath, recursive:=False)
End If
End If
End If
#Else
Throw New PlatformNotSupportedException(SR.NoShellCopyOrMove)
#End If
End Sub
''' <summary>
''' Sets relevant flags on the SHFILEOPSTRUCT and calls into SHFileOperation to delete file / directory.
''' </summary>
''' <param name="FullPath">Full path to the file / directory.</param>
''' <param name="ShowUI">ShowDialogs to display progress and confirmation dialogs. Otherwise HideDialogs.</param>
''' <param name="recycle">SendToRecycleBin to delete to Recycle Bin. Otherwise DeletePermanently.</param>
''' <param name="OnUserCancel">Throw exception or not if the operation was canceled (by user or errors in the system).</param>
''' <remarks>
''' We don't need to consider Recursive flag here since we already verify that in DeleteDirectory.
''' </remarks>
Private Shared Sub ShellDelete(ByVal FullPath As String,
ByVal ShowUI As UIOptionInternal, ByVal recycle As RecycleOption, ByVal OnUserCancel As UICancelOption, ByVal FileOrDirectory As FileOrDirectory)
Debug.Assert(FullPath <> "" And IO.Path.IsPathRooted(FullPath), "FullPath must be a full path")
Debug.Assert(ShowUI <> UIOptionInternal.NoUI, "Why call ShellDelete if ShowUI is NoUI???")
#If PLATFORM_WINDOWS Then
' Set fFlags to control the operation details.
Dim OperationFlags As ShFileOperationFlags = GetOperationFlags(ShowUI)
If (recycle = RecycleOption.SendToRecycleBin) Then
OperationFlags = OperationFlags Or ShFileOperationFlags.FOF_ALLOWUNDO
End If
ShellFileOperation(SHFileOperationType.FO_DELETE, OperationFlags, FullPath, Nothing, OnUserCancel, FileOrDirectory)
#Else
Throw New PlatformNotSupportedException(SR.NoShellCopyOrMove)
#End If
End Sub
#If PLATFORM_WINDOWS Then
''' <summary>
''' Calls NativeMethods.SHFileOperation with the given SHFILEOPSTRUCT, notifies the shell of change,
''' and throw exceptions if needed.
''' </summary>
''' <param name="OperationType">Value from SHFileOperationType, specifying Copy / Move / Delete</param>
''' <param name="OperationFlags">Value from ShFileOperationFlags, specifying overwrite, recycle bin, etc...</param>
''' <param name="FullSource">The full path to the source.</param>
''' <param name="FullTarget">The full path to the target. Nothing if this is a Delete operation.</param>
''' <param name="OnUserCancel">Value from UICancelOption, specifying to throw or not when user cancels the operation.</param>
Private Shared Sub ShellFileOperation(ByVal OperationType As SHFileOperationType, ByVal OperationFlags As ShFileOperationFlags,
ByVal FullSource As String, ByVal FullTarget As String, ByVal OnUserCancel As UICancelOption, ByVal FileOrDirectory As FileOrDirectory)
Debug.Assert(System.Enum.IsDefined(GetType(SHFileOperationType), OperationType))
Debug.Assert(OperationType <> SHFileOperationType.FO_RENAME, "Don't call Shell to rename")
Debug.Assert(FullSource <> "" And IO.Path.IsPathRooted(FullSource), "Invalid FullSource path")
Debug.Assert(OperationType = SHFileOperationType.FO_DELETE OrElse (FullTarget <> "" And IO.Path.IsPathRooted(FullTarget)), "Invalid FullTarget path")
' Get the SHFILEOPSTRUCT
Dim OperationInfo As SHFILEOPSTRUCT = GetShellOperationInfo(OperationType, OperationFlags, FullSource, FullTarget)
Dim Result As Integer
Try
Result = NativeMethods.SHFileOperation(OperationInfo)
' Notify the shell in case some changes happened.
NativeMethods.SHChangeNotify(SHChangeEventTypes.SHCNE_DISKEVENTS,
SHChangeEventParameterFlags.SHCNF_DWORD, IntPtr.Zero, IntPtr.Zero)
Catch
Throw
Finally
End Try
' If the operation was canceled, check OnUserCancel and throw OperationCanceledException if needed.
' Otherwise, check the result and throw the appropriate exception if there is an error code.
If OperationInfo.fAnyOperationsAborted Then
If OnUserCancel = UICancelOption.ThrowException Then
Throw New OperationCanceledException()
End If
ElseIf Result <> 0 Then
ThrowWinIOError(Result)
End If
End Sub
''' <summary>
''' Returns an SHFILEOPSTRUCT used by SHFileOperation based on the given parameters.
''' </summary>
''' <param name="OperationType">One of the SHFileOperationType value: copy, move or delete.</param>
''' <param name="OperationFlags">Combination SHFileOperationFlags values: details of the operation.</param>
''' <param name="SourcePath">The source file / directory path.</param>
''' <param name="TargetPath">The target file / directory path. Nothing in case of delete.</param>
''' <returns>A fully initialized SHFILEOPSTRUCT.</returns>
Private Shared Function GetShellOperationInfo(
ByVal OperationType As SHFileOperationType, ByVal OperationFlags As ShFileOperationFlags,
ByVal SourcePath As String, Optional ByVal TargetPath As String = Nothing) As SHFILEOPSTRUCT
Debug.Assert(SourcePath <> "" And IO.Path.IsPathRooted(SourcePath), "Invalid SourcePath")
Return GetShellOperationInfo(OperationType, OperationFlags, New String() {SourcePath}, TargetPath)
End Function
''' <summary>
''' Returns an SHFILEOPSTRUCT used by SHFileOperation based on the given parameters.
''' </summary>
''' <param name="OperationType">One of the SHFileOperationType value: copy, move or delete.</param>
''' <param name="OperationFlags">Combination SHFileOperationFlags values: details of the operation.</param>
''' <param name="SourcePaths">A string array containing the paths of source files. Must not be empty.</param>
''' <param name="TargetPath">The target file / directory path. Nothing in case of delete.</param>
''' <returns>A fully initialized SHFILEOPSTRUCT.</returns>
Private Shared Function GetShellOperationInfo(
ByVal OperationType As SHFileOperationType, ByVal OperationFlags As ShFileOperationFlags,
ByVal SourcePaths() As String, Optional ByVal TargetPath As String = Nothing) As SHFILEOPSTRUCT
Debug.Assert(System.Enum.IsDefined(GetType(SHFileOperationType), OperationType), "Invalid OperationType")
Debug.Assert(TargetPath = "" Or IO.Path.IsPathRooted(TargetPath), "Invalid TargetPath")
Debug.Assert(SourcePaths IsNot Nothing AndAlso SourcePaths.Length > 0, "Invalid SourcePaths")
Dim OperationInfo As SHFILEOPSTRUCT
' Set wFunc - the operation.
OperationInfo.wFunc = CType(OperationType, UInteger)
' Set fFlags - the operation details.
OperationInfo.fFlags = CType(OperationFlags, UShort)
' Set pFrom and pTo - the paths.
OperationInfo.pFrom = GetShellPath(SourcePaths)
If TargetPath Is Nothing Then
OperationInfo.pTo = Nothing
Else
OperationInfo.pTo = GetShellPath(TargetPath)
End If
' Set other fields.
OperationInfo.hNameMappings = IntPtr.Zero
' Try to set hwnd to the process's MainWindowHandle. If exception occurs, use IntPtr.Zero, which is desktop.
Try
OperationInfo.hwnd = Process.GetCurrentProcess.MainWindowHandle
Catch ex As Exception
If TypeOf (ex) Is SecurityException OrElse
TypeOf (ex) Is InvalidOperationException OrElse
TypeOf (ex) Is NotSupportedException Then
' GetCurrentProcess can throw SecurityException. MainWindowHandle can throw InvalidOperationException or NotSupportedException.
OperationInfo.hwnd = IntPtr.Zero
Else
Throw
End If
End Try
OperationInfo.lpszProgressTitle = String.Empty ' We don't set this since we don't have any FOF_SIMPLEPROGRESS.
Return OperationInfo
End Function
''' <summary>
''' Return the ShFileOperationFlags based on the ShowUI option.
''' </summary>
''' <param name="ShowUI">UIOptionInternal value.</param>
Private Shared Function GetOperationFlags(ByVal ShowUI As UIOptionInternal) As ShFileOperationFlags
Dim OperationFlags As ShFileOperationFlags = m_SHELL_OPERATION_FLAGS_BASE
If (ShowUI = UIOptionInternal.OnlyErrorDialogs) Then
OperationFlags = OperationFlags Or m_SHELL_OPERATION_FLAGS_HIDE_UI
End If
Return OperationFlags
End Function
''' <summary>
''' Returns the special path format required for pFrom and pTo of SHFILEOPSTRUCT. See NativeMethod.
''' </summary>
''' <param name="FullPath">The full path to be converted.</param>
''' <returns>A string in the required format.</returns>
Private Shared Function GetShellPath(ByVal FullPath As String) As String
Debug.Assert(FullPath <> "" And IO.Path.IsPathRooted(FullPath), "Must be full path")
Return GetShellPath(New String() {FullPath})
End Function
''' <summary>
''' Returns the special path format required for pFrom and pTo of SHFILEOPSTRUCT. See NativeMethod.
''' </summary>
''' <param name="FullPaths">A string array containing the paths for the operation.</param>
''' <returns>A string in the required format.</returns>
Private Shared Function GetShellPath(ByVal FullPaths() As String) As String
#If DEBUG Then
Debug.Assert(FullPaths IsNot Nothing, "FullPaths is NULL")
Debug.Assert(FullPaths.Length > 0, "FullPaths() is empty array")
For Each FullPath As String In FullPaths
Debug.Assert(FullPath <> "" And IO.Path.IsPathRooted(FullPath), FullPath)
Next
#End If
' Each path will end with a Null character.
Dim MultiString As New StringBuilder()
For Each FullPath As String In FullPaths
MultiString.Append(FullPath & ControlChars.NullChar)
Next
' Don't need to append another Null character since String always end with Null character by default.
Debug.Assert(MultiString.ToString.EndsWith(ControlChars.NullChar, StringComparison.Ordinal))
Return MultiString.ToString()
End Function
#End If
''' <summary>
''' Throw an argument exception if the given path starts with "\\.\" (device path).
''' </summary>
''' <param name="path">The path to check.</param>
''' <remarks>
''' FileStream already throws exception with device path, so our code only check for device path in Copy / Move / Delete / Rename.
''' </remarks>
Private Shared Sub ThrowIfDevicePath(ByVal path As String)
If path.StartsWith("\\.\", StringComparison.Ordinal) Then
Throw ExceptionUtils.GetArgumentExceptionWithArgName("path", SR.IO_DevicePath)
End If
End Sub
#If PLATFORM_WINDOWS Then
''' <summary>
''' Given an error code from winerror.h, throw the appropriate exception.
''' </summary>
''' <param name="errorCode">An error code from winerror.h.</param>
''' <remarks>
''' - This method is based on sources\ndp\clr\src\BCL\System\IO\_Error.cs::WinIOError, except the following.
''' - Exception message does not contain the path since at this point it is normalized.
''' - Instead of using PInvoke of GetMessage and MakeHRFromErrorCode, use managed code.
''' </remarks>
Private Shared Sub ThrowWinIOError(ByVal errorCode As Integer)
Select Case errorCode
Case NativeTypes.ERROR_FILE_NOT_FOUND
Throw New IO.FileNotFoundException()
Case NativeTypes.ERROR_PATH_NOT_FOUND
Throw New IO.DirectoryNotFoundException()
Case NativeTypes.ERROR_ACCESS_DENIED
Throw New UnauthorizedAccessException()
Case NativeTypes.ERROR_FILENAME_EXCED_RANGE
Throw New IO.PathTooLongException()
Case NativeTypes.ERROR_INVALID_DRIVE
Throw New IO.DriveNotFoundException()
Case NativeTypes.ERROR_OPERATION_ABORTED, NativeTypes.ERROR_CANCELLED
Throw New OperationCanceledException()
Case Else
' Including these from _Error.cs::WinIOError.
'Case NativeTypes.ERROR_ALREADY_EXISTS
'Case NativeTypes.ERROR_INVALID_PARAMETER
'Case NativeTypes.ERROR_SHARING_VIOLATION
'Case NativeTypes.ERROR_FILE_EXISTS
Throw New IO.IOException((New Win32Exception(errorCode)).Message,
System.Runtime.InteropServices.Marshal.GetHRForLastWin32Error())
End Select
End Sub
#End If
''' <summary>
''' Convert UIOption to UIOptionInternal to use internally.
''' </summary>
''' <remarks>
''' Only accept valid UIOption values.
''' </remarks>
Private Shared Function ToUIOptionInternal(ByVal showUI As UIOption) As UIOptionInternal
Select Case showUI
Case FileIO.UIOption.AllDialogs
Return UIOptionInternal.AllDialogs
Case FileIO.UIOption.OnlyErrorDialogs
Return UIOptionInternal.OnlyErrorDialogs
Case Else
Throw New System.ComponentModel.InvalidEnumArgumentException("showUI", showUI, GetType(UIOption))
End Select
End Function
''' <summary>
''' Verify that the given argument value is a valid DeleteDirectoryOption. If not, throw InvalidEnumArgumentException.
''' </summary>
''' <param name="argName">The argument name.</param>
''' <param name="argValue">The argument value.</param>
''' <remarks></remarks>
Private Shared Sub VerifyDeleteDirectoryOption(ByVal argName As String, ByVal argValue As DeleteDirectoryOption)
If argValue = FileIO.DeleteDirectoryOption.DeleteAllContents OrElse
argValue = FileIO.DeleteDirectoryOption.ThrowIfDirectoryNonEmpty Then
Exit Sub
End If
Throw New InvalidEnumArgumentException(argName, argValue, GetType(DeleteDirectoryOption))
End Sub
''' <summary>
''' Verify that the given argument value is a valid RecycleOption. If not, throw InvalidEnumArgumentException.
''' </summary>
''' <param name="argName">The argument name.</param>
''' <param name="argValue">The argument value.</param>
Private Shared Sub VerifyRecycleOption(ByVal argName As String, ByVal argValue As RecycleOption)
If argValue = RecycleOption.DeletePermanently OrElse
argValue = RecycleOption.SendToRecycleBin Then
Exit Sub
End If
Throw New InvalidEnumArgumentException(argName, argValue, GetType(RecycleOption))
End Sub
''' <summary>
''' Verify that the given argument value is a valid SearchOption. If not, throw InvalidEnumArgumentException.
''' </summary>
''' <param name="argName">The argument name.</param>
''' <param name="argValue">The argument value.</param>
Private Shared Sub VerifySearchOption(ByVal argName As String, ByVal argValue As SearchOption)
If argValue = SearchOption.SearchAllSubDirectories OrElse
argValue = SearchOption.SearchTopLevelOnly Then
Exit Sub
End If
Throw New InvalidEnumArgumentException(argName, argValue, GetType(SearchOption))
End Sub
''' <summary>
''' Verify that the given argument value is a valid UICancelOption. If not, throw InvalidEnumArgumentException.
''' </summary>
''' <param name="argName">The argument name.</param>
''' <param name="argValue">The argument value.</param>
Private Shared Sub VerifyUICancelOption(ByVal argName As String, ByVal argValue As UICancelOption)
If argValue = UICancelOption.DoNothing OrElse
argValue = UICancelOption.ThrowException Then
Exit Sub
End If
Throw New InvalidEnumArgumentException(argName, argValue, GetType(UICancelOption))
End Sub
#If PLATFORM_WINDOWS Then
' Base operation flags used in shell IO operation.
' - DON'T move connected files as a group.
' - DON'T confirm directory creation - our silent copy / move do not.
Private Const m_SHELL_OPERATION_FLAGS_BASE As ShFileOperationFlags =
ShFileOperationFlags.FOF_NO_CONNECTED_ELEMENTS Or
ShFileOperationFlags.FOF_NOCONFIRMMKDIR
' Hide UI operation flags for Delete.
' - DON'T show progress bar.
' - DON'T confirm (answer yes to everything). NOTE: In exception cases (read-only file), shell still asks.
Private Const m_SHELL_OPERATION_FLAGS_HIDE_UI As ShFileOperationFlags =
ShFileOperationFlags.FOF_SILENT Or
ShFileOperationFlags.FOF_NOCONFIRMATION
' When calling MoveFileEx, set the following flags:
' - Simulate CopyFile and DeleteFile if copied to a different volume.
' - Replace contents of existing target with the contents of source file.
' - Do not return until the file has actually been moved on the disk.
Private Const m_MOVEFILEEX_FLAGS As Integer = CInt(
MoveFileExFlags.MOVEFILE_COPY_ALLOWED Or
MoveFileExFlags.MOVEFILE_REPLACE_EXISTING Or
MoveFileExFlags.MOVEFILE_WRITE_THROUGH)
#End If
' Array containing all the path separator chars. Used to verify that input is a name, not a path.
Private Shared ReadOnly m_SeparatorChars() As Char = {
IO.Path.DirectorySeparatorChar, IO.Path.AltDirectorySeparatorChar, IO.Path.VolumeSeparatorChar}
''' <summary>
''' Private enumeration: The operation is a Copy or Move.
''' </summary>
Private Enum CopyOrMove
Copy
Move
End Enum
''' <summary>
''' Private enumeration: Target of the operation is a File or Directory.
''' </summary>
''' <remarks></remarks>
Private Enum FileOrDirectory
File
Directory
End Enum
''' <summary>
''' Private enumeration: Indicate the options of ShowUI to use internally.
''' This includes NoUI so that we can base the decision on 1 variable.
''' </summary>
''' <remarks></remarks>
Private Enum UIOptionInternal
OnlyErrorDialogs = UIOption.OnlyErrorDialogs
AllDialogs = UIOption.AllDialogs
NoUI
End Enum
''' <summary>
''' A simple tree node to build up the directory structure used for a snapshot in Copy / Move Directory.
''' </summary>
Private Class DirectoryNode
''' <summary>
''' Given a DirectoryPath, create the node and add the sub-directory nodes.
''' </summary>
''' <param name="DirectoryPath">Path to the directory. NOTE: must exist.</param>
''' <param name="TargetDirectoryPath">Path to the target directory of the move / copy. NOTE: must be a full path.</param>
Friend Sub New(ByVal DirectoryPath As String, ByVal TargetDirectoryPath As String)
Debug.Assert(IO.Directory.Exists(DirectoryPath), "Directory does not exist")
Debug.Assert(TargetDirectoryPath <> "" And IO.Path.IsPathRooted(TargetDirectoryPath), "Invalid TargetPath")
m_Path = DirectoryPath
m_TargetPath = TargetDirectoryPath
m_SubDirs = New ObjectModel.Collection(Of DirectoryNode)
For Each SubDirPath As String In IO.Directory.GetDirectories(m_Path)
Dim SubTargetDirPath As String = IO.Path.Combine(m_TargetPath, IO.Path.GetFileName(SubDirPath))
m_SubDirs.Add(New DirectoryNode(SubDirPath, SubTargetDirPath))
Next
End Sub
''' <summary>
''' Return the Path of the current node.
''' </summary>
''' <value>A String containing the Path of the current node.</value>
Friend ReadOnly Property Path() As String
Get
Return m_Path
End Get
End Property
''' <summary>
''' Return the TargetPath for copy / move.
''' </summary>
''' <value>A String containing the copy / move target path of the current node.</value>
Friend ReadOnly Property TargetPath() As String
Get
Return m_TargetPath
End Get
End Property
''' <summary>
''' Return the sub directories of the current node.
''' </summary>
''' <value>A Collection(Of DirectoryNode) containing the sub-directory nodes.</value>
Friend ReadOnly Property SubDirs() As ObjectModel.Collection(Of DirectoryNode)
Get
Return m_SubDirs
End Get
End Property
Private m_Path As String
Private m_TargetPath As String
Private m_SubDirs As ObjectModel.Collection(Of DirectoryNode)
End Class 'Private Class DirectoryNode
''' <summary>
''' Helper class to search for text in an array of byte using a specific Decoder.
''' </summary>
''' <remarks>
''' To search for text that might exist in an encoding, construct this class with the text and Decoder.
''' Then call IsTextFound() and pass in byte arrays.
''' This class will take care of text spanning byte arrays by caching a part of the array and use it in
''' the next IsTextFound() call.
''' </remarks>
Private Class TextSearchHelper
''' <summary>
''' Constructs a new helper with a given encoding and a text to search for.
''' </summary>
''' <param name="Encoding">The Encoding to use to convert byte to text.</param>
''' <param name="Text">The text to search for in subsequent byte array.</param>
Friend Sub New(ByVal Encoding As Text.Encoding, ByVal Text As String, ByVal IgnoreCase As Boolean)
Debug.Assert(Encoding IsNot Nothing, "Null Decoder")
Debug.Assert(Text <> "", "Empty Text")
m_Decoder = Encoding.GetDecoder
m_Preamble = Encoding.GetPreamble
m_IgnoreCase = IgnoreCase
' If use wants to ignore case, convert search text to lower case.
If m_IgnoreCase Then
m_SearchText = Text.ToUpper(CultureInfo.CurrentCulture)
Else
m_SearchText = Text
End If
End Sub
''' <summary>
''' Determines whether the text is found in the given byte array.
''' </summary>
''' <param name="ByteBuffer">The byte array to find the text in</param>
''' <param name="Count">The number of valid bytes in the byte array</param>
''' <returns>True if the text is found. Otherwise, False.</returns>
Friend Function IsTextFound(ByVal ByteBuffer() As Byte, ByVal Count As Integer) As Boolean
Debug.Assert(ByteBuffer IsNot Nothing, "Null ByteBuffer")
Debug.Assert(Count > 0, Count.ToString(CultureInfo.InvariantCulture))
Debug.Assert(m_Decoder IsNot Nothing, "Null Decoder")
Debug.Assert(m_Preamble IsNot Nothing, "Null Preamble")
Dim ByteBufferStartIndex As Integer = 0 ' If need to handle BOM, ByteBufferStartIndex will increase.
' Check for the preamble the first time IsTextFound is called. If find it, shrink ByteBuffer.
If m_CheckPreamble Then
If BytesMatch(ByteBuffer, m_Preamble) Then
ByteBufferStartIndex = m_Preamble.Length
Count -= m_Preamble.Length ' Reduce the valid byte count if ByteBuffer was shrinked.
End If
m_CheckPreamble = False
' In case of an empty file with BOM at the beginning return FALSE.
If Count <= 0 Then
Return False
End If
End If
' Get the number of characters in the byte array.
Dim ExpectedCharCount As Integer = m_Decoder.GetCharCount(ByteBuffer, ByteBufferStartIndex, Count)
' The character buffer used to search will be a combination of the cached buffer and the current one.
Dim CharBuffer(m_PreviousCharBuffer.Length + ExpectedCharCount - 1) As Char
' Start the buffer with the cached buffer.
Array.Copy(sourceArray:=m_PreviousCharBuffer, sourceIndex:=0,
destinationArray:=CharBuffer, destinationIndex:=0, length:=m_PreviousCharBuffer.Length)
' And fill the rest with the ones from byte array.
Dim CharCount As Integer = m_Decoder.GetChars(
bytes:=ByteBuffer, byteIndex:=ByteBufferStartIndex, byteCount:=Count,
chars:=CharBuffer, charIndex:=m_PreviousCharBuffer.Length)
Debug.Assert(CharCount = ExpectedCharCount, "Should read all characters")
' Refresh the cached buffer for the possible next search.
If CharBuffer.Length > m_SearchText.Length Then
If m_PreviousCharBuffer.Length <> m_SearchText.Length Then
ReDim m_PreviousCharBuffer(m_SearchText.Length - 1)
End If
Array.Copy(sourceArray:=CharBuffer, sourceIndex:=(CharBuffer.Length - m_SearchText.Length),
destinationArray:=m_PreviousCharBuffer, destinationIndex:=0, length:=m_SearchText.Length)
Else
m_PreviousCharBuffer = CharBuffer
End If
' If user wants to ignore case, convert new string to lower case. m_SearchText was converted in constructor.
If m_IgnoreCase Then
Return New String(CharBuffer).ToUpper(CultureInfo.CurrentCulture).Contains(m_SearchText)
Else
Return New String(CharBuffer).Contains(m_SearchText)
End If
End Function
''' <summary>
''' No default constructor.
''' </summary>
Private Sub New()
End Sub
''' <summary>
''' Returns whether the big buffer starts with the small buffer.
''' </summary>
''' <param name="BigBuffer"></param>
''' <param name="SmallBuffer"></param>
''' <returns>True if BigBuffer starts with SmallBuffer.Otherwise, False.</returns>
Private Shared Function BytesMatch(ByVal BigBuffer() As Byte, ByVal SmallBuffer() As Byte) As Boolean
Debug.Assert(BigBuffer.Length > SmallBuffer.Length, "BigBuffer should be longer")
If BigBuffer.Length < SmallBuffer.Length Or SmallBuffer.Length = 0 Then
Return False
End If
For i As Integer = 0 To SmallBuffer.Length - 1
If BigBuffer(i) <> SmallBuffer(i) Then
Return False
End If
Next
Return True
End Function
Private m_SearchText As String ' The text to search.
Private m_IgnoreCase As Boolean ' Should we ignore case?
Private m_Decoder As Text.Decoder ' The Decoder to use.
Private m_PreviousCharBuffer() As Char = {} ' The cached character array from previous call to IsTextExist.
Private m_CheckPreamble As Boolean = True ' True to check for preamble. False otherwise.
Private m_Preamble() As Byte ' The byte order mark we need to consider.
End Class 'Private Class TextSearchHelper
End Class 'Public Class FileSystem
''' <summary>
''' Specify the action to do when deleting a directory and it is not empty.
''' </summary>
''' <remarks>
''' Again, avoid Integer values that VB Compiler will convert Boolean to (0 and -1).
''' IMPORTANT: Change VerifyDeleteDirectoryOption if this enum is changed.
''' Also, values in DeleteDirectoryOption must be different from UIOption.
''' </remarks>
Public Enum DeleteDirectoryOption As Integer
ThrowIfDirectoryNonEmpty = 4
DeleteAllContents = 5
End Enum
''' <summary>
''' Specify whether to delete a file / directory to Recycle Bin or not.
''' </summary>
Public Enum RecycleOption As Integer
DeletePermanently = 2
SendToRecycleBin = 3
End Enum
''' <summary>
''' Specify whether to perform the search for files/directories recursively or not.
''' </summary>
Public Enum SearchOption As Integer
SearchTopLevelOnly = 2
SearchAllSubDirectories = 3
End Enum
''' <summary>
''' Defines option whether to throw exception when user cancels a UI operation or not.
''' </summary>
Public Enum UICancelOption As Integer
DoNothing = 2
ThrowException = 3
End Enum
''' <summary>
''' Specify which UI dialogs to show.
''' </summary>
''' <remarks>
''' To fix common issues; avoid Integer values that VB Compiler
''' will convert Boolean to (0 and -1).
''' </remarks>
Public Enum UIOption As Integer
OnlyErrorDialogs = 2
AllDialogs = 3
End Enum
End Namespace
' NOTE:
' - All path returned by us will NOT have the Directory Separator Character ('\') at the end.
' - All path accepted by us will NOT consider the meaning of Directory Separator Character ('\') at the end.
' - Parameter accepting path will accept both relative and absolute paths unless specified.
' Relative paths will be resolved using the current working directory.
' - IO.Path.GetFullPath is used to normalized the path. It will only throw in case of not well-formed path.
' - Hidden Files and Directories will be moved / copied by Framework code.
'
' - On both Read and Write, we use the default Share mode that FX uses for the StreamReader/Writer, which is Share.Read.
' Details on what share mode means:
' When a call is made to open the file, the share mode not only means that the caller wants to restrict every call
' afterwards, but also every call before as well, which means that the caller will fail if any calls before it
' already obtained a conflict right.
' For example: if this call succeeds,
' Open(FileA, OpenMode.Write, ShareMode.Read)
' Although it is sharing FileA for reading, if the 2nd call is
' Open(FileA, OpenMode.Read, ShareMode.Read)
' the 2nd call will fail since it wants to restrict everybody else to read only, but 1st caller has already obtained
' write access.
' So the default behavior is fine since novice Mort can't run into trouble using it.
'
' - All IO functions involving ShowUI have dependency on Windows Shell and sometimes have different behavior.
' - CopyDirectory will attempt to copy all the files in the directory. If there are files or sub-directories
' that cause exception, CopyDirectory will not stop, since that will leave the result in unknown state.
' Instead, an exception will be thrown at the end containing a list of exception files in Data property.
' - MoveDirectory behaves the same so MoveDirectory is not equal to calling CopyDirectory and DeleteDirectory.
' - Overwrite in directory case means overwrite sub files. Sub directories will always be merged.
'
' Shell behavior in exception cases:
' - Copy / Move File
' . Existing target:
' Overwrite = True: Overwrite target.
' Overwrite = False: Dialog Yes: Overwrite target.
' No: Error code 7. ERROR_ARENA_TRASHED
' . Existing target and Read-Only (Framework will throw).
' Always ask. No: Error code 7. ERROR_ARENA_TRASHED
' . OS access denied: Error code 1223. ERROR_CANCELLED
' - Copy / Move Directory Existing target:
' . Has an existing file:
' Overwrite = True: Overwrite file.
' Overwrite = False: Dialog Yes / Yes to all : Overwrite target.
' No: Leave and copy the rest.
' Cancel: Error code 2. ERROR_FILE_NOT_FOUND.
' . Has an existing file and Read-Only (Framework will throw).
' Behave as when Overwrite = False.
' . File in source same name with directory in target:
' * Copy: Error code 1223 ERROR_CANCELLED.
' * Move: Overwrite = True: Error code 183. ERROR_ALREADY_EXISTS.
' Overwrite = False: Ask question Yes: Error code 183.
' Cancel: Error code 2.
' . Directory in source same name with file in target:
' Error code 183 in all cases.
'
' NOTE: Some different behavior when deleting files / directories.
' ShowUI RecycleBin Normal file. Read-only file.
' F F Gone Exception. *
' T F Question + UI + Gone Question + UI + Gone
' F T Bin Question + Bin *
' T T Question + UI + Bin Question + UI + Bin
|
shimingsg/corefx
|
src/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/FileSystem.vb
|
Visual Basic
|
mit
| 134,362
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Expressions
''' <summary>
''' Recommends the "MyBase" keyword.
''' </summary>
Friend Class MyBaseKeywordRecommender
Inherits AbstractKeywordRecommender
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As IEnumerable(Of RecommendedKeyword)
Dim targetToken = context.TargetToken
If (context.IsAnyExpressionContext OrElse context.IsSingleLineStatementContext OrElse context.IsNameOfContext) AndAlso
targetToken.GetInnermostDeclarationContext().IsKind(SyntaxKind.ClassBlock) Then
Return SpecializedCollections.SingletonEnumerable(New RecommendedKeyword(SyntaxFacts.GetText(SyntaxKind.MyBaseKeyword), VBFeaturesResources.MyBaseKeywordToolTip))
End If
If context.IsAccessibleEventContext(startAtEnclosingBaseType:=True, cancellationToken:=cancellationToken) Then
Return SpecializedCollections.SingletonEnumerable(New RecommendedKeyword(SyntaxFacts.GetText(SyntaxKind.MyBaseKeyword), VBFeaturesResources.MyBaseKeywordToolTip))
End If
Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)()
End Function
End Class
End Namespace
|
zmaruo/roslyn
|
src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Expressions/MyBaseKeywordRecommender.vb
|
Visual Basic
|
apache-2.0
| 1,660
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Imports TestHelper
Namespace BasicAnalyzers.Test
<TestClass>
Public Class CodeBlockStartedAnalyzerUnitTests
Inherits DiagnosticVerifier
<TestMethod>
Public Sub Test1()
Dim test = "
Class C
Public Function M1(p1 As Integer, p2 As Integer) As Integer
Return M2(p1, p1)
End Function
Public Function M2(p1 As Integer, p2 As Integer) As Integer
Return p1 + p2
End Function
End Class"
Dim expected = New DiagnosticResult() With {
.Id = DiagnosticIds.CodeBlockStartedAnalyzerRuleId,
.Message = String.Format(My.Resources.CodeBlockStartedAnalyzerMessageFormat, "p2", "M1"),
.Severity = DiagnosticSeverity.Warning,
.Locations = {New DiagnosticResultLocation("Test0.vb", 3, 36)}
}
VerifyBasicDiagnostic(test, expected)
End Sub
Protected Overrides Function GetBasicDiagnosticAnalyzer() As DiagnosticAnalyzer
Return New CodeBlockStartedAnalyzer()
End Function
End Class
End Namespace
|
mmitche/roslyn
|
src/Samples/VisualBasic/Analyzers/BasicAnalyzers/BasicAnalyzers.Test/Tests/CodeBlockStartedAnalyzerUnitTests.vb
|
Visual Basic
|
apache-2.0
| 1,359
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Form1))
Me.GameSelector = New System.Windows.Forms.ComboBox()
Me.Label1 = New System.Windows.Forms.Label()
Me.ImportButton = New System.Windows.Forms.Button()
Me.TrackList = New System.Windows.Forms.ListView()
Me.LoadedCol = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
Me.TrackCol = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
Me.HotKeyCol = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
Me.VolumeCol = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
Me.Trimmed = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
Me.TagsCol = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
Me.StartButton = New System.Windows.Forms.Button()
Me.ImportDialog = New System.Windows.Forms.OpenFileDialog()
Me.ProgressBar1 = New System.Windows.Forms.ProgressBar()
Me.WavWorker = New System.ComponentModel.BackgroundWorker()
Me.PollRelayWorker = New System.ComponentModel.BackgroundWorker()
Me.ChangeDirButton = New System.Windows.Forms.Button()
Me.TrackContextMenu = New System.Windows.Forms.ContextMenuStrip(Me.components)
Me.ContextDelete = New System.Windows.Forms.ToolStripMenuItem()
Me.GoToToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
Me.ContextRefresh = New System.Windows.Forms.ToolStripMenuItem()
Me.RemoveHotkeyToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
Me.RenameToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
Me.ContextHotKey = New System.Windows.Forms.ToolStripMenuItem()
Me.SetVolumeToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
Me.TrimToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
Me.PlayKeyButton = New System.Windows.Forms.Button()
Me.StatusLabel = New System.Windows.Forms.Label()
Me.StreamB = New System.Windows.Forms.Button()
Me.TrackContextMenu.SuspendLayout()
Me.SuspendLayout()
'
'GameSelector
'
Me.GameSelector.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.GameSelector.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
Me.GameSelector.FormattingEnabled = True
Me.GameSelector.Location = New System.Drawing.Point(56, 12)
Me.GameSelector.MaxDropDownItems = 100
Me.GameSelector.Name = "GameSelector"
Me.GameSelector.Size = New System.Drawing.Size(405, 21)
Me.GameSelector.TabIndex = 0
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Location = New System.Drawing.Point(12, 15)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(38, 13)
Me.Label1.TabIndex = 1
Me.Label1.Text = "Game:"
'
'ImportButton
'
Me.ImportButton.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
Me.ImportButton.Location = New System.Drawing.Point(15, 297)
Me.ImportButton.Name = "ImportButton"
Me.ImportButton.Size = New System.Drawing.Size(75, 23)
Me.ImportButton.TabIndex = 3
Me.ImportButton.Text = "Import"
Me.ImportButton.UseVisualStyleBackColor = True
'
'TrackList
'
Me.TrackList.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.TrackList.AutoArrange = False
Me.TrackList.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.LoadedCol, Me.TrackCol, Me.HotKeyCol, Me.VolumeCol, Me.Trimmed, Me.TagsCol})
Me.TrackList.FullRowSelect = True
Me.TrackList.HideSelection = False
Me.TrackList.ImeMode = System.Windows.Forms.ImeMode.Off
Me.TrackList.Location = New System.Drawing.Point(15, 39)
Me.TrackList.Name = "TrackList"
Me.TrackList.Size = New System.Drawing.Size(527, 252)
Me.TrackList.TabIndex = 4
Me.TrackList.UseCompatibleStateImageBehavior = False
Me.TrackList.View = System.Windows.Forms.View.Details
'
'LoadedCol
'
Me.LoadedCol.Text = "Loaded"
'
'TrackCol
'
Me.TrackCol.Text = "Track"
Me.TrackCol.Width = 137
'
'HotKeyCol
'
Me.HotKeyCol.Text = "Bind"
'
'VolumeCol
'
Me.VolumeCol.Text = "Volume"
Me.VolumeCol.Width = 100
'
'Trimmed
'
Me.Trimmed.Text = "Trimmed"
'
'TagsCol
'
Me.TagsCol.Text = "Tags"
Me.TagsCol.Width = 43
'
'StartButton
'
Me.StartButton.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
Me.StartButton.Location = New System.Drawing.Point(96, 297)
Me.StartButton.Name = "StartButton"
Me.StartButton.Size = New System.Drawing.Size(75, 23)
Me.StartButton.TabIndex = 5
Me.StartButton.Text = "Start"
Me.StartButton.UseVisualStyleBackColor = True
'
'ImportDialog
'
Me.ImportDialog.FileName = "ImportDialog"
Me.ImportDialog.Filter = "Media files|*.mp3;*.wav;*.aac;*.wma;*.m4a;*.mp4;*.wmv;*.avi;*.m4v;*.mov;|Audio fi" &
"les|*.mp3;*.wav;*.aac;*.wma;*.m4a;|Video files|*.mp4;*.wmv;*.avi;*.m4v;*.mov;|Al" &
"l files|*.*"
Me.ImportDialog.Multiselect = True
'
'ProgressBar1
'
Me.ProgressBar1.Anchor = CType(((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.ProgressBar1.Location = New System.Drawing.Point(15, 326)
Me.ProgressBar1.Name = "ProgressBar1"
Me.ProgressBar1.Size = New System.Drawing.Size(527, 23)
Me.ProgressBar1.Step = 1
Me.ProgressBar1.TabIndex = 6
'
'WavWorker
'
Me.WavWorker.WorkerReportsProgress = True
'
'PollRelayWorker
'
Me.PollRelayWorker.WorkerReportsProgress = True
Me.PollRelayWorker.WorkerSupportsCancellation = True
'
'ChangeDirButton
'
Me.ChangeDirButton.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.ChangeDirButton.Location = New System.Drawing.Point(467, 10)
Me.ChangeDirButton.Name = "ChangeDirButton"
Me.ChangeDirButton.Size = New System.Drawing.Size(75, 23)
Me.ChangeDirButton.TabIndex = 7
Me.ChangeDirButton.Text = "Settings"
Me.ChangeDirButton.UseVisualStyleBackColor = True
'
'TrackContextMenu
'
Me.TrackContextMenu.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ContextDelete, Me.GoToToolStripMenuItem, Me.ContextRefresh, Me.RemoveHotkeyToolStripMenuItem, Me.RenameToolStripMenuItem, Me.ContextHotKey, Me.SetVolumeToolStripMenuItem, Me.TrimToolStripMenuItem})
Me.TrackContextMenu.Name = "TrackContextMenu"
Me.TrackContextMenu.Size = New System.Drawing.Size(145, 180)
'
'ContextDelete
'
Me.ContextDelete.Name = "ContextDelete"
Me.ContextDelete.Size = New System.Drawing.Size(144, 22)
Me.ContextDelete.Text = "Delete"
'
'GoToToolStripMenuItem
'
Me.GoToToolStripMenuItem.Name = "GoToToolStripMenuItem"
Me.GoToToolStripMenuItem.Size = New System.Drawing.Size(144, 22)
Me.GoToToolStripMenuItem.Text = "Go To"
'
'ContextRefresh
'
Me.ContextRefresh.Name = "ContextRefresh"
Me.ContextRefresh.Size = New System.Drawing.Size(144, 22)
Me.ContextRefresh.Text = "Refresh"
'
'RemoveHotkeyToolStripMenuItem
'
Me.RemoveHotkeyToolStripMenuItem.Name = "RemoveHotkeyToolStripMenuItem"
Me.RemoveHotkeyToolStripMenuItem.Size = New System.Drawing.Size(144, 22)
Me.RemoveHotkeyToolStripMenuItem.Text = "Remove Bind"
'
'RenameToolStripMenuItem
'
Me.RenameToolStripMenuItem.Name = "RenameToolStripMenuItem"
Me.RenameToolStripMenuItem.Size = New System.Drawing.Size(144, 22)
Me.RenameToolStripMenuItem.Text = "Rename"
'
'ContextHotKey
'
Me.ContextHotKey.Name = "ContextHotKey"
Me.ContextHotKey.Size = New System.Drawing.Size(144, 22)
Me.ContextHotKey.Text = "Set Bind"
'
'SetVolumeToolStripMenuItem
'
Me.SetVolumeToolStripMenuItem.Name = "SetVolumeToolStripMenuItem"
Me.SetVolumeToolStripMenuItem.Size = New System.Drawing.Size(144, 22)
Me.SetVolumeToolStripMenuItem.Text = "Set Volume"
'
'TrimToolStripMenuItem
'
Me.TrimToolStripMenuItem.Name = "TrimToolStripMenuItem"
Me.TrimToolStripMenuItem.Size = New System.Drawing.Size(144, 22)
Me.TrimToolStripMenuItem.Text = "Trim"
'
'PlayKeyButton
'
Me.PlayKeyButton.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.PlayKeyButton.Location = New System.Drawing.Point(350, 297)
Me.PlayKeyButton.Name = "PlayKeyButton"
Me.PlayKeyButton.Size = New System.Drawing.Size(192, 23)
Me.PlayKeyButton.TabIndex = 8
Me.PlayKeyButton.Text = "Play key: """"{0}"""" (change)"
Me.PlayKeyButton.UseVisualStyleBackColor = True
'
'StatusLabel
'
Me.StatusLabel.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
Me.StatusLabel.AutoSize = True
Me.StatusLabel.Location = New System.Drawing.Point(258, 302)
Me.StatusLabel.Name = "StatusLabel"
Me.StatusLabel.Size = New System.Drawing.Size(60, 13)
Me.StatusLabel.TabIndex = 9
Me.StatusLabel.Text = "Status: Idle"
'
'StreamB
'
Me.StreamB.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
Me.StreamB.Location = New System.Drawing.Point(177, 297)
Me.StreamB.Name = "StreamB"
Me.StreamB.Size = New System.Drawing.Size(75, 23)
Me.StreamB.TabIndex = 10
Me.StreamB.Text = "Download"
Me.StreamB.UseVisualStyleBackColor = True
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(554, 361)
Me.Controls.Add(Me.StreamB)
Me.Controls.Add(Me.StatusLabel)
Me.Controls.Add(Me.PlayKeyButton)
Me.Controls.Add(Me.ChangeDirButton)
Me.Controls.Add(Me.ProgressBar1)
Me.Controls.Add(Me.StartButton)
Me.Controls.Add(Me.TrackList)
Me.Controls.Add(Me.ImportButton)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.GameSelector)
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.MinimumSize = New System.Drawing.Size(550, 400)
Me.Name = "Form1"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "Source Live Audio Mixer"
Me.TrackContextMenu.ResumeLayout(False)
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents GameSelector As System.Windows.Forms.ComboBox
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents ImportButton As System.Windows.Forms.Button
Friend WithEvents TrackList As System.Windows.Forms.ListView
Friend WithEvents LoadedCol As System.Windows.Forms.ColumnHeader
Friend WithEvents TrackCol As System.Windows.Forms.ColumnHeader
Friend WithEvents TagsCol As System.Windows.Forms.ColumnHeader
Friend WithEvents StartButton As System.Windows.Forms.Button
Friend WithEvents ImportDialog As System.Windows.Forms.OpenFileDialog
Friend WithEvents ProgressBar1 As System.Windows.Forms.ProgressBar
Friend WithEvents WavWorker As System.ComponentModel.BackgroundWorker
Friend WithEvents PollRelayWorker As System.ComponentModel.BackgroundWorker
Friend WithEvents ChangeDirButton As System.Windows.Forms.Button
Friend WithEvents TrackContextMenu As System.Windows.Forms.ContextMenuStrip
Friend WithEvents ContextDelete As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents ContextRefresh As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents ContextHotKey As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents HotKeyCol As System.Windows.Forms.ColumnHeader
Friend WithEvents RemoveHotkeyToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents GoToToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents PlayKeyButton As System.Windows.Forms.Button
Friend WithEvents VolumeCol As System.Windows.Forms.ColumnHeader
Friend WithEvents SetVolumeToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents TrimToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents Trimmed As System.Windows.Forms.ColumnHeader
Friend WithEvents StatusLabel As System.Windows.Forms.Label
Friend WithEvents RenameToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents StreamB As Button
End Class
|
NoSpread/SLAM-EXTRA
|
SLAM/Form1.Designer.vb
|
Visual Basic
|
mit
| 15,365
|
Option Strict On
Option Explicit On
Imports NUnit.Framework
'Imports Microsoft.VisualBasic
Imports CompuMaster.Data
Namespace CompuMaster.Test.Data
<TestFixture(Category:="Common Utils")> Public Class MsVisualBasicMethodTests
<Test> Public Sub IsDbNullTest()
Assert.IsTrue(Information.IsDBNull(DBNull.Value))
Assert.IsFalse(Information.IsDBNull(Nothing))
Assert.IsFalse(Information.IsDBNull(String.Empty))
Assert.IsFalse(Information.IsDBNull(2.0))
Assert.IsFalse(Information.IsDBNull(New Object))
End Sub
<Test> Public Sub IsNothingTest()
Assert.IsFalse(Information.IsNothing(DBNull.Value))
Assert.IsTrue(Information.IsNothing(Nothing))
Assert.IsTrue(Information.IsNothing(CType(Nothing, String)))
Assert.IsFalse(Information.IsNothing(String.Empty))
Assert.IsFalse(Information.IsNothing(0))
Assert.IsFalse(Information.IsNothing(New Object))
Assert.IsFalse(Information.IsNothing(New Object()))
Assert.IsTrue(Information.IsNothing(CType(Nothing, Object())))
End Sub
<Test> Public Sub IsNumericTest()
Assert.IsFalse(Information.IsNumeric(DBNull.Value))
Assert.IsFalse(Information.IsNumeric(Nothing))
Assert.IsFalse(Information.IsNumeric(CType(Nothing, String)))
Assert.IsFalse(Information.IsNumeric(String.Empty))
Assert.IsTrue(Information.IsNumeric(True))
Assert.IsTrue(Information.IsNumeric(0))
Assert.IsTrue(Information.IsNumeric(0S))
Assert.IsTrue(Information.IsNumeric(Byte.MaxValue))
Assert.IsTrue(Information.IsNumeric(2.0!))
Assert.IsTrue(Information.IsNumeric(2.0))
Assert.IsTrue(Information.IsNumeric(20L))
Assert.IsTrue(Information.IsNumeric(-200D))
Assert.IsFalse(Information.IsNumeric(New Object))
Assert.IsFalse(Information.IsNumeric(New Byte() {200}))
End Sub
<Test> Public Sub IsDateTest()
Assert.IsFalse(Information.IsDate(DBNull.Value))
Assert.IsFalse(Information.IsDate(Nothing))
Assert.IsFalse(Information.IsDate(CType(Nothing, String)))
Assert.IsFalse(Information.IsDate(String.Empty))
Assert.IsFalse(Information.IsDate(0))
Assert.IsFalse(Information.IsDate(New Object))
Assert.IsTrue(Information.IsDate(New DateTime))
Assert.IsFalse(Information.IsDate(New TimeSpan))
End Sub
<Test> Public Sub ControlCharsTest()
Assert.AreEqual(ChrW(13) & ChrW(10), ControlChars.CrLf)
Assert.AreEqual(ChrW(13), ControlChars.Cr)
Assert.AreEqual(ChrW(10), ControlChars.Lf)
Assert.AreEqual(ChrW(9), ControlChars.Tab)
End Sub
<Test> Public Sub TriStateTest()
Assert.AreEqual(-2, CType(TriState.UseDefault, Integer))
Assert.AreEqual(-1, CType(TriState.True, Integer))
Assert.AreEqual(0, CType(TriState.False, Integer))
End Sub
<Test> Public Sub MidTest()
Assert.AreEqual(Nothing, Strings.Mid(Nothing, 2))
Assert.AreEqual("", Strings.Mid(Nothing, 2, 2))
Assert.AreEqual("bcdef", Strings.Mid("abcdef", 2))
Assert.AreEqual("bc", Strings.Mid("abcdef", 2, 2))
Assert.AreEqual("", Strings.Mid("", 2))
Assert.AreEqual("", Strings.Mid("", 2, 2))
End Sub
<Test> Public Sub ReplaceTest()
Assert.AreEqual(Nothing, Strings.Replace(Nothing, "kj", "DD"))
Assert.AreEqual("abcDEfDEf", Strings.Replace("abcdefdef", "de", "DE"))
Assert.AreEqual("abcdefdef", Strings.Replace("abcdefdef", "kj", "DD"))
'Assert.AreEqual(Nothing, Strings.Replace(String.Empty, "kj", "DD")) 'MS VisualBasic behaviour
Assert.AreEqual("", Strings.Replace(String.Empty, "kj", "DD")) 'CM.Data behaviour
End Sub
<Test> Public Sub SpaceTest()
Assert.AreEqual("", Strings.Space(0))
Assert.AreEqual(" ", Strings.Space(4))
End Sub
<Test> Public Sub TrimTest()
Assert.AreEqual("", Strings.Trim(Nothing))
Assert.AreEqual("", Strings.Trim(String.Empty))
Assert.AreEqual("", Strings.Trim(" "))
Assert.AreEqual("ÖLKJ", Strings.Trim(" ÖLKJ "))
End Sub
<Test> Public Sub LenTest()
Assert.AreEqual(0, Strings.Len(CType(Nothing, String)))
Assert.AreEqual(0, Strings.Len(String.Empty))
Assert.AreEqual(4, Strings.Len(" "))
Assert.AreEqual(8, Strings.Len(" ÖLKJ "))
Assert.AreEqual(0, Strings.Len(CType(Nothing, Object)))
Assert.AreEqual(4, Strings.Len(0))
Assert.AreEqual(1, Strings.Len(Byte.MaxValue))
Assert.AreEqual(4, Strings.Len(0!))
Assert.AreEqual(8, Strings.Len(0D))
Assert.AreEqual(8, Strings.Len(0L))
Assert.AreEqual(8, Strings.Len(New DateTime))
Assert.AreEqual(8, Strings.Len(New DateTime(2020, 1, 1)))
Assert.AreEqual(0, Strings.Len(New TimeSpan))
Assert.AreEqual(0, Strings.Len(New TimeSpan(20, 10, 15)))
'Assert.AreEqual(0, Strings.Len(New Byte() {}))
'Assert.AreEqual(2, Strings.Len(New Integer() {1, 2}))
End Sub
<Test> Public Sub StrDupTest()
Assert.AreEqual("", Strings.StrDup(0, "K"c))
Assert.AreEqual(" ", Strings.StrDup(4, " "c))
Assert.AreEqual("KKKK", Strings.StrDup(4, "K"c))
Assert.AreEqual("", Strings.StrDup(0, "K"c))
'Assert.AreEqual(" ", Strings.StrDup(4, " "))
'Assert.AreEqual("KKKK", Strings.StrDup(4, "K"))
'Assert.AreEqual("KKKK", Strings.StrDup(4, "KK"))
End Sub
<Test> Public Sub InStrTest()
Assert.AreEqual(0, Strings.InStr(Nothing, Nothing))
Assert.AreEqual(0, Strings.InStr(Nothing, String.Empty))
Assert.AreEqual(0, Strings.InStr(String.Empty, String.Empty))
Assert.AreEqual(1, Strings.InStr("abcdefdef", String.Empty))
Assert.AreEqual(0, Strings.InStr("abcdefdef", "DE"))
Assert.AreEqual(4, Strings.InStr("abcdefdef", "de"))
End Sub
<Test> Public Sub LSetTest()
Assert.AreEqual("", Strings.LSet("text", 0))
Assert.AreEqual("tex", Strings.LSet("text", 3))
Assert.AreEqual("text", Strings.LSet("text", 4))
Assert.AreEqual("text ", Strings.LSet("text", 8))
Assert.AreEqual("", Strings.LSet("", 0))
Assert.AreEqual(" ", Strings.LSet("", 3))
Assert.AreEqual(" ", Strings.LSet("", 4))
Assert.AreEqual(" ", Strings.LSet("", 8))
Assert.AreEqual("", Strings.LSet(Nothing, 0))
Assert.AreEqual(" ", Strings.LSet(Nothing, 3))
Assert.AreEqual(" ", Strings.LSet(Nothing, 4))
Assert.AreEqual(" ", Strings.LSet(Nothing, 8))
End Sub
<Test> Public Sub RSetTest()
Assert.AreEqual("", Strings.RSet("text", 0))
Assert.AreEqual("tex", Strings.RSet("text", 3))
Assert.AreEqual("text", Strings.RSet("text", 4))
Assert.AreEqual(" text", Strings.RSet("text", 8))
Assert.AreEqual("", Strings.RSet("", 0))
Assert.AreEqual(" ", Strings.RSet("", 3))
Assert.AreEqual(" ", Strings.RSet("", 4))
Assert.AreEqual(" ", Strings.RSet("", 8))
Assert.AreEqual("", Strings.RSet(Nothing, 0))
Assert.AreEqual(" ", Strings.RSet(Nothing, 3))
Assert.AreEqual(" ", Strings.RSet(Nothing, 4))
Assert.AreEqual(" ", Strings.RSet(Nothing, 8))
End Sub
<Test> Public Sub LCaseTest()
'Assert.AreEqual(ChrW(0), Strings.LCase(Nothing)) 'MS.VisualBasic behaviour
Assert.AreEqual("", Strings.LCase(Nothing)) 'CM.Data behaviour
Assert.AreEqual("", Strings.LCase(""))
Assert.AreEqual("abcdefdef", Strings.LCase("abcDEfdef"))
Assert.AreEqual("abcdefdefäöüß", Strings.LCase("abcDEfdefäÖüß"))
End Sub
<Test> Public Sub UCaseTest()
'Assert.AreEqual(ChrW(0), Strings.UCase(Nothing)) 'MS.VisualBasic behaviour
Assert.AreEqual("", Strings.UCase(Nothing)) 'CM.Data behaviour
Assert.AreEqual("", Strings.UCase(""))
Assert.AreEqual("ABCDEFDEF", Strings.UCase("abcDEfdef"))
Assert.AreEqual("ABCDEFDEFÄÖÜß", Strings.UCase("abcDEfdefäÖüß"))
End Sub
End Class
End Namespace
|
CompuMasterGmbH/CompuMaster.Data
|
CompuMaster.Test.Tools.Data/MsVisualBasicMethodTests.vb
|
Visual Basic
|
mit
| 8,840
|
**Archive**
Imports mshtml
Imports BeffsBrowser.My.Resources
Imports System.Net
Imports System.IO
Imports System.Deployment.Application
Public Class BBMain
#Region "load items"
Dim int As Integer = 0
Private Sub Loading(ByVal sender As Object, ByVal e As Windows.Forms.WebBrowserProgressChangedEventArgs)
ToolStripProgressBar1.Maximum = e.MaximumProgress
ToolStripProgressBar1.Value = e.MaximumProgress
End Sub
Private Sub Done(ByVal sender As Object, ByVal e As Windows.Forms.WebBrowserDocumentCompletedEventArgs)
Tabcontrol1.SelectedTab.Text = CType(Tabcontrol1.SelectedTab.Controls.Item(0), WebBrowser).DocumentTitle
ToolStripTextBox1.Text = CType(Tabcontrol1.SelectedTab.Controls.Item(0), WebBrowser).Url.ToString
History.ListBox1.Items.Add(ToolStripTextBox1.Text)
Save_History()
End Sub
Public Sub LoadUpSettings()
RestartComputerToolStripMenuItem.Visible = False
CheckBox1.Visible = False
Timer1.Start()
ToolStripLabel1.Text = Today
ToolStripTextBox1.ShortcutsEnabled = False
Try
Dim tab As New TabPage
Dim brws As New WebBrowser
brws.Dock = DockStyle.Fill
tab.Text = " New Tab"
tab.Controls.Add(brws)
Me.Tabcontrol1.TabPages.Add(tab)
Me.Tabcontrol1.SelectedTab = tab
brws.Navigate(My.Settings.HomeSpace)
brws.ScriptErrorsSuppressed = True
AddHandler brws.ProgressChanged, AddressOf Loading
AddHandler brws.DocumentCompleted, AddressOf Done
int = int + 0.5
Catch ex As Exception
End Try
End Sub
Public Sub favload()
Try
int = int + 0.5
Dim tab As New TabPage
Dim brws As New WebBrowser
brws.Dock = DockStyle.Fill
tab.Text = " New Tab"
tab.Controls.Add(brws)
Me.Tabcontrol1.TabPages.Add(tab)
Me.Tabcontrol1.SelectedTab = tab
brws.Navigate(ToolStripTextBox1.Text)
brws.ScriptErrorsSuppressed = True
Catch ex As Exception
End Try
End Sub
Private Sub BBMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
WebBrowserHelper.FixBrowserVersion()
AutoScaleMode = My.Settings.Visual
CheckBox1.Visible = False
If CheckBox1.Checked = True Then favload()
CheckBox2.Visible = False
ToolStripButton6.Visible = False
Dim statuslabel As New Label
statuslabel.Anchor = AnchorStyles.Bottom
If Today = "04/06/2016" Then
MsgBox("You should check for news or updates today!")
Try
int = int + 0.5
Dim tab As New TabPage
Dim brws As New WebBrowser
brws.Dock = DockStyle.Fill
tab.Text = " New Tab"
tab.Controls.Add(brws)
Me.Tabcontrol1.TabPages.Add(tab)
Me.Tabcontrol1.SelectedTab = tab
brws.Navigate("http://beffsbrowser.codeplex.com")
brws.ScriptErrorsSuppressed = True
Catch ex As Exception
End Try
End If
LoadUpSettings()
End Sub
#End Region
#Region "navigation controls"
Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click, RefreshToolStripMenuItem.Click
Try
Dim brws As New WebBrowser
brws.ScriptErrorsSuppressed = True
AddHandler brws.ProgressChanged, AddressOf Loading
AddHandler brws.DocumentCompleted, AddressOf Done
int = int + 0.5
CType(Tabcontrol1.SelectedTab.Controls.Item(0), WebBrowser).Refresh()
Catch ex As Exception
End Try
End Sub
Private Sub ToolStripButton2_Click(sender As Object, e As EventArgs) Handles ToolStripButton2.Click
Try
Dim brws As New WebBrowser
brws.ScriptErrorsSuppressed = True
AddHandler brws.ProgressChanged, AddressOf Loading
AddHandler brws.DocumentCompleted, AddressOf Done
int = int + 1
CType(Tabcontrol1.SelectedTab.Controls.Item(0), WebBrowser).Navigate(ToolStripTextBox1.Text)
Catch ex As Exception
End Try
End Sub
Private Sub ForwardToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ForwardToolStripMenuItem.Click
Try
Dim brws As New WebBrowser
brws.ScriptErrorsSuppressed = True
AddHandler brws.ProgressChanged, AddressOf Loading
AddHandler brws.DocumentCompleted, AddressOf Done
int = int + 1
CType(Tabcontrol1.SelectedTab.Controls.Item(0), WebBrowser).GoForward()
Catch ex As Exception
End Try
End Sub
Private Sub BackToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles BackToolStripMenuItem.Click
Try
Dim brws As New WebBrowser
brws.ScriptErrorsSuppressed = True
AddHandler brws.ProgressChanged, AddressOf Loading
AddHandler brws.DocumentCompleted, AddressOf Done
int = int + 1
CType(Tabcontrol1.SelectedTab.Controls.Item(0), WebBrowser).GoBack()
Catch ex As Exception
End Try
End Sub
Private Sub NewTabToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NewTabToolStripMenuItem.Click
Try
Dim tab As New TabPage
Dim brws As New WebBrowser
brws.Dock = DockStyle.Fill
tab.Text = " New Tab"
tab.Controls.Add(brws)
Me.Tabcontrol1.TabPages.Add(tab)
Me.Tabcontrol1.SelectedTab = tab
brws.Navigate(My.Settings.HomeSpace)
brws.ScriptErrorsSuppressed = True
AddHandler brws.ProgressChanged, AddressOf Loading
AddHandler brws.DocumentCompleted, AddressOf Done
int = int + 1
Catch ex As Exception
End Try
End Sub
Private Sub NewWindowToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NewWindowToolStripMenuItem.Click
Dim window As New BBMain
window.Show()
End Sub
Private Sub CloseWindowToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CloseWindowToolStripMenuItem.Click
Close()
End Sub
#End Region
#Region "full screen and form close"
Private Sub BeffsBrowserMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
Dim Result As DialogResult
If Tabcontrol1.TabCount = 2 Then
Result = MessageBox.Show("You have 2 or more Tabs open. Are you sure you wanna exit?", "BeffsBrowser is shutting down", MessageBoxButtons.YesNo)
'if user clicked no, cancel form closing
ElseIf Result = System.Windows.Forms.DialogResult.No Then
e.Cancel = True
End If
End Sub
#End Region
#Region "Others"
Dim tabcontrol As New BeffsBrowser.beffscustomtabcontrol
#End Region
#Region "Utility"
Private Sub ToolStripButton3_Click(sender As Object, e As EventArgs) Handles ToolStripButton3.Click
Try
Dim brws As New WebBrowser
brws.ScriptErrorsSuppressed = True
AddHandler brws.ProgressChanged, AddressOf Loading
AddHandler brws.DocumentCompleted, AddressOf Done
int = int + 0.5
CType(Tabcontrol1.SelectedTab.Controls.Item(0), WebBrowser).Navigate(My.Settings.SearchP & ToolStripTextBox1.Text)
Catch ex As Exception
End Try
End Sub
Private Sub ToolStripButton4_Click(sender As Object, e As EventArgs) Handles ToolStripButton4.Click, StopToolStripMenuItem.Click
Try
Dim brws As New WebBrowser
brws.ScriptErrorsSuppressed = True
AddHandler brws.ProgressChanged, AddressOf Loading
AddHandler brws.DocumentCompleted, AddressOf Done
int = int - 0.5
CType(Tabcontrol1.SelectedTab.Controls.Item(0), WebBrowser).Stop()
Catch ex As Exception
End Try
End Sub
Private Sub Timer1_Tick_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Label1.Text = TimeOfDay
End Sub
Private Sub ToolStripLabel1_textchanged(sender As Object, e As EventArgs) Handles ToolStripLabel1.TextChanged
ToolStripLabel1.Text = Today
End Sub
Private Sub WhatsNewToolStripMenuItem1_Click(sender As Object, e As EventArgs)
MsgBox("Added some new improvements removed christmas items. Copyright 2015-2016 BeffsBrowser ")
End Sub
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
MsgBox("The current time is:" + vbNewLine + Label1.Text)
End Sub
Private Sub ToolStripButton6_Click(sender As Object, e As EventArgs)
MsgBox("BeffsEasy Keyboard is coming soon!")
End Sub
Private Sub ToolStripLabel1_Click(sender As Object, e As EventArgs) Handles ToolStripLabel1.Click
MsgBox("Todays date is:" + vbNewLine + ToolStripLabel1.Text)
End Sub
Private Sub RestartComputerToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles RestartComputerToolStripMenuItem.Click
'Dim window As New rebootcomputercap
'window.Show()
MessageBox.Show("This feature has been temp. removed. See the change log for version 1.6.0 for more information.")
End Sub
Private Sub DaysTillXmasToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DaysTillXmasToolStripMenuItem.Click
MsgBox("Days until Xmas: " & DateDiff("d", Now, "December 25, 2016"))
End Sub
#Region "MoreItems mostly random and newer"
Private Sub ToolStripButton7_Click(sender As Object, e As EventArgs) Handles ToolStripButton7.Click
Try
Dim tab As New TabPage
Dim brws As New WebBrowser
brws.ScriptErrorsSuppressed = True
AddHandler brws.ProgressChanged, AddressOf Loading
AddHandler brws.DocumentCompleted, AddressOf Done
int = int + 0.5
brws.Dock = DockStyle.Fill
tab.Text = " New Tab"
tab.Controls.Add(brws)
Me.Tabcontrol1.TabPages.Add(tab)
Me.Tabcontrol1.SelectedTab = tab
brws.Navigate(My.Settings.HomeSpace) 'change it to your browser control name
My.Settings.Save()
My.Settings.Reload()
Catch ex As Exception
End Try
End Sub
Private Sub SettingsToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles SettingsToolStripMenuItem1.Click
Dim window As New BBSettingsBasics
window.Show()
End Sub
Private Sub PrintToolStripMenuItem_Click(sender As Object, e As EventArgs)
Dim brws As New WebBrowser
Try
CType(Tabcontrol1.SelectedTab.Controls.Item(0), WebBrowser).ShowPrintDialog()
Catch ex As Exception
End Try
End Sub
Private Sub AboutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AboutToolStripMenuItem.Click
Beep()
MsgBox(" BeffsBrowser (c) 2015-2017")
End Sub
Private Sub PrintToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles PrintToolStripMenuItem1.Click
Dim brws As New WebBrowser
Try
CType(Tabcontrol1.SelectedTab.Controls.Item(0), WebBrowser).ShowPrintDialog()
Catch ex As Exception
End Try
End Sub
#End Region
#Region "Lastly items"
Public Event Navigated As WebBrowserNavigatedEventHandler
Private Sub toolStripTextBox1_KeyDown( _
ByVal sender As Object, ByVal e As KeyEventArgs) _
Handles ToolStripTextBox1.KeyDown
Try
If (e.KeyCode = Keys.Enter) Then
Dim brws As New WebBrowser
brws.ScriptErrorsSuppressed = True
AddHandler brws.ProgressChanged, AddressOf Loading
AddHandler brws.DocumentCompleted, AddressOf Done
int = int + 0.5
CType(Tabcontrol1.SelectedTab.Controls.Item(0), WebBrowser).Navigate(ToolStripTextBox1.Text)
End If
Catch ex As Exception
End Try
End Sub
Private Sub SaveFileAsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveFileAsToolStripMenuItem.Click
CType(Tabcontrol1.SelectedTab.Controls.Item(0), WebBrowser).ShowSaveAsDialog()
End Sub
Private Sub toolstripTextBox1_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles ToolStripTextBox1.MouseDown
If e.Button = Windows.Forms.MouseButtons.Right Then
If My.Computer.Clipboard.ContainsText Then
ToolStripTextBox1.Paste()
CType(Tabcontrol1.SelectedTab.Controls.Item(0), WebBrowser).Navigate(ToolStripTextBox1.Text)
If Not ToolStripTextBox1.Text = "http://" & "https://" Then
MsgBox("sorry for shortcuts you will need the http:// or https://")
CType(Tabcontrol1.SelectedTab.Controls.Item(0), WebBrowser).GoBack()
End If
End If
End If
End Sub
Public Sub Save_History()
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter(My.Settings.History, True)
For Each Str As String In History.ListBox1.Items
file.WriteLine(Str)
Next
file.Close()
End Sub
Private Sub PrintPreviewToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles PrintPreviewToolStripMenuItem1.Click
CType(Tabcontrol1.SelectedTab.Controls.Item(0), WebBrowser).ShowPrintPreviewDialog()
End Sub
'FullScreen
Private Sub ToolStripButton5_Click(sender As Object, e As EventArgs) Handles ToolStripButton5.Click, FullScreenToolStripMenuItem.Click
ToolStripButton5.Visible = False
ControlBox = False
Me.WindowState = FormWindowState.Maximized
Me.Size = SystemInformation.PrimaryMonitorSize
Me.WindowState = 2
Me.Location = New Point(0, 0)
Me.TopMost = True
Me.FormBorderStyle = 0
Me.TopMost = True
ToolStripButton6.Visible = True
End Sub
'Exit FullScreen.
Private Sub ToolStripButton6_Click_1(sender As Object, e As EventArgs) Handles ToolStripButton6.Click, ExitFullScreenToolStripMenuItem.Click
Me.WindowState = FormWindowState.Normal
Me.Size = MaximumSize
Me.FormBorderStyle = FormBorderStyle.Sizable
ToolStripButton5.Visible = True
ControlBox = True
Me.TopMost = False
ToolStripButton6.Visible = False
End Sub
Public Sub favorites()
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter(My.Settings.Favlist, True)
For Each Str As String In NewFavs.ListBox1.Items
file.WriteLine(Str)
Next
file.Close()
End Sub
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked = True Then
favload()
ElseIf CheckBox1.Checked = False Then
'do nothing
End If
End Sub
Private Sub CheckBox2_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox2.CheckedChanged
If CheckBox2.Checked = True Then
Try
int = int + 0.5
Dim tab As New TabPage
Dim brws As New WebBrowser
brws.Dock = DockStyle.Fill
tab.Text = " New Tab"
tab.Controls.Add(brws)
Me.Tabcontrol1.TabPages.Add(tab)
Me.Tabcontrol1.SelectedTab = tab
brws.Navigate(ToolStripTextBox1.Text)
brws.ScriptErrorsSuppressed = True
Catch ex As Exception
End Try
Else
'do nothing
End If
End Sub
Private Sub ToolStripLabel2_Click(sender As Object, e As EventArgs) Handles ToolStripLabel2.Click
CheckForUpdates.Show()
End Sub
Public Sub updates()
Try
Dim tab As New TabPage
Dim brws As New WebBrowser
brws.ScriptErrorsSuppressed = True
AddHandler brws.ProgressChanged, AddressOf Loading
AddHandler brws.DocumentCompleted, AddressOf Done
int = int + 0.5
brws.Dock = DockStyle.Fill
tab.Text = " New Tab"
tab.Controls.Add(brws)
Me.Tabcontrol1.TabPages.Add(tab)
Me.Tabcontrol1.SelectedTab = tab
brws.Navigate("http://" + CheckForUpdates.TextBox1.Text) 'change it to your browser control name
My.Settings.Save()
My.Settings.Reload()
Catch ex As Exception
End Try
End Sub
Private Sub YouTubeConverterToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles YouTubeConverterToolStripMenuItem.Click
Dim a As New BeffsYouTubeDownloader
a.Show()
End Sub
Private Sub AddToFavoritesToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AddToFavoritesToolStripMenuItem.Click
NewFavs.ListBox1.Items.Add(ToolStripTextBox1.Text)
favorites()
End Sub
End Class
|
jdc20181/BeffsBrowser
|
Archive/BeffsBrowserMain.vb
|
Visual Basic
|
mit
| 17,435
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'<summary>
' A strongly-typed resource class, for looking up localized strings, etc.
'</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'<summary>
' Returns the cached ResourceManager instance used by this class.
'</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("Problem_5.Youngest_person.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'<summary>
' Overrides the current thread's CurrentUICulture property for all
' resource lookups using this strongly typed resource class.
'</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set(ByVal value As Global.System.Globalization.CultureInfo)
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
Telerik-Homework-ValentinRangelov/Homework
|
Web/JavaScript/Using Objects/Problem 5. Youngest person/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,775
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:2.0.50727.5420
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings),MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.asclc.My.MySettings
Get
Return Global.asclc.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
Damillora/ascl
|
My Project/Settings.Designer.vb
|
Visual Basic
|
apache-2.0
| 2,896
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.269
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Imports System
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("App.Tests.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
WillSams/CustomerOrders-NancyFX-VB
|
tests/My Project/Resources.Designer.vb
|
Visual Basic
|
apache-2.0
| 2,713
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Language
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageFeatures
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
''' Note:
''' * Tests for Flow Analysis APIs are under FlowAnalysis folder
''' * Tests for GetDeclaredSymbol API are in SemanticModelGetDeclaredSymbolAPITests.vb
''' * Tests for LookupSymbols API are in SemanticModelLookupSymbolsAPITests.vb
Public Class SemanticModelAPITests
Inherits SemanticModelTestBase
#Region "Get Various Semantic Info, such as GetSymbolInfo, GetTypeInfo"
<WorkItem(541500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541500")>
<Fact()>
Public Sub TestModuleNamespaceClassNesting()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation name="TestModuleNamespaceClassNesting">
<file name="a.vb">
Module
Namespace
Public Class
Public Shared x As Integer1 = 0
End Class
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim syntaxNode = tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierName, 2).AsNode()
Dim info = model.GetSemanticInfoSummary(DirectCast(syntaxNode, ExpressionSyntax))
Assert.Equal(CandidateReason.None, info.CandidateReason)
End Sub
<Fact(), WorkItem(543532, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543532")>
Public Sub GetSymbolInfoForImplicitDeclaredControlVariable()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Friend Module M
Sub Main(args As String())
For i = 0 To 1
Console.Write("Hi")
Next
For Each i In args
Next
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim children = tree.GetCompilationUnitRoot().DescendantNodes()
Dim forstat = children.OfType(Of ForStatementSyntax).First()
Dim ctrlvar = TryCast(forstat.ControlVariable, ExpressionSyntax)
Assert.NotNull(ctrlvar)
Dim syminfo = semanticModel.GetSymbolInfo(ctrlvar)
Assert.NotNull(syminfo.Symbol)
Assert.Equal(SymbolKind.Local, syminfo.Symbol.Kind)
Dim foreach = children.OfType(Of ForEachStatementSyntax).First()
ctrlvar = TryCast(foreach.ControlVariable, ExpressionSyntax)
Assert.NotNull(ctrlvar)
syminfo = semanticModel.GetSymbolInfo(ctrlvar)
Assert.NotNull(syminfo.Symbol)
Assert.Equal(SymbolKind.Local, syminfo.Symbol.Kind)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact()>
Public Sub GetSymbolInfoForVarianceConversion()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System.Collections.Generic
Class A : End Class
Class B
Inherits A
End Class
Module Module1
Sub Main()
Dim c1 As IEnumerable(Of B) = New List(Of B) From {New B}
Dim c2 As IEnumerable(Of A) = c1
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LocalDeclarationStatementSyntax).Skip(1).First
Dim expr1 As ExpressionSyntax = node.Declarators(0).Initializer.Value
Assert.Equal("c1", expr1.ToString())
Dim infoP = semanticModel.GetSemanticInfoSummary(expr1)
Dim node2 = CompilationUtils.FindTokenFromText(tree, "c2").Parent
Dim declSym = semanticModel.GetDeclaredSymbol(DirectCast(node2, ModifiedIdentifierSyntax))
Dim IEnumerableOfA As TypeSymbol = DirectCast(declSym, LocalSymbol).Type
Assert.Equal(IEnumerableOfA, infoP.ConvertedType)
Assert.Equal(SymbolKind.Local, infoP.Symbol.Kind)
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub GetSymbolInfoForVarianceConversionWithStaticLocals()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System.Collections.Generic
Class A : End Class
Class B
Inherits A
End Class
Module Module1
Sub Main()
Static c1 As IEnumerable(Of B) = New List(Of B) From {New B}
Static c2 As IEnumerable(Of A) = c1
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LocalDeclarationStatementSyntax).Skip(1).First
Dim expr1 As ExpressionSyntax = node.Declarators(0).Initializer.Value
Assert.Equal("c1", expr1.ToString())
Dim infoP = semanticModel.GetSemanticInfoSummary(expr1)
Dim node2 = CompilationUtils.FindTokenFromText(tree, "c2").Parent
Dim declSym = semanticModel.GetDeclaredSymbol(DirectCast(node2, ModifiedIdentifierSyntax))
Dim IEnumerableOfA As TypeSymbol = DirectCast(declSym, LocalSymbol).Type
Assert.Equal(IEnumerableOfA, infoP.ConvertedType)
Assert.Equal(SymbolKind.Local, infoP.Symbol.Kind)
End Sub
<Fact(), WorkItem(542861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542861"), WorkItem(529673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529673")>
Public Sub GetSymbolInfoForAccessorParameters()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Public Class Test
Dim _Items(3) As Object
Default Public Property Item(index As Integer) As Object
Get
Return _Items(index)
End Get
Set(value As Object)
_Items(index) = value
End Set
End Property
End Class
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim descendants = tree.GetCompilationUnitRoot().DescendantNodes()
Dim paras = descendants.OfType(Of ParameterSyntax)()
Dim parasym = semanticModel.GetDeclaredSymbol(paras.First())
Dim ploc = parasym.Locations(0)
Dim args = descendants.OfType(Of SimpleArgumentSyntax).Where(Function(s) s.ToString() = "index").Select(Function(s) s)
Assert.Equal(2, args.Count())
Dim argsym1 = semanticModel.GetSymbolInfo(args.First().Expression).Symbol
Dim argsym2 = semanticModel.GetSymbolInfo(args.Last().Expression).Symbol
Assert.NotNull(argsym1)
Assert.NotNull(argsym2)
Assert.Equal(ploc, argsym1.Locations(0))
Assert.Equal(ploc, argsym2.Locations(0))
Assert.Equal(parasym.Kind, argsym1.Kind)
Assert.Equal(parasym.Kind, argsym2.Kind)
Assert.NotEqual(parasym, argsym1)
Assert.NotEqual(parasym, argsym2)
End Sub
<Fact>
Public Sub LabelSymbolsAreEquivalentAcrossSemanticModelsFromSameCompilation()
Dim text = <code>
Public Class C
Public Sub M()
label:
goto label
End Sub
End Class
</code>.Value
Dim tree = Parse(text)
Dim comp = CreateCompilationWithMscorlib40({tree})
Dim model1 = comp.GetSemanticModel(tree)
Dim model2 = comp.GetSemanticModel(tree)
Assert.NotEqual(model1, model2)
Dim statement = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of GoToStatementSyntax)().First()
Dim symbol1 = model1.GetSymbolInfo(statement.Label).Symbol
Dim symbol2 = model2.GetSymbolInfo(statement.Label).Symbol
Assert.Equal(False, symbol1 Is symbol2)
Assert.Equal(symbol1, symbol2)
End Sub
#End Region
#Region "GetSpeculativeXXXInfo"
<Fact()>
Public Sub BindExpression()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="GetSemanticInfo">
<file name="a.vb">
Imports System
Class B
Public f1 as Integer
End Class
Class M
Public Sub Main()
Dim bInstance As B
Console.WriteLine("hi") 'BIND:"Console.WriteLine"
End Sub
End Class
</file>
</compilation>)
Dim globalNS = compilation.GlobalNamespace
Dim classB = DirectCast(globalNS.GetMembers("B").Single(), NamedTypeSymbol)
Dim fieldF1 = DirectCast(classB.GetMembers("f1").Single(), FieldSymbol)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim position As Integer = CompilationUtils.FindPositionFromText(tree, "WriteLine")
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim treeForExpression = CompilationUtils.CreateParseTree(
<file name="speculative.vb">
Module Q
Sub x()
a = bInstance.GetType()
End Sub
End Module
</file>)
Dim expression = CompilationUtils.FindNodeOfTypeFromText(Of NameSyntax)(treeForExpression, "bInstance")
Dim semanticInfo As SemanticInfoSummary = semanticModel.GetSpeculativeSemanticInfoSummary(position, expression, SpeculativeBindingOption.BindAsExpression)
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind)
Assert.Equal("bInstance", semanticInfo.Symbol.Name)
Assert.Equal("B", semanticInfo.Type.ToTestDisplayString())
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact()>
Public Sub BindExpressionWithErrors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="GetSemanticInfo">
<file name="a.vb">
Option Strict On
Imports System
Class B
Public f1 as Integer
Public Sub goo(x as Object)
End Sub
End Class
Class M
Public Shared Sub Main()
Dim o As Object
Console.WriteLine("hi")
End Sub
Public Sub Bar()
dim zip as Object
End Sub
End Class
</file>
</compilation>)
Dim globalNS = compilation.GlobalNamespace
Dim classB = DirectCast(globalNS.GetMembers("B").Single(), NamedTypeSymbol)
Dim fieldF1 = DirectCast(classB.GetMembers("f1").Single(), FieldSymbol)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim position1 = CompilationUtils.FindPositionFromText(tree, "WriteLine")
Dim position2 = CompilationUtils.FindPositionFromText(tree, "zip")
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim treeForExpression = CompilationUtils.CreateParseTree(
<file name="speculative.vb">
Class Q
Sub x()
o = Me
End Sub
End Class
</file>)
Dim expression = CompilationUtils.FindNodeOfTypeFromText(Of ExpressionSyntax)(treeForExpression, "Me")
Dim semanticInfo As SemanticInfoSummary = semanticModel.GetSpeculativeSemanticInfoSummary(position1, expression, SpeculativeBindingOption.BindAsExpression)
Assert.Equal("M", semanticInfo.Type.ToTestDisplayString())
semanticInfo = semanticModel.GetSpeculativeSemanticInfoSummary(position2, expression, SpeculativeBindingOption.BindAsExpression)
Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind)
Assert.True(DirectCast(semanticInfo.Symbol, ParameterSymbol).IsMe)
Assert.Equal("M", semanticInfo.Type.ToTestDisplayString())
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact()>
Public Sub BindAsExpressionVsBindAsType()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Option Strict On
Imports System
Imports B = System.Console
Class M
Public B As Integer
Public Sub M()
Console.WriteLine("hi")
End Sub
End Class
</file>
</compilation>)
Dim globalNS = compilation.GlobalNamespace
Dim classM = DirectCast(globalNS.GetMembers("M").Single(), NamedTypeSymbol)
Dim fieldB = DirectCast(classM.GetMembers("B").Single(), FieldSymbol)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim position1 = CompilationUtils.FindPositionFromText(tree, "WriteLine")
Dim expression = SyntaxFactory.ParseExpression("B")
Dim semanticInfoExpression = semanticModel.GetSpeculativeSemanticInfoSummary(position1, expression, SpeculativeBindingOption.BindAsExpression)
Assert.Equal(fieldB, semanticInfoExpression.Symbol)
Assert.Equal("System.Int32", semanticInfoExpression.Type.ToTestDisplayString())
Assert.Null(semanticInfoExpression.Alias)
semanticInfoExpression = semanticModel.GetSpeculativeSemanticInfoSummary(position1, expression, SpeculativeBindingOption.BindAsTypeOrNamespace)
Assert.Equal("System.Console", semanticInfoExpression.Symbol.ToTestDisplayString())
Assert.Equal("System.Console", semanticInfoExpression.Type.ToTestDisplayString())
Assert.NotNull(semanticInfoExpression.Alias)
Assert.Equal("B=System.Console", semanticInfoExpression.Alias.ToTestDisplayString())
End Sub
<Fact>
Public Sub BindSpeculativeAttribute()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Option Strict On
Imports System
Imports O = System.ObsoleteAttribute
Class C
Class DAttribute : Inherits Attribute
End Class
Class E
End Class
Sub Goo(Of O)()
End Sub
<Serializable> Private i As Integer
End Class </file>
</compilation>, options:=TestOptions.ReleaseExe.WithEmbedVbCoreRuntime(True))
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim position1 = CompilationUtils.FindPositionFromText(tree, "Class C")
Dim attr1 = ParseAttributeSyntax("<Obsolete>")
Dim symbolInfo = semanticModel.GetSpeculativeSymbolInfo(position1, attr1)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, CandidateReason.None)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("Sub System.ObsoleteAttribute..ctor()", symbolInfo.Symbol.ToTestDisplayString())
Dim attr2 = ParseAttributeSyntax("<ObsoleteAttribute(4)>")
symbolInfo = semanticModel.GetSpeculativeSymbolInfo(position1, attr2)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, CandidateReason.OverloadResolutionFailure)
Assert.Equal(3, symbolInfo.CandidateSymbols.Length)
Assert.Equal("Sub System.ObsoleteAttribute..ctor()", symbolInfo.CandidateSymbols(0).ToTestDisplayString())
Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", symbolInfo.CandidateSymbols(1).ToTestDisplayString())
Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String, [error] As System.Boolean)", symbolInfo.CandidateSymbols(2).ToTestDisplayString())
Dim attr3 = ParseAttributeSyntax("<O(""hello"")>")
symbolInfo = semanticModel.GetSpeculativeSymbolInfo(position1, attr3)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, CandidateReason.None)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", symbolInfo.Symbol.ToTestDisplayString())
Dim attr4 = ParseAttributeSyntax("<P>")
symbolInfo = semanticModel.GetSpeculativeSymbolInfo(position1, attr4)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, CandidateReason.None)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim position2 = CompilationUtils.FindPositionFromText(tree, "Class E")
Dim attr5 = ParseAttributeSyntax("<D>")
symbolInfo = semanticModel.GetSpeculativeSymbolInfo(position2, attr5)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, CandidateReason.None)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("Sub C.DAttribute..ctor()", symbolInfo.Symbol.ToTestDisplayString())
Dim position3 = CompilationUtils.FindPositionFromText(tree, "Sub Goo")
Dim attr6 = ParseAttributeSyntax("<O(""hello"")>")
symbolInfo = semanticModel.GetSpeculativeSymbolInfo(position2, attr6)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, CandidateReason.None)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", symbolInfo.Symbol.ToTestDisplayString())
Dim position4 = CompilationUtils.FindPositionFromText(tree, "Serializable")
Dim attr7 = ParseAttributeSyntax("<D>")
symbolInfo = semanticModel.GetSpeculativeSymbolInfo(position2, attr5)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, CandidateReason.None)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("Sub C.DAttribute..ctor()", symbolInfo.Symbol.ToTestDisplayString())
End Sub
<Fact>
<WorkItem(92898, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems?_a=edit&id=92898")>
<WorkItem(755801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755801")>
Public Sub GetSpeculativeSymbolInfoForQualifiedNameInCref()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="GetSemanticInfo">
<file name="a.vb"><![CDATA[
Class C
Public Sub Bar(Of T)(ByVal x As T)
End Sub
Public Sub Bar(ByVal x As Integer)
End Sub
''' <summary>
''' <see cref="Global.C.Bar(Of T)"/>
''' </summary>
Public Sub F()
End Sub
End Class]]>
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot
Dim crefSyntax = root.DescendantNodes(descendIntoTrivia:=True).OfType(Of CrefReferenceSyntax).Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim symbolInfo = semanticModel.GetSymbolInfo(crefSyntax.Name)
Assert.Equal(SyntaxKind.QualifiedName, crefSyntax.Name.Kind())
Assert.Equal("Global.C.Bar(Of T)", crefSyntax.Name.ToString())
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal(SymbolKind.Method, symbolInfo.Symbol.Kind)
Assert.Equal("Sub C.Bar(Of T)(x As T)", symbolInfo.Symbol.ToTestDisplayString())
Dim speculatedName = DirectCast(SyntaxFactory.ParseName("C.Bar(Of T)"), QualifiedNameSyntax)
Dim speculativeSymbolInfo = semanticModel.GetSpeculativeSymbolInfo(crefSyntax.Name.Position, speculatedName, SpeculativeBindingOption.BindAsExpression)
Const bug92898IsFixed = False
If bug92898IsFixed Then
Assert.NotNull(speculativeSymbolInfo.Symbol)
Assert.Equal(SymbolKind.Method, speculativeSymbolInfo.Symbol.Kind)
Assert.Equal("Sub C.Bar(Of T)(x As T)", speculativeSymbolInfo.Symbol.ToTestDisplayString())
Else
Assert.Null(speculativeSymbolInfo.Symbol)
End If
End Sub
<Fact>
<WorkItem(96477, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems#_a=edit&id=96477")>
<WorkItem(1015560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1015560")>
Public Sub GetSpeculativeSymbolInfoForGenericNameInCref()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="GetSemanticInfo">
<file name="a.vb"><![CDATA[Imports System.Collections.Generic
Module Program
''' <see cref="System.Collections.Generic.List(Of T).Contains(T)"/>
Sub Main()
End Sub
End Module]]>
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees.Single()
Dim root = tree.GetCompilationUnitRoot
Dim crefSyntax = root.DescendantNodes(descendIntoTrivia:=True).OfType(Of CrefReferenceSyntax).Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node = DirectCast(DirectCast(crefSyntax.Name, QualifiedNameSyntax).Left, QualifiedNameSyntax)
Assert.Equal("System.Collections.Generic.List(Of T)", node.ToString())
Dim symbolInfo = semanticModel.GetSymbolInfo(node)
Dim oldSymbol = symbolInfo.Symbol
Assert.NotNull(oldSymbol)
Assert.Equal(SymbolKind.NamedType, oldSymbol.Kind)
Assert.Equal("System.Collections.Generic.List(Of T)", oldSymbol.ToTestDisplayString())
Assert.False(DirectCast(oldSymbol, NamedTypeSymbol).TypeArguments.Single.IsErrorType)
Dim speculatedName = DirectCast(SyntaxFactory.ParseName("List(Of T)"), GenericNameSyntax)
Dim speculativeSymbolInfo = semanticModel.GetSpeculativeSymbolInfo(crefSyntax.SpanStart, speculatedName, SpeculativeBindingOption.BindAsTypeOrNamespace)
Dim newSymbol = speculativeSymbolInfo.Symbol
Assert.NotNull(newSymbol)
Assert.Equal(SymbolKind.NamedType, newSymbol.Kind)
Assert.Equal("System.Collections.Generic.List(Of T)", newSymbol.ToTestDisplayString())
Const bug96477IsFixed = False
If bug96477IsFixed Then
Assert.False(DirectCast(newSymbol, NamedTypeSymbol).TypeArguments.Single.IsErrorType)
Assert.True(newSymbol.Equals(oldSymbol))
Else
Assert.True(DirectCast(newSymbol, NamedTypeSymbol).TypeArguments.Single.IsErrorType)
End If
End Sub
#End Region
#Region "TryGetSpeculativeSemanticModel"
<Fact()>
Public Sub TestGetSpeculativeSemanticModelForExpression_ConstantInfo()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="GetSemanticInfo">
<file name="a.vb">
Imports System
Class B
Public f1 as Integer
End Class
Class M
Public Sub Main()
Dim bInstance As B = New B()
Console.WriteLine("hi")
End Sub
End Class
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim typeBlock = DirectCast(root.Members(1), TypeBlockSyntax)
Dim methodBlock = DirectCast(typeBlock.Members(0), MethodBlockSyntax)
Dim originalStatement = DirectCast(methodBlock.Statements(0), ExecutableStatementSyntax)
Dim originalExpression = originalStatement.DescendantNodes().Where(Function(syntax) syntax.Kind = SyntaxKind.ObjectCreationExpression).FirstOrDefault()
Dim speculatedExpression = SyntaxFactory.ParseExpression("DirectCast(3, Integer)")
Dim speculatedStatement = originalStatement.ReplaceNode(originalExpression, speculatedExpression)
speculatedExpression = speculatedStatement.DescendantNodes().OfType(Of CastExpressionSyntax).Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Assert.False(semanticModel.IsSpeculativeSemanticModel)
Assert.Null(semanticModel.ParentModel)
Assert.Equal(0, semanticModel.OriginalPositionForSpeculation)
' Test Speculative binding.
Dim position As Integer = originalExpression.SpanStart
Dim speculativeModel As SemanticModel = Nothing
Dim success = semanticModel.TryGetSpeculativeSemanticModel(position, speculatedStatement, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
Assert.True(speculativeModel.IsSpeculativeSemanticModel)
Assert.Equal(semanticModel, speculativeModel.ParentModel)
Assert.Equal(position, speculativeModel.OriginalPositionForSpeculation)
Dim identifierSyntax = DirectCast(speculatedStatement, LocalDeclarationStatementSyntax).Declarators(0).Names(0)
Dim symbol = speculativeModel.GetDeclaredSymbol(identifierSyntax)
Assert.NotNull(symbol)
Assert.Equal("bInstance", symbol.Name)
Dim initializerTypeInfo = speculativeModel.GetTypeInfo(speculatedExpression)
Assert.NotNull(initializerTypeInfo.Type)
Assert.Equal("System.Int32", initializerTypeInfo.Type.ToTestDisplayString())
Dim initializerConstantVal = speculativeModel.GetConstantValue(speculatedExpression)
Assert.True(initializerConstantVal.HasValue, "must be a constant")
Assert.Equal(3, initializerConstantVal.Value)
End Sub
<Fact>
<WorkItem(680657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/680657")>
Public Sub TestGetSpeculativeSemanticModelInFieldInitializer()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Class C
Private y As Object = 1
End Class
</file>
</compilation>)
TestGetSpeculativeSemanticModelInFieldOrPropertyInitializer(compilation)
End Sub
<Fact>
<WorkItem(680657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/680657")>
Public Sub TestGetSpeculativeSemanticModelInPropertyInitializer()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Class C
Property y As Object = 1
End Class
</file>
</compilation>)
TestGetSpeculativeSemanticModelInFieldOrPropertyInitializer(compilation)
End Sub
Private Sub TestGetSpeculativeSemanticModelInFieldOrPropertyInitializer(compilation As VisualBasicCompilation)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim position1 = CompilationUtils.FindPositionFromText(tree, "= 1")
' Speculate on the EqualsValue syntax
' Conversion info available, ConvertedType: Object.
Dim equalsValue = SyntaxFactory.EqualsValue(SyntaxFactory.ParseExpression(<![CDATA["hi"]]>.Value))
Dim expression = equalsValue.Value
Dim speculativeModel As SemanticModel = Nothing
Dim success = semanticModel.TryGetSpeculativeSemanticModel(position1, equalsValue, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
Dim typeInfo = speculativeModel.GetTypeInfo(expression)
Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString())
Assert.Equal("System.Object", typeInfo.ConvertedType.ToTestDisplayString())
Dim constantInfo = speculativeModel.GetConstantValue(expression)
Assert.True(constantInfo.HasValue, "must be a constant")
Assert.Equal("hi", constantInfo.Value)
End Sub
<Fact()>
Public Sub TestGetSpeculativeSemanticModelInEnumMemberDecl()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Enum E
y = 1
End Enum
</file>
</compilation>)
TestGetSpeculativeSemanticModelInEnumMemberDeclOrDefaultParameterValue(compilation)
End Sub
<Fact()>
Public Sub TestGetSpeculativeSemanticModelInDefaultParameterValue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Class C
Sub M(Optional x as Integer = 1)
End Sub
End Class
</file>
</compilation>)
TestGetSpeculativeSemanticModelInEnumMemberDeclOrDefaultParameterValue(compilation)
End Sub
Private Sub TestGetSpeculativeSemanticModelInEnumMemberDeclOrDefaultParameterValue(compilation As VisualBasicCompilation)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim position1 = CompilationUtils.FindPositionFromText(tree, "= 1")
' Speculate on the EqualsValue syntax
' Conversion info available, ConvertedType: Int32.
Dim initializer = SyntaxFactory.EqualsValue(SyntaxFactory.ParseExpression("CType(0, System.Int16)"))
Dim expression = initializer.Value
Dim speculativeModel As SemanticModel = Nothing
Dim success = semanticModel.TryGetSpeculativeSemanticModel(position1, initializer, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
Dim typeInfo = speculativeModel.GetTypeInfo(expression)
Assert.Equal("System.Int16", typeInfo.Type.ToTestDisplayString())
Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString())
Dim constantInfo = speculativeModel.GetConstantValue(expression)
Assert.True(constantInfo.HasValue, "must be a constant")
Assert.Equal(CType(0, System.Int16), constantInfo.Value)
End Sub
<Fact()>
Public Sub TestGetSpeculativeSemanticModelForStatement()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Class C
Private Sub M(x As Integer)
Dim y As Integer = 1000
End Sub
End Class
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim typeBlock = DirectCast(root.Members(0), TypeBlockSyntax)
Dim methodBlock = DirectCast(typeBlock.Members(0), MethodBlockSyntax)
Dim originalStatement = methodBlock.Statements(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim position1 = originalStatement.SpanStart
Dim speculatedStatement = DirectCast(SyntaxFactory.ParseExecutableStatement(<![CDATA[
If y > 0 Then
Dim z As Integer = 0
M(z)
M(y)
End If]]>.Value), ExecutableStatementSyntax)
Dim speculativeModel As SemanticModel = Nothing
Dim success = semanticModel.TryGetSpeculativeSemanticModel(position1, speculatedStatement, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
Dim ifStatement = DirectCast(speculatedStatement, MultiLineIfBlockSyntax)
Dim declStatement = DirectCast(ifStatement.Statements(0), LocalDeclarationStatementSyntax)
Dim varDecl = declStatement.Declarators(0).Names(0)
Dim local = speculativeModel.GetDeclaredSymbol(varDecl)
Assert.NotNull(local)
Assert.Equal("z", local.Name)
Assert.Equal(SymbolKind.Local, local.Kind)
Assert.Equal("System.Int32", DirectCast(local, LocalSymbol).Type.ToTestDisplayString())
Dim typeSyntax = DirectCast(declStatement.Declarators(0).AsClause, SimpleAsClauseSyntax).Type
Dim typeInfo = speculativeModel.GetTypeInfo(typeSyntax)
Assert.NotNull(typeInfo.Type)
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString())
Dim call1 = DirectCast(ifStatement.Statements(1), ExpressionStatementSyntax)
Dim arg = DirectCast(DirectCast(call1.Expression, InvocationExpressionSyntax).ArgumentList.Arguments(0), SimpleArgumentSyntax).Expression
Dim argSymbolInfo = speculativeModel.GetSymbolInfo(arg)
Assert.NotNull(argSymbolInfo.Symbol)
Assert.Equal("z", argSymbolInfo.Symbol.Name)
Assert.Equal(SymbolKind.Local, argSymbolInfo.Symbol.Kind)
Dim call2 = DirectCast(ifStatement.Statements(2), ExpressionStatementSyntax)
arg = DirectCast(DirectCast(call2.Expression, InvocationExpressionSyntax).ArgumentList.Arguments(0), SimpleArgumentSyntax).Expression
argSymbolInfo = speculativeModel.GetSymbolInfo(arg)
Assert.NotNull(argSymbolInfo.Symbol)
Assert.Equal("y", argSymbolInfo.Symbol.Name)
Assert.Equal(SymbolKind.Local, argSymbolInfo.Symbol.Kind)
End Sub
<Fact()>
Public Sub TestGetSpeculativeSemanticModelForStatement_DeclaredLocal()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Class C
Private Sub M(x As Integer)
Dim y As Integer = 1000
End Sub
End Class
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim typeBlock = DirectCast(root.Members(0), TypeBlockSyntax)
Dim methodBlock = DirectCast(typeBlock.Members(0), MethodBlockSyntax)
Dim originalStatement = DirectCast(methodBlock.Statements(0), ExecutableStatementSyntax)
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim position1 = originalStatement.SpanStart
' different name local
Dim speculatedStatement = DirectCast(SyntaxFactory.ParseExecutableStatement("Dim z As Integer = 0"), ExecutableStatementSyntax)
Dim speculativeModel As SemanticModel = Nothing
Dim success = semanticModel.TryGetSpeculativeSemanticModel(position1, speculatedStatement, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
Dim declStatement = DirectCast(speculatedStatement, LocalDeclarationStatementSyntax)
Dim varDecl = declStatement.Declarators(0).Names(0)
Dim local = speculativeModel.GetDeclaredSymbol(varDecl)
Assert.NotNull(local)
Assert.Equal("z", local.Name)
Assert.Equal(SymbolKind.Local, local.Kind)
Assert.Equal("System.Int32", DirectCast(local, LocalSymbol).Type.ToTestDisplayString())
' same name local
speculatedStatement = DirectCast(SyntaxFactory.ParseExecutableStatement("Dim y As String = Nothing"), ExecutableStatementSyntax)
success = semanticModel.TryGetSpeculativeSemanticModel(position1, speculatedStatement, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
declStatement = DirectCast(speculatedStatement, LocalDeclarationStatementSyntax)
varDecl = declStatement.Declarators(0).Names(0)
local = speculativeModel.GetDeclaredSymbol(varDecl)
Assert.NotNull(local)
Assert.Equal("y", local.Name)
Assert.Equal(SymbolKind.Local, local.Kind)
Assert.Equal("System.String", DirectCast(local, LocalSymbol).Type.ToTestDisplayString())
End Sub
<Fact>
<WorkItem(97599, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems#_a=edit&id=97599")>
<WorkItem(1019361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019361")>
Public Sub TestGetSpeculativeSemanticModelForStatement_DeclaredLocal_2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Imports N
Namespace N
Class A
Public Const X As Integer = 1
End Class
End Namespace
Class Program
Sub Main()
Dim x = N.A.X
Dim a As A = Nothing
End Sub
End Class
</file>
</compilation>)
compilation.AssertTheseDiagnostics()
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim typeBlock = root.Members.OfType(Of TypeBlockSyntax).First
Dim methodBlock = DirectCast(typeBlock.Members(0), MethodBlockSyntax)
Dim originalStatement = DirectCast(methodBlock.Statements(0), LocalDeclarationStatementSyntax)
Assert.Equal("Dim x = N.A.X", originalStatement.ToString())
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim originalX = semanticModel.GetDeclaredSymbol(originalStatement.Declarators(0).Names(0))
Assert.Equal("x As System.Int32", originalX.ToTestDisplayString())
Assert.Equal(False, DirectCast(originalX, LocalSymbol).Type.IsErrorType)
Dim position1 = originalStatement.SpanStart
' different initializer for local, whose type should be error type as "A" bounds to the local "a" instead of "N.A"
Dim speculatedStatement = DirectCast(SyntaxFactory.ParseExecutableStatement("Dim x = A.X"), ExecutableStatementSyntax)
Dim speculativeModel As SemanticModel = Nothing
Dim success = semanticModel.TryGetSpeculativeSemanticModel(position1, speculatedStatement, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
Dim declStatement = DirectCast(speculatedStatement, LocalDeclarationStatementSyntax)
Dim varDecl = declStatement.Declarators(0).Names(0)
Dim local = speculativeModel.GetDeclaredSymbol(varDecl)
Assert.NotNull(local)
Assert.Equal("x", local.Name)
Assert.Equal(SymbolKind.Local, local.Kind)
Assert.Equal("x As System.Int32", local.ToTestDisplayString())
Assert.NotEqual(originalX, local)
Assert.Equal(False, DirectCast(local, LocalSymbol).Type.IsErrorType)
End Sub
<Fact()>
Public Sub TestGetSpeculativeSemanticModelForStatement_DeclaredLabel()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Class C
Private Sub M(x As Integer)
Dim y As Integer = 1000
End Sub
End Class
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim typeBlock = DirectCast(root.Members(0), TypeBlockSyntax)
Dim methodBlock = DirectCast(typeBlock.Members(0), MethodBlockSyntax)
Dim originalStatement = methodBlock.Statements(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim position1 = originalStatement.Span.End
Dim speculatedStatement = DirectCast(SyntaxFactory.ParseExecutableStatement("Label: y = y + 1"), ExecutableStatementSyntax)
Dim speculativeModel As SemanticModel = Nothing
Dim success = semanticModel.TryGetSpeculativeSemanticModel(position1, speculatedStatement, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
Dim label = speculativeModel.GetDeclaredSymbol(speculatedStatement)
Assert.NotNull(label)
Assert.Equal("Label", label.Name)
Assert.Equal(SymbolKind.Label, label.Kind)
End Sub
<Fact()>
Public Sub TestGetSpeculativeSemanticModelForStatement_GetDeclaredLambdaParameterSymbol()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Class C
Private Sub M(x As Integer)
Dim y As Integer = 0
End Sub
End Class
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim typeBlock = DirectCast(root.Members(0), TypeBlockSyntax)
Dim methodBlock = DirectCast(typeBlock.Members(0), MethodBlockSyntax)
Dim originalStatement = methodBlock.Statements(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim position1 = originalStatement.Span.End
Dim speculatedStatement = DirectCast(SyntaxFactory.ParseExecutableStatement("Dim var As Func(Of Integer, Integer) = Function(z) x + z"), ExecutableStatementSyntax)
Dim speculativeModel As SemanticModel = Nothing
Dim success = semanticModel.TryGetSpeculativeSemanticModel(position1, speculatedStatement, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
Dim lambdaExpressionHeader = speculatedStatement.DescendantNodes().OfType(Of LambdaHeaderSyntax)().FirstOrDefault()
Dim lambdaParam = lambdaExpressionHeader.ParameterList.Parameters(0)
Dim parameterSymbol = speculativeModel.GetDeclaredSymbol(lambdaParam)
Assert.NotNull(parameterSymbol)
Assert.Equal("z", parameterSymbol.Name)
End Sub
<Fact, WorkItem(1084086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084086")>
Public Sub TestGetSpeculativeSemanticModelForStatement_InEmptyMethodBody()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Class C
Private Sub M(x As Integer)
End Sub
End Class
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim typeBlock = DirectCast(root.Members(0), TypeBlockSyntax)
Dim methodBlock = DirectCast(typeBlock.Members(0), MethodBlockSyntax)
Dim endStatement = methodBlock.EndBlockStatement
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim position1 = endStatement.SpanStart
Dim speculatedStatement = DirectCast(SyntaxFactory.ParseExecutableStatement("Dim y = 0"), LocalDeclarationStatementSyntax)
Dim speculativeModel As SemanticModel = Nothing
Dim success = semanticModel.TryGetSpeculativeSemanticModel(position1, speculatedStatement, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
Dim local = speculativeModel.GetDeclaredSymbol(speculatedStatement.Declarators.First().Names.First)
Assert.NotNull(local)
Assert.Equal("y", local.Name)
Assert.Equal(SymbolKind.Local, local.Kind)
End Sub
<Fact()>
Public Sub TestGetSpeculativeSemanticModelForRangeArgument_InField()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Module Program
' Extract method
Dim x(0 To 1 + 2)
Public Static Function NewMethod() As Integer
Return 1
End Function
End Module
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetRoot()
Dim rangeArg = root.DescendantNodes().OfType(Of RangeArgumentSyntax).Single()
Dim position1 = rangeArg.SpanStart
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim speculatedRangeArgument = rangeArg.ReplaceNode(rangeArg.UpperBound, SyntaxFactory.ParseExpression("NewMethod()"))
Dim speculativeModel As SemanticModel = Nothing
Dim success = semanticModel.TryGetSpeculativeSemanticModel(position1, speculatedRangeArgument, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
Dim upperBound = speculatedRangeArgument.UpperBound
Dim symbolInfo = speculativeModel.GetSymbolInfo(upperBound)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal(SymbolKind.Method, symbolInfo.Symbol.Kind)
Assert.Equal("NewMethod", symbolInfo.Symbol.Name)
End Sub
<Fact()>
Public Sub TestGetSpeculativeSemanticModelForRangeArgument_InLocal()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Module Program
Public Static Function Method() As Integer
' Extract method
Dim x(0 To 1 + 2)
End Function
Public Static Function NewMethod() As Integer
Return 1
End Function
End Module
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetRoot()
Dim rangeArg = root.DescendantNodes().OfType(Of RangeArgumentSyntax).Single()
Dim position1 = rangeArg.SpanStart
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim speculatedRangeArgument = rangeArg.ReplaceNode(rangeArg.UpperBound, SyntaxFactory.ParseExpression("NewMethod()"))
Dim speculativeModel As SemanticModel = Nothing
Dim success = semanticModel.TryGetSpeculativeSemanticModel(position1, speculatedRangeArgument, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
Dim upperBound = speculatedRangeArgument.UpperBound
Dim symbolInfo = speculativeModel.GetSymbolInfo(upperBound)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal(SymbolKind.Method, symbolInfo.Symbol.Kind)
Assert.Equal("NewMethod", symbolInfo.Symbol.Name)
End Sub
<Fact()>
Public Sub TestArgumentsToGetSpeculativeSemanticModelAPI()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb"><![CDATA[
Class C
<System.Obsolete>
Private Sub M(x As Integer)
Dim y As String = "Hello"
End Sub
End Class]]>
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim typeBlock = DirectCast(root.Members(0), TypeBlockSyntax)
Dim methodBlock = DirectCast(typeBlock.Members(0), MethodBlockSyntax)
Dim originalStatement = methodBlock.Statements(0)
Dim model = compilation.GetSemanticModel(tree)
Dim statement = DirectCast(methodBlock.Statements(0), LocalDeclarationStatementSyntax)
Dim initializer = statement.Declarators(0).Initializer
Dim attribute = methodBlock.BlockStatement.AttributeLists(0).Attributes(0)
Dim speculativeModel As SemanticModel = Nothing
Assert.Throws(Of ArgumentNullException)(Function() model.TryGetSpeculativeSemanticModel(statement.SpanStart, initializer:=Nothing, speculativeModel:=speculativeModel))
Assert.Throws(Of ArgumentNullException)(Function() model.TryGetSpeculativeSemanticModel(statement.SpanStart, statement:=Nothing, speculativeModel:=speculativeModel))
Assert.Throws(Of ArgumentNullException)(Function() model.TryGetSpeculativeSemanticModel(statement.SpanStart, attribute:=Nothing, speculativeModel:=speculativeModel))
' Speculate on a node from the same syntax tree.
Assert.Throws(Of ArgumentException)(Function() model.TryGetSpeculativeSemanticModel(statement.SpanStart, initializer:=initializer, speculativeModel:=speculativeModel))
Assert.Throws(Of ArgumentException)(Function() model.TryGetSpeculativeSemanticModel(statement.SpanStart, statement:=statement, speculativeModel:=speculativeModel))
Assert.Throws(Of ArgumentException)(Function() model.TryGetSpeculativeSemanticModel(attribute.SpanStart, attribute:=attribute, speculativeModel:=speculativeModel))
' Chaining speculative semantic model is not supported.
Dim speculatedStatement = statement.ReplaceNode(initializer.Value, SyntaxFactory.ParseExpression("0"))
model.TryGetSpeculativeSemanticModel(statement.SpanStart, speculatedStatement, speculativeModel)
Assert.NotNull(speculativeModel)
Dim newSpeculativeModel As SemanticModel = Nothing
Assert.Throws(Of InvalidOperationException)(Function() speculativeModel.TryGetSpeculativeSemanticModel(speculatedStatement.SpanStart, speculatedStatement, newSpeculativeModel))
End Sub
<Fact()>
Public Sub TestGetSpeculativeSemanticModelOnSpeculativeSemanticModel()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb"><![CDATA[
Class C
<System.Obsolete>
Private Sub M(x As Integer)
Dim y As String = "Hello"
End Sub
End Class]]>
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim typeBlock = DirectCast(root.Members(0), TypeBlockSyntax)
Dim methodBlock = DirectCast(typeBlock.Members(0), MethodBlockSyntax)
Dim originalStatement = methodBlock.Statements(0)
Dim model = compilation.GetSemanticModel(tree)
Dim statement = DirectCast(methodBlock.Statements(0), LocalDeclarationStatementSyntax)
Dim expression = statement.Declarators(0).Initializer.Value
Dim attribute = methodBlock.BlockStatement.AttributeLists(0).Attributes(0)
Dim speculatedStatement = DirectCast(statement.ReplaceNode(expression, SyntaxFactory.ParseExpression("0")), LocalDeclarationStatementSyntax)
Dim speculativeModel As SemanticModel = Nothing
Dim success = model.TryGetSpeculativeSemanticModel(statement.SpanStart, speculatedStatement, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
' Chaining speculative semantic model is not supported.
' (a) Expression
Dim newSpeculatedStatement = DirectCast(statement.ReplaceNode(expression, SyntaxFactory.ParseExpression("1.1")), LocalDeclarationStatementSyntax)
Dim newSpeculativeModel As SemanticModel = Nothing
Assert.Throws(Of InvalidOperationException)(Sub() speculativeModel.TryGetSpeculativeSemanticModel(speculatedStatement.SpanStart, statement:=newSpeculatedStatement, speculativeModel:=newSpeculativeModel))
' (b) Statement
newSpeculatedStatement = DirectCast(SyntaxFactory.ParseExecutableStatement("Dim z = 0"), LocalDeclarationStatementSyntax)
Assert.Throws(Of InvalidOperationException)(Sub() speculativeModel.TryGetSpeculativeSemanticModel(speculatedStatement.SpanStart, newSpeculatedStatement, newSpeculativeModel))
End Sub
' Helper to parse an attribute.
Private Function ParseAttributeSyntax(source As String) As AttributeSyntax
Return DirectCast(SyntaxFactory.ParseCompilationUnit(source + " Class X" + vbCrLf + "End Class").Members.First(), TypeBlockSyntax).BlockStatement.AttributeLists.First().Attributes.First()
End Function
<Fact>
Public Sub TestGetSpeculativeSemanticModelForAttribute()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Option Strict On
Imports System
Imports O = System.ObsoleteAttribute
Class C
Class DAttribute : Inherits Attribute
End Class
Class E
End Class
Sub Goo(Of O)()
End Sub
<Serializable> Private i As Integer
End Class </file>
</compilation>, options:=TestOptions.ReleaseExe.WithEmbedVbCoreRuntime(True))
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim parentModel = compilation.GetSemanticModel(tree)
Dim position1 = CompilationUtils.FindPositionFromText(tree, "Class C")
Dim attr1 = ParseAttributeSyntax("<Obsolete>")
Dim speculativeModel As SemanticModel = Nothing
Dim success = parentModel.TryGetSpeculativeSemanticModel(position1, attr1, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
Dim symbolInfo = speculativeModel.GetSymbolInfo(attr1)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, CandidateReason.None)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("Sub System.ObsoleteAttribute..ctor()", symbolInfo.Symbol.ToTestDisplayString())
Dim attr2 = ParseAttributeSyntax("<ObsoleteAttribute(4)>")
success = parentModel.TryGetSpeculativeSemanticModel(position1, attr2, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
symbolInfo = speculativeModel.GetSymbolInfo(attr2)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, CandidateReason.OverloadResolutionFailure)
Assert.Equal(3, symbolInfo.CandidateSymbols.Length)
Assert.Equal("Sub System.ObsoleteAttribute..ctor()", symbolInfo.CandidateSymbols(0).ToTestDisplayString())
Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", symbolInfo.CandidateSymbols(1).ToTestDisplayString())
Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String, [error] As System.Boolean)", symbolInfo.CandidateSymbols(2).ToTestDisplayString())
Dim argument = DirectCast(attr2.ArgumentList.Arguments(0), SimpleArgumentSyntax).Expression
Dim constantInfo = speculativeModel.GetConstantValue(argument)
Assert.True(constantInfo.HasValue, "must be constant")
Assert.Equal(4, constantInfo.Value)
Dim attr3 = ParseAttributeSyntax("<O(""hello"")>")
success = parentModel.TryGetSpeculativeSemanticModel(position1, attr3, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
symbolInfo = speculativeModel.GetSymbolInfo(attr3)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, CandidateReason.None)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", symbolInfo.Symbol.ToTestDisplayString())
argument = DirectCast(attr3.ArgumentList.Arguments(0), SimpleArgumentSyntax).Expression
constantInfo = speculativeModel.GetConstantValue(argument)
Assert.True(constantInfo.HasValue, "must be constant")
Assert.Equal("hello", constantInfo.Value)
Dim aliasSymbol = speculativeModel.GetAliasInfo(DirectCast(attr3.Name, IdentifierNameSyntax))
Assert.NotNull(aliasSymbol)
Assert.Equal("O", aliasSymbol.Name)
Assert.NotNull(aliasSymbol.Target)
Assert.Equal("ObsoleteAttribute", aliasSymbol.Target.Name)
Dim attr4 = ParseAttributeSyntax("<P>")
success = parentModel.TryGetSpeculativeSemanticModel(position1, attr4, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
symbolInfo = speculativeModel.GetSymbolInfo(attr4)
Assert.Null(symbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, CandidateReason.None)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Dim position2 = CompilationUtils.FindPositionFromText(tree, "Class E")
Dim attr5 = ParseAttributeSyntax("<D>")
success = parentModel.TryGetSpeculativeSemanticModel(position2, attr5, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
symbolInfo = speculativeModel.GetSymbolInfo(attr5)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, CandidateReason.None)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("Sub C.DAttribute..ctor()", symbolInfo.Symbol.ToTestDisplayString())
Dim position3 = CompilationUtils.FindPositionFromText(tree, "Sub Goo")
Dim attr6 = ParseAttributeSyntax("<O(""hello"")>")
success = parentModel.TryGetSpeculativeSemanticModel(position2, attr6, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
symbolInfo = speculativeModel.GetSymbolInfo(attr6)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, CandidateReason.None)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", symbolInfo.Symbol.ToTestDisplayString())
argument = DirectCast(attr6.ArgumentList.Arguments(0), SimpleArgumentSyntax).Expression
constantInfo = speculativeModel.GetConstantValue(argument)
Assert.True(constantInfo.HasValue, "must be constant")
Assert.Equal("hello", constantInfo.Value)
aliasSymbol = speculativeModel.GetAliasInfo(DirectCast(attr6.Name, IdentifierNameSyntax))
Assert.NotNull(aliasSymbol)
Assert.Equal("O", aliasSymbol.Name)
Assert.NotNull(aliasSymbol.Target)
Assert.Equal("ObsoleteAttribute", aliasSymbol.Target.Name)
Dim position4 = CompilationUtils.FindPositionFromText(tree, "Serializable")
Dim attr7 = ParseAttributeSyntax("<D>")
success = parentModel.TryGetSpeculativeSemanticModel(position4, attr7, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
symbolInfo = speculativeModel.GetSymbolInfo(attr7)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, CandidateReason.None)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("Sub C.DAttribute..ctor()", symbolInfo.Symbol.ToTestDisplayString())
Dim attr8 = SyntaxFactory.ParseCompilationUnit("<Assembly: O(""hello"")>").Attributes(0).AttributeLists(0).Attributes(0)
success = parentModel.TryGetSpeculativeSemanticModel(position4, attr8, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
symbolInfo = speculativeModel.GetSymbolInfo(attr8)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal(symbolInfo.CandidateReason, CandidateReason.None)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal("Sub System.ObsoleteAttribute..ctor(message As System.String)", symbolInfo.Symbol.ToTestDisplayString())
argument = DirectCast(attr8.ArgumentList.Arguments(0), SimpleArgumentSyntax).Expression
constantInfo = speculativeModel.GetConstantValue(argument)
Assert.True(constantInfo.HasValue, "must be constant")
Assert.Equal("hello", constantInfo.Value)
aliasSymbol = speculativeModel.GetAliasInfo(DirectCast(attr8.Name, IdentifierNameSyntax))
Assert.NotNull(aliasSymbol)
Assert.Equal("O", aliasSymbol.Name)
Assert.NotNull(aliasSymbol.Target)
Assert.Equal("ObsoleteAttribute", aliasSymbol.Target.Name)
End Sub
<Fact()>
Public Sub TestGetSymbolInfoOnSpeculativeModel()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Public Function Goo() As String
Return "Goo"
End Function
End Class
Module Program
Public Sub Main(a As A)
Dim x = a.Goo()
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim position As Integer = CompilationUtils.FindPositionFromText(tree, "x = a.Goo()")
Dim localDecl = tree.GetRoot().DescendantNodes().OfType(Of LocalDeclarationStatementSyntax)().Single()
Dim parsedInvocation = SyntaxFactory.ParseExpression("a.Goo()")
Dim newLocalDecl = DirectCast(localDecl.ReplaceNode(localDecl.Declarators(0).Initializer.Value, parsedInvocation), LocalDeclarationStatementSyntax)
Dim newInitializer = DirectCast(newLocalDecl.Declarators(0).Initializer.Value, InvocationExpressionSyntax)
Dim speculativeModel As SemanticModel = Nothing
Dim success = semanticModel.TryGetSpeculativeSemanticModel(position, newLocalDecl, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
Dim memberAccess = DirectCast(newInitializer.Expression, MemberAccessExpressionSyntax)
Dim symbolInfo = speculativeModel.GetSymbolInfo(memberAccess.Name)
Assert.NotNull(symbolInfo.Symbol)
Assert.Equal("Goo", symbolInfo.Symbol.Name)
End Sub
<Fact()>
Public Sub TestGetSpeculativeSemanticModelForMethodBody()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Class C
Private Sub M(x As Integer)
Dim y As Integer = 1000
End Sub
End Class
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim typeBlock = DirectCast(root.Members(0), TypeBlockSyntax)
Dim methodBlock = DirectCast(typeBlock.Members(0), MethodBlockSyntax)
Dim originalStatement = methodBlock.Statements(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim position1 = originalStatement.SpanStart
Dim speculatedStatement = DirectCast(SyntaxFactory.ParseExecutableStatement(<![CDATA[
If y > 0 Then
Dim z As Integer = 0
M(z)
M(y) ' Should generate error here for undefined "y" as we are replacing the method body.
End If]]>.Value), ExecutableStatementSyntax)
Dim ifStatement = DirectCast(speculatedStatement, MultiLineIfBlockSyntax)
Dim speculatedMethod = methodBlock.WithStatements(ifStatement.Statements)
Dim speculativeModel As SemanticModel = Nothing
Dim success = semanticModel.TryGetSpeculativeSemanticModelForMethodBody(position1, speculatedMethod, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
VerifySpeculativeSemanticModelForMethodBody(speculatedMethod, speculativeModel)
End Sub
Private Shared Sub VerifySpeculativeSemanticModelForMethodBody(speculatedMethod As MethodBlockBaseSyntax, speculativeModel As SemanticModel)
Dim declStatement = DirectCast(speculatedMethod.Statements(0), LocalDeclarationStatementSyntax)
Dim varDecl = declStatement.Declarators(0).Names(0)
Dim local = speculativeModel.GetDeclaredSymbol(varDecl)
Assert.NotNull(local)
Assert.Equal("z", local.Name)
Assert.Equal(SymbolKind.Local, local.Kind)
Assert.Equal("System.Int32", DirectCast(local, LocalSymbol).Type.ToTestDisplayString())
Dim typeSyntax = DirectCast(declStatement.Declarators(0).AsClause, SimpleAsClauseSyntax).Type
Dim typeInfo = speculativeModel.GetTypeInfo(typeSyntax)
Assert.NotNull(typeInfo.Type)
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString())
Dim call1 = DirectCast(speculatedMethod.Statements(1), ExpressionStatementSyntax)
Dim arg = DirectCast(DirectCast(call1.Expression, InvocationExpressionSyntax).ArgumentList.Arguments(0), SimpleArgumentSyntax).Expression
Dim argSymbolInfo = speculativeModel.GetSymbolInfo(arg)
Assert.NotNull(argSymbolInfo.Symbol)
Assert.Equal("z", argSymbolInfo.Symbol.Name)
Assert.Equal(SymbolKind.Local, argSymbolInfo.Symbol.Kind)
' Shouldn't bind to local y in the original method as we are replacing the method body.
Dim call2 = DirectCast(speculatedMethod.Statements(2), ExpressionStatementSyntax)
arg = DirectCast(DirectCast(call2.Expression, InvocationExpressionSyntax).ArgumentList.Arguments(0), SimpleArgumentSyntax).Expression
argSymbolInfo = speculativeModel.GetSymbolInfo(arg)
Assert.Null(argSymbolInfo.Symbol)
End Sub
<Fact()>
Public Sub TestGetSpeculativeSemanticModelForPropertyAccessorBody()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Class C
Private WriteOnly Property M(x As Integer) As Integer
Set(value As Integer)
Dim y As Integer = 1000
End Set
End Property
End Class
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim typeBlock = DirectCast(root.Members(0), TypeBlockSyntax)
Dim propertyBlock = DirectCast(typeBlock.Members(0), PropertyBlockSyntax)
Dim methodBlock = propertyBlock.Accessors(0)
Dim originalStatement = methodBlock.Statements(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim position1 = originalStatement.SpanStart
Dim speculatedStatement = DirectCast(SyntaxFactory.ParseExecutableStatement(<![CDATA[
If y > 0 Then
Dim z As Integer = 0
M(z)
M(y) ' Should generate error here for undefined "y" as we are replacing the method body.
End If]]>.Value), ExecutableStatementSyntax)
Dim ifStatement = DirectCast(speculatedStatement, MultiLineIfBlockSyntax)
Dim speculatedMethod = methodBlock.WithStatements(ifStatement.Statements)
Dim speculativeModel As SemanticModel = Nothing
Dim success = semanticModel.TryGetSpeculativeSemanticModelForMethodBody(position1, speculatedMethod, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
VerifySpeculativeSemanticModelForMethodBody(speculatedMethod, speculativeModel)
End Sub
<Fact()>
Public Sub TestGetSpeculativeSemanticModelForEventAccessorBody()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Class C
Private Custom Event M As System.Action
AddHandler(x As Action)
Dim y As Integer = 1000
End AddHandler
RemoveHandler(value As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim typeBlock = DirectCast(root.Members(0), TypeBlockSyntax)
Dim eventBlock = DirectCast(typeBlock.Members(0), EventBlockSyntax)
Dim methodBlock = eventBlock.Accessors(0)
Dim originalStatement = methodBlock.Statements(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim position1 = originalStatement.SpanStart
Dim speculatedStatement = DirectCast(SyntaxFactory.ParseExecutableStatement(<![CDATA[
If y > 0 Then
Dim z As Integer = 0
M(z)
M(y) ' Should generate error here for undefined "y" as we are replacing the method body.
End If]]>.Value), ExecutableStatementSyntax)
Dim ifStatement = DirectCast(speculatedStatement, MultiLineIfBlockSyntax)
Dim speculatedMethod = methodBlock.WithStatements(ifStatement.Statements)
Dim speculativeModel As SemanticModel = Nothing
Dim success = semanticModel.TryGetSpeculativeSemanticModelForMethodBody(position1, speculatedMethod, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
VerifySpeculativeSemanticModelForMethodBody(speculatedMethod, speculativeModel)
End Sub
<Fact()>
Public Sub TestGetSpeculativeSemanticModelForMethodBody_DeclaredLocal()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Class C
Private Sub M(x As Integer)
Dim y As Integer = 1000
End Sub
End Class
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim typeBlock = DirectCast(root.Members(0), TypeBlockSyntax)
Dim methodBlock = DirectCast(typeBlock.Members(0), MethodBlockSyntax)
Dim originalStatement = DirectCast(methodBlock.Statements(0), ExecutableStatementSyntax)
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim position1 = originalStatement.SpanStart
' different name local
Dim speculatedStatement = DirectCast(SyntaxFactory.ParseExecutableStatement("Dim z As Integer = 0"), ExecutableStatementSyntax)
Dim speculatedMethod = methodBlock.WithStatements(SyntaxFactory.SingletonList(Of StatementSyntax)(speculatedStatement))
Dim speculativeModel As SemanticModel = Nothing
Dim success = semanticModel.TryGetSpeculativeSemanticModelForMethodBody(position1, speculatedMethod, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
Dim declStatement = DirectCast(speculatedMethod.Statements(0), LocalDeclarationStatementSyntax)
Dim varDecl = declStatement.Declarators(0).Names(0)
Dim local = speculativeModel.GetDeclaredSymbol(varDecl)
Assert.NotNull(local)
Assert.Equal("z", local.Name)
Assert.Equal(SymbolKind.Local, local.Kind)
Assert.Equal("System.Int32", DirectCast(local, LocalSymbol).Type.ToTestDisplayString())
' same name local
speculatedStatement = DirectCast(SyntaxFactory.ParseExecutableStatement("Dim y As String = Nothing"), ExecutableStatementSyntax)
speculatedMethod = methodBlock.WithStatements(SyntaxFactory.SingletonList(Of StatementSyntax)(speculatedStatement))
success = semanticModel.TryGetSpeculativeSemanticModelForMethodBody(position1, speculatedMethod, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
declStatement = DirectCast(speculatedMethod.Statements(0), LocalDeclarationStatementSyntax)
varDecl = declStatement.Declarators(0).Names(0)
local = speculativeModel.GetDeclaredSymbol(varDecl)
Assert.NotNull(local)
Assert.Equal("y", local.Name)
Assert.Equal(SymbolKind.Local, local.Kind)
Assert.Equal("System.String", DirectCast(local, LocalSymbol).Type.ToTestDisplayString())
' parameter symbol
speculatedStatement = DirectCast(SyntaxFactory.ParseExecutableStatement("Dim y = x"), ExecutableStatementSyntax)
speculatedMethod = methodBlock.WithStatements(SyntaxFactory.SingletonList(Of StatementSyntax)(speculatedStatement))
success = semanticModel.TryGetSpeculativeSemanticModelForMethodBody(position1, speculatedMethod, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
declStatement = DirectCast(speculatedMethod.Statements(0), LocalDeclarationStatementSyntax)
varDecl = declStatement.Declarators(0).Names(0)
local = speculativeModel.GetDeclaredSymbol(varDecl)
Assert.NotNull(local)
Assert.Equal("y", local.Name)
Assert.Equal(SymbolKind.Local, local.Kind)
Assert.Equal("System.Int32", DirectCast(local, LocalSymbol).Type.ToTestDisplayString())
Dim param = speculativeModel.GetSymbolInfo(declStatement.Declarators(0).Initializer.Value).Symbol
Assert.NotNull(param)
Assert.Equal(SymbolKind.Parameter, param.Kind)
Dim paramSymbol = DirectCast(param, ParameterSymbol)
Assert.Equal("x", paramSymbol.Name)
Assert.Equal("System.Int32", paramSymbol.Type.ToTestDisplayString())
End Sub
<Fact()>
Public Sub TestGetSpeculativeSemanticModelForMethodBody_DeclaredLabel()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Class C
Private Sub M(x As Integer)
Dim y As Integer = 1000
End Sub
End Class
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim typeBlock = DirectCast(root.Members(0), TypeBlockSyntax)
Dim methodBlock = DirectCast(typeBlock.Members(0), MethodBlockSyntax)
Dim originalStatement = methodBlock.Statements(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim position1 = originalStatement.Span.End
Dim speculatedStatement = DirectCast(SyntaxFactory.ParseExecutableStatement("Label: y = y + 1"), ExecutableStatementSyntax)
Dim speculatedMethod = methodBlock.WithStatements(SyntaxFactory.SingletonList(Of StatementSyntax)(speculatedStatement))
Dim speculativeModel As SemanticModel = Nothing
Dim success = semanticModel.TryGetSpeculativeSemanticModelForMethodBody(position1, speculatedMethod, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
Dim label = speculativeModel.GetDeclaredSymbol(speculatedMethod.Statements(0))
Assert.NotNull(label)
Assert.Equal("Label", label.Name)
Assert.Equal(SymbolKind.Label, label.Kind)
End Sub
<Fact()>
Public Sub TestGetSpeculativeSemanticModelForMethodBody_GetDeclaredLambdaParameterSymbol()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Class C
Private Sub M(x As Integer)
Dim y As Integer = 0
End Sub
End Class
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim typeBlock = DirectCast(root.Members(0), TypeBlockSyntax)
Dim methodBlock = DirectCast(typeBlock.Members(0), MethodBlockSyntax)
Dim originalStatement = methodBlock.Statements(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim position1 = originalStatement.Span.End
Dim speculatedStatement = DirectCast(SyntaxFactory.ParseExecutableStatement("Dim var As Func(Of Integer, Integer) = Function(z) x + z"), ExecutableStatementSyntax)
Dim speculatedMethod = methodBlock.WithStatements(SyntaxFactory.SingletonList(Of StatementSyntax)(speculatedStatement))
Dim speculativeModel As SemanticModel = Nothing
Dim success = semanticModel.TryGetSpeculativeSemanticModelForMethodBody(position1, speculatedMethod, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
Dim lambdaExpressionHeader = speculatedMethod.Statements(0).DescendantNodes().OfType(Of LambdaHeaderSyntax)().FirstOrDefault()
Dim lambdaParam = lambdaExpressionHeader.ParameterList.Parameters(0)
Dim parameterSymbol = speculativeModel.GetDeclaredSymbol(lambdaParam)
Assert.NotNull(parameterSymbol)
Assert.Equal("z", parameterSymbol.Name)
End Sub
Private Shared Sub TestGetSpeculativeSemanticModelForTypeSyntax_Common(model As SemanticModel, position As Integer, speculatedTypeSyntax As TypeSyntax, bindingOption As SpeculativeBindingOption, expectedSymbolKind As SymbolKind, expectedTypeDisplayString As String)
Assert.False(model.IsSpeculativeSemanticModel)
Assert.Null(model.ParentModel)
Assert.Equal(0, model.OriginalPositionForSpeculation)
Dim speculativeModel As SemanticModel = Nothing
Dim success = model.TryGetSpeculativeSemanticModel(position, speculatedTypeSyntax, speculativeModel, bindingOption)
Assert.True(success)
Assert.NotNull(speculativeModel)
Assert.True(speculativeModel.IsSpeculativeSemanticModel)
Assert.Equal(model, speculativeModel.ParentModel)
Assert.Equal(position, speculativeModel.OriginalPositionForSpeculation)
Dim symbol = speculativeModel.GetSymbolInfo(speculatedTypeSyntax).Symbol
Assert.NotNull(symbol)
Assert.Equal(expectedSymbolKind, symbol.Kind)
Assert.Equal(expectedTypeDisplayString, symbol.ToDisplayString())
Dim typeSymbol = speculativeModel.GetTypeInfo(speculatedTypeSyntax).Type
Assert.NotNull(symbol)
Assert.Equal(expectedSymbolKind, symbol.Kind)
Assert.Equal(expectedTypeDisplayString, symbol.ToDisplayString())
Dim methodGroupInfo = speculativeModel.GetMemberGroup(speculatedTypeSyntax)
Dim constantInfo = speculativeModel.GetConstantValue(speculatedTypeSyntax)
If speculatedTypeSyntax.Kind = SyntaxKind.QualifiedName Then
Dim right = DirectCast(speculatedTypeSyntax, QualifiedNameSyntax).Right
symbol = speculativeModel.GetSymbolInfo(right).Symbol
Assert.NotNull(symbol)
Assert.Equal(expectedSymbolKind, symbol.Kind)
Assert.Equal(expectedTypeDisplayString, symbol.ToDisplayString())
typeSymbol = speculativeModel.GetTypeInfo(right).Type
Assert.NotNull(symbol)
Assert.Equal(expectedSymbolKind, symbol.Kind)
Assert.Equal(expectedTypeDisplayString, symbol.ToDisplayString())
End If
End Sub
<Fact>
Public Sub TestGetSpeculativeSemanticModelForTypeSyntax_InGlobalImports()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Imports System.Runtime
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim importsStatement = root.Imports(0)
Dim importsClause = DirectCast(importsStatement.ImportsClauses(0), SimpleImportsClauseSyntax)
Dim model = compilation.GetSemanticModel(tree)
Dim speculatedTypeExpression = SyntaxFactory.ParseName("System.Collections")
TestGetSpeculativeSemanticModelForTypeSyntax_Common(model, importsClause.Name.Position,
speculatedTypeExpression, SpeculativeBindingOption.BindAsTypeOrNamespace, SymbolKind.Namespace, "System.Collections")
End Sub
<Fact>
Public Sub TestGetSpeculativeSemanticModelForTypeSyntax_InGlobalAlias()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Imports A = System.Exception
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim importsStatement = root.Imports(0)
Dim importsClause = DirectCast(importsStatement.ImportsClauses(0), SimpleImportsClauseSyntax)
Dim model = compilation.GetSemanticModel(tree)
Dim speculatedTypeExpression = SyntaxFactory.ParseName("System.ArgumentException")
TestGetSpeculativeSemanticModelForTypeSyntax_Common(model, importsClause.Name.Position,
speculatedTypeExpression, SpeculativeBindingOption.BindAsExpression, SymbolKind.NamedType, "System.ArgumentException")
End Sub
<Fact>
Public Sub TestGetSpeculativeSemanticModelForTypeSyntax_InBaseList()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Imports N
Class MyException
Inherits System.Exception
Implements N.I
End Class
Namespace N
Public Interface I
End Interface
End Namespace
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim typeBlock = DirectCast(root.Members(0), TypeBlockSyntax)
Dim model = compilation.GetSemanticModel(tree)
Dim speculatedTypeExpression = SyntaxFactory.ParseName("System.ArgumentException")
Dim inheritsClause = typeBlock.Inherits(0)
TestGetSpeculativeSemanticModelForTypeSyntax_Common(model, inheritsClause.Types.First.Position,
speculatedTypeExpression, SpeculativeBindingOption.BindAsExpression, SymbolKind.NamedType, "System.ArgumentException")
speculatedTypeExpression = SyntaxFactory.ParseName("I")
Dim implementsClause = typeBlock.Implements(0)
TestGetSpeculativeSemanticModelForTypeSyntax_Common(model, implementsClause.Types.First.Position,
speculatedTypeExpression, SpeculativeBindingOption.BindAsExpression, SymbolKind.NamedType, "N.I")
End Sub
<Fact>
Public Sub TestGetSpeculativeSemanticModelForTypeSyntax_InMemberDeclaration()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Class Program
Implements I
Private field As System.Exception = Nothing
Public Function Method(param As System.Exception) As System.Exception
Return field
End Function
End Class
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim typeBlock = DirectCast(root.Members(0), TypeBlockSyntax)
Dim field = DirectCast(typeBlock.Members(0), FieldDeclarationSyntax)
Dim methodBlock = DirectCast(typeBlock.Members(1), MethodBlockBaseSyntax)
Dim methodDecl = DirectCast(methodBlock.BlockStatement, MethodStatementSyntax)
Dim model = compilation.GetSemanticModel(tree)
Dim speculatedTypeExpression = SyntaxFactory.ParseName("System.ArgumentException")
TestGetSpeculativeSemanticModelForTypeSyntax_Common(model, field.Declarators.First.AsClause.Type.Position,
speculatedTypeExpression, SpeculativeBindingOption.BindAsExpression, SymbolKind.NamedType, "System.ArgumentException")
TestGetSpeculativeSemanticModelForTypeSyntax_Common(model, methodDecl.AsClause.Type.Position,
speculatedTypeExpression, SpeculativeBindingOption.BindAsExpression, SymbolKind.NamedType, "System.ArgumentException")
TestGetSpeculativeSemanticModelForTypeSyntax_Common(model, methodDecl.ParameterList.Parameters.First.AsClause.Type.Position,
speculatedTypeExpression, SpeculativeBindingOption.BindAsExpression, SymbolKind.NamedType, "System.ArgumentException")
End Sub
<Fact>
<WorkItem(120491, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems#_a=edit&id=120491")>
<WorkItem(745766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/745766")>
Public Sub TestGetSpeculativeSemanticModelForTypeSyntax_InImplementsClauseForMember()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Class Program
Implements I
Public Function Method(param As System.Exception) As System.Exception Implements I.Method
Return field
End Function
End Class
Interface I
Function Method(param As System.Exception) As System.Exception
Function Method2() As System.Exception
Function Method2(param As System.Exception) As System.Exception
End Interface
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim typeBlock = DirectCast(root.Members(0), TypeBlockSyntax)
Dim methodBlock = DirectCast(typeBlock.Members(0), MethodBlockBaseSyntax)
Dim methodDecl = DirectCast(methodBlock.BlockStatement, MethodStatementSyntax)
Dim model = compilation.GetSemanticModel(tree)
Dim implementsClause = methodDecl.ImplementsClause
Dim implementsName = implementsClause.InterfaceMembers(0)
Dim symbol = model.GetSymbolInfo(implementsName).Symbol
Assert.Equal("I.Method", implementsName.ToString())
Assert.NotNull(symbol)
Assert.Equal("Function Method(param As System.Exception) As System.Exception", symbol.ToDisplayString())
Dim speculatedMemberName = SyntaxFactory.ParseName("I.Method2")
Const bug120491IsFixed = False
If bug120491IsFixed Then
TestGetSpeculativeSemanticModelForTypeSyntax_Common(model, implementsName.Position,
speculatedMemberName, SpeculativeBindingOption.BindAsExpression, SymbolKind.Method, "I.Method2")
Else
Dim speculativeModel As SemanticModel = Nothing
Dim success = model.TryGetSpeculativeSemanticModel(implementsName.Position, speculatedMemberName, speculativeModel, SpeculativeBindingOption.BindAsExpression)
Assert.True(success)
symbol = speculativeModel.GetSymbolInfo(speculatedMemberName).Symbol
Assert.Null(symbol)
End If
End Sub
<Fact>
Public Sub TestGetSpeculativeSemanticModelForTypeSyntax_AliasName()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Imports A = System.ArgumentException
Class Program
Private field As System.Exception = Nothing
End Class
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim typeBlock = DirectCast(root.Members(0), TypeBlockSyntax)
Dim field = DirectCast(typeBlock.Members(0), FieldDeclarationSyntax)
Dim position = field.Declarators.First.AsClause.Type.Position
Dim model = compilation.GetSemanticModel(tree)
Dim speculatedAliasName = DirectCast(SyntaxFactory.ParseName("A"), IdentifierNameSyntax)
Dim speculativeModel As SemanticModel = Nothing
Dim success = model.TryGetSpeculativeSemanticModel(position, speculatedAliasName, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
Dim symbol = DirectCast(speculativeModel.GetAliasInfo(speculatedAliasName), AliasSymbol)
Assert.NotNull(symbol)
Assert.Equal("A", symbol.ToDisplayString())
Assert.Equal("System.ArgumentException", symbol.Target.ToDisplayString())
End Sub
<Fact, WorkItem(849360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849360")>
Public Sub TestGetSpeculativeSemanticModelForLocalDeclaration_Incomplete_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Module M
Sub T()
Namespace A
Class B
Function S()
Dim c = Me.goo
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim moduleBlock = DirectCast(root.Members(0), ModuleBlockSyntax)
Dim namespaceBlock = DirectCast(root.Members(1), NamespaceBlockSyntax)
Dim typeBlockSyntax = DirectCast(namespaceBlock.Members(0), TypeBlockSyntax)
Dim methodBlockSyntax = DirectCast(typeBlockSyntax.Members(0), MethodBlockSyntax)
Dim statementSyntax = DirectCast(methodBlockSyntax.Statements(0), LocalDeclarationStatementSyntax)
Dim initializer = statementSyntax.DescendantNodes().Single(Function(n) n.ToString() = "Me.goo")
Dim position = statementSyntax.SpanStart
Dim model = compilation.GetSemanticModel(tree)
Dim speculatedExpression = DirectCast(SyntaxFactory.ParseExpression("goo"), ExpressionSyntax)
Dim speculatedStatement = statementSyntax.ReplaceNode(initializer, speculatedExpression)
Dim speculativeModel As SemanticModel = Nothing
Dim success = model.TryGetSpeculativeSemanticModel(position, speculatedStatement, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
End Sub
<Fact, WorkItem(849360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849360")>
Public Sub TestGetSpeculativeSemanticModelForLocalDeclaration_Incomplete_2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BindAsExpressionVsBindAsType">
<file name="a.vb">
Module M
Class D
Sub T()
Namespace A
Class B
Function S()
Dim c = Me.goo
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot()
Dim moduleBlock = DirectCast(root.Members(0), ModuleBlockSyntax)
Dim namespaceBlock = DirectCast(root.Members(1), NamespaceBlockSyntax)
Dim typeBlockSyntax = DirectCast(namespaceBlock.Members(0), TypeBlockSyntax)
Dim methodBlockSyntax = DirectCast(typeBlockSyntax.Members(0), MethodBlockSyntax)
Dim statementSyntax = DirectCast(methodBlockSyntax.Statements(0), LocalDeclarationStatementSyntax)
Dim initializer = statementSyntax.DescendantNodes().Single(Function(n) n.ToString() = "Me.goo")
Dim position = statementSyntax.SpanStart
Dim model = compilation.GetSemanticModel(tree)
Dim speculatedExpression = DirectCast(SyntaxFactory.ParseExpression("goo"), ExpressionSyntax)
Dim speculatedStatement = statementSyntax.ReplaceNode(initializer, speculatedExpression)
Dim speculativeModel As SemanticModel = Nothing
Dim success = model.TryGetSpeculativeSemanticModel(position, speculatedStatement, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
End Sub
#End Region
#Region "ClassifyConversion"
' Check invariants of Conversion.
Private Sub ValidateConversionInvariants(conv As Conversion)
' Exactly 1 of NOT IsConvertible, IsWidening, IsNarrowing must be true
Assert.Equal(-1, CInt(Not conv.Exists) + CInt(conv.IsWidening) + CInt(conv.IsNarrowing))
If conv.Exists Then
' Exactly 1 of conversion classifications: must be true
Assert.Equal(-1, CInt(conv.IsIdentity) + CInt(conv.IsDefault) + CInt(conv.IsNumeric) +
CInt(conv.IsBoolean) + CInt(conv.IsReference) + CInt(conv.IsAnonymousDelegate) +
CInt(conv.IsArray) + CInt(conv.IsValueType) + CInt(conv.IsNullableValueType) +
CInt(conv.IsString) + CInt(conv.IsTypeParameter) + CInt(conv.IsUserDefined))
End If
' Method set only if user defined set.
Assert.True((conv.IsUserDefined And conv.Method IsNot Nothing) Or
(Not conv.IsUserDefined And conv.Method Is Nothing),
"UserDefinedConversionMethod should be set if and only if IsUserDefined is true.")
End Sub
' Unit tests for ClassifyConversion on Compilation.
' We already have very extensive tests on the internal ClassifyConversion API; this just exercises the
' public API to make sure we're mapping correctly to the external interface.
<Fact()>
Public Sub ClassifyConversion()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ClassifyConversion">
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Enum EEE
Red
End Enum
Class AAA(Of T)
Implements ICloneable
Public Function Clone() As Object Implements ICloneable.Clone
Return Me
End Function
Public field_li1 As List(Of Integer)
Public field_li2 As List(Of Integer)
public field_enum as EEE
public field_aaa_array as AAA(Of T)()
public field_obj_array as Object()
Public field_null_int as Integer?
public field_tp As T
End Class
</file>
</compilation>)
Dim conv As Conversion
Dim globalNS = compilation.GlobalNamespace
Dim int64 = compilation.GetTypeByMetadataName("System.Int64")
Dim int32 = compilation.GetTypeByMetadataName("System.Int32")
Dim int16 = compilation.GetTypeByMetadataName("System.Int16")
Dim str = compilation.GetTypeByMetadataName("System.String")
Dim bool = compilation.GetTypeByMetadataName("System.Boolean")
Dim objType = compilation.GetTypeByMetadataName("System.Object")
Dim cloneableType = compilation.GetTypeByMetadataName("System.ICloneable")
Dim classAAA = globalNS.GetTypeMembers("AAA").Single()
Dim listOfInt32_1 As TypeSymbol = DirectCast(classAAA.GetMembers("field_li1").Single(), FieldSymbol).Type
Dim listOfInt32_2 As TypeSymbol = DirectCast(classAAA.GetMembers("field_li2").Single(), FieldSymbol).Type
Dim enumType As TypeSymbol = DirectCast(classAAA.GetMembers("field_enum").Single(), FieldSymbol).Type
Dim aaaArray As TypeSymbol = DirectCast(classAAA.GetMembers("field_aaa_array").Single(), FieldSymbol).Type
Dim objArray As TypeSymbol = DirectCast(classAAA.GetMembers("field_obj_array").Single(), FieldSymbol).Type
Dim nullInt32 As TypeSymbol = DirectCast(classAAA.GetMembers("field_null_int").Single(), FieldSymbol).Type
Dim typeParam As TypeSymbol = DirectCast(classAAA.GetMembers("field_tp").Single(), FieldSymbol).Type
' Convert List(Of Integer) -> List(Of Integer) : Should be widening identity conversion
conv = compilation.ClassifyConversion(listOfInt32_1, listOfInt32_2)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.True(conv.IsWidening)
Assert.False(conv.IsNarrowing)
Assert.True(conv.IsIdentity)
Assert.True(compilation.HasImplicitConversion(listOfInt32_1, listOfInt32_2))
' Convert List(Of Integer) -> Integer : Should be no conversion
conv = compilation.ClassifyConversion(listOfInt32_1, int32)
ValidateConversionInvariants(conv)
Assert.False(conv.Exists)
Assert.False(conv.IsWidening)
Assert.False(conv.IsNarrowing)
Assert.False(compilation.HasImplicitConversion(listOfInt32_1, int32))
' Convert String -> Integer: Should be narrowing string conversion
conv = compilation.ClassifyConversion(str, int32)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.False(conv.IsWidening)
Assert.True(conv.IsNarrowing)
Assert.True(conv.IsString)
Assert.Equal("NarrowingString", conv.ToString())
Assert.False(compilation.HasImplicitConversion(str, int32))
' Convert Enum -> Integer: Should be widening numeric conversion
conv = compilation.ClassifyConversion(enumType, int32)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.True(conv.IsWidening)
Assert.False(conv.IsNarrowing)
Assert.True(conv.IsNumeric)
Assert.Equal("WideningNumeric, InvolvesEnumTypeConversions", conv.ToString())
Assert.True(compilation.HasImplicitConversion(enumType, int32))
' Convert Enum -> String: Should be narrowing string conversion
conv = compilation.ClassifyConversion(enumType, str)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.False(conv.IsWidening)
Assert.True(conv.IsNarrowing)
Assert.True(conv.IsString)
Assert.False(compilation.HasImplicitConversion(enumType, str))
' Convert Long -> Integer: Should be narrowing numeric conversion
conv = compilation.ClassifyConversion(int64, int32)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.False(conv.IsWidening)
Assert.True(conv.IsNarrowing)
Assert.True(conv.IsNumeric)
Assert.False(compilation.HasImplicitConversion(int64, int32))
' Convert Boolean -> Enum: Should be narrowing boolean conversion
conv = compilation.ClassifyConversion(bool, enumType)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.False(conv.IsWidening)
Assert.True(conv.IsNarrowing)
Assert.True(conv.IsBoolean)
Assert.Equal("NarrowingBoolean, InvolvesEnumTypeConversions", conv.ToString())
Assert.False(compilation.HasImplicitConversion(bool, enumType))
' Convert List(Of Integer) -> Object: Should be widening reference conversion
conv = compilation.ClassifyConversion(listOfInt32_1, objType)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.True(conv.IsWidening)
Assert.False(conv.IsNarrowing)
Assert.True(conv.IsReference)
Assert.Equal("WideningReference", conv.ToString())
Assert.True(compilation.HasImplicitConversion(listOfInt32_1, objType))
' Convert Object -> List(Of Integer): Should be narrow reference conversion
conv = compilation.ClassifyConversion(objType, listOfInt32_1)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.False(conv.IsWidening)
Assert.True(conv.IsNarrowing)
Assert.True(conv.IsReference)
Assert.False(compilation.HasImplicitConversion(objType, listOfInt32_1))
' Convert AAA -> System.ICloneable: SHould be widening reference conversion
conv = compilation.ClassifyConversion(classAAA, cloneableType)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.True(conv.IsWidening)
Assert.False(conv.IsNarrowing)
Assert.True(conv.IsReference)
Assert.True(compilation.HasImplicitConversion(classAAA, cloneableType))
' Convert AAA() -> Object(): SHould be widening array conversion
conv = compilation.ClassifyConversion(aaaArray, objArray)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.True(conv.IsWidening)
Assert.False(conv.IsNarrowing)
Assert.True(conv.IsArray)
Assert.True(compilation.HasImplicitConversion(aaaArray, objArray))
' Convert Object() -> AAA(): SHould be narrowing array conversion
conv = compilation.ClassifyConversion(objArray, aaaArray)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.False(conv.IsWidening)
Assert.True(conv.IsNarrowing)
Assert.True(conv.IsArray)
Assert.Equal("NarrowingArray", conv.ToString())
Assert.False(compilation.HasImplicitConversion(objArray, aaaArray))
' Convert Short -> Integer?: Should be widening nullable value type conversion
conv = compilation.ClassifyConversion(int16, nullInt32)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.True(conv.IsWidening)
Assert.False(conv.IsNarrowing)
Assert.True(conv.IsNullableValueType)
Assert.Equal("WideningNullable", conv.ToString())
Assert.True(compilation.HasImplicitConversion(int16, nullInt32))
' Convert Integer? -> Integer: Should be narrowing nullable value type conversion
conv = compilation.ClassifyConversion(nullInt32, int32)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.False(conv.IsWidening)
Assert.True(conv.IsNarrowing)
Assert.True(conv.IsNullableValueType)
Assert.False(compilation.HasImplicitConversion(nullInt32, int32))
' Convert T -> Object: Widening type parameter conversion
conv = compilation.ClassifyConversion(typeParam, objType)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.True(conv.IsWidening)
Assert.False(conv.IsNarrowing)
Assert.True(conv.IsTypeParameter)
Assert.True(compilation.HasImplicitConversion(typeParam, objType))
' Convert Object -> T : Narrowing type parameter conversion
conv = compilation.ClassifyConversion(objType, typeParam)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.False(conv.IsWidening)
Assert.True(conv.IsNarrowing)
Assert.True(conv.IsTypeParameter)
Assert.Equal("NarrowingTypeParameter", conv.ToString())
Assert.False(compilation.HasImplicitConversion(objType, typeParam))
' Check equality, hash code.
Dim conv2 = compilation.ClassifyConversion(objType, typeParam)
Dim conv3 = compilation.ClassifyConversion(typeParam, objType)
Assert.True(conv = conv2, "Check equality implementation")
Assert.False(conv <> conv2, "Check equality implementation")
Assert.True(conv.Equals(conv2), "Check equality implementation")
Assert.True(conv.Equals(DirectCast(conv2, Object)), "Check equality implementation")
Assert.True(conv.GetHashCode() = conv2.GetHashCode(), "Check equality implementation")
Assert.False(conv3 = conv2, "Check equality implementation")
Assert.True(conv3 <> conv2, "Check equality implementation")
Assert.False(conv3.Equals(conv2), "Check equality implementation")
Assert.False(conv3.Equals(DirectCast(conv2, Object)), "Check equality implementation")
CompilationUtils.AssertNoErrors(compilation)
End Sub
' Unit tests for ClassifyConversion on SemanticModel.
' We already have very extensive tests on the internal ClassifyConversion API; this just exercises the
' public API to make sure we're mapping correctly to the external interface.
<Fact()>
Public Sub ClassifyConversionSemanticModel()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ClassifyConversionSemanticModel">
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Enum EEE
Red
End Enum
Class AAA
Public Sub Goo()
anInt = 0
anInt = 14
anObj = Nothing
End Sub
Private anInt As Integer
Private anObj As Object
End Class
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim nodeZero As ExpressionSyntax = DirectCast(CompilationUtils.FindNodeFromText(tree, "0"), ExpressionSyntax)
Dim nodeFourteen As ExpressionSyntax = DirectCast(CompilationUtils.FindNodeFromText(tree, "14"), ExpressionSyntax)
Dim nodeNothing As ExpressionSyntax = DirectCast(CompilationUtils.FindNodeFromText(tree, "Nothing"), ExpressionSyntax)
Dim nodeIntField As ExpressionSyntax = DirectCast(CompilationUtils.FindNodeFromText(tree, "anInt"), ExpressionSyntax)
Dim nodeObjField As ExpressionSyntax = DirectCast(CompilationUtils.FindNodeFromText(tree, "anObj"), ExpressionSyntax)
Dim conv As Conversion
Dim globalNS = compilation.GlobalNamespace
Dim int16 = compilation.GetTypeByMetadataName("System.Int16")
Dim str = compilation.GetTypeByMetadataName("System.String")
Dim bool = compilation.GetTypeByMetadataName("System.Boolean")
Dim objType = compilation.GetTypeByMetadataName("System.Object")
Dim classAAA = globalNS.GetTypeMembers("AAA").Single()
Dim enumEEE = globalNS.GetTypeMembers("EEE").Single()
' Convert 0 -> Int16 : Should be widening numeric conversion
conv = semanticModel.ClassifyConversion(nodeZero, int16)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.True(conv.IsWidening)
Assert.False(conv.IsNarrowing)
Assert.True(conv.IsNumeric)
' Convert 14 -> Int16 : Should be widening numeric conversion
conv = semanticModel.ClassifyConversion(nodeFourteen, int16)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.True(conv.IsWidening)
Assert.False(conv.IsNarrowing)
Assert.True(conv.IsNumeric)
' Convert int field -> Int16 : Should be narrowing numeric conversion
conv = semanticModel.ClassifyConversion(nodeIntField, int16)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.False(conv.IsWidening)
Assert.True(conv.IsNarrowing)
Assert.True(conv.IsNumeric)
' Converts 0 -> enum: Should be widening numeric
conv = semanticModel.ClassifyConversion(nodeZero, enumEEE)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.True(conv.IsWidening)
Assert.False(conv.IsNarrowing)
Assert.True(conv.IsNumeric)
' Converts 14 -> enum: Should be narrowing numeric
conv = semanticModel.ClassifyConversion(nodeFourteen, enumEEE)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.False(conv.IsWidening)
Assert.True(conv.IsNarrowing)
Assert.True(conv.IsNumeric)
' Converts int field -> enum: Should be narrowing numeric
conv = semanticModel.ClassifyConversion(nodeIntField, enumEEE)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.False(conv.IsWidening)
Assert.True(conv.IsNarrowing)
Assert.True(conv.IsNumeric)
' Convert Nothing to enum: should be widening default
conv = semanticModel.ClassifyConversion(nodeNothing, enumEEE)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.True(conv.IsWidening)
Assert.False(conv.IsNarrowing)
Assert.True(conv.IsDefault)
' Convert Object field to enum: should be narrowing value type
conv = semanticModel.ClassifyConversion(nodeObjField, enumEEE)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.False(conv.IsWidening)
Assert.True(conv.IsNarrowing)
Assert.True(conv.IsValueType)
' Convert Nothing to string: should be widening default
conv = semanticModel.ClassifyConversion(nodeNothing, str)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.True(conv.IsWidening)
Assert.False(conv.IsNarrowing)
Assert.True(conv.IsDefault)
' Convert object field to string: should be narrowing reference
conv = semanticModel.ClassifyConversion(nodeObjField, str)
ValidateConversionInvariants(conv)
Assert.True(conv.Exists)
Assert.False(conv.IsWidening)
Assert.True(conv.IsNarrowing)
Assert.True(conv.IsReference)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<WorkItem(527766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527766")>
<Fact()>
Public Sub ClassifyConversionSemanticModel2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ClassifyConversionSemanticModel2">
<file name="a.vb">
Imports System
Imports Microsoft.VisualBasic
Module Program
Sub Main()
Dim en As E = 0 'widening numeric
Dim enullable As E? = 0 'narrowing nullable
Dim chary(2) As Char
chary(0) = "0"
chary(1) = "."
chary(2) = "2"
Dim str As String = chary ' widening string
Dim chary2 As Char() = str ' narrowing string
Dim float As Single = str ' string->num: narrowing string
Dim bb As Boolean = True
str = bb ' narrowing string
End Sub
End Module
Enum E
Zero
One
End Enum
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim cunit = tree.GetCompilationUnitRoot()
Dim v1 = TryCast(cunit.Members(0), TypeBlockSyntax)
Dim v2 = TryCast(v1.Members(0), MethodBlockSyntax)
' Dim en As E = 0 'widening numeric
Dim v3 = DirectCast(v2.ChildNodesAndTokens()(1).AsNode(), LocalDeclarationStatementSyntax)
Assert.NotNull(v3)
Dim expr1 As ExpressionSyntax = v3.Declarators(0).Initializer.Value
Assert.Equal("0", expr1.ToString())
Dim infoP = semanticModel.GetSemanticInfoSummary(expr1)
Dim enumE = compilation.GlobalNamespace.GetTypeMembers("E").Single()
Assert.Equal(enumE, infoP.ConvertedType)
Dim conv1 = semanticModel.ClassifyConversion(expr1, infoP.ConvertedType)
ValidateConversionInvariants(conv1)
Assert.True(conv1.IsWidening)
Assert.False(conv1.IsNarrowing)
Assert.True(conv1.IsNumeric)
'Dim enullable As E? = 0 'narrowing nullable
v3 = DirectCast(v2.ChildNodesAndTokens()(2).AsNode(), LocalDeclarationStatementSyntax)
Assert.NotNull(v3)
expr1 = v3.Declarators(0).Initializer.Value
infoP = semanticModel.GetSemanticInfoSummary(expr1)
Assert.NotNull(infoP.ConvertedType)
Assert.Equal("E?", infoP.ConvertedType.ToString())
conv1 = semanticModel.ClassifyConversion(expr1, infoP.ConvertedType)
ValidateConversionInvariants(conv1)
' Bug#5034 (exp Widening + Nullable) & C#: ImplicitEnum
' Conversion for C# and VB are very different by nature
Assert.False(conv1.IsWidening)
Assert.True(conv1.IsNarrowing)
Assert.False(conv1.IsNumeric)
Assert.True(conv1.IsNullableValueType)
' Dim str As String = chary
Dim v4 = DirectCast(v2.ChildNodesAndTokens()(7).AsNode(), LocalDeclarationStatementSyntax)
Assert.NotNull(v4)
Dim expr2 As ExpressionSyntax = v4.Declarators(0).Initializer.Value
Assert.Equal("chary", expr2.ToString())
infoP = semanticModel.GetSemanticInfoSummary(expr2)
Assert.NotNull(infoP.ConvertedType)
Dim conv2 = semanticModel.ClassifyConversion(expr2, infoP.ConvertedType)
ValidateConversionInvariants(conv2)
Assert.True(conv2.IsWidening)
Assert.False(conv2.IsNarrowing)
Assert.True(conv2.IsString)
' Dim chary2 As Char() = str
v4 = DirectCast(v2.ChildNodesAndTokens()(8).AsNode(), LocalDeclarationStatementSyntax)
Assert.NotNull(v4)
expr2 = v4.Declarators(0).Initializer.Value
Assert.Equal("str", expr2.ToString())
infoP = semanticModel.GetSemanticInfoSummary(expr2)
Assert.NotNull(infoP.ConvertedType)
conv2 = semanticModel.ClassifyConversion(expr2, infoP.ConvertedType)
ValidateConversionInvariants(conv2)
Assert.False(conv2.IsWidening)
Assert.True(conv2.IsNarrowing)
Assert.True(conv2.IsString)
' Dim float As Single = str
v4 = DirectCast(v2.ChildNodesAndTokens()(9).AsNode(), LocalDeclarationStatementSyntax)
Assert.NotNull(v4)
expr2 = v4.Declarators(0).Initializer.Value
infoP = semanticModel.GetSemanticInfoSummary(expr2)
Assert.NotNull(infoP.ConvertedType)
conv2 = semanticModel.ClassifyConversion(expr2, infoP.ConvertedType)
ValidateConversionInvariants(conv2)
Assert.False(conv2.IsWidening)
Assert.True(conv2.IsNarrowing)
Assert.True(conv2.IsString)
' str = bb ' narrowing string
Dim strSym = compilation.GetTypeByMetadataName("System.String")
Dim v5 = DirectCast(v2.ChildNodesAndTokens()(11).AsNode(), AssignmentStatementSyntax)
Assert.NotNull(v5)
expr2 = v5.Right
conv2 = semanticModel.ClassifyConversion(expr2, strSym)
ValidateConversionInvariants(conv2)
Assert.False(conv2.IsWidening)
Assert.True(conv2.IsNarrowing)
Assert.True(conv2.IsString)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub ClassifyConversionSemanticModel2WithStaticLocals()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ClassifyConversionSemanticModel2">
<file name="a.vb">
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub Main()
Static en As E = 0 'widening numeric
Static enullable As E? = 0 'narrowing nullable
Static chary(2) As Char
chary(0) = "0"
chary(1) = "."
chary(2) = "2"
Static str As String = chary ' widening string
Static chary2 As Char() = str ' narrowing string
Static float As Single = str ' string->num: narrowing string
Static bb As Boolean = True
str = bb ' narrowing string
End Sub
End Module
Enum E
Zero
One
End Enum
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim cunit = tree.GetCompilationUnitRoot()
Dim v1 = TryCast(cunit.Members(0), TypeBlockSyntax)
Dim v2 = TryCast(v1.Members(0), MethodBlockSyntax)
' Dim en As E = 0 'widening numeric
Dim v3 = DirectCast(v2.ChildNodesAndTokens()(1).AsNode(), LocalDeclarationStatementSyntax)
Assert.NotNull(v3)
Dim expr1 As ExpressionSyntax = v3.Declarators(0).Initializer.Value
Assert.Equal("0", expr1.ToString())
Dim infoP = semanticModel.GetSemanticInfoSummary(expr1)
Dim enumE = compilation.GlobalNamespace.GetTypeMembers("E").Single()
Assert.Equal(enumE, infoP.ConvertedType)
Dim conv1 = semanticModel.ClassifyConversion(expr1, infoP.ConvertedType)
ValidateConversionInvariants(conv1)
Assert.True(conv1.IsWidening)
Assert.False(conv1.IsNarrowing)
Assert.True(conv1.IsNumeric)
'Dim enullable As E? = 0 'narrowing nullable
v3 = DirectCast(v2.ChildNodesAndTokens()(2).AsNode(), LocalDeclarationStatementSyntax)
Assert.NotNull(v3)
expr1 = v3.Declarators(0).Initializer.Value
infoP = semanticModel.GetSemanticInfoSummary(expr1)
Assert.NotNull(infoP.ConvertedType)
Assert.Equal("E?", infoP.ConvertedType.ToString())
conv1 = semanticModel.ClassifyConversion(expr1, infoP.ConvertedType)
ValidateConversionInvariants(conv1)
Assert.False(conv1.IsWidening)
Assert.True(conv1.IsNarrowing) ' should be IsWidening (Bug#5034 is out of scope)
Assert.False(conv1.IsNumeric)
Assert.True(conv1.IsNullableValueType)
' Dim str As String = chary
Dim v4 = DirectCast(v2.ChildNodesAndTokens()(7).AsNode(), LocalDeclarationStatementSyntax)
Assert.NotNull(v4)
Dim expr2 As ExpressionSyntax = v4.Declarators(0).Initializer.Value
Assert.Equal("chary", expr2.ToString())
infoP = semanticModel.GetSemanticInfoSummary(expr2)
Assert.NotNull(infoP.ConvertedType)
Dim conv2 = semanticModel.ClassifyConversion(expr2, infoP.ConvertedType)
ValidateConversionInvariants(conv2)
Assert.True(conv2.IsWidening)
Assert.False(conv2.IsNarrowing)
Assert.True(conv2.IsString)
' Dim chary2 As Char() = str
v4 = DirectCast(v2.ChildNodesAndTokens()(8).AsNode(), LocalDeclarationStatementSyntax)
Assert.NotNull(v4)
expr2 = v4.Declarators(0).Initializer.Value
Assert.Equal("str", expr2.ToString())
infoP = semanticModel.GetSemanticInfoSummary(expr2)
Assert.NotNull(infoP.ConvertedType)
conv2 = semanticModel.ClassifyConversion(expr2, infoP.ConvertedType)
ValidateConversionInvariants(conv2)
Assert.False(conv2.IsWidening)
Assert.True(conv2.IsNarrowing)
Assert.True(conv2.IsString)
' Dim float As Single = str
v4 = DirectCast(v2.ChildNodesAndTokens()(9).AsNode(), LocalDeclarationStatementSyntax)
Assert.NotNull(v4)
expr2 = v4.Declarators(0).Initializer.Value
infoP = semanticModel.GetSemanticInfoSummary(expr2)
Assert.NotNull(infoP.ConvertedType)
conv2 = semanticModel.ClassifyConversion(expr2, infoP.ConvertedType)
ValidateConversionInvariants(conv2)
Assert.False(conv2.IsWidening)
Assert.True(conv2.IsNarrowing)
Assert.True(conv2.IsString)
' str = bb ' narrowing string
Dim strSym = compilation.GetTypeByMetadataName("System.String")
Dim v5 = DirectCast(v2.ChildNodesAndTokens()(11).AsNode(), AssignmentStatementSyntax)
Assert.NotNull(v5)
expr2 = v5.Right
conv2 = semanticModel.ClassifyConversion(expr2, strSym)
ValidateConversionInvariants(conv2)
Assert.False(conv2.IsWidening)
Assert.True(conv2.IsNarrowing)
Assert.True(conv2.IsString)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<WorkItem(541564, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541564")>
<Fact()>
Public Sub ClassifyConversionForParameter()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ClassifyConversion">
<file name="a.vb">
Imports System
Module Test
Public Property AP As String
Private s As String
Public Property P As String
Get
Return s
End Get
Set(value As String)
s = value
End Set
End Property
Sub ObjectParameter(o As Object)
End Sub
Sub Main()
P = "123"
ObjectParameter(P)
AP = "456"
ObjectParameter(AP)
End Sub
End Module
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
' property
Dim argList = DirectCast(CompilationUtils.FindNodeFromText(tree, "(P)"), ArgumentListSyntax)
Dim arg = DirectCast(argList.ChildNodes().First(), SimpleArgumentSyntax).Expression
Dim semanticInfo = semanticModel.GetSemanticInfoSummary(arg)
Dim conv As Conversion = semanticModel.ClassifyConversion(arg, semanticInfo.ConvertedType)
Assert.True(semanticInfo.ImplicitConversion.IsWidening AndAlso semanticInfo.ImplicitConversion.IsReference, "Expected WideningReference")
Assert.Equal(semanticInfo.ImplicitConversion, conv)
' Auto-implemented
argList = DirectCast(CompilationUtils.FindNodeFromText(tree, "(AP)"), ArgumentListSyntax)
arg = DirectCast(argList.ChildNodes().First(), SimpleArgumentSyntax).Expression
semanticInfo = semanticModel.GetSemanticInfoSummary(arg)
conv = semanticModel.ClassifyConversion(arg, semanticInfo.ConvertedType)
Assert.True(semanticInfo.ImplicitConversion.IsWidening AndAlso semanticInfo.ImplicitConversion.IsReference, "Expected WideningReference")
Assert.Equal(semanticInfo.ImplicitConversion, conv)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<WorkItem(541577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541577")>
<Fact()>
Public Sub ClassifyConversionForPropAsBinaryOperand()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Friend Module M
Sub S()
If Prop = 12 Then
Console.WriteLine(1)
End If
End Sub
Public Property Prop As Integer
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node = DirectCast(CompilationUtils.FindNodeFromText(tree, "Prop"), IdentifierNameSyntax)
Dim info = semanticModel.GetSemanticInfoSummary(node)
Dim expr = DirectCast(node.Parent, BinaryExpressionSyntax)
Dim infoP = semanticModel.GetSemanticInfoSummary(expr)
Dim conv1 As Conversion = semanticModel.ClassifyConversion(node, infoP.Type)
Dim conv2 As Conversion = compilation.ClassifyConversion(info.Type, infoP.Type)
Assert.Equal(conv2, conv1)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact(), WorkItem(544251, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544251")>
Public Sub ClassifyConversionEnumExplicitOn()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Imports System
Friend Module M
Sub S()
Dim x = Color.Red
End Sub
Enum Color
Red = 3
End Enum
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of MemberAccessExpressionSyntax).First()
Dim expr = node.Name
Assert.Equal("Red", expr.ToString())
Dim info = semanticModel.GetTypeInfo(expr)
Assert.NotNull(info.Type)
Dim conv1 = semanticModel.GetConversion(expr)
Assert.True(conv1.IsIdentity, "Identity")
Dim conv2 = semanticModel.ClassifyConversion(expr, info.Type)
Assert.Equal(conv1, conv2)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact(), WorkItem(544251, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544251")>
Public Sub ClassifyConversionEnumExplicitOff()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit Off
Imports System
Friend Module M
Sub Main()
Dim x = Color.Red
End Sub
Enum Color
Red = 3
End Enum
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of MemberAccessExpressionSyntax).First()
Dim expr = node.Name
Dim info = semanticModel.GetTypeInfo(expr)
Assert.NotNull(info.Type)
Dim conv1 = semanticModel.GetConversion(expr)
Dim conv2 = semanticModel.ClassifyConversion(expr, info.Type)
Assert.Equal(conv1, conv2)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact(), WorkItem(545101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545101")>
Public Sub ClassifyConversionNarrowingNullableStrictOff()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Friend Module M
Sub Main()
Dim d1 As Double = 1.2
Dim d2 As Double? = 1.2
Dim ret = 1 << d1 AndAlso 2 << d2
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
' AndAlso
Dim node = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of BinaryExpressionSyntax).First()
' Shift
Dim expr = DirectCast(node.Left, BinaryExpressionSyntax)
' Double
Dim id = TryCast(expr.Right, IdentifierNameSyntax)
Assert.Equal("d1", id.ToString())
Assert.NotNull(id)
Dim info = semanticModel.GetTypeInfo(id)
Assert.NotNull(info.Type)
Dim conv1 = semanticModel.GetConversion(id)
Assert.True(conv1.IsNarrowing, "Narrowing")
Dim conv2 = semanticModel.ClassifyConversion(id, info.ConvertedType)
Assert.Equal(conv1, conv2)
' Shift
expr = DirectCast(node.Right, BinaryExpressionSyntax)
' Duble?
id = TryCast(expr.Right, IdentifierNameSyntax)
Assert.Equal("d2", id.ToString())
Assert.NotNull(id)
info = semanticModel.GetTypeInfo(id)
Assert.NotNull(info.Type)
conv1 = semanticModel.GetConversion(id)
Assert.True(conv1.IsNarrowing, "Narrowing")
conv2 = semanticModel.ClassifyConversion(id, info.ConvertedType)
Assert.Equal(conv1, conv2)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<WorkItem(799045, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/799045")>
<Fact()>
Public Sub ClassifyConversionForArrayLiteral()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Public Class Class1
Sub Goo()
Dim a As Object = CType({1, 2, 3}, Integer())
End Sub
End Class
]]></file>
</compilation>)
AssertNoErrors(compilation)
Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim model = compilation.GetSemanticModel(tree)
Dim castNode = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of CTypeExpressionSyntax).First()
Dim expr = castNode.Expression
Dim castType = DirectCast(model.GetTypeInfo(castNode.Type).Type, TypeSymbol)
Assert.Equal("System.Int32()", castType.ToTestDisplayString())
Dim typeInfo = model.GetTypeInfo(expr)
Assert.Equal("System.Int32()", typeInfo.ConvertedType.ToTestDisplayString())
Assert.Null(typeInfo.Type)
Dim conv1 = model.ClassifyConversion(expr, castType)
Assert.Equal(ConversionKind.Widening, conv1.Kind)
Dim conv2 = model.ClassifyConversion(castNode.Span.Start, expr, castType)
Assert.Equal(ConversionKind.Widening, conv2.Kind)
End Sub
#End Region
#Region "Msic."
<Fact()>
Public Sub IsAccessible()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="IsAccessible">
<file name="a.vb">
Imports System
Class A
Public X As Integer
Protected Y As Integer
Private Protected Z As Integer
End Class
Class B
Inherits A
Sub Goo()
Console.WriteLine() ' in B.Goo
End Sub
' in B class level
Dim field as Integer
End Class
Class C
Sub Goo()
Console.WriteLine() ' in C.Goo
End Sub
End Class
Namespace N ' in N
End Namespace
</file>
</compilation>,
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_5))
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim positionInB As Integer = CompilationUtils.FindPositionFromText(tree, "in B class level")
Dim positionInBGoo As Integer = CompilationUtils.FindPositionFromText(tree, "in B.Goo")
Dim positionInCGoo As Integer = CompilationUtils.FindPositionFromText(tree, "in C.Goo")
Dim positionInN As Integer = CompilationUtils.FindPositionFromText(tree, "in N")
Dim globalNS = compilation.GlobalNamespace
Dim classA = DirectCast(globalNS.GetMembers("A").Single(), NamedTypeSymbol)
Dim fieldX = DirectCast(classA.GetMembers("X").Single(), FieldSymbol)
Dim fieldY = DirectCast(classA.GetMembers("Y").Single(), FieldSymbol)
Dim fieldZ = DirectCast(classA.GetMembers("Z").Single(), FieldSymbol)
Assert.True(semanticModel.IsAccessible(positionInN, fieldX))
Assert.False(semanticModel.IsAccessible(positionInN, fieldY))
Assert.False(semanticModel.IsAccessible(positionInN, fieldZ))
Assert.True(semanticModel.IsAccessible(positionInB, fieldX))
Assert.True(semanticModel.IsAccessible(positionInB, fieldY))
Assert.True(semanticModel.IsAccessible(positionInB, fieldZ))
Assert.True(semanticModel.IsAccessible(positionInBGoo, fieldX))
Assert.True(semanticModel.IsAccessible(positionInBGoo, fieldY))
Assert.True(semanticModel.IsAccessible(positionInBGoo, fieldZ))
Assert.True(semanticModel.IsAccessible(positionInCGoo, fieldX))
Assert.False(semanticModel.IsAccessible(positionInCGoo, fieldY))
Assert.False(semanticModel.IsAccessible(positionInCGoo, fieldZ))
CompilationUtils.AssertNoErrors(compilation)
End Sub
<WorkItem(652109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/652109")>
<Fact()>
Public Sub Bug652109()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="IsAccessible">
<file name="a.vb">
<![CDATA[
but specify providing one type on the lamb infer others")
'INFERENCE nfence by specify a single lambda allowingric Extension Method, Lambda arguments - I--------
apInitScenario("Gene------------------------------------------ '--------------------------------------Function(c) c, Function(d) d)
Object)(1, Function(a) a, Function(b) b, z1d = Target5(Of Integer, Single, Double,tion(c) c, Function(d) d)
Dimect)(1, Function(a) a, Function(b) b, Func= Target5(Of Integer, Integer, Double, Objc) c, Function(d) d)
Dim z1c 1, Function(a) a, Function(b) b, Function(get5(Of Integer, Integer, Object, Object)( in the lambdas
Dim z1b = Tareneric types as well as the variable typesnt
'Verify the return type G Different Types using generic Type argument c, Function(d) d)
'Specify Function(a) a, Function(b) b, Function(c)et5(Of Integer, Object, Object, Object)(1,e - All Object
Dim z1a = Targ Generic Types which result in no inferenc 'SPECIFY TYPES
'Specifyingments - Specify Generic Type ")
rio("Generic Extension Method, Lambda argu-----------------
apInitScena------------------------------------------ '-----------------------------, Function(c) c, Function(d) d)
#End If
= sv.Target5(Function(a) a, Function(b) bc) c, Function(d) d)"
Dim z0at5(Function(a) a, Function(b) b, Function( 'COMPILEERROR: BC36646, "sv.Targeb) b, Function(c) c, Function(d) d)
z0 = Target5(sv, Function(a) a, Function(ion(c) c, Function(d) d)"
Dimt5(sv, Function(a) a, Function(b) b, Funct 'COMPILEERROR: BC36645, "TargeTYPES - Shared and Extension Method Call
n(c) c, Function(d) d)
apCompingle) a, Function(b As Double) b, Functio Dim z5a = sv.Target5(Function(a As Sype.ToString, "Unexpected Type")
nc`2[System.Int32,System.Single]", z5.GetTon(d) d)
apCompare("System.Fution(b As Single) b, Function(c) c, Functi sv.Target5(Function(a As Integer) a, Funcom Func 1st argument
Dim z5 =pes
'Infer T and U directy fr 'Provide 2 different types - infer tyin lambda allowing infer others")
arguments - Infence by specify two types Scenario("Generic Extension Method, Lambda----------------------
apInit------------------------------------------)
'------------------------]", z4.GetType.ToString, "Unexpected Type"e("System.Func`2[System.Int32,System.Int32ion(d As Integer) d)
apCompar(a) a, Function(b) b, Function(c) c, Funct
Dim z4 = sv.Target5(Function z3.GetType.ToString, "Unexpected Type")
System.Func`2[System.Int32,System.Int32]",c, Function(d) d)
apCompare(" a, Function(b) b, Function(c As Integer) Dim z3 = sv.Target5(Function(a).GetType.ToString, "Unexpected Type")
tem.Func`2[System.Int32,System.Int32]", z2Function(d) d)
apCompare("Sys Function(b As Integer) b, Function(c) c, Dim z2 = sv.Target5(Function(a) a,tType.ToString, "Unexpected Type")
.Func`2[System.Int32,System.Int32]", z1.Gection(d) d)
apCompare("Systemeger) a, Function(b) b, Function(c) c, Fun Dim z1 = sv.Target5(Function(a As Inty specifyint a type on the lambda
'In this case I define T,U,V be arguments then I can infer other types
So if I provide a single type to any of thda - others will be infered
'
End Module
Return x
End Function
Val w As Func(Of U, V)) As Func(Of T, U)
T), _
By ByVal z As Func(Of V, ByVal y As Func(Of U, T), _
f T, U), _
ByVal x As Func(Ot5(Of S, T, U, V)(ByVal a As S, _
lerServices.Extension()> _
Function TargedTest()
End Sub
<Runtime.Compiry
#End If
End Try
apEnCatch ex As Exception
End T
p.Kill()
.Diagnostics.Process.GetProcessById(appid)m p As System.Diagnostics.Process = System Then
Try
Diap()
Finally
#If Not ULTRAVIOLETest:
Catch
apErrorTr ' Exit test routine
'
ExitTected Type")
'
tem.Single]", z6a.GetType.ToString, "UnexpapCompare("System.Func`2[System.Single,SysAs Double) c, Function(d) d)
a As Single) a, Function(b) b, Function(c Dim z6a = sv.Target5(Function(6.GetType.ToString, "Unexpected Type")
stem.Func`2[System.Int32,System.Int32]", z Function(d) d)
apCompare("Sya, Function(b) b, Function(c As Single) c,im z6 = sv.Target5(Function(a As Integer) or T and U will be the same
Da result of T
'result types frovide Types for T and V, U is infered as ring, "Unexpected Type")
'p.Boolean,System.Double]", z5b.GetType.ToSt apCompare("System.Func`2[SystemFunction(c) c, Function(d As Double) d)
(Function(a As Boolean) a, Function(b) b, Type")
Dim z5b = sv.Target5uble]", z5a.GetType.ToString, "Unexpected are("System.Func`2[System.Single,System.Do
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim model = compilation.GetSemanticModel(tree)
For Each name In From x In NameSyntaxFinder.FindNames(tree.GetRoot()) Where x.ToString() = "sv" Select x
model.GetSymbolInfo(name)
Next
End Sub
<WorkItem(652026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/652026")>
<Fact()>
Public Sub Bug652026()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="IsAccessible">
<file name="a.vb">
<![CDATA[
oads Property olp5(ByVal Sng As Single) As End Property
Public Overlnfo = "Integer"
End Set
I4 = I4 + 1
strIr, VarType(I4), "Wrong Type", "")
apCompare(VariantType.Intege Set(ByVal Value As String)
olp5 = "Integer"
End Get
I4 = I4 + 1
nteger, VarType(I4), "Wrong Type", "")
t
apCompare(VariantType.Il I4 As Integer) As String
Ge Public Overloads Property olp5(ByVa End Set
End Property
strInfo = "Single"
ype", "")
Sng = Sng + 1
VariantType.Single, VarType(Sng), "Wrong Tlue As String)
apCompare( End Get
Set(ByVal Va + 1
olp4 = "Single"
ng Type", "")
Sng = Sngare(VariantType.Single, VarType(Sng), "Wrog
Get
apComproperty olp4(ByVal Sng As Single) As Strind Property
Public Overloads PatedType"
End Set
Enenu + 1
strInfo = "EnumerWrong Type", "")
enu = apCompare(VbInteger, VarType(enu), " Set(ByVal Value)
= "EnumeratedType"
End Get
enu = enu + 1
olp4rType(enu), "Wrong Type", "")
t
apCompare(VbInteger, VaVal enu As EnumeratedType)
Ge
Public Overloads Property olp4(By-----------------------------------
------------------------------------------ ' Properties
'
'-----------------------------
'
------------------------------------------versions
'
'------------
e(Dec), "Wrong Type", "")
apCompare(VariantType.Decimal, VarTyp Set(ByVal Value As String)
Decimal"
End Get
Dec = Dec + 1
olp7 = "e(Dec), "Wrong Type", "")
apCompare(VariantType.Decimal, VarTypl) As String
Get
verloads Property olp7(ByVal Dec As Decima End Property
Public O strInfo = "Single"
End Set
Sng = Sng + 1
e, VarType(Sng), "Wrong Type", "")
apCompare(VariantType.Singl Set(ByVal Value As String)
olp6 = "Single"
End Get
Sng = Sng + 1
gle, VarType(Sng), "Wrong Type", "")
apCompare(VariantType.SinSng As Single) As String
Get
Public Overloads Property olp6(ByVal End Set
End Property
strInfo = "Long"
ype", "")
I8 = I8 + 1
apCompare(VbLong, VarType(I8), "Wrong Tet(ByVal Value As String)
"Long"
End Get
S I8 = I8 + 1
olp6 = rType(I8), "Wrong Type", "")
Get
apCompare(VbLong, Va6(ByVal I8 As Long) As String
Public Overloads Property olp End Set
End Property
+ 1
strInfo = "Single"
rong Type", "")
Sng = Sngmpare(VariantType.Single, VarType(Sng), "Wl Value As String)
apCo
End Get
Set(ByVa Sng + 1
olp5 = "Single"
, "Wrong Type", "")
Sng =apCompare(VariantType.Single, VarType(Sng) String
Get
e(Cur), "Wrong Type", "")
apCompare(VariantType.Decimal, VarTypl) As String
Get
erloads Property olp10(ByVal Cur As Decima End Property
Public OvstrInfo = "Single"
End Set
Sng = Sng + 1
, VarType(Sng), "Wrong Type", "")
apCompare(VariantType.Single Set(ByVal Value As String)
olp9 = "Single"
End Get
Sng = Sng + 1
le, VarType(Sng), "Wrong Type", "")
apCompare(VariantType.Singng As Single) As String
Get
Public Overloads Property olp9(ByVal S End Set
End Property
strInfo = "Double"
"")
Dbl = Dbl + 1
ntType.Double, VarType(Dbl), "Wrong Type",String)
apCompare(Varia End Get
Set(ByVal Value As olp9 = "Double"
", "")
Dbl = Dbl + 1
iantType.Double, VarType(Dbl), "Wrong Type Get
apCompare(Varlp9(ByVal Dbl As Double) As String
y
Public Overloads Property o
End Set
End Propertng + 1
strInfo = "Single"rong Type", "")
Sng = Smpare(VariantType.Single, VarType(Sng), "Wl Value As String)
apCo
End Get
Set(ByVa Sng + 1
olp7 = "Single"
"Wrong Type", "")
Sng =Compare(VariantType.Single, VarType(Sng), ing
Get
ap Property olp7(ByVal Sng As Single) As StrEnd Property
Public Overloads= "Decimal"
End Set
Dec = Dec + 1
strInfo
strInfo = "Single"
"")
Sng = Sng + 1
ntType.Single, VarType(Sng), "Wrong Type",String)
apCompare(Varia End Get
Set(ByVal Value As olp12 = "Single"
, "")
Sng = Sng + 1
antType.Single, VarType(Sng), "Wrong Type" Get
apCompare(Vari12(ByVal Sng As Single) As String
Public Overloads Property olp End Set
End Property
x"
strInfo = "String"
ype", "")
Str = Str & "VariantType.String, VarType(Str), "Wrong Te As String)
apCompare( End Get
Set(ByVal Valu"
olp12 = "String"
pe", "")
Str = Str & "xariantType.String, VarType(Str), "Wrong Ty Get
apCompare(Volp12(ByVal Str As String) As String
ty
Public Overloads Property "
End Set
End ProperSng + 1
strInfo = "SingleWrong Type", "")
Sng = ompare(VariantType.Single, VarType(Sng), "al Value As String)
apC
End Get
Set(ByV Sng + 1
olp10 = "Single""Wrong Type", "")
Sng =Compare(VariantType.Single, VarType(Sng), tring
Get
aps Property olp10(ByVal Sng As Single) As S End Property
Public Overload = "Decimal"
End Set
Cur = Cur + 1
strInfope(Cur), "Wrong Type", "")
apCompare(VariantType.Decimal, VarTy Set(ByVal Value As String)
"Decimal"
End Get
Cur = Cur + 1
olp10 =
, "Wrong Type", "")
SngapCompare(VariantType.Single, VarType(Sng)tring
Get
s Property olp14(ByVal Sng As Single) As S End Property
Public Overloadnfo = "Date"
End Set
nterval.Day, 1, Dte)
strI"")
Dte = DateAdd(DateIantType.Date, VarType(Dte), "Wrong Type", String)
apCompare(Vari End Get
Set(ByVal Value As
olp14 = "Date"
Dte = DateAdd(DateInterval.Day, 1, Dte)
(Dte), "Wrong Type", "")
apCompare(VariantType.Date, VarTypee) As String
Get
Overloads Property olp14(ByVal Dte As Dat End Property
Public strInfo = "Single"
End Set
Sng = Sng + 1
e, VarType(Sng), "Wrong Type", "")
apCompare(VariantType.Singl Set(ByVal Value As String)
olp13 = "Single"
End Get
Sng = Sng + 1
le, VarType(Sng), "Wrong Type", "")
apCompare(VariantType.Sing As Single) As String
Get
Public Overloads Property olp13(ByVal SngEnd Set
End Property
strInfo = "String"
Str = Str & "x"
e.String, VarType(Str), "Wrong Type", "")
apCompare(VariantTypet
Set(ByVal Value As String) olp13 = "String"
End G Str = Str & "x"
tring, VarType(Str), "Wrong Type", "")
apCompare(VariantType.SStr As String) As String
Get
Public Overloads Property olp13(ByVal End Set
End Property
ype", "")
Dbl = Dbl + 1VariantType.Double, VarType(Dbl), "Wrong Te As String)
apCompare( End Get
Set(ByVal Valu1
olp9b = "Double"
Type", "")
Dbl = Dbl + (VariantType.Double, VarType(Dbl), "Wrong Get
apCompares Double, ByVal Dbl As Double) As String
blic Overloads Property olp9b(ByVal Dbl2 A Set
End Property
Pu strInfo = "Single"
End
Sng = Sng + 1
.Single, VarType(Sng), "Wrong Type", "")
)
apCompare(VariantTypeGet
Set(ByVal Value As String olp15 = "Single"
End
Sng = Sng + 1
e.Single, VarType(Sng), "Wrong Type", "")
et
apCompare(VariantTypal Sng As Single) As String
G Public Overloads Property olp15(ByVnd Set
End Property
#End If
strInfo = "object "
E
vnt = vnt & "x"
String, VarType(vnt), "Wrong Type", "")
apCompare(VariantType.et
Set(ByVal Value As String) olp15 = "object "
End G vnt = vnt & "x"
ring, VarType(vnt), "Wrong Type", "")
apCompare(VariantType.Stnt As Object) As String
Get
Public Overloads Property olp15(ByVal verty
#If VBCORE=True Then
#Else
le"
End Set
End Prop= Sng + 1
strInfo = "Sing "Wrong Type", "")
Sng pCompare(VariantType.Single, VarType(Sng),yVal Value As String)
ae"
End Get
Set(B = Sng + 1
olp14 = "Singl
nd Namespace
End Property
End Class
E strInfo = "Single"
End Set Sng = Sng + 1
gle, VarType(Sng), "Wrong Type", "")
apCompare(VariantType.Sin
Set(ByVal Value As String)
olp14b = "Single"
End Get
Sng = Sng + 1
gle, VarType(Sng), "Wrong Type", "")
apCompare(VariantType.SinDbl As Double) As String
Get
Val Sng As Single, ByVal C As Char, ByVal Public Overloads Property olp14b(By End Set
End Property
strInfo = "Date"
Dte = DateAdd(DateInterval.Day, 1, Dte)e(Dte), "Wrong Type", "")
apCompare(VariantType.Date, VarTyp Set(ByVal Value As String)
4b = "Date"
End Get
nterval.Day, 1, Dte)
olp1"")
Dte = DateAdd(DateIantType.Date, VarType(Dte), "Wrong Type", Get
apCompare(Varihar, ByVal Dbl As Double) As String
rty olp14b(ByVal Dte As Date, ByVal C As Coperty
Public Overloads Propengle"
End Set
End Prg = Sng + 1
strInfo = "Si), "Wrong Type", "")
Sn apCompare(VariantType.Single, VarType(Sng(ByVal Value As String)
gle"
End Get
Setng = Sng + 1
olp9b = "Sing), "Wrong Type", "")
S apCompare(VariantType.Single, VarType(SnAs String
Get
yVal Dbl2 As Double, ByVal Sng As Single)
Public Overloads Property olp9b(B End Set
End Property
strInfo = "Double"
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim model = compilation.GetSemanticModel(tree)
For Each name In From x In ExpressionSyntaxFinder.FindExpression(tree.GetRoot())
Where x.Kind = SyntaxKind.StringLiteralExpression AndAlso
x.ToString() = """Single""" Select x
model.GetSymbolInfo(name)
Next
End Sub
<WorkItem(652118, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/652118")>
<Fact()>
Public Sub Bug652118()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="IsAccessible">
<file name="a.vb">
<![CDATA[
b "goo" (ByRef aa@,ByRef aa@)
Declare Sub SUB29 Lio" (ByRef aa@,ByRef aa&)
Declare Sub SUB28 Lib "foyRef aa@,ByRef aa!)
Declare Sub SUB27 Lib "goo" (Baa@,ByRef aa%)
Declare Sub SUB26 Lib "goo" (ByRef yRef aa$)
Declare Sub SUB25 Lib "goo" (ByRef aa@,B
' currency with all datatypes aa&,ByRef aa#)
Declare Sub SUB24 Lib "goo" (ByRefByRef aa@)
Declare Sub SUB23 Lib "goo" (ByRef aa&, aa&) clare Sub SUB22 Lib "goo" (ByRef aa&,ByRef)
De Sub SUB21 Lib "goo" (ByRef aa&,ByRef aa!
DeclareSUB20 Lib "goo" (ByRef aa&,ByRef aa%)
Declare Sub Lib "goo" (ByRef aa&,ByRef aa$) long with all datatypes
Declare Sub SUB19)
' Sub SUB18 Lib "goo" (ByRef aa!,ByRef aa#
DeclareSUB17 Lib "goo" (ByRef aa!,ByRef aa@)
Declare Sub Lib "goo" (ByRef aa!,ByRef aa&)
Declare Sub SUB16"goo" (ByRef aa!,ByRef aa!)
Declare Sub SUB15 Lib (ByRef aa!,ByRef aa%)
Declare Sub SUB14 Lib "goo"ef aa!,ByRef aa$) atatypes
Declare Sub SUB13 Lib "goo" (ByR
' single with all doo" (ByRef aa#,ByRef aa#)
Declare Sub SUB12 Lib "fByRef aa#,ByRef aa@)
Declare Sub SUB11 Lib "goo" (
a As String)
Declare Sub SUB46 LiB45 Lib "goo" (ByRef aa As Object, ByRef ape w/all datatypes
Declare Sub SU
' default datatynteger, ByRef aa As Object) Single, ByRef aa As Decimal, ByRef aa As IAs String, ByRef aa As Short, ByRef aa As a As Object, ByRef aa As Double, ByRef aa Declare Sub SUB44 Lib "goo" (ByRef a aa%, ByRef aa!, ByRef aa@, ByRef aa&)
aa As Object, ByRef aa#, ByRef aa$, ByRef Declare Sub SUB43 Lib "goo" (ByRef
' all datatypes
"goo" (ByRef aa$,ByRef aa#)
Declare Sub SUB42 Lib (ByRef aa$,ByRef aa@)
Declare Sub SUB41 Lib "goo"ef aa$,ByRef aa&)
Declare Sub SUB40 Lib "goo" (ByR$,ByRef aa!)
Declare Sub SUB39 Lib "goo" (ByRef aaef aa%) Declare Sub SUB38 Lib "goo" (ByRef aa$,ByRa$)
re Sub SUB37 Lib "goo" (ByRef aa$,ByRef a
' string with all datatypes
DeclaByRef aa#)
Declare Sub SUB36 Lib "goo" (ByRef aa%, aa@) clare Sub SUB35 Lib "goo" (ByRef aa%,ByRef)
De Sub SUB34 Lib "goo" (ByRef aa%,ByRef aa&
DeclareSUB33 Lib "goo" (ByRef aa%,ByRef aa!)
Declare Sub Lib "goo" (ByRef aa%,ByRef aa%)
Declare Sub SUB32"goo" (ByRef aa%,ByRef aa$) with all datatypes
Declare Sub SUB31 Lib
' integer 30 Lib "goo" (ByRef aa@,ByRef aa#)
Declare Sub SUB
oo" (ByRef aa!,ByRef aa as Decimal)
Declare Sub SUB61 Lib "fByRef aa as integer)
Declare Sub SUB60 Lib "goo" (ByRef aa!,ingle) SUB59 Lib "goo" (ByRef aa!,ByRef aa as s
Declare Suboo" (ByRef aa!,ByRef aa as short)
Declare Sub SUB58 Lib "f,ByRef aa as string) es
Declare Sub SUB57 Lib "goo" (ByRef aa!
' single with all datatypByRef aa as object)
Declare Sub SUB50_2 Lib "goo" (ByRef aa#,ble)
UB56 Lib "goo" (ByRef aa#,ByRef aa as dou
Declare Sub S goo" (ByRef aa#,ByRef aa as Decimal)
Declare Sub SUB55 Lib ",ByRef aa as integer)
Declare Sub SUB54 Lib "goo" (ByRef aa#single) b SUB53 Lib "goo" (ByRef aa#,ByRef aa as
Declare Sufoo" (ByRef aa#,ByRef aa as short)
Declare Sub SUB52 Lib "#,ByRef aa as string) pes
Declare Sub SUB51 Lib "goo" (ByRef aaef aa As Object)
' double with all datatySUB50_1 Lib "goo" (ByRef aa As Object, ByR ByRef aa As Double)
Declare Sub e Sub SUB50 Lib "goo" (ByRef aa As Object,
DeclarAs Object, ByRef aa As Decimal) Declare Sub SUB49 Lib "goo" (ByRef aa f aa As Object, ByRef aa As Integer)
Declare Sub SUB48 Lib "goo" (ByRe (ByRef aa As Object, ByRef aa As Single)
hort)
Declare Sub SUB47 Lib "goo"b "goo" (ByRef aa As Object, ByRef aa As S
' integer with all datatypesef aa as object) clare Sub SUB50_5 Lib "goo" (ByRef aa@,ByR)
De4 Lib "goo" (ByRef aa@,ByRef aa as double
Declare Sub SUB7 " (ByRef aa@,ByRef aa as Decimal)
Declare Sub SUB73 Lib "gooRef aa as integer)
Declare Sub SUB72 Lib "goo" (ByRef aa@,Bygle)
UB71 Lib "goo" (ByRef aa@,ByRef aa as sin
Declare Sub S" (ByRef aa@,ByRef aa as short)
Declare Sub SUB70 Lib "gooyRef aa as string)
Declare Sub SUB69 Lib "goo" (ByRef aa@,B
' currency with all datatypesf aa as object) lare Sub SUB50_4 Lib "goo" (ByRef aa&,ByRe
Dec Lib "goo" (ByRef aa&,ByRef aa as double)
Declare Sub SUB68 (ByRef aa&,ByRef aa as Decimal)
Declare Sub SUB67 Lib "goo"ef aa as integer) Declare Sub SUB66 Lib "goo" (ByRef aa&,ByRle)
B65 Lib "goo" (ByRef aa&,ByRef aa as sing
Declare Sub SU (ByRef aa&,ByRef aa as short)
Declare Sub SUB64 Lib "goo"Ref aa as string)
Declare Sub SUB63 Lib "goo" (ByRef aa&,By
' long with all datatypes
yRef aa as object) Declare Sub SUB50_3 Lib "goo" (ByRef aa!,Ble)
B62 Lib "goo" (ByRef aa!,ByRef aa as doub
Declare Sub SU
Declare Sub SUB89 Lib "goo" (ByRef as short) 88 Lib "goo" (ByRef aa as double,ByRef aa
Declare Sub SUBas double,ByRef aa as string) es
Declare Sub SUB87 Lib "goo" (ByRef aa
' double with all datatypf aa as object) lare Sub SUB50_7 Lib "goo" (ByRef aa$,ByRe
Dec Lib "goo" (ByRef aa$,ByRef aa as double)
Declare Sub SUB86 (ByRef aa$,ByRef aa as Decimal)
Declare Sub SUB85 Lib "goo"ef aa as integer) Declare Sub SUB84 Lib "goo" (ByRef aa$,ByRle)
B83 Lib "goo" (ByRef aa$,ByRef aa as sing
Declare Sub SU (ByRef aa$,ByRef aa as short)
Declare Sub SUB82 Lib "goo"Ref aa as string)
Declare Sub SUB81 Lib "goo" (ByRef aa$,By
' string with all datatypes
ef aa as object) clare Sub SUB50_6 Lib "goo" (ByRef aa%,ByR)
De0 Lib "goo" (ByRef aa%,ByRef aa as double
Declare Sub SUB8 " (ByRef aa%,ByRef aa as Decimal)
Declare Sub SUB79 Lib "gooRef aa as integer)
Declare Sub SUB78 Lib "goo" (ByRef aa%,Bygle)
UB77 Lib "goo" (ByRef aa%,ByRef aa as sin
Declare Sub S" (ByRef aa%,ByRef aa as short)
Declare Sub SUB76 Lib "gooyRef aa as string)
Declare Sub SUB75 Lib "goo" (ByRef aa%,B
Declare Sub SU aa as integer,ByRef aa as Decimal)
Declare Sub SUB103 Lib "goo" (ByRefs integer) Lib "goo" (ByRef aa as integer,ByRef aa a
Declare Sub SUB102 teger,ByRef aa as single) clare Sub SUB101 Lib "goo" (ByRef aa as in)
Deo" (ByRef aa as integer,ByRef aa as short
Declare Sub SUB100 Lib "foyRef aa as string) Sub SUB99 Lib "goo" (ByRef aa as integer,B
' long with all datatypes
Declare as double) 8 Lib "goo" (ByRef aa as single,ByRef aa
Declare Sub SUB9 aa as single,ByRef aa as Decimal)
Declare Sub SUB97 Lib "goo" (ByRef s integer) Lib "goo" (ByRef aa as single,ByRef aa a
Declare Sub SUB96 single,ByRef aa as single)
Declare Sub SUB95 Lib "goo" (ByRef aa ashort) b "goo" (ByRef aa as single,ByRef aa as s
Declare Sub SUB94 Lingle,ByRef aa as string) eclare Sub SUB93 Lib "goo" (ByRef aa as si
' single with all datatypes
D aa as double) SUB92 Lib "goo" (ByRef aa as double,ByRef
Declare Sub yRef aa as double,ByRef aa as Decimal)
Declare Sub SUB91 Lib "goo" (B aa as integer) SUB90 Lib "goo" (ByRef aa as double,ByRef
Declare Sub aa as double,ByRef aa as single)
with all datatypes
Declare Sub SUB117 Lib
' string Ref aa as short,ByRef aa as double)
Declare Sub SUB116 Lib "goo" (By ef aa as Decimal) ub SUB115 Lib "goo" (ByRef aa as short,ByR
Declare Sef aa as short,ByRef aa as integer)
Declare Sub SUB114 Lib "goo" (ByRa as single) B113 Lib "goo" (ByRef aa as short,ByRef a
Declare Sub SUaa as short,ByRef aa as short)
Declare Sub SUB112 Lib "goo" (ByRef s string) 1 Lib "goo" (ByRef aa as short,ByRef aa aeger with all datatypes
Declare Sub SUB11
' intle) oo" (ByRef aa as Decimal,ByRef aa as doub
Declare Sub SUB110 Lib "f mal,ByRef aa as Decimal) are Sub SUB109 Lib "goo" (ByRef aa as Deci
Declger) oo" (ByRef aa as Decimal,ByRef aa as inte
Declare Sub SUB108 Lib "f imal,ByRef aa as single) lare Sub SUB107 Lib "goo" (ByRef aa as Dec
Dechort) "goo" (ByRef aa as Decimal,ByRef aa as s
Declare Sub SUB106 Lib Decimal,ByRef aa as string) Declare Sub SUB105 Lib "goo" (ByRef aa as
' currency with all datatypes
aa as double) B104 Lib "goo" (ByRef aa as integer,ByRef
End Namespace
End Module eger, ByRef aa As Object) ngle, ByRef aa As Decimal, ByRef aa As Int String, ByRef aa As Short, ByRef aa As SiAs Object, ByRef aa As Double, ByRef aa As Declare Sub SUB139 Lib "goo" (ByRef aa
f aa as object,ByRef aa as double)
Declare Sub SUB128 Lib "goo" (ByRe aa as Decimal) SUB127 Lib "goo" (ByRef aa as object,ByRef
Declare Sub a as object,ByRef aa as integer)
Declare Sub SUB126 Lib "goo" (ByRef a single) Lib "goo" (ByRef aa as object,ByRef aa as
Declare Sub SUB125 object,ByRef aa as short) Declare Sub SUB124 Lib "goo" (ByRef aa as ng)
goo" (ByRef aa as object,ByRef aa as strith all datatypes
Declare Sub SUB123 Lib "
' ANY wiRef aa as string,ByRef aa as double)
Declare Sub SUB122 Lib "goo" (By ef aa as Decimal) b SUB121 Lib "goo" (ByRef aa as string,ByR
Declare Su aa as string,ByRef aa as integer)
Declare Sub SUB120 Lib "goo" (ByRefas single) 9 Lib "goo" (ByRef aa as string,ByRef aa
Declare Sub SUB11s string,ByRef aa as short)
Declare Sub SUB118 Lib "goo" (ByRef aa aring) "goo" (ByRef aa as string,ByRef aa as st
]]></file>
</compilation>)
Dim tree As SyntaxTree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
For Each name In SyntaxNodeFinder.FindNodes(tree.GetRoot(), SyntaxKind.DeclareSubStatement)
model.GetDeclaredSymbol(DirectCast(name, DeclareStatementSyntax))
Next
End Sub
<Fact>
Public Sub Codecoverage_Additions()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Coverage">
<file name="a.vb">
Public Module M
Sub SelectCaseExpression()
Select Case (Function(arg) arg Is Nothing)'BIND:""Function(arg) arg Is Nothing""
End Select
End Sub
End Module
</file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim syntaxNode1 = tree.FindNodeOrTokenByKind(SyntaxKind.SingleLineFunctionLambdaExpression).AsNode()
Dim semanticSummary = semanticModel.GetSemanticInfoSummary(DirectCast(syntaxNode1, SingleLineLambdaExpressionSyntax))
Assert.Null(semanticSummary.Type)
Assert.Equal("Function <generated method>(arg As System.Object) As System.Boolean", semanticSummary.ConvertedType.ToTestDisplayString())
Assert.True(semanticSummary.ImplicitConversion.IsLambda)
Assert.False(semanticSummary.ImplicitConversion.IsAnonymousDelegate)
Dim typeSymbolList As IList(Of TypeSymbol) = TypeSymbol.EmptyTypeSymbolsList
Assert.Equal(0, typeSymbolList.Count)
Assert.Equal(GetType(TypeSymbol).MakeArrayType().FullName, typeSymbolList.GetType.ToString)
compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Coverage">
<file name="a.vb">
Public Module M
Sub SelectCaseExpression()
Select Case (Function(arg) arg Is Nothing)'BIND:""Function(arg) arg Is Nothing""
End Select
End Sub
Sub Goo1(Of t)(x As t)
End Sub
Sub Goo2(Of t)(x As t)
End Sub
Sub Goo3(Of t As New)(x As t)
End Sub
Sub Goo4(Of t As New)(x As t)
End Sub
Function A(Of t)() As Integer
End Function
Function B(Of t)() As t
End Function
End Module
Class C1
Sub Goo1(Of t)(x As t)
End Sub
Sub Goo2(Of t)(x As t)
End Sub
Sub Goo3(Of t As New)(x As t)
End Sub
Sub Goo4(Of t As Structure)(x As t)
End Sub
Function A(Of t)() As t
End Function
Function B(Of t)() As t
End Function
End Class
Class C2
Sub Goo1(Of t)(x As t)
End Sub
Sub Goo3(Of t As New)(x As t)
End Sub
Function A(Of t)() As Integer
End Function
Function B(Of t)() As t
End Function
End Class
</file>
</compilation>)
tree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
semanticModel = compilation.GetSemanticModel(tree)
syntaxNode1 = tree.FindNodeOrTokenByKind(SyntaxKind.SingleLineFunctionLambdaExpression).AsNode()
semanticSummary = semanticModel.GetSemanticInfoSummary(DirectCast(syntaxNode1, SingleLineLambdaExpressionSyntax))
Dim methodMember1 As MethodSymbol = Nothing
Dim methodMember2 As MethodSymbol = Nothing
Dim methodMember3 As MethodSymbol = Nothing
'HaveSameSignature / HaveSameSignatureAndConstraintsAndReturnType
Symbol.HaveSameSignature(methodMember1, methodMember2)
Symbol.HaveSameSignatureAndConstraintsAndReturnType(methodMember1, methodMember2)
Dim globalNS = compilation.GlobalNamespace
methodMember1 = CType(DirectCast(globalNS.GetMembers("M").Single(), NamedTypeSymbol).GetMember("Goo1"), MethodSymbol)
methodMember2 = CType(DirectCast(globalNS.GetMembers("M").Single(), NamedTypeSymbol).GetMember("Goo2"), MethodSymbol)
methodMember3 = CType(DirectCast(globalNS.GetMembers("C1").Single(), NamedTypeSymbol).GetMember("Goo1"), MethodSymbol)
Assert.False(Symbol.HaveSameSignature(methodMember1, methodMember2))
Assert.True(Symbol.HaveSameSignature(methodMember1, methodMember1))
Assert.True(Symbol.HaveSameSignature(methodMember1, methodMember3))
Assert.True(Symbol.HaveSameSignature(CType(DirectCast(globalNS.GetMembers("C2").Single(), NamedTypeSymbol).GetMember("Goo1"), MethodSymbol), methodMember3))
methodMember2 = CType(DirectCast(globalNS.GetMembers("C1").Single(), NamedTypeSymbol).GetMember("Goo3"), MethodSymbol)
methodMember3 = CType(DirectCast(globalNS.GetMembers("C2").Single(), NamedTypeSymbol).GetMember("Goo3"), MethodSymbol)
Assert.False(Symbol.HaveSameSignatureAndConstraintsAndReturnType(methodMember1, methodMember2))
Assert.True(Symbol.HaveSameSignatureAndConstraintsAndReturnType(methodMember2, methodMember2))
Assert.True(Symbol.HaveSameSignatureAndConstraintsAndReturnType(methodMember2, methodMember3))
methodMember1 = CType(DirectCast(globalNS.GetMembers("C1").Single(), NamedTypeSymbol).GetMember("Goo3"), MethodSymbol)
methodMember2 = CType(DirectCast(globalNS.GetMembers("C2").Single(), NamedTypeSymbol).GetMember("Goo3"), MethodSymbol)
Assert.True(Symbol.HaveSameSignatureAndConstraintsAndReturnType(methodMember1, methodMember2))
methodMember1 = CType(DirectCast(globalNS.GetMembers("M").Single(), NamedTypeSymbol).GetMember("Goo4"), MethodSymbol)
methodMember3 = CType(DirectCast(globalNS.GetMembers("C1").Single(), NamedTypeSymbol).GetMember("Goo4"), MethodSymbol)
Assert.False(Symbol.HaveSameSignatureAndConstraintsAndReturnType(methodMember1, methodMember3))
methodMember1 = CType(DirectCast(globalNS.GetMembers("M").Single(), NamedTypeSymbol).GetMember("A"), MethodSymbol)
methodMember3 = CType(DirectCast(globalNS.GetMembers("C1").Single(), NamedTypeSymbol).GetMember("A"), MethodSymbol)
Assert.False(Symbol.HaveSameSignatureAndConstraintsAndReturnType(methodMember1, methodMember3))
methodMember2 = CType(DirectCast(globalNS.GetMembers("C1").Single(), NamedTypeSymbol).GetMember("A"), MethodSymbol)
Assert.True(Symbol.HaveSameSignatureAndConstraintsAndReturnType(methodMember3, methodMember2))
methodMember1 = CType(DirectCast(globalNS.GetMembers("C1").Single(), NamedTypeSymbol).GetMember("B"), MethodSymbol)
methodMember3 = CType(DirectCast(globalNS.GetMembers("C2").Single(), NamedTypeSymbol).GetMember("B"), MethodSymbol)
Assert.True(Symbol.HaveSameSignatureAndConstraintsAndReturnType(methodMember1, methodMember3))
End Sub
<WorkItem(791793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/791793")>
<Fact>
Public Sub SpeculateAboutParamElementOnField()
Dim source =
<compilation name="xmlAndQueries">
<file name="sam.vb"><![CDATA[
Class C
''' <param name='X'/>
Public F As Integer
End Class
]]></file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, parseOptions:=New VisualBasicParseOptions(documentationMode:=DocumentationMode.Diagnose))
comp.AssertTheseDiagnostics(<expected><![CDATA[
BC42306: XML comment tag 'param' is not permitted on a 'variable' language element.
''' <param name='X'/>
~~~~~~~~~~~~~~~~~
]]></expected>)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim position = tree.ToString().IndexOf("X"c)
Dim paramName = DirectCast(SyntaxFactory.ParseExpression("Y"), IdentifierNameSyntax)
Dim speculativeModel As SemanticModel = Nothing
Dim success = model.TryGetSpeculativeSemanticModel(position, paramName, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
Dim info = speculativeModel.GetSymbolInfo(paramName)
Assert.Null(info.Symbol)
Assert.Equal(CandidateReason.None, info.CandidateReason)
Assert.Equal(0, info.CandidateSymbols.Length)
End Sub
<Fact()>
Public Sub ExpressionInQueryInXml()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="xmlAndQueries">
<file name="sam.vb"><![CDATA[
Class C
Public Function ToXml(errors As IEnumerable(Of Diagnostic)) As XElement
Return <errors><%= From e In errors
Select <error id=<%= e.Code %> />
%>
</errors>
End Function
End Class
]]></file>
</compilation>, references:=XmlReferences)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "sam.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim nodes = From n In tree.GetCompilationUnitRoot().DescendantNodes() Where n.Kind = SyntaxKind.IdentifierName Select CType(n, IdentifierNameSyntax)
Dim enode = nodes.First(Function(n) n.ToString() = "e")
Dim symbol = semanticModel.GetSymbolInfo(enode).Symbol
Assert.NotNull(symbol)
Assert.Equal(symbol.Name, "e")
End Sub
<Fact()>
Public Sub PropertyReturnValueVariable()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="xmlAndQueries">
<file name="sam.vb"><![CDATA[
Imports System
Class Program
Shared Sub Main()
End Sub
Shared Property P As Integer
Get
P = 1
Exit Property
End Get
Set(ByVal value As Integer)
P = 1
Exit Property
End Set
End Property
End Class
]]></file>
</compilation>, references:=XmlReferences)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "sam.vb").Single()
Dim model = compilation.GetSemanticModel(tree)
Dim assignments = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of AssignmentStatementSyntax)()
Assert.Equal(2, assignments.Count)
Const propertyName As String = "P"
Dim pInGetter = assignments.First().Left
Assert.Equal(propertyName, pInGetter.ToString())
Dim getterSymbol = model.GetSymbolInfo(pInGetter).Symbol
Assert.NotNull(getterSymbol)
Assert.Equal(propertyName, getterSymbol.Name)
Assert.Equal(SymbolKind.Local, getterSymbol.Kind)
Assert.True(DirectCast(getterSymbol, LocalSymbol).IsFunctionValue)
Dim pInSetter = assignments.Last().Left
Assert.Equal(propertyName, pInSetter.ToString())
Dim setterSymbol = model.GetSymbolInfo(pInSetter).Symbol
Assert.NotNull(setterSymbol)
Assert.Equal(propertyName, setterSymbol.Name)
Assert.Equal(SymbolKind.Property, setterSymbol.Kind)
End Sub
<Fact>
<WorkItem(654753, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/654753")>
Public Sub Repro654753()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Public Class C
Private ReadOnly Instance As New C()
Function M(d As IDisposable) As Boolean
Using (D)
Dim any As Boolean = Me.Instance.GetList().OfType(Of D)().Any()
Return any
End Using
End Function
Function GetList() As IEnumerable(Of C)
Return Nothing
End Function
End Class
Public Class D
Inherits C
End Class
]]></file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40AndReferences(source, {SystemCoreRef})
comp.VerifyDiagnostics()
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim position = source.Value.IndexOf("Me", StringComparison.Ordinal)
Dim statement = tree.GetRoot().DescendantNodes().OfType(Of LocalDeclarationStatementSyntax).Single()
Dim newSyntax = SyntaxFactory.ParseExpression("Instance.GetList().OfType(Of D)().Any()")
Dim newStatement = statement.ReplaceNode(statement.Declarators(0).Initializer.Value, newSyntax)
newSyntax = newStatement.Declarators(0).Initializer.Value
Dim speculativeModel As SemanticModel = Nothing
Dim success = model.TryGetSpeculativeSemanticModel(position, newStatement, speculativeModel)
Assert.True(success)
Assert.NotNull(speculativeModel)
Dim newSyntaxMemberAccess = newSyntax.DescendantNodesAndSelf().OfType(Of MemberAccessExpressionSyntax)().
Single(Function(e) e.ToString() = "Instance.GetList().OfType(Of D)")
speculativeModel.GetTypeInfo(newSyntaxMemberAccess)
End Sub
<Fact>
Public Sub Test_SemanticLanguage_VB()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Friend Module Program
Sub Main()
Dim o2 As Object = "E"
End Sub
End Module
]]></file>
</compilation>, Nothing, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Off))
Dim semanticModel = CompilationUtils.GetSemanticModel(compilation, "a.vb")
Assert.Equal("Visual Basic", semanticModel.Language)
End Sub
<Fact>
Public Sub DiagnosticsInStages()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Class Test
Dim obj01 As Object
Sub T(obj02 As Test)
obj02 = obj01
End Sub
Dim b As BindingError
parse errrrrror
End Class
]]></file>
</compilation>, Nothing, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On))
Dim semanticModel = CompilationUtils.GetSemanticModel(compilation, "a.vb")
Dim errs = semanticModel.GetDiagnostics()
Assert.Equal(5, errs.Length())
errs = semanticModel.GetDeclarationDiagnostics()
Assert.Equal(2, errs.Length())
errs = semanticModel.GetMethodBodyDiagnostics()
Assert.Equal(1, errs.Length())
Dim treeErrs = compilation.GetParseDiagnostics()
Assert.Equal(2, treeErrs.Length())
End Sub
<Fact()>
<WorkItem(10211, "https://github.com/dotnet/roslyn/issues/10211")>
Public Sub GetDependenceChainRegression_10211_working()
Dim source = <compilation>
<file name="a.vb"><![CDATA[
Public Class Parent
End Class
Public Class Child
Inherits Parent
End Class
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilation(source)
Dim semanticModel = compilation.GetSemanticModel(compilation.SyntaxTrees(0))
' Ensuring that this doesn't throw
semanticModel.GetMethodBodyDiagnostics()
End Sub
<Fact()>
<WorkItem(10211, "https://github.com/dotnet/roslyn/issues/10211")>
Public Sub GetDependenceChainRegression_10211()
Dim source = <compilation>
<file name="a.vb"><![CDATA[
Public Class Child
Inherits Parent
End Class
Public Class Parent
End Class
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilation(source)
Dim semanticModel = compilation.GetSemanticModel(compilation.SyntaxTrees(0))
' Ensuring that this doesn't throw
semanticModel.GetMethodBodyDiagnostics()
End Sub
<WorkItem(859721, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/859721")>
<Fact()>
Public Sub TestMethodBodyDiagnostics()
' Even with a root namespace, we should still have these diagnostics with or without root namespace specified
Dim sourceExplicitGlobalNamespace = <compilation>
<file name="a.vb"><![CDATA[
Namespace Global
Class C
Sub S()
Dim _A As A ' error BC30002: Type 'A' is not defined.
End Sub
End Class
End Namespace
]]></file>
</compilation>
Dim ExpectedErrors = <expected>BC42024: Unused local variable: '_A'.
Dim _A As A ' error BC30002: Type 'A' is not defined.
~~
BC30002: Type 'A' is not defined.
Dim _A As A ' error BC30002: Type 'A' is not defined.
~
</expected>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sourceExplicitGlobalNamespace, Nothing, TestOptions.ReleaseDll)
Dim semanticModel = GetSemanticModel(compilation, "a.vb")
Dim errs = semanticModel.GetMethodBodyDiagnostics()
CompilationUtils.AssertTheseDiagnostics(errs, ExpectedErrors)
compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sourceExplicitGlobalNamespace, Nothing, TestOptions.ReleaseDll.WithRootNamespace("ClassLibrary1"))
semanticModel = GetSemanticModel(compilation, "a.vb")
errs = semanticModel.GetMethodBodyDiagnostics()
CompilationUtils.AssertTheseDiagnostics(errs, ExpectedErrors)
' No namespace declared in source code
Dim sourceNoNamespaceSpecified = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub S()
Dim _A As A ' error BC30002: Type 'A' is not defined.
End Sub
End Class
]]></file>
</compilation>
compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sourceNoNamespaceSpecified, Nothing)
semanticModel = GetSemanticModel(compilation, "a.vb")
errs = semanticModel.GetMethodBodyDiagnostics()
CompilationUtils.AssertTheseDiagnostics(errs, ExpectedErrors)
compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sourceNoNamespaceSpecified, Nothing, TestOptions.ReleaseDll.WithRootNamespace("ClassLibrary1"))
semanticModel = GetSemanticModel(compilation, "a.vb")
errs = semanticModel.GetMethodBodyDiagnostics()
CompilationUtils.AssertTheseDiagnostics(errs, ExpectedErrors)
' Even with an escaped global namespace
Dim sourceEscapedGlobal = <compilation>
<file name="a.vb"><![CDATA[
Namespace [Global]
Class C
Sub S()
Dim _A As A ' error BC30002: Type 'A' is not defined.
End Sub
End Class
End Namespace
]]></file>
</compilation>
compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sourceEscapedGlobal, Nothing)
semanticModel = GetSemanticModel(compilation, "a.vb")
errs = semanticModel.GetMethodBodyDiagnostics()
CompilationUtils.AssertTheseDiagnostics(errs, ExpectedErrors)
compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sourceEscapedGlobal, Nothing, TestOptions.ReleaseDll.WithRootNamespace("ClassLibrary1"))
semanticModel = GetSemanticModel(compilation, "a.vb")
errs = semanticModel.GetMethodBodyDiagnostics()
CompilationUtils.AssertTheseDiagnostics(errs, ExpectedErrors)
'Global namespace as part of namespace specified but no match on root namespace
Dim sourceWithGlobalAsStartOfNamespace = <compilation>
<file name="a.vb"><![CDATA[
Namespace Global.Goo
Class C
Sub S()
Dim _A As A ' error BC30002: Type 'A' is not defined.
End Sub
End Class
End Namespace
]]></file>
</compilation>
compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sourceWithGlobalAsStartOfNamespace, Nothing)
semanticModel = GetSemanticModel(compilation, "a.vb")
errs = semanticModel.GetMethodBodyDiagnostics()
CompilationUtils.AssertTheseDiagnostics(errs, ExpectedErrors)
compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sourceWithGlobalAsStartOfNamespace, Nothing, TestOptions.ReleaseDll.WithRootNamespace("ClassLibrary1"))
semanticModel = GetSemanticModel(compilation, "a.vb")
errs = semanticModel.GetMethodBodyDiagnostics()
CompilationUtils.AssertTheseDiagnostics(errs, ExpectedErrors)
'namespace starting with a string Global but not specifically Global.
Dim sourceWithANameStartingGlobal = <compilation>
<file name="a.vb"><![CDATA[
Namespace GlobalGoo
Class C
Sub S()
Dim _A As A ' error BC30002: Type 'A' is not defined.
End Sub
End Class
End Namespace
]]></file>
</compilation>
compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sourceWithANameStartingGlobal, Nothing)
semanticModel = GetSemanticModel(compilation, "a.vb")
errs = semanticModel.GetMethodBodyDiagnostics()
CompilationUtils.AssertTheseDiagnostics(errs, ExpectedErrors)
compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sourceWithANameStartingGlobal, Nothing, TestOptions.ReleaseDll.WithRootNamespace("ClassLibrary1"))
semanticModel = GetSemanticModel(compilation, "a.vb")
errs = semanticModel.GetMethodBodyDiagnostics()
CompilationUtils.AssertTheseDiagnostics(errs, ExpectedErrors)
'Two namespaces in same source file - global is 1st namespace
Dim sourceWithGlobalAndMultipleNS1 = <compilation>
<file name="a.vb"><![CDATA[
Namespace Global
Class C
Sub S()
Dim _A As A ' error BC30002: Type 'A' is not defined.
End Sub
End Class
End Namespace
Namespace NS2
Class C
Sub S()
Dim _A As A ' error BC30002: Type 'A' is not defined.
End Sub
End Class
End Namespace
]]></file>
</compilation>
Dim ExpectedErrors2 = <Expected>BC42024: Unused local variable: '_A'.
Dim _A As A ' error BC30002: Type 'A' is not defined.
~~
BC30002: Type 'A' is not defined.
Dim _A As A ' error BC30002: Type 'A' is not defined.
~
BC42024: Unused local variable: '_A'.
Dim _A As A ' error BC30002: Type 'A' is not defined.
~~
BC30002: Type 'A' is not defined.
Dim _A As A ' error BC30002: Type 'A' is not defined.
~
</Expected>
compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sourceWithGlobalAndMultipleNS1, Nothing)
semanticModel = GetSemanticModel(compilation, "a.vb")
errs = semanticModel.GetMethodBodyDiagnostics()
CompilationUtils.AssertTheseDiagnostics(errs, ExpectedErrors2)
compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sourceWithGlobalAndMultipleNS1, Nothing, TestOptions.ReleaseDll.WithRootNamespace("ClassLibrary1"))
semanticModel = GetSemanticModel(compilation, "a.vb")
errs = semanticModel.GetMethodBodyDiagnostics()
CompilationUtils.AssertTheseDiagnostics(errs, ExpectedErrors2)
'Two namespaces in same source file - global is 2nd namespace
Dim sourceWithGlobalAndMultipleNS2 = <compilation>
<file name="a.vb"><![CDATA[
Namespace NS1
Class C
Sub S()
Dim _A As A ' error BC30002: Type 'A' is not defined.
End Sub
End Class
End Namespace
Namespace Global
Class C
Sub S()
Dim _A As A ' error BC30002: Type 'A' is not defined.
End Sub
End Class
End Namespace
]]></file>
</compilation>
compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sourceWithGlobalAndMultipleNS2, Nothing)
semanticModel = GetSemanticModel(compilation, "a.vb")
errs = semanticModel.GetMethodBodyDiagnostics()
CompilationUtils.AssertTheseDiagnostics(errs, ExpectedErrors2)
compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sourceWithGlobalAndMultipleNS2, Nothing, TestOptions.ReleaseDll.WithRootNamespace("ClassLibrary1"))
semanticModel = GetSemanticModel(compilation, "a.vb")
errs = semanticModel.GetMethodBodyDiagnostics()
CompilationUtils.AssertTheseDiagnostics(errs, ExpectedErrors2)
'Namespace starting Global.xxxx with xxxx matching the rootnamespace
Dim sourceWithGlobalCombinedNamespace = <compilation>
<file name="a.vb"><![CDATA[
Namespace Global.Goo
Class C
Sub S()
Dim _A As A ' error BC30002: Type 'A' is not defined.
End Sub
End Class
End Namespace
Namespace NS2
Class C
Sub S()
Dim _A As A ' error BC30002: Type 'A' is not defined.
End Sub
End Class
End Namespace
]]></file>
</compilation>
compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sourceWithGlobalCombinedNamespace, Nothing)
semanticModel = GetSemanticModel(compilation, "a.vb")
errs = semanticModel.GetMethodBodyDiagnostics()
CompilationUtils.AssertTheseDiagnostics(errs, ExpectedErrors2)
compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sourceWithGlobalCombinedNamespace, Nothing, TestOptions.ReleaseDll.WithRootNamespace("Goo"))
semanticModel = GetSemanticModel(compilation, "a.vb")
errs = semanticModel.GetMethodBodyDiagnostics()
CompilationUtils.AssertTheseDiagnostics(errs, ExpectedErrors2)
End Sub
<Fact>
Public Sub PartialMethodImplementationDiagnostics()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Partial Class MyPartialClass
Partial Private Sub MyPartialMethod(t As MyUndefinedType)
End Sub
End Class
]]></file>
<file name="b.vb"><![CDATA[
Partial Class MyPartialClass
Private Sub MyPartialMethod(t As MyUndefinedType)
Dim c = New MyUndefinedType(23, True)
End Sub
End Class
]]></file>
</compilation>, Nothing, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On))
Dim semanticModel = CompilationUtils.GetSemanticModel(compilation, "b.vb")
Dim errs = semanticModel.GetDiagnostics()
Assert.Equal(2, errs.Length())
errs = semanticModel.GetDeclarationDiagnostics()
Assert.Equal(1, errs.Length())
errs = semanticModel.GetMethodBodyDiagnostics()
Assert.Equal(1, errs.Length())
Dim treeErrs = compilation.GetParseDiagnostics()
Assert.Equal(0, treeErrs.Length())
End Sub
#End Region
<Fact, WorkItem(1146124, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1146124")>
Public Sub GetTypeInfoForXmlStringInCref()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GetSemanticInfo">
<file name="a.vb"><![CDATA[
Module Program
''' <summary>
''' <see cref=""/>
''' </summary>
Sub Main(args As String())
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot
Dim xmlString = root.DescendantNodes(descendIntoTrivia:=True).OfType(Of XmlStringSyntax).Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim typelInfo = semanticModel.GetTypeInfo(xmlString)
Assert.Null(typelInfo.Type)
End Sub
<WorkItem(1104539, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1104539")>
<Fact()>
Public Sub GetDiagnosticsWithRootNamespace()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Imports System.Threading
Module TestModule
Sub Main()
DoesntExist()
End Sub
<Extension>
Public Function ToFullWidth(c As Char) As Char
Return If(IsHalfWidth(c), MakeFullWidth(c), c)
End Function
End Module
]]></file>
<file name="b.vb"><![CDATA[
Imports Microsoft.VisualBasic.Strings
Namespace Global.Microsoft.CodeAnalysis.VisualBasic
Partial Public Class SyntaxFacts
Friend Shared Function MakeFullWidth(c As Char) As Char
Return c
End Function
Friend Shared Function IsHalfWidth(c As Char) As Boolean
Return c >= ChrW(&H21S) AndAlso c <= ChrW(&H7ES)
End Function
End Class
End Namespace
]]></file>
</compilation>, {SystemCoreRef}, options:=TestOptions.DebugDll.WithRootNamespace("Microsoft.CodeAnalysis.VisualBasic.UnitTests"))
Dim semanticModel = CompilationUtils.GetSemanticModel(compilation, "a.vb")
semanticModel.GetDiagnostics().AssertTheseDiagnostics(<errors>
BC50001: Unused import statement.
Imports System.Threading
~~~~~~~~~~~~~~~~~~~~~~~~
BC30451: 'DoesntExist' is not declared. It may be inaccessible due to its protection level.
DoesntExist()
~~~~~~~~~~~
</errors>, suppressInfos:=False)
End Sub
<Fact, WorkItem(976, "https://github.com/dotnet/roslyn/issues/976")>
Public Sub ConstantValueOfInterpolatedString()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GetSemanticInfo">
<file name="a.vb"><![CDATA[
Module Program
''' <summary>
''' <see cref=""/>
''' </summary>
Sub Main(args As String())
System.Console.WriteLine($""Hello, world!"");
System.Console.WriteLine($""{DateTime.Now.ToString()}.{args(0)}"");
End Sub
End Module
]]></file>
</compilation>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim root = tree.GetCompilationUnitRoot
Dim model = compilation.GetSemanticModel(tree)
For Each interp In root.DescendantNodes().OfType(Of InterpolatedStringExpressionSyntax)
Assert.False(model.GetConstantValue(interp).HasValue)
Next
End Sub
End Class
End Namespace
|
AdamSpeight2008/roslyn-AdamSpeight2008
|
src/Compilers/VisualBasic/Test/Semantic/Compilation/SemanticModelAPITests.vb
|
Visual Basic
|
apache-2.0
| 201,458
|
Partial Public MustInherit Class Statement
Public Function ToInstance(
instanceType As Type
) As Object
Dim result As Object = Nothing
Try
result = ActiveRecord.Entity.ToInstance(
Me.Reader, instanceType
)
Catch e As Exception
Events.RaiseError(e)
End Try
Return result
End Function
Public Function ToInstance(
instanceCompleter As InstanceCompleter
) As Object
Dim result As Object = Nothing
Try
result = ActiveRecord.Entity.ToInstance(
Me.Reader, instanceCompleter
)
Catch e As Exception
Events.RaiseError(e)
End Try
Return result
End Function
Public Function ToInstance(
instanceCompleter As InstanceCompleterWithColumns
) As Object
Dim result As Object = Nothing
Try
result = ActiveRecord.Entity.ToInstance(
Me.Reader,
instanceCompleter
)
Catch e As Exception
Events.RaiseError(e)
End Try
Return result
End Function
Public Function ToInstance(
instanceCompleter As InstanceCompleterWithAllInfo,
instanceType As Type,
Optional propertiesOnly As Boolean = True
) As Object
Dim result As Object = Nothing
Try
result = ActiveRecord.Entity.ToInstance(
Me.Reader, instanceCompleter, instanceType, propertiesOnly
)
Catch e As Exception
Events.RaiseError(e)
End Try
Return result
End Function
End Class
|
databasic-net/databasic-core
|
Statement/Reading/ToInstance.vb
|
Visual Basic
|
bsd-3-clause
| 1,323
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports CompilationCreationTestHelpers
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata
Public Class MetadataMemberTests
Inherits BasicTestBase
Private VTableGapClassIL As String = <![CDATA[
.class public auto ansi beforefieldinit Class
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void _VtblGap1_1() cil managed
{
ret
}
.method public hidebysig specialname instance int32
_VtblGap2_1() cil managed
{
ret
}
.method public hidebysig specialname instance void
set_GetterIsGap(int32 'value') cil managed
{
ret
}
.method public hidebysig specialname instance int32
get_SetterIsGap() cil managed
{
ret
}
.method public hidebysig specialname instance void
_VtblGap3_1(int32 'value') cil managed
{
ret
}
.method public hidebysig specialname instance int32
_VtblGap4_1() cil managed
{
ret
}
.method public hidebysig specialname instance void
_VtblGap5_1(int32 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ret
}
.property instance int32 GetterIsGap()
{
.get instance int32 Class::_VtblGap2_1()
.set instance void Class::set_GetterIsGap(int32)
} // end of property Class::GetterIsGap
.property instance int32 SetterIsGap()
{
.get instance int32 Class::get_SetterIsGap()
.set instance void Class::_VtblGap3_1(int32)
} // end of property Class::SetterIsGap
.property instance int32 BothAccessorsAreGaps()
{
.get instance int32 Class::_VtblGap4_1()
.set instance void Class::_VtblGap5_1(int32)
} // end of property Class::BothAccessorsAreGaps
} // end of class Class
]]>.Value
Private VTableGapInterfaceIL As String = <![CDATA[
.class interface public abstract auto ansi Interface
{
.method public hidebysig newslot specialname rtspecialname abstract virtual
instance void _VtblGap1_1() cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance int32 _VtblGap2_1() cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance void set_GetterIsGap(int32 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance int32 get_SetterIsGap() cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance void _VtblGap3_1(int32 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance int32 _VtblGap4_1() cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance void _VtblGap5_1(int32 'value') cil managed
{
}
.property instance int32 GetterIsGap()
{
.get instance int32 Interface::_VtblGap2_1()
.set instance void Interface::set_GetterIsGap(int32)
} // end of property Interface::GetterIsGap
.property instance int32 SetterIsGap()
{
.get instance int32 Interface::get_SetterIsGap()
.set instance void Interface::_VtblGap3_1(int32)
} // end of property Interface::SetterIsGap
.property instance int32 BothAccessorsAreGaps()
{
.get instance int32 Interface::_VtblGap4_1()
.set instance void Interface::_VtblGap5_1(int32)
} // end of property Interface::BothAccessorsAreGaps
} // end of class Interface
]]>.Value
<WorkItem(527152, "DevDiv")>
<Fact>
Public Sub MetadataMethodSymbolCtor01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="MT">
<file name="a.vb">
Public Class A
End Class
</file>
</compilation>)
Dim mscorNS = compilation.GetReferencedAssemblySymbol(compilation.References(0))
Assert.Equal("mscorlib", mscorNS.Name)
Assert.Equal(SymbolKind.Assembly, mscorNS.Kind)
Dim ns1 = DirectCast(mscorNS.GlobalNamespace.GetMembers("System").Single(), NamespaceSymbol)
Dim type1 = DirectCast(ns1.GetTypeMembers("StringComparer").Single(), NamedTypeSymbol)
Dim ctors = type1.InstanceConstructors
' instance only
Assert.Equal(1, ctors.Length())
Dim ctor = DirectCast(ctors(0), MethodSymbol)
Assert.Equal(type1, ctor.ContainingSymbol)
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, ctor.Name)
Assert.Equal(SymbolKind.Method, ctor.Kind)
Assert.Equal(MethodKind.Constructor, ctor.MethodKind)
Assert.Equal(Accessibility.Protected, ctor.DeclaredAccessibility)
Assert.True(ctor.IsDefinition)
Assert.False(ctor.IsShared)
Assert.False(ctor.IsNotOverridable)
Assert.False(ctor.IsOverrides)
Assert.True(ctor.IsOverloads)
Assert.True(ctor.IsSub)
Assert.Equal("Sub System.StringComparer." + WellKnownMemberNames.InstanceConstructorName + "()", ctor.ToTestDisplayString())
Assert.Equal(0, ctor.TypeParameters.Length)
Assert.Equal("Void", ctor.ReturnType.Name)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<WorkItem(537334, "DevDiv")>
<Fact>
Public Sub MetadataMethodSymbol01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="MT">
<file name="a.vb">
Public Class A
End Class
</file>
</compilation>)
Dim mscorNS = compilation.GetReferencedAssemblySymbol(compilation.References(0))
Assert.Equal("mscorlib", mscorNS.Name)
Assert.Equal(SymbolKind.Assembly, mscorNS.Kind)
Dim ns1 = DirectCast(mscorNS.GlobalNamespace.GetMembers("Microsoft").Single(), NamespaceSymbol)
Dim ns2 = DirectCast(ns1.GetMembers("Runtime").Single(), NamespaceSymbol)
Dim ns3 = DirectCast(ns2.GetMembers("Hosting").Single(), NamespaceSymbol)
Dim class1 = DirectCast(ns3.GetTypeMembers("StrongNameHelpers").First(), NamedTypeSymbol)
Dim members = class1.GetMembers("StrongNameSignatureGeneration")
' 4 overloads
Assert.Equal(4, members.Length())
Dim member1 = DirectCast(members(3), MethodSymbol)
Assert.Equal(mscorNS, member1.ContainingAssembly)
Assert.Equal(class1, member1.ContainingSymbol)
Assert.Equal(SymbolKind.Method, member1.Kind)
' Not Impl
Assert.Equal(MethodKind.Ordinary, member1.MethodKind)
Assert.Equal(Accessibility.Public, member1.DeclaredAccessibility)
Assert.True(member1.IsDefinition)
Assert.True(member1.IsShared)
Assert.False(member1.IsMustOverride)
Assert.False(member1.IsNotOverridable)
Assert.False(member1.IsOverridable)
Assert.False(member1.IsOverrides)
Assert.True(member1.IsOverloads)
Assert.False(member1.IsGenericMethod)
Assert.False(member1.IsExternalMethod)
' Not Impl
Assert.False(member1.IsExtensionMethod)
Assert.False(member1.IsSub)
Assert.False(member1.IsVararg)
Dim fullName = "Function Microsoft.Runtime.Hosting.StrongNameHelpers.StrongNameSignatureGeneration(pwzFilePath As System.String, pwzKeyContainer As System.String, bKeyBlob As System.Byte(), cbKeyBlob As System.Int32, ByRef ppbSignatureBlob As System.IntPtr, ByRef pcbSignatureBlob As System.Int32) As System.Boolean"
Assert.Equal(fullName, member1.ToTestDisplayString())
Assert.Equal(0, member1.TypeArguments.Length)
Assert.Equal(0, member1.TypeParameters.Length)
Assert.Equal(6, member1.Parameters.Length)
Assert.Equal("Boolean", member1.ReturnType.Name)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<WorkItem(527150, "DevDiv")>
<WorkItem(537337, "DevDiv")>
<Fact>
Public Sub MetadataParameterSymbol01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="MT">
<file name="a.vb">
Public Class A
End Class
</file>
</compilation>)
Dim mscorNS = compilation.GetReferencedAssemblySymbol(compilation.References(0))
Assert.Equal("mscorlib", mscorNS.Name)
Assert.Equal(SymbolKind.Assembly, mscorNS.Kind)
Dim ns1 = DirectCast(mscorNS.GlobalNamespace.GetMembers("Microsoft").Single(), NamespaceSymbol)
Dim ns2 = DirectCast(DirectCast(ns1.GetMembers("Runtime").Single(), NamespaceSymbol).GetMembers("Hosting").Single(), NamespaceSymbol)
Dim class1 = DirectCast(ns2.GetTypeMembers("StrongNameHelpers").First(), NamedTypeSymbol)
Dim members = class1.GetMembers("StrongNameSignatureGeneration")
Dim member1 = DirectCast(members(3), MethodSymbol)
Assert.Equal(6, member1.Parameters.Length)
Dim p1 = DirectCast(member1.Parameters(0), ParameterSymbol)
Dim p2 = DirectCast(member1.Parameters(1), ParameterSymbol)
Dim p3 = DirectCast(member1.Parameters(2), ParameterSymbol)
Dim p4 = DirectCast(member1.Parameters(3), ParameterSymbol)
Dim p5 = DirectCast(member1.Parameters(4), ParameterSymbol)
Dim p6 = DirectCast(member1.Parameters(5), ParameterSymbol)
Assert.Equal(mscorNS, p1.ContainingAssembly)
Assert.Equal(class1, p1.ContainingType)
Assert.Equal(member1, p1.ContainingSymbol)
Assert.Equal(SymbolKind.Parameter, p1.Kind)
Assert.Equal(Accessibility.NotApplicable, p1.DeclaredAccessibility) ' chk C#
Assert.Equal("pwzFilePath", p1.Name)
Dim fullName = " bKeyBlob As System.Byte(), cbKeyBlob As System.Int32, ppbSignatureBlob As ByRef System.IntPtr, pcbSignatureBlob As ByRef System.Int32) As System.Boolean"
Assert.Equal("pwzKeyContainer As System.String", p2.ToTestDisplayString())
Assert.Equal("String", p2.Type.Name)
Assert.True(p2.IsDefinition)
Assert.Equal("bKeyBlob As System.Byte()", p3.ToTestDisplayString())
' Bug - 2056
Assert.Equal("System.Byte()", p3.Type.ToTestDisplayString())
Assert.False(p1.IsShared)
Assert.False(p1.IsMustOverride)
Assert.False(p2.IsNotOverridable)
Assert.False(p2.IsOverridable)
Assert.False(p3.IsOverrides)
' Not Impl
'Assert.False(p3.IsParamArray)
Assert.False(p4.IsOptional)
Assert.False(p4.HasExplicitDefaultValue)
' Not Impl
'Assert.Null(p4.DefaultValue)
Assert.Equal("ppbSignatureBlob", p5.Name)
Assert.Equal("IntPtr", p5.Type.Name)
Assert.True(p5.IsByRef)
Assert.Equal("ByRef pcbSignatureBlob As System.Int32", p6.ToTestDisplayString())
Assert.True(p6.IsByRef)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub MetadataMethodSymbolGen02()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="MT">
<file name="a.vb">
Public Class A
End Class
</file>
</compilation>)
Dim mscorNS = compilation.GetReferencedAssemblySymbol(compilation.References(0))
Assert.Equal("mscorlib", mscorNS.Name)
Assert.Equal(SymbolKind.Assembly, mscorNS.Kind)
Dim ns1 = DirectCast(DirectCast(mscorNS.GlobalNamespace.GetMembers("System").Single(), NamespaceSymbol).GetMembers("Collections").Single(), NamespaceSymbol)
Dim ns2 = DirectCast(ns1.GetMembers("Generic").Single(), NamespaceSymbol)
Dim type1 = DirectCast(ns2.GetTypeMembers("IDictionary").First(), NamedTypeSymbol)
Dim member1 = DirectCast(type1.GetMembers("Add").Single(), MethodSymbol)
Dim member2 = DirectCast(type1.GetMembers("TryGetValue").Single(), MethodSymbol)
Assert.Equal(mscorNS, member1.ContainingAssembly)
Assert.Equal(type1, member1.ContainingSymbol)
Assert.Equal(SymbolKind.Method, member1.Kind)
' Not Impl
'Assert.Equal(MethodKind.Ordinary, member2.MethodKind)
Assert.Equal(Accessibility.Public, member2.DeclaredAccessibility)
Assert.True(member2.IsDefinition)
Assert.False(member1.IsShared)
Assert.True(member1.IsMustOverride)
Assert.False(member2.IsNotOverridable)
Assert.False(member2.IsOverridable)
Assert.False(member2.IsOverrides)
' Bug
' Assert.False(member1.IsOverloads)
' Assert.False(member2.IsOverloads)
Assert.False(member1.IsGenericMethod)
Assert.False(member1.IsExternalMethod)
' Not Impl
'Assert.False(member1.IsExtensionMethod)
Assert.True(member1.IsSub)
Assert.False(member2.IsVararg)
Assert.Equal(0, member1.TypeArguments.Length)
Assert.Equal(0, member2.TypeParameters.Length)
Assert.Equal(2, member1.Parameters.Length)
Assert.Equal("Boolean", member2.ReturnType.Name)
Assert.Equal("Function System.Collections.Generic.IDictionary(Of TKey, TValue).TryGetValue(key As TKey, ByRef value As TValue) As System.Boolean", member2.ToTestDisplayString())
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<WorkItem(537335, "DevDiv")>
<Fact>
Public Sub MetadataParameterSymbolGen02()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="MT">
<file name="a.vb">
Public Class A
End Class
</file>
</compilation>)
Dim mscorNS = compilation.GetReferencedAssemblySymbol(compilation.References(0))
Assert.Equal("mscorlib", mscorNS.Name)
Assert.Equal(SymbolKind.Assembly, mscorNS.Kind)
Dim ns1 = DirectCast(DirectCast(mscorNS.GlobalNamespace.GetMembers("System").Single(), NamespaceSymbol).GetMembers("Collections").Single(), NamespaceSymbol)
Dim ns2 = DirectCast(ns1.GetMembers("Generic").Single(), NamespaceSymbol)
Dim type1 = DirectCast(ns2.GetTypeMembers("IDictionary").First(), NamedTypeSymbol)
Dim member1 = DirectCast(type1.GetMembers("TryGetValue").Single(), MethodSymbol)
Assert.Equal(2, member1.Parameters.Length)
Dim p1 = DirectCast(member1.Parameters(0), ParameterSymbol)
Dim p2 = DirectCast(member1.Parameters(1), ParameterSymbol)
Assert.Equal(mscorNS, p1.ContainingAssembly)
Assert.Equal(type1, p2.ContainingType)
Assert.Equal(member1, p1.ContainingSymbol)
Assert.Equal(SymbolKind.Parameter, p2.Kind)
Assert.Equal(Accessibility.NotApplicable, p1.DeclaredAccessibility)
Assert.Equal("value", p2.Name)
Assert.Equal("key As TKey", p1.ToTestDisplayString())
Assert.Equal("TValue", p2.Type.Name)
Assert.True(p2.IsDefinition)
Assert.False(p1.IsShared)
Assert.False(p1.IsMustOverride)
Assert.False(p2.IsNotOverridable)
Assert.False(p2.IsOverridable)
Assert.False(p1.IsOverrides)
' 2054
Assert.False(p1.IsParamArray)
Assert.False(p2.IsOptional)
Assert.False(p2.HasExplicitDefaultValue)
' Not Impl - not in M2 scope
'Assert.Null(p2.DefaultValue)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact()>
Public Sub ImportConstantsWithIllegalConstantValues()
Dim ilsource = <![CDATA[
// =============== CLASS MEMBERS DECLARATION ===================
.class public auto ansi beforefieldinit C2
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
}
.class sequential ansi sealed public beforefieldinit C3
extends [mscorlib]System.ValueType
{
.field public static int32 bar
.method private specialname rtspecialname static
void .cctor() cil managed
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldc.i4.s 23
IL_0002: stsfld int32 C3::bar
IL_0007: ret
} // end of method foo::.cctor
} // end of class foo
.class public auto ansi beforefieldinit C1
extends [mscorlib]System.Object
{
.field public static literal bool MyConstBoolean = "a string 01"
.field public static literal char MyConstChar = "a string 02"
.field public static literal int8 MyConstSByte = "a string 03"
.field public static literal int16 MyConstInt16 = "a string 04"
.field public static literal int32 MyConstInt32 = "a string 05"
.field public static literal int64 MyConstInt64 = "a string 06"
.field public static literal uint8 MyConstByte = "a string 07"
.field public static literal uint16 MyConstUInt16 = "a string 08"
.field public static literal uint32 MyConstUInt32 = "a string 09"
.field public static literal uint64 MyConstUInt64 = "a string 10"
.field public static literal float32 MyConstSingle = "a string 11"
.field public static literal float64 MyConstDouble = "a string 12"
.field public static initonly valuetype [mscorlib]System.Decimal MyConstDecimal
.custom instance void [mscorlib]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 00 C0 28 6A 27 0C CB 08 00 00 ) // ....(j'.....
.field public static initonly valuetype [mscorlib]System.DateTime MyConstDateTime
.custom instance void [mscorlib]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8,
uint8,
uint32,
uint32,
uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 E4 AC E5 00
00 00 )
.field public static initonly valuetype [mscorlib]System.DateTime MyConstDateTime2
.custom instance void [mscorlib]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 00 C0 28 6A 27 0C CB 08 00 00 ) // ....(j'.....
.field public static literal valuetype [mscorlib]System.Decimal MyConstDecimal2 = "booo!"
.field public static literal valuetype [mscorlib]System.Decimal MyConstDecimal3 = nullref
.field public static literal valuetype [mscorlib]System.DateTime MyConstDateTime3 = nullref
.field public static literal string MyConstString2 = nullref
.field public static literal char MyConstChar2 = nullref
.field public static literal bool MyConstBoolean2 = nullref
.field public static literal class C2 MyConstC2 = nullref
.field public static literal valuetype C3 MyConstC3 = nullref
.field public static literal string MyConstString = uint32(34)
.method private specialname rtspecialname static
void .cctor() cil managed
{
// Code size 36 (0x24)
.maxstack 8
IL_0000: ldc.i4 0xe5ace4
IL_0005: conv.i8
IL_0006: newobj instance void [mscorlib]System.Decimal::.ctor(int64)
IL_000b: stsfld valuetype [mscorlib]System.Decimal C1::MyConstDecimal
IL_0010: ldc.i8 0x8cb0c276a28c000
IL_0019: newobj instance void [mscorlib]System.DateTime::.ctor(int64)
IL_001e: stsfld valuetype [mscorlib]System.DateTime C1::MyConstDateTime
IL_0020: ldc.i8 0x8cb0c276a28c000
IL_0021: newobj instance void [mscorlib]System.DateTime::.ctor(int64)
IL_0022: stsfld valuetype [mscorlib]System.DateTime C1::MyConstDateTime2
IL_0027: ret
} // end of method C1::.cctor
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method C1::.ctor
} // end of class C1
]]>.Value
Dim source =
<compilation>
<file name="a.vb">
Imports System
Public Class C2
Public Shared Sub DoStuff()
Console.WriteLine(C1.MyConstBoolean)
Console.WriteLine(C1.MyConstChar)
Console.WriteLine(C1.MyConstSByte)
Console.WriteLine(C1.MyConstInt16)
Console.WriteLine(C1.MyConstInt32)
Console.WriteLine(C1.MyConstInt64)
Console.WriteLine(C1.MyConstByte)
Console.WriteLine(C1.MyConstUInt16)
Console.WriteLine(C1.MyConstUInt32)
Console.WriteLine(C1.MyConstUInt64)
Console.WriteLine(C1.MyConstSingle)
Console.WriteLine(C1.MyConstDouble)
Console.WriteLine(C1.MyConstString)
Console.WriteLine(C1.MyConstDecimal2)
Console.WriteLine(C1.MyConstC3)
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithCustomILSource(source,
includeVbRuntime:=True,
ilSource:=ilsource)
AssertTheseDiagnostics(compilation,
<errors>
BC30799: Field 'C1.MyConstBoolean' has an invalid constant value.
Console.WriteLine(C1.MyConstBoolean)
~~~~~~~~~~~~~~~~~
BC30799: Field 'C1.MyConstChar' has an invalid constant value.
Console.WriteLine(C1.MyConstChar)
~~~~~~~~~~~~~~
BC30799: Field 'C1.MyConstSByte' has an invalid constant value.
Console.WriteLine(C1.MyConstSByte)
~~~~~~~~~~~~~~~
BC30799: Field 'C1.MyConstInt16' has an invalid constant value.
Console.WriteLine(C1.MyConstInt16)
~~~~~~~~~~~~~~~
BC30799: Field 'C1.MyConstInt32' has an invalid constant value.
Console.WriteLine(C1.MyConstInt32)
~~~~~~~~~~~~~~~
BC30799: Field 'C1.MyConstInt64' has an invalid constant value.
Console.WriteLine(C1.MyConstInt64)
~~~~~~~~~~~~~~~
BC30799: Field 'C1.MyConstByte' has an invalid constant value.
Console.WriteLine(C1.MyConstByte)
~~~~~~~~~~~~~~
BC30799: Field 'C1.MyConstUInt16' has an invalid constant value.
Console.WriteLine(C1.MyConstUInt16)
~~~~~~~~~~~~~~~~
BC30799: Field 'C1.MyConstUInt32' has an invalid constant value.
Console.WriteLine(C1.MyConstUInt32)
~~~~~~~~~~~~~~~~
BC30799: Field 'C1.MyConstUInt64' has an invalid constant value.
Console.WriteLine(C1.MyConstUInt64)
~~~~~~~~~~~~~~~~
BC30799: Field 'C1.MyConstSingle' has an invalid constant value.
Console.WriteLine(C1.MyConstSingle)
~~~~~~~~~~~~~~~~
BC30799: Field 'C1.MyConstDouble' has an invalid constant value.
Console.WriteLine(C1.MyConstDouble)
~~~~~~~~~~~~~~~~
BC30799: Field 'C1.MyConstString' has an invalid constant value.
Console.WriteLine(C1.MyConstString)
~~~~~~~~~~~~~~~~
BC30799: Field 'C1.MyConstDecimal2' has an invalid constant value.
Console.WriteLine(C1.MyConstDecimal2)
~~~~~~~~~~~~~~~~~~
BC30799: Field 'C1.MyConstC3' has an invalid constant value.
Console.WriteLine(C1.MyConstC3)
~~~~~~~~~~~~
</errors>)
source =
<compilation>
<file name="b.vb">
Imports System
Module Program
Dim cul = System.Globalization.CultureInfo.InvariantCulture
Public Sub Main()
Console.WriteLine(if(C1.MyConstString2, "MyConstString2=nullref"))
Console.WriteLine(if(C1.MyConstChar2 = Char.MinValue,"\0",C1.MyConstChar2))
Console.WriteLine(C1.MyConstBoolean2)
Console.WriteLine(if(C1.MyConstC2, "MyConstC2=nullref"))
Console.WriteLine(C1.MyConstDateTime.ToString("M/d/yyyy h:mm:ss tt", cul)) 'BIND:"MyConstDateTime"
Console.WriteLine(C1.MyConstDecimal) 'BIND1:"MyConstDecimal"
Console.WriteLine(C1.MyConstDateTime2.ToString("M/d/yyyy h:mm:ss tt", cul)) 'BIND2:"MyConstDateTime2"
Console.WriteLine(C1.MyConstDecimal3) 'BIND3:"MyConstDecimal3"
Console.WriteLine(C1.MyConstDateTime3.ToString("M/d/yyyy h:mm:ss tt", cul)) 'BIND4:"MyConstDateTime3"
End Sub
End Module
</file>
</compilation>
compilation = CreateCompilationWithCustomILSource(source,
includeVbRuntime:=True,
options:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
ilSource:=ilsource)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[
MyConstString2=nullref
\0
False
MyConstC2=nullref
11/4/2008 12:00:00 AM
15052004
11/4/2008 12:00:00 AM
0
1/1/0001 12:00:00 AM
]]>)
Dim model = GetSemanticModel(compilation, "b.vb")
Dim expressionSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "b.vb", 0)
Assert.Equal(SyntaxKind.IdentifierName, expressionSyntax.Kind)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "b.vb", 0)
Dim symbol = DirectCast(semanticInfo.Symbol, FieldSymbol)
Assert.NotNull(symbol)
Assert.Equal(SymbolKind.Field, symbol.Kind)
Assert.Equal("MyConstDateTime", symbol.Name)
Assert.False(symbol.IsConst)
expressionSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "b.vb", 1)
Assert.Equal(SyntaxKind.IdentifierName, expressionSyntax.Kind)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "b.vb", 1)
symbol = DirectCast(semanticInfo.Symbol, FieldSymbol)
Assert.NotNull(symbol)
Assert.Equal(SymbolKind.Field, symbol.Kind)
Assert.Equal("MyConstDecimal", symbol.Name)
Assert.False(symbol.IsConst)
expressionSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "b.vb", 2)
Assert.Equal(SyntaxKind.IdentifierName, expressionSyntax.Kind)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "b.vb", 2)
symbol = DirectCast(semanticInfo.Symbol, FieldSymbol)
Assert.NotNull(symbol)
Assert.Equal(SymbolKind.Field, symbol.Kind)
Assert.Equal("MyConstDateTime2", symbol.Name)
Assert.True(symbol.IsConst)
expressionSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "b.vb", 3)
Assert.Equal(SyntaxKind.IdentifierName, expressionSyntax.Kind)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "b.vb", 3)
symbol = DirectCast(semanticInfo.Symbol, FieldSymbol)
Assert.NotNull(symbol)
Assert.Equal(SymbolKind.Field, symbol.Kind)
Assert.Equal("MyConstDecimal3", symbol.Name)
Assert.True(symbol.IsConst)
expressionSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "b.vb", 4)
Assert.Equal(SyntaxKind.IdentifierName, expressionSyntax.Kind)
semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "b.vb", 4)
symbol = DirectCast(semanticInfo.Symbol, FieldSymbol)
Assert.NotNull(symbol)
Assert.Equal(SymbolKind.Field, symbol.Kind)
Assert.Equal("MyConstDateTime3", symbol.Name)
Assert.True(symbol.IsConst)
End Sub
<Fact>
Public Sub AccessorWithImportedGenericType()
Dim comp0 = CreateCompilationWithMscorlib(
<compilation name="GT">
<file name="a.vb">
Public Class MC(Of T)
End Class
public delegate Sub MD(Of T)(T t)
</file>
</compilation>)
Dim comp1 = CreateCompilationWithMscorlibAndReferences(
<compilation name="MT">
<file name="b.vb">
Public Class G(Of T)
Public Property Prop As MC(Of T)
Set(value As MC(Of T))
End Set
Get
End Get
End Property
Public Custom Event E As MD(Of T)
AddHandler(value As MD(Of T))
End AddHandler
RemoveHandler(value As MD(Of T))
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>, references:={New VisualBasicCompilationReference(comp0)})
Dim mtdata = DirectCast(comp1, Compilation).EmitToArray(options:=New EmitOptions(metadataOnly:=True))
Dim mtref = MetadataReference.CreateFromImage(mtdata)
Dim comp2 = CreateCompilationWithMscorlibAndReferences(
<compilation name="App">
<file name="c.vb">
</file>
</compilation>, references:={mtref})
Dim tsym = comp2.GetReferencedAssemblySymbol(mtref).GlobalNamespace.GetMember(Of NamedTypeSymbol)("G")
Assert.NotNull(tsym)
Dim mm = tsym.GetMembers()
Dim mems = tsym.GetMembers().Where(Function(s) s.Kind = SymbolKind.Method)
'
Assert.Equal(5, mems.Count())
For Each m As MethodSymbol In mems
If m.MethodKind = MethodKind.Constructor Then
Continue For
End If
Assert.NotNull(m.AssociatedSymbol)
Assert.NotEqual(MethodKind.Ordinary, m.MethodKind)
Next
End Sub
' TODO: Update this test if we decide to include gaps in the symbol table for NoPIA (DevDiv #17472).
<Fact, WorkItem(546951, "DevDiv")>
Public Sub VTableGapsNotInSymbolTable()
Dim vb = <compilation name="MT">
<file name="a.vb">
</file>
</compilation>
Dim comp = CreateCompilationWithCustomILSource(vb, VTableGapClassIL, includeVbRuntime:=True)
comp.VerifyDiagnostics()
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Class")
AssertEx.None(type.GetMembersUnordered().AsEnumerable(), Function(symbol) symbol.Name.StartsWith("_VtblGap"))
' Dropped entirely.
Assert.Equal(0, type.GetMembers("_VtblGap1_1").Length)
' Dropped entirely, since both accessors are dropped.
Assert.Equal(0, type.GetMembers("BothAccessorsAreGaps").Length)
' Getter is silently dropped, property appears valid and write-only.
Dim propWithoutGetter = type.GetMember(Of PropertySymbol)("GetterIsGap")
Assert.Null(propWithoutGetter.GetMethod)
Assert.NotNull(propWithoutGetter.SetMethod)
' Setter is silently dropped, property appears valid and read-only.
Dim propWithoutSetter = type.GetMember(Of PropertySymbol)("SetterIsGap")
Assert.NotNull(propWithoutSetter.GetMethod)
Assert.Null(propWithoutSetter.SetMethod)
End Sub
<Fact, WorkItem(546951, "DevDiv")>
Public Sub CallVTableGap()
Dim vb = <compilation name="MT">
<file name="a.vb">
Module Test
Sub Main()
dim c as new [Class]()
c._VtblGap1_1() ' CS1061
dim x as Integer
x = c.BothAccessorsAreGaps ' CS1061
c.BothAccessorsAreGaps = x ' CS1061
x = c.GetterIsGap ' CS0154
c.GetterIsGap = x
x = c.SetterIsGap
c.SetterIsGap = x ' CS0200
End Sub
End Module
</file>
</compilation>
' BREAK: Dev11 produces no diagnostics, but the emitted code does not peverify.
Dim comp = CreateCompilationWithCustomILSource(vb, VTableGapClassIL, includeVbRuntime:=True)
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_NameNotMember2, "c._VtblGap1_1").WithArguments("_VtblGap1_1", "[Class]"),
Diagnostic(ERRID.ERR_NameNotMember2, "c.BothAccessorsAreGaps").WithArguments("BothAccessorsAreGaps", "[Class]"),
Diagnostic(ERRID.ERR_NameNotMember2, "c.BothAccessorsAreGaps").WithArguments("BothAccessorsAreGaps", "[Class]"),
Diagnostic(ERRID.ERR_NoGetProperty1, "c.GetterIsGap").WithArguments("GetterIsGap"),
Diagnostic(ERRID.ERR_NoSetProperty1, "c.SetterIsGap = x").WithArguments("SetterIsGap"))
End Sub
<Fact, WorkItem(546951, "DevDiv")>
Public Sub ImplementVTableGap()
Dim vb = <compilation name="MT">
<file name="a.vb">
Class Empty
Implements [Interface]
End Class
Class Full
Implements [Interface]
Public Sub _VtblGap1_1() Implements [Interface]._VtblGap1_1
End Sub
Public Property GetterIsGap As Integer Implements [Interface].GetterIsGap
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
Public Property SetterIsGap As Integer Implements [Interface].SetterIsGap
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
Public Property BothAccessorsAreGaps As Integer Implements [Interface].BothAccessorsAreGaps
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
End Class
</file>
</compilation>
' BREAK: Dev11 produces errors for the vtable gaps that Empty does not implement and not for the
' vtable gaps that Full does implement.
Dim comp = CreateCompilationWithCustomILSource(vb, VTableGapInterfaceIL, includeVbRuntime:=True)
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_UnimplementedMember3, "[Interface]").WithArguments("Class", "Empty", "WriteOnly Property GetterIsGap As Integer", "[Interface]"),
Diagnostic(ERRID.ERR_UnimplementedMember3, "[Interface]").WithArguments("Class", "Empty", "ReadOnly Property SetterIsGap As Integer", "[Interface]"),
Diagnostic(ERRID.ERR_IdentNotMemberOfInterface4, "[Interface]._VtblGap1_1").WithArguments("_VtblGap1_1", "_VtblGap1_1", "sub", "[Interface]"),
Diagnostic(ERRID.ERR_IdentNotMemberOfInterface4, "[Interface].BothAccessorsAreGaps").WithArguments("BothAccessorsAreGaps", "BothAccessorsAreGaps", "property", "[Interface]"))
End Sub
<Fact, WorkItem(1094411, "DevDiv")>
Public Sub Bug1094411_01()
Dim source1 =
<compilation>
<file name="a.vb">
Class Test
Public F As Integer
Property P As Integer
Event E As System.Action
Sub M()
End Sub
End Class
</file>
</compilation>
Dim members = {"F", "P", "E", "M"}
Dim comp1 = CreateCompilationWithMscorlib(source1, options:=TestOptions.ReleaseDll)
Dim test1 = comp1.GetTypeByMetadataName("Test")
Dim memberNames1 = New HashSet(Of String)(test1.MemberNames)
For Each m In members
Assert.True(memberNames1.Contains(m), m)
Next
Dim comp2 = CreateCompilationWithMscorlibAndReferences(<compilation><file name="a.vb"/></compilation>, {comp1.EmitToImageReference()})
Dim test2 = comp2.GetTypeByMetadataName("Test")
Dim memberNames2 = New HashSet(Of String)(test2.MemberNames)
For Each m In members
Assert.True(memberNames2.Contains(m), m)
Next
End Sub
<Fact, WorkItem(1094411, "DevDiv")>
Public Sub Bug1094411_02()
Dim source1 =
<compilation>
<file name="a.vb">
Class Test
Public F As Integer
Property P As Integer
Event E As System.Action
Sub M()
End Sub
End Class
</file>
</compilation>
Dim members = {"F", "P", "E", "M"}
Dim comp1 = CreateCompilationWithMscorlib(source1, options:=TestOptions.ReleaseDll)
Dim test1 = comp1.GetTypeByMetadataName("Test")
test1.GetMembers()
Dim memberNames1 = New HashSet(Of String)(test1.MemberNames)
For Each m In members
Assert.True(memberNames1.Contains(m), m)
Next
Dim comp2 = CreateCompilationWithMscorlibAndReferences(<compilation><file name="a.vb"/></compilation>, {comp1.EmitToImageReference()})
Dim test2 = comp2.GetTypeByMetadataName("Test")
test2.GetMembers()
Dim memberNames2 = New HashSet(Of String)(test2.MemberNames)
For Each m In members
Assert.True(memberNames2.Contains(m), m)
Next
End Sub
End Class
End Namespace
|
DavidKarlas/roslyn
|
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/MetadataMemberTests.vb
|
Visual Basic
|
apache-2.0
| 38,003
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.FindSymbols.Finders
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.FindSymbols
<ExportLanguageService(GetType(ILanguageServiceReferenceFinder), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicReferenceFinder
Implements ILanguageServiceReferenceFinder
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Function DetermineCascadedSymbolsAsync(
symbol As ISymbol,
project As Project,
cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of ISymbol)) Implements ILanguageServiceReferenceFinder.DetermineCascadedSymbolsAsync
If symbol.Kind = SymbolKind.Property Then
Return DetermineCascadedSymbolsAsync(DirectCast(symbol, IPropertySymbol), project, cancellationToken)
ElseIf symbol.Kind = SymbolKind.NamedType Then
Return DetermineCascadedSymbolsAsync(DirectCast(symbol, INamedTypeSymbol), project, cancellationToken)
Else
Return SpecializedTasks.EmptyImmutableArray(Of ISymbol)
End If
End Function
Private Shared Async Function DetermineCascadedSymbolsAsync(
[property] As IPropertySymbol,
project As Project,
cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of ISymbol))
Dim compilation = Await project.GetCompilationAsync(cancellationToken).ConfigureAwait(False)
Dim relatedSymbol = [property].FindRelatedExplicitlyDeclaredSymbol(compilation)
Return If([property].Equals(relatedSymbol),
ImmutableArray(Of ISymbol).Empty,
ImmutableArray.Create(relatedSymbol))
End Function
Private Shared Async Function DetermineCascadedSymbolsAsync(
namedType As INamedTypeSymbol,
project As Project,
cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of ISymbol))
Dim compilation = Await project.GetCompilationAsync(cancellationToken).ConfigureAwait(False)
' If this is a WinForms project, then the VB 'my' feature may have synthesized
' a property that would return an instance of the main Form type for the project.
' Search for such properties and cascade to them as well.
Dim matchingMyPropertySymbols =
From childNamespace In compilation.RootNamespace.GetNamespaceMembers()
Where childNamespace.IsMyNamespace(compilation)
From type In childNamespace.GetAllTypes(cancellationToken)
Where type.Name = "MyForms"
From childProperty In type.GetMembers().OfType(Of IPropertySymbol)
Where childProperty.IsImplicitlyDeclared AndAlso childProperty.Type.Equals(namedType)
Select DirectCast(childProperty, ISymbol)
Return matchingMyPropertySymbols.Distinct().ToImmutableArray()
End Function
End Class
End Namespace
|
wvdd007/roslyn
|
src/Workspaces/VisualBasic/Portable/FindSymbols/VisualBasicReferenceFinder.vb
|
Visual Basic
|
apache-2.0
| 3,524
|
'*******************************************************************************************'
' '
' Download Free Evaluation Version From: https://bytescout.com/download/web-installer '
' '
' Also available as Web API! Get free API Key https://app.pdf.co/signup '
' '
' Copyright © 2017-2020 ByteScout, Inc. All rights reserved. '
' https://www.bytescout.com '
' https://www.pdf.co '
'*******************************************************************************************'
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
<Assembly: AssemblyTitle("FindTableAndExtractAsCsv")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyConfiguration("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("FindTableAndExtractAsCsv")>
<Assembly: AssemblyCopyright("Copyright © 2017")>
<Assembly: AssemblyTrademark("")>
<Assembly: AssemblyCulture("")>
' Setting ComVisible to false makes the types in this assembly not visible
' to COM components. If you need to access a type in this assembly from
' COM, set the ComVisible attribute to true on that type.
<Assembly: ComVisible(False)>
' The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("90c92623-11ae-4ddb-9982-80552a4cc3f5")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
bytescout/ByteScout-SDK-SourceCode
|
Premium Suite/VB.NET/Find table in pdf and extract as xml with pdf extractor sdk/Properties/AssemblyInfo.vb
|
Visual Basic
|
apache-2.0
| 2,228
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.IO
Imports System.Text
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
''' <summary>
''' Tests for lambdas converted to expression trees.
''' </summary>
Public Class CodeGenExprLambda
Inherits BasicTestBase
#Region "Literals"
<Fact>
Public Sub Literals()
Dim source = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Linq.Expressions
Module Module1
Sub Main()
Dim exprTree1 As Expression(Of Func(Of Integer)) = Function() 3
Console.WriteLine(exprtree1.Dump)
Dim exprTree2 As Expression(Of Func(Of Integer, Integer)) = Function(x) 3 + x
Console.WriteLine(exprtree2.Dump)
End Sub
End Module]]></file>
<%= _exprTesting %>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
options:=TestOptions.ReleaseExe.WithOverflowChecks(True),
expectedOutput:=<![CDATA[
Lambda(
body {
Constant(
3
type: System.Int32
)
}
return type: System.Int32
type: System.Func`1[System.Int32]
)
Lambda(
Parameter(
x
type: System.Int32
)
body {
AddChecked(
Constant(
3
type: System.Int32
)
Parameter(
x
type: System.Int32
)
type: System.Int32
)
}
return type: System.Int32
type: System.Func`2[System.Int32,System.Int32]
)
]]>).VerifyDiagnostics()
End Sub
#End Region
#Region "Unary Operations"
<Fact()>
Public Sub TestUnaryOperator_Unchecked_PlusMinus()
TestUnaryOperator_AllTypes_PlusMinus(False, result:=ExpTreeTestResources.UncheckedUnaryPlusMinusNot)
End Sub
<Fact()>
Public Sub TestUnaryOperator_Checked_PlusMinusNot()
TestUnaryOperator_AllTypes_PlusMinus(True, result:=ExpTreeTestResources.CheckedUnaryPlusMinusNot)
End Sub
<Fact()>
Public Sub UserDefinedIsTrueIsFalse_Unchecked()
Dim file = <file name="expr.vb"><%= ExpTreeTestResources.TestUnary_UDO_IsTrueIsFalse %></file>
TestExpressionTrees(file, ExpTreeTestResources.CheckedAndUncheckedIsTrueIsFalse, checked:=False)
End Sub
<Fact()>
Public Sub UserDefinedIsTrueIsFalse_Checked()
Dim file = <file name="expr.vb"><%= ExpTreeTestResources.TestUnary_UDO_IsTrueIsFalse %></file>
TestExpressionTrees(file, ExpTreeTestResources.CheckedAndUncheckedIsTrueIsFalse, checked:=True)
End Sub
<Fact()>
Public Sub UserDefinedPlusMinusNot_Unchecked()
Dim file = <file name="expr.vb"><%= ExpTreeTestResources.TestUnary_UDO_PlusMinusNot %></file>
TestExpressionTrees(file, ExpTreeTestResources.CheckedAndUncheckedUdoUnaryPlusMinusNot1, checked:=False)
End Sub
<Fact()>
Public Sub UserDefinedPlusMinusNot_Checked()
Dim file = <file name="expr.vb"><%= ExpTreeTestResources.TestUnary_UDO_PlusMinusNot %></file>
TestExpressionTrees(file, ExpTreeTestResources.CheckedAndUncheckedUdoUnaryPlusMinusNot1, checked:=True)
End Sub
#Region "Implementation"
Public Sub TestUnaryOperator_AllTypes_IsIsNot(checked As Boolean, result As String)
Dim ops() As String = {"Is", "IsNot"}
Dim tests As New List(Of ExpressionTreeTest)
For Each op In ops
TestUnaryOperator_AllTypesWithNullableAndEnum_InIsNot(checked, op, tests)
Next
tests(0).Prefix = s_enumDeclarations
TestExpressionTrees(checked, result, tests.ToArray())
End Sub
Public Sub TestUnaryOperator_AllTypes_PlusMinus(checked As Boolean, result As String)
Dim ops() As String = {"+", "-", "Not"}
Dim tests As New List(Of ExpressionTreeTest)
For Each op In ops
TestUnaryOperator_AllTypesWithNullableAndEnum_PlusMinus(checked, op, tests)
Next
tests(0).Prefix = s_enumDeclarations
TestExpressionTrees(checked, result, tests.ToArray())
End Sub
#Region "Expression(Of Func(Of Type, Type)) <= Function(x) <op> x"
Private Sub TestUnaryOperator_AllTypesWithNullableAndEnum_PlusMinus(checked As Boolean, operation As String, list As List(Of ExpressionTreeTest))
TestUnaryOperator_AddTestsForTypeAndEnum_PlusMinus("SByte", operation, list)
TestUnaryOperator_AddTestsForTypeAndEnum_PlusMinus("Byte", operation, list)
TestUnaryOperator_AddTestsForTypeAndEnum_PlusMinus("Short", operation, list)
TestUnaryOperator_AddTestsForTypeAndEnum_PlusMinus("UShort", operation, list)
TestUnaryOperator_AddTestsForTypeAndEnum_PlusMinus("Integer", operation, list)
TestUnaryOperator_AddTestsForTypeAndEnum_PlusMinus("UInteger", operation, list)
TestUnaryOperator_AddTestsForTypeAndEnum_PlusMinus("Long", operation, list)
TestUnaryOperator_AddTestsForTypeAndEnum_PlusMinus("ULong", operation, list)
TestUnaryOperator_AddTestsForTypeAndNullable_PlusMinus("Boolean", operation, list)
TestUnaryOperator_AddTestsForTypeAndNullable_PlusMinus("Single", operation, list)
TestUnaryOperator_AddTestsForTypeAndNullable_PlusMinus("Double", operation, list)
TestUnaryOperator_AddTestsForTypeAndNullable_PlusMinus("Decimal", operation, list)
'TestUnaryOperator_AddTestsForTypeAndNullable_PlusMinus("Date", operation, list)
TestUnaryOperator_AddTestsForType_PlusMinus("String", operation, list)
TestUnaryOperator_AddTestsForType_PlusMinus("Object", operation, list)
End Sub
Private Sub TestUnaryOperator_AddTestsForTypeAndEnum_PlusMinus(type As String, operation As String, list As List(Of ExpressionTreeTest))
TestUnaryOperator_AddTestsForTypeAndNullable_PlusMinus(type, operation, list)
TestUnaryOperator_AddTestsForTypeAndNullable_PlusMinus(GetEnumTypeName(type), operation, list)
End Sub
Private Sub TestUnaryOperator_AddTestsForTypeAndNullable_PlusMinus(type As String, operation As String, list As List(Of ExpressionTreeTest))
TestUnaryOperator_AddTestsForType_PlusMinus(type, operation, list)
TestUnaryOperator_AddTestsForType_PlusMinus(type + "?", operation, list)
End Sub
Private Sub TestUnaryOperator_AddTestsForType_PlusMinus(type1 As String, operation As String, list As List(Of ExpressionTreeTest))
Dim descr1 = String.Format("-=-=-=-=-=-=-=-=- {0} {{0}} => {{0}} -=-=-=-=-=-=-=-=-", operation)
list.Add(New ExpressionTreeTest With {.Description = String.Format(descr1, type1),
.ExpressionTypeArgument =
String.Format("Func(Of {0}, {0})", type1),
.Lambda = String.Format("Function(x) {0} x ", operation)})
End Sub
#End Region
#Region "Expression(Of Func(Of Type, Type)) <= Function(x) x <op> Nothing"
Private Sub TestUnaryOperator_AllTypesWithNullableAndEnum_InIsNot(checked As Boolean, operation As String, list As List(Of ExpressionTreeTest))
TestUnaryOperator_AddTestsForTypeAndEnum_IsIsNot("SByte?", operation, list)
TestUnaryOperator_AddTestsForTypeAndEnum_IsIsNot("Byte?", operation, list)
TestUnaryOperator_AddTestsForTypeAndEnum_IsIsNot("Short?", operation, list)
TestUnaryOperator_AddTestsForTypeAndEnum_IsIsNot("UShort?", operation, list)
TestUnaryOperator_AddTestsForTypeAndEnum_IsIsNot("Integer?", operation, list)
TestUnaryOperator_AddTestsForTypeAndEnum_IsIsNot("UInteger?", operation, list)
TestUnaryOperator_AddTestsForTypeAndEnum_IsIsNot("Long?", operation, list)
TestUnaryOperator_AddTestsForTypeAndEnum_IsIsNot("ULong?", operation, list)
TestUnaryOperator_AddTestsForType_IsIsNot("Boolean?", operation, list)
TestUnaryOperator_AddTestsForType_IsIsNot("Single?", operation, list)
TestUnaryOperator_AddTestsForType_IsIsNot("Double?", operation, list)
TestUnaryOperator_AddTestsForType_IsIsNot("Decimal?", operation, list)
TestUnaryOperator_AddTestsForType_IsIsNot("Date?", operation, list)
TestUnaryOperator_AddTestsForType_IsIsNot("String", operation, list)
TestUnaryOperator_AddTestsForType_IsIsNot("Object", operation, list)
End Sub
Private Sub TestUnaryOperator_AddTestsForTypeAndEnum_IsIsNot(type As String, operation As String, list As List(Of ExpressionTreeTest))
TestUnaryOperator_AddTestsForType_IsIsNot(type, operation, list)
TestUnaryOperator_AddTestsForType_IsIsNot(GetEnumTypeName(type), operation, list)
End Sub
Private Sub TestUnaryOperator_AddTestsForType_IsIsNot(type As String, operation As String, list As List(Of ExpressionTreeTest))
TestUnaryOperator_AddTestsForType_IsIsNot(type, "Object", operation, list)
TestUnaryOperator_AddTestsForType_IsIsNot(type, "Boolean", operation, list)
TestUnaryOperator_AddTestsForType_IsIsNot(type, "Boolean?", operation, list)
End Sub
Private Sub TestUnaryOperator_AddTestsForType_IsIsNot(type1 As String, type2 As String, operation As String, list As List(Of ExpressionTreeTest))
Dim descr1 = String.Format("-=-=-=-=-=-=-=-=- {{0}} {0} Nothing => {{1}} -=-=-=-=-=-=-=-=-", operation)
list.Add(New ExpressionTreeTest With {.Description = String.Format(descr1, type1, type2),
.ExpressionTypeArgument =
String.Format("Func(Of {0}, {1})", type1, type2),
.Lambda = String.Format("Function(x) x {0} Nothing", operation)})
End Sub
#End Region
#End Region
#End Region
#Region "Binary Operations"
<Fact>
Public Sub TestBinaryOperator_Unchecked_Arithmetic()
TestBinaryOperator_AllTypes_NumericOperations(False, result:=ExpTreeTestResources.UncheckedArithmeticBinaryOperators)
End Sub
<Fact>
Public Sub TestBinaryOperator_Checked_Arithmetic()
TestBinaryOperator_AllTypes_NumericOperations(True, result:=ExpTreeTestResources.CheckedArithmeticBinaryOperators)
End Sub
<Fact>
Public Sub TestBinaryOperator_Unchecked_AndOrXor()
TestBinaryOperator_AllTypes_AndOrXor(False, result:=ExpTreeTestResources.UncheckedAndOrXor)
End Sub
<Fact>
Public Sub TestBinaryOperator_Checked_AndOrXor()
TestBinaryOperator_AllTypes_AndOrXor(True, result:=ExpTreeTestResources.CheckedAndOrXor)
End Sub
<Fact>
Public Sub TestBinaryOperator_Unhecked_ShortCircuit()
TestBinaryOperator_AllTypes_ShortCircuit(False, result:=ExpTreeTestResources.UncheckedShortCircuit)
End Sub
<Fact>
Public Sub TestBinaryOperator_Checked_ShortCircuit()
TestBinaryOperator_AllTypes_ShortCircuit(True, result:=ExpTreeTestResources.CheckedShortCircuit)
End Sub
<Fact>
Public Sub TestBinaryOperator_Unchecked_Comparisons()
TestBinaryOperator_AllTypes_Comparisons(False, result:=ExpTreeTestResources.UncheckedComparisonOperators)
End Sub
<Fact>
Public Sub TestBinaryOperator_Checked_Comparisons()
TestBinaryOperator_AllTypes_Comparisons(True, result:=ExpTreeTestResources.CheckedComparisonOperators)
End Sub
<Fact>
Public Sub TestBinaryOperator_Unchecked_IsIsNot()
TestBinaryOperator_AllTypes_IsIsNot(False, result:=ExpTreeTestResources.CheckedAndUncheckedIsIsNot)
End Sub
<Fact>
Public Sub TestBinaryOperator_Checked_IsIsNot()
TestBinaryOperator_AllTypes_IsIsNot(True, result:=ExpTreeTestResources.CheckedAndUncheckedIsIsNot)
End Sub
<Fact()>
Public Sub TestBinaryOperator_Unchecked_IsIsNot_Nothing()
TestUnaryOperator_AllTypes_IsIsNot(False, result:=ExpTreeTestResources.CheckedAndUncheckedIsIsNotNothing)
End Sub
<Fact()>
Public Sub TestBinaryOperator_Checked_IsIsNot_Nothing()
TestUnaryOperator_AllTypes_IsIsNot(True, result:=ExpTreeTestResources.CheckedAndUncheckedIsIsNotNothing)
End Sub
<Fact>
Public Sub TestBinaryOperator_Unhecked_Concatenate()
TestBinaryOperator_ConcatenatePlus(False, result:=ExpTreeTestResources.UncheckedConcatenate)
End Sub
<Fact>
Public Sub TestBinaryOperator_Checked_Concatenate()
TestBinaryOperator_ConcatenatePlus(True, result:=ExpTreeTestResources.CheckedConcatenate)
End Sub
<Fact>
Public Sub TestBinaryOperator_Unhecked_Like()
TestBinaryOperator_Like(False, result:=ExpTreeTestResources.UncheckedLike)
End Sub
<Fact>
Public Sub TestBinaryOperator_Checked_Like()
TestBinaryOperator_Like(True, result:=ExpTreeTestResources.CheckedLike)
End Sub
<Fact>
Public Sub TestBinaryOperator_Unchecked_WithDate()
TestBinaryOperator_DateAsOperand(False, result:=ExpTreeTestResources.CheckedAndUncheckedWithDate)
End Sub
<Fact>
Public Sub TestBinaryOperator_Checked_WithDate()
TestBinaryOperator_DateAsOperand(True, result:=ExpTreeTestResources.CheckedAndUncheckedWithDate)
End Sub
<Fact>
Public Sub TestBinaryOperator_Unchecked_UserDefinedBinaryOperator()
TestBinaryOperator_UserDefinedBinaryOperator(False, result:=ExpTreeTestResources.UncheckedUserDefinedBinaryOperators)
End Sub
<Fact>
Public Sub TestBinaryOperator_Checked_UserDefinedBinaryOperator()
TestBinaryOperator_UserDefinedBinaryOperator(True, result:=ExpTreeTestResources.CheckedUserDefinedBinaryOperators)
End Sub
#Region "Implementation"
Private Sub TestBinaryOperator_AllTypes_NumericOperations(checked As Boolean, result As String)
TestBinaryOperator_AllTypesAndSomeOperations(checked, {"+", "-", "*", "/", "\", "^", "Mod", "<<", ">>"}, result)
End Sub
Private Sub TestBinaryOperator_AllTypes_AndOrXor(checked As Boolean, result As String)
TestBinaryOperator_AllTypesAndSomeOperations(checked, {"And", "Or", "Xor"}, result)
End Sub
Public Sub TestBinaryOperator_AllTypes_ShortCircuit(checked As Boolean, result As String)
TestBinaryOperator_AllTypesAndSomeOperations(checked, {"AndAlso", "OrElse"}, result)
End Sub
Private Sub TestBinaryOperator_AllTypesAndSomeOperations(checked As Boolean, ops() As String, result As String)
Dim tests As New List(Of ExpressionTreeTest)
For Each op In ops
TestBinaryOperator_AllTypesWithNullableAndEnum(checked, op, tests)
Next
tests(0).Prefix = s_enumDeclarations
TestExpressionTrees(checked, result, tests.ToArray())
End Sub
Public Sub TestBinaryOperator_AllTypes_Comparisons(checked As Boolean, result As String)
Dim ops() As String = {"=", "<>", "<", "<=", ">=", ">"}
Dim tests As New List(Of ExpressionTreeTest)
For Each op In ops
TestBinaryOperator_AllTypesWithNullableAndEnum(checked, op, tests)
Next
For Each op In ops
TestBinaryOperator_AllTypesWithNullableAndEnum_Bool(checked, op, tests)
Next
tests(0).Prefix = s_enumDeclarations
TestExpressionTrees(checked, result, tests.ToArray())
End Sub
Public Sub TestBinaryOperator_AllTypes_IsIsNot(checked As Boolean, result As String)
Dim tests As New List(Of ExpressionTreeTest)
TestBinaryOperator_AddTestsForType_BoolObject("String", "Is", tests)
TestBinaryOperator_AddTestsForType_BoolObject("String", "IsNot", tests)
TestBinaryOperator_AddTestsForType_BoolObject("Object", "Is", tests)
TestBinaryOperator_AddTestsForType_BoolObject("Object", "IsNot", tests)
tests(0).Prefix = s_enumDeclarations
TestExpressionTrees(checked, result, tests.ToArray())
End Sub
Public Sub TestBinaryOperator_ConcatenatePlus(checked As Boolean, result As String)
Dim tests As New List(Of ExpressionTreeTest)
For Each type1 In _allTypes
TestBinaryOperator_AddTestsForType(type1, "String", "String", "&", tests)
TestBinaryOperator_AddTestsForType(type1, "String", "String", "+", tests)
TestBinaryOperator_AddTestsForType("String", type1, "String", "&", tests)
TestBinaryOperator_AddTestsForType("String", type1, "String", "+", tests)
Next
TestBinaryOperator_AddTestsForType("Object", "Object", "Object", "&", tests)
tests(0).Prefix = s_enumDeclarations
TestExpressionTrees(checked, result, tests.ToArray())
End Sub
Public Sub TestBinaryOperator_Like(checked As Boolean, result As String)
Dim tests As New List(Of ExpressionTreeTest)
Dim index As Integer = 0
For Each type1 In _allTypes
Select Case index Mod 4
Case 0, 3
TestBinaryOperator_AddTestsForType(type1, "String", "Boolean", "Like", tests)
TestBinaryOperator_AddTestsForType("Object", type1, "Boolean", "Like", tests)
Case Else
TestBinaryOperator_AddTestsForType("String", type1, "Boolean", "Like", tests)
TestBinaryOperator_AddTestsForType(type1, "Object", "Boolean", "Like", tests)
End Select
index += 1
Next
TestBinaryOperator_AddTestsForType("Object", "Object", "Object", "Like", tests)
tests(0).Prefix = s_enumDeclarations
TestExpressionTrees(checked, result, tests.ToArray())
End Sub
Public Sub TestBinaryOperator_DateAsOperand(checked As Boolean, result As String)
Dim tests As New List(Of ExpressionTreeTest)
Dim flag = True
For Each op In {">", "<", "<=", ">=", "+", "-"}
If op <> "-" Then
If flag Then
TestBinaryOperator_AddTestsForType("String", "Date", "Object", op, tests)
TestBinaryOperator_AddTestsForType("Date?", "String", "Object", op, tests)
TestBinaryOperator_AddTestsForType("Date", "Object", "Object", op, tests)
TestBinaryOperator_AddTestsForType("Object", "Date?", "Object", op, tests)
Else
TestBinaryOperator_AddTestsForType("Date", "String", "Object", op, tests)
TestBinaryOperator_AddTestsForType("String", "Date?", "Object", op, tests)
TestBinaryOperator_AddTestsForType("Object", "Date", "Object", op, tests)
TestBinaryOperator_AddTestsForType("Date?", "Object", "Object", op, tests)
End If
Else
TestBinaryOperator_AddTestsForType("Date", "Date", "TimeSpan", op, tests)
TestBinaryOperator_AddTestsForType("Date", "Date?", "TimeSpan", op, tests)
TestBinaryOperator_AddTestsForType("Date?", "Date", "TimeSpan?", op, tests)
TestBinaryOperator_AddTestsForType("Date?", "Date?", "TimeSpan?", op, tests)
TestBinaryOperator_AddTestsForType("Date?", "Date?", "TimeSpan", op, tests)
End If
TestBinaryOperator_AddTestsForType("Date", "Date", "Object", op, tests)
TestBinaryOperator_AddTestsForType("Date", "Date?", "Object", op, tests)
TestBinaryOperator_AddTestsForType("Date?", "Date", "Object", op, tests)
TestBinaryOperator_AddTestsForType("Date?", "Date?", "Object", op, tests)
flag = Not flag
Next
tests(0).Prefix = s_enumDeclarations
TestExpressionTrees(checked, result, tests.ToArray())
End Sub
#Region "User Defined Binary Operator"
Public Sub TestBinaryOperator_UserDefinedBinaryOperator(checked As Boolean, result As String)
Dim tests As New List(Of ExpressionTreeTest)
Dim index As Integer = 0
For Each suffix1 In {"", "?"}
For Each suffix2 In {"", "?"}
Dim type As String = "UserDefinedBinaryOperator" & index
For Each op In {"+", "-", "*", "/", "\", "Mod", "^", "=", "<>", "<", ">", "<=", ">=", "Like", "&", "And", "Or", "Xor"}
TestBinaryOperator_AddTestsForTypeWithNullable(type, op, tests)
Next
For Each op In {"<<", ">>"}
TestBinaryOperator_AddTestsForType(type, "Integer", type + "?", op, tests)
TestBinaryOperator_AddTestsForType(type + "?", "Integer", type, op, tests)
Next
index += 1
Next
Next
tests(0).Prefix = <![CDATA[]]>
index = 0
For Each suffix1 In {"", "?"}
For Each suffix2 In {"", "?"}
tests(0).Prefix.Value = tests(0).Prefix.Value & vbLf &
String.Format(ExpTreeTestResources.UserDefinedBinaryOperators,
suffix1, suffix2, index)
index += 1
Next
Next
TestExpressionTrees(checked, result, tests.ToArray())
End Sub
#End Region
#Region "Expression(Of Func(Of Type[?], Type[?], Type[?])) <= Function(x, y) x <op> y"
Private Sub TestBinaryOperator_AllTypesWithNullableAndEnum(checked As Boolean, operation As String, list As List(Of ExpressionTreeTest))
TestBinaryOperator_AddTestsForTypeWithNullableAndEnum("SByte", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullableAndEnum("Byte", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullableAndEnum("Short", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullableAndEnum("UShort", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullableAndEnum("Integer", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullableAndEnum("UInteger", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullableAndEnum("Long", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullableAndEnum("ULong", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullable("Boolean", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullable("Single", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullable("Double", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullable("Decimal", operation, list)
TestBinaryOperator_AddTestsForType("String", operation, list)
TestBinaryOperator_AddTestsForType("Object", operation, list)
End Sub
Private Sub TestBinaryOperator_AddTestsForTypeWithNullable(type As String, operation As String, list As List(Of ExpressionTreeTest))
Dim nullable As String = type + "?"
TestBinaryOperator_AddTestsForType(type, type, type, operation, list)
TestBinaryOperator_AddTestsForType(type, type, nullable, operation, list)
TestBinaryOperator_AddTestsForType(nullable, type, type, operation, list)
TestBinaryOperator_AddTestsForType(type, nullable, nullable, operation, list)
TestBinaryOperator_AddTestsForType(nullable, nullable, nullable, operation, list)
End Sub
Private Sub TestBinaryOperator_AddTestsForType(type As String, operation As String, list As List(Of ExpressionTreeTest))
TestBinaryOperator_AddTestsForType(type, type, type, operation, list)
End Sub
Private Sub TestBinaryOperator_AddTestsForTypeWithNullableAndEnum(type As String, operation As String, list As List(Of ExpressionTreeTest))
TestBinaryOperator_AddTestsForTypeWithNullable(type, operation, list)
TestBinaryOperator_AddTestsForTypeWithNullable(GetEnumTypeName(type), operation, list)
End Sub
#End Region
#Region "Expression(Of Func(Of Type[?], Type[?], Boolean[?])) <= Function(x, y) x <op> y"
Private Sub TestBinaryOperator_AllTypesWithNullableAndEnum_Bool(checked As Boolean, operation As String, list As List(Of ExpressionTreeTest))
TestBinaryOperator_AddTestsForTypeWithNullableAndEnum_Bool("SByte", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullableAndEnum_Bool("Byte", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullableAndEnum_Bool("Short", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullableAndEnum_Bool("UShort", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullableAndEnum_Bool("Integer", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullableAndEnum_Bool("UInteger", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullableAndEnum_Bool("Long", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullableAndEnum_Bool("ULong", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullable_Bool("Boolean", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullable_Bool("Single", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullable_Bool("Double", operation, list)
TestBinaryOperator_AddTestsForTypeWithNullable_Bool("Decimal", operation, list)
TestBinaryOperator_AddTestsForType_Bool("String", operation, list)
TestBinaryOperator_AddTestsForType_Bool("Object", operation, list)
End Sub
Private Sub TestBinaryOperator_AddTestsForTypeWithNullableAndEnum_Bool(type As String, operation As String, list As List(Of ExpressionTreeTest))
TestBinaryOperator_AddTestsForTypeWithNullable_Bool(type, operation, list)
TestBinaryOperator_AddTestsForTypeWithNullable_Bool(GetEnumTypeName(type), operation, list)
End Sub
Private Sub TestBinaryOperator_AddTestsForTypeWithNullable_Bool(type As String, operation As String, list As List(Of ExpressionTreeTest))
Dim nullable As String = type + "?"
TestBinaryOperator_AddTestsForType(type, type, "Boolean", operation, list)
TestBinaryOperator_AddTestsForType(type, type, "Boolean?", operation, list)
TestBinaryOperator_AddTestsForType(type, nullable, "Boolean", operation, list)
TestBinaryOperator_AddTestsForType(type, nullable, "Boolean?", operation, list)
TestBinaryOperator_AddTestsForType(nullable, type, "Boolean", operation, list)
TestBinaryOperator_AddTestsForType(nullable, type, "Boolean?", operation, list)
TestBinaryOperator_AddTestsForType(nullable, nullable, "Boolean", operation, list)
TestBinaryOperator_AddTestsForType(nullable, nullable, "Boolean?", operation, list)
End Sub
Private Sub TestBinaryOperator_AddTestsForType_Bool(type As String, operation As String, list As List(Of ExpressionTreeTest))
TestBinaryOperator_AddTestsForType(type, type, "Boolean", operation, list)
TestBinaryOperator_AddTestsForType(type, type, "Boolean?", operation, list)
End Sub
#End Region
#Region "Expression(Of Func(Of Type, Type, {Bool|Bool?|Object})) <= Function(x, y) x <op> y"
Private Sub TestBinaryOperator_AddTestsForType_BoolObject(type As String, operation As String, list As List(Of ExpressionTreeTest))
TestBinaryOperator_AddTestsForType_BoolObject(type, type, operation, list)
End Sub
Private Sub TestBinaryOperator_AddTestsForType_BoolObject(type1 As String, type2 As String, operation As String, list As List(Of ExpressionTreeTest))
TestBinaryOperator_AddTestsForType(type1, type2, "Object", operation, list)
TestBinaryOperator_AddTestsForType(type1, type2, "Boolean", operation, list)
TestBinaryOperator_AddTestsForType(type1, type2, "Boolean?", operation, list)
End Sub
#End Region
Private Sub TestBinaryOperator_AddTestsForType(type1 As String, type2 As String, type3 As String, operation As String, list As List(Of ExpressionTreeTest))
Dim descr1 = String.Format("-=-=-=-=-=-=-=-=- {{0}} {0} {{1}} => {{2}} -=-=-=-=-=-=-=-=-", operation)
list.Add(New ExpressionTreeTest With {.Description = String.Format(descr1, type1, type2, type3),
.ExpressionTypeArgument =
String.Format("Func(Of {0}, {1}, {2})", type1, type2, type3),
.Lambda = String.Format("Function(x, y) x {0} y", operation)})
End Sub
#End Region
#End Region
#Region "Conversions"
<Fact()>
Public Sub NothingLiteralConversions_Unchecked()
TestConversion_NothingLiteral(False, ExpTreeTestResources.CheckedAndUncheckedNothingConversions)
End Sub
<Fact()>
Public Sub NothingLiteralConversions_Checked()
TestConversion_NothingLiteral(True, ExpTreeTestResources.CheckedAndUncheckedNothingConversions)
End Sub
<Fact()>
Public Sub NothingLiteralConversionsDate_CheckedUnchecked()
Dim source = <compilation>
<%= _exprTesting %>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Linq.Expressions
Public Class TestClass
Public Sub Test()
Console.WriteLine("-=-=-=-=-=-=-=-=- Nothing -> Date -=-=-=-=-=-=-=-=-")
Dim exprtree1 As Expression(Of Func(Of Date)) = Function() Nothing
Console.WriteLine(exprtree1.Dump)
Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Nothing, Date) -> Date -=-=-=-=-=-=-=-=-")
Dim exprtree2 As Expression(Of Func(Of Date)) = Function() CType(Nothing, Date)
Console.WriteLine(exprtree2.Dump)
Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Nothing, Date) -> Date -=-=-=-=-=-=-=-=-")
Dim exprtree3 As Expression(Of Func(Of Date)) = Function() DirectCast(Nothing, Date)
Console.WriteLine(exprtree3.Dump)
Console.WriteLine("-=-=-=-=-=-=-=-=- Nothing -> Date? -=-=-=-=-=-=-=-=-")
Dim exprtree4 As Expression(Of Func(Of Date?)) = Function() Nothing
Console.WriteLine(exprtree4.Dump)
Console.WriteLine("-=-=-=-=-=-=-=-=- CType(Nothing, Date?) -> Date? -=-=-=-=-=-=-=-=-")
Dim exprtree5 As Expression(Of Func(Of Date?)) = Function() CType(Nothing, Date?)
Console.WriteLine(exprtree5.Dump)
Console.WriteLine("-=-=-=-=-=-=-=-=- DirectCast(Nothing, Date?) -> Date? -=-=-=-=-=-=-=-=-")
Dim exprtree6 As Expression(Of Func(Of Date?)) = Function() DirectCast(Nothing, Date?)
Console.Write(exprtree6.Dump.TrimEnd)
End Sub
End Class
Module Form1
Sub Main()
Dim inst As New TestClass()
inst.Test()
End Sub
End Module
]]></file>
</compilation>
Dim expected = <![CDATA[-=-=-=-=-=-=-=-=- Nothing -> Date -=-=-=-=-=-=-=-=-
Lambda(
body {
Constant(
1/1/0001 12:00:00 AM
type: System.DateTime
)
}
return type: System.DateTime
type: System.Func`1[System.DateTime]
)
-=-=-=-=-=-=-=-=- CType(Nothing, Date) -> Date -=-=-=-=-=-=-=-=-
Lambda(
body {
Constant(
1/1/0001 12:00:00 AM
type: System.DateTime
)
}
return type: System.DateTime
type: System.Func`1[System.DateTime]
)
-=-=-=-=-=-=-=-=- DirectCast(Nothing, Date) -> Date -=-=-=-=-=-=-=-=-
Lambda(
body {
Constant(
1/1/0001 12:00:00 AM
type: System.DateTime
)
}
return type: System.DateTime
type: System.Func`1[System.DateTime]
)
-=-=-=-=-=-=-=-=- Nothing -> Date? -=-=-=-=-=-=-=-=-
Lambda(
body {
Constant(
null
type: System.Nullable`1[System.DateTime]
)
}
return type: System.Nullable`1[System.DateTime]
type: System.Func`1[System.Nullable`1[System.DateTime]]
)
-=-=-=-=-=-=-=-=- CType(Nothing, Date?) -> Date? -=-=-=-=-=-=-=-=-
Lambda(
body {
Constant(
null
type: System.Nullable`1[System.DateTime]
)
}
return type: System.Nullable`1[System.DateTime]
type: System.Func`1[System.Nullable`1[System.DateTime]]
)
-=-=-=-=-=-=-=-=- DirectCast(Nothing, Date?) -> Date? -=-=-=-=-=-=-=-=-
Lambda(
body {
Constant(
null
type: System.Nullable`1[System.DateTime]
)
}
return type: System.Nullable`1[System.DateTime]
type: System.Func`1[System.Nullable`1[System.DateTime]]
)
]]>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
options:=TestOptions.ReleaseExe.WithOverflowChecks(True),
expectedOutput:=expected
)
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
options:=TestOptions.ReleaseExe.WithOverflowChecks(False),
expectedOutput:=expected
)
End Sub
<Fact()>
Public Sub TypeParameterConversions_Unchecked()
TestConversion_TypeParameters(False, ExpTreeTestResources.CheckedAndUncheckedTypeParameters)
End Sub
<Fact()>
Public Sub TypeParameterConversions_Checked()
TestConversion_TypeParameters(True, ExpTreeTestResources.CheckedAndUncheckedTypeParameters)
End Sub
<Fact()>
Public Sub TypeConversions_Unchecked_Std_DirectTrySpecialized()
TestConversion_TypeMatrix_Standard_DirectTrySpecialized(False, ExpTreeTestResources.UncheckedDirectTrySpecificConversions)
End Sub
<Fact()>
Public Sub TypeConversions_Checked_Std_DirectTrySpecialized()
TestConversion_TypeMatrix_Standard_DirectTrySpecialized(True, ExpTreeTestResources.CheckedDirectTrySpecificConversions)
End Sub
<Fact()>
Public Sub TypeConversions_Unchecked_Std_ImplicitAndCType()
TestConversion_TypeMatrix_Standard_ImplicitAndCType(False, ExpTreeTestResources.UncheckedCTypeAndImplicitConversionsEven, True)
TestConversion_TypeMatrix_Standard_ImplicitAndCType(False, ExpTreeTestResources.UncheckedCTypeAndImplicitConversionsOdd, False)
End Sub
<Fact()>
Public Sub TypeConversions_Checked_Std_ImplicitAndCType()
TestConversion_TypeMatrix_Standard_ImplicitAndCType(True, ExpTreeTestResources.CheckedCTypeAndImplicitConversionsEven, True)
TestConversion_TypeMatrix_Standard_ImplicitAndCType(True, ExpTreeTestResources.CheckedCTypeAndImplicitConversionsOdd, False)
End Sub
<Fact()>
Public Sub TypeConversions_Unchecked_UserTypes()
TestConversion_TypeMatrix_UserTypes(False, ExpTreeTestResources.CheckedAndUncheckedUserTypeConversions)
End Sub
<Fact()>
Public Sub TypeConversions_Checked_UserTypes()
TestConversion_TypeMatrix_UserTypes(True, ExpTreeTestResources.CheckedAndUncheckedUserTypeConversions)
End Sub
<Fact()>
Public Sub TypeConversions_Unchecked_Narrowing_UserDefinedConversions()
TestConversion_UserDefinedTypes_Narrowing(False, ExpTreeTestResources.CheckedAndUncheckedNarrowingUDC)
End Sub
<Fact()>
Public Sub TypeConversions_Checked_Narrowing_UserDefinedConversions()
TestConversion_UserDefinedTypes_Narrowing(True, ExpTreeTestResources.CheckedAndUncheckedNarrowingUDC)
End Sub
<Fact()>
Public Sub TypeConversions_Unchecked_Widening_UserDefinedConversions()
TestConversion_UserDefinedTypes_Widening(False, ExpTreeTestResources.CheckedAndUncheckedWideningUDC)
End Sub
<Fact()>
Public Sub TypeConversions_Checked_Widening_UserDefinedConversions()
TestConversion_UserDefinedTypes_Widening(True, ExpTreeTestResources.CheckedAndUncheckedWideningUDC)
End Sub
<Fact()>
Public Sub ExpressionTrees_UDC_NullableAndConversion()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Public Structure Type01
Public Shared Widening Operator CType(x As Integer) As Type01?
Return Nothing
End Operator
Public Shared Widening Operator CType(x As Double?) As Type01
Return Nothing
End Operator
End Structure
Public Structure Type02
Public Shared Widening Operator CType(x As Type02) As Integer?
Return Nothing
End Operator
End Structure
Public Structure Type03
Public Shared Widening Operator CType(x As Type03?) As Double
Return Nothing
End Operator
End Structure
Module Form1
Sub Main()
Console.WriteLine((DirectCast(Function(x) x, Expression(Of Func(Of SByte, Type01)))).Dump)
Console.WriteLine((DirectCast(Function(x) x, Expression(Of Func(Of Single, Type01)))).Dump)
Console.WriteLine((DirectCast(Function(x) x, Expression(Of Func(Of SByte?, Type01)))).Dump)
Console.WriteLine((DirectCast(Function(x) x, Expression(Of Func(Of Single?, Type01)))).Dump)
Console.WriteLine((DirectCast(Function(x) x, Expression(Of Func(Of SByte?, Type01?)))).Dump)
Console.WriteLine((DirectCast(Function(x) x, Expression(Of Func(Of Single, Type01?)))).Dump)
Console.WriteLine((DirectCast(Function(x) x, Expression(Of Func(Of Type02, SByte)))).Dump)
Console.WriteLine((DirectCast(Function(x) x, Expression(Of Func(Of Type03, Single)))).Dump)
Console.WriteLine((DirectCast(Function(x) x, Expression(Of Func(Of Type02, SByte?)))).Dump)
Console.WriteLine((DirectCast(Function(x) x, Expression(Of Func(Of Type03, Single?)))).Dump)
Console.WriteLine((DirectCast(Function(x) x, Expression(Of Func(Of Type02?, SByte?)))).Dump)
Console.WriteLine((DirectCast(Function(x) x, Expression(Of Func(Of Type03, Single)))).Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file, <![CDATA[
Lambda(
Parameter(
x
type: System.SByte
)
body {
Convert(
Convert(
Convert(
Parameter(
x
type: System.SByte
)
type: System.Double
)
method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double]
type: System.Nullable`1[System.Double]
)
method: Type01 op_Implicit(System.Nullable`1[System.Double]) in Type01
type: Type01
)
}
return type: Type01
type: System.Func`2[System.SByte,Type01]
)
Lambda(
Parameter(
x
type: System.Single
)
body {
Convert(
Convert(
Convert(
Parameter(
x
type: System.Single
)
type: System.Double
)
method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double]
type: System.Nullable`1[System.Double]
)
method: Type01 op_Implicit(System.Nullable`1[System.Double]) in Type01
type: Type01
)
}
return type: Type01
type: System.Func`2[System.Single,Type01]
)
Lambda(
Parameter(
x
type: System.Nullable`1[System.SByte]
)
body {
Convert(
Convert(
Parameter(
x
type: System.Nullable`1[System.SByte]
)
Lifted
LiftedToNull
type: System.Nullable`1[System.Double]
)
method: Type01 op_Implicit(System.Nullable`1[System.Double]) in Type01
type: Type01
)
}
return type: Type01
type: System.Func`2[System.Nullable`1[System.SByte],Type01]
)
Lambda(
Parameter(
x
type: System.Nullable`1[System.Single]
)
body {
Convert(
Convert(
Parameter(
x
type: System.Nullable`1[System.Single]
)
Lifted
LiftedToNull
type: System.Nullable`1[System.Double]
)
method: Type01 op_Implicit(System.Nullable`1[System.Double]) in Type01
type: Type01
)
}
return type: Type01
type: System.Func`2[System.Nullable`1[System.Single],Type01]
)
Lambda(
Parameter(
x
type: System.Nullable`1[System.SByte]
)
body {
Convert(
Convert(
Convert(
Parameter(
x
type: System.Nullable`1[System.SByte]
)
Lifted
LiftedToNull
type: System.Nullable`1[System.Double]
)
method: Type01 op_Implicit(System.Nullable`1[System.Double]) in Type01
type: Type01
)
Lifted
LiftedToNull
type: System.Nullable`1[Type01]
)
}
return type: System.Nullable`1[Type01]
type: System.Func`2[System.Nullable`1[System.SByte],System.Nullable`1[Type01]]
)
Lambda(
Parameter(
x
type: System.Single
)
body {
Convert(
Convert(
Convert(
Convert(
Parameter(
x
type: System.Single
)
type: System.Double
)
method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double]
type: System.Nullable`1[System.Double]
)
method: Type01 op_Implicit(System.Nullable`1[System.Double]) in Type01
type: Type01
)
Lifted
LiftedToNull
type: System.Nullable`1[Type01]
)
}
return type: System.Nullable`1[Type01]
type: System.Func`2[System.Single,System.Nullable`1[Type01]]
)
Lambda(
Parameter(
x
type: Type02
)
body {
ConvertChecked(
ConvertChecked(
ConvertChecked(
Parameter(
x
type: Type02
)
method: System.Nullable`1[System.Int32] op_Implicit(Type02) in Type02
type: System.Nullable`1[System.Int32]
)
method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32]
type: System.Int32
)
type: System.SByte
)
}
return type: System.SByte
type: System.Func`2[Type02,System.SByte]
)
Lambda(
Parameter(
x
type: Type03
)
body {
Convert(
Convert(
Convert(
Parameter(
x
type: Type03
)
Lifted
LiftedToNull
type: System.Nullable`1[Type03]
)
method: Double op_Implicit(System.Nullable`1[Type03]) in Type03
type: System.Double
)
type: System.Single
)
}
return type: System.Single
type: System.Func`2[Type03,System.Single]
)
Lambda(
Parameter(
x
type: Type02
)
body {
ConvertChecked(
ConvertChecked(
Parameter(
x
type: Type02
)
method: System.Nullable`1[System.Int32] op_Implicit(Type02) in Type02
type: System.Nullable`1[System.Int32]
)
Lifted
LiftedToNull
type: System.Nullable`1[System.SByte]
)
}
return type: System.Nullable`1[System.SByte]
type: System.Func`2[Type02,System.Nullable`1[System.SByte]]
)
Lambda(
Parameter(
x
type: Type03
)
body {
Convert(
Convert(
Convert(
Convert(
Parameter(
x
type: Type03
)
Lifted
LiftedToNull
type: System.Nullable`1[Type03]
)
method: Double op_Implicit(System.Nullable`1[Type03]) in Type03
type: System.Double
)
type: System.Single
)
method: System.Nullable`1[System.Single] op_Implicit(Single) in System.Nullable`1[System.Single]
type: System.Nullable`1[System.Single]
)
}
return type: System.Nullable`1[System.Single]
type: System.Func`2[Type03,System.Nullable`1[System.Single]]
)
Lambda(
Parameter(
x
type: System.Nullable`1[Type02]
)
body {
ConvertChecked(
ConvertChecked(
Convert(
Parameter(
x
type: System.Nullable`1[Type02]
)
Lifted
type: Type02
)
method: System.Nullable`1[System.Int32] op_Implicit(Type02) in Type02
type: System.Nullable`1[System.Int32]
)
Lifted
LiftedToNull
type: System.Nullable`1[System.SByte]
)
}
return type: System.Nullable`1[System.SByte]
type: System.Func`2[System.Nullable`1[Type02],System.Nullable`1[System.SByte]]
)
Lambda(
Parameter(
x
type: Type03
)
body {
Convert(
Convert(
Convert(
Parameter(
x
type: Type03
)
Lifted
LiftedToNull
type: System.Nullable`1[Type03]
)
method: Double op_Implicit(System.Nullable`1[Type03]) in Type03
type: System.Double
)
type: System.Single
)
}
return type: System.Single
type: System.Func`2[Type03,System.Single]
)
]]>)
End Sub
#Region "Conversions: User Defined Types"
Public Sub TestConversion_UserDefinedTypes_Narrowing(checked As Boolean, result As String)
'Dim tests As New List(Of ExpressionTreeTest)
'TestConversion_UserDefinedTypes_ClassClass(True, tests)
'TestConversion_UserDefinedTypes_ClassStruct(True, tests)
'TestConversion_UserDefinedTypes_StructClass(True, tests)
'TestConversion_UserDefinedTypes_StructStruct(True, tests)
'TestExpressionTrees(checked, result, tests.ToArray())
Dim source = <compilation>
<file name="a.vb">
<%= ExpTreeTestResources.TestConversion_Narrowing_UDC %>
</file>
<%= _exprTesting %>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
options:=TestOptions.ReleaseExe.WithOverflowChecks(checked),
expectedOutput:=result.Trim
).VerifyDiagnostics()
End Sub
Public Sub TestConversion_UserDefinedTypes_Widening(checked As Boolean, result As String)
'Dim tests As New List(Of ExpressionTreeTest)
'TestConversion_UserDefinedTypes_ClassClass(False, tests)
'TestConversion_UserDefinedTypes_ClassStruct(False, tests)
'TestConversion_UserDefinedTypes_StructClass(False, tests)
'TestConversion_UserDefinedTypes_StructStruct(False, tests)
'TestExpressionTrees(checked, result, tests.ToArray())
Dim source = <compilation>
<file name="a.vb">
<%= ExpTreeTestResources.TestConversion_Widening_UDC %>
</file>
<%= _exprTesting %>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
options:=TestOptions.ReleaseExe.WithOverflowChecks(checked),
expectedOutput:=result.Trim
).VerifyDiagnostics()
End Sub
#Region "Generation"
Private Class OperatorDescriptor
Public TypeFrom As String
Public TypeFromLifted As Boolean = False
Public TypeTo As String
Public TypeToLifted As Boolean = False
Public IsWidenning As Boolean
Public ReadOnly Property Keyword As String
Get
Return If(IsWidenning, "Widening", "Narrowing")
End Get
End Property
Public ReadOnly Property Code As String
Get
Dim builder As New StringBuilder
builder.AppendFormat(" Public Shared {2} Operator CType(x As {0}{3}) As {1}{4}",
TypeFrom, TypeTo, Keyword,
If(TypeFromLifted, "?", ""),
If(TypeToLifted, "?", "")).AppendLine()
builder.AppendLine(" Return Nothing")
builder.AppendLine(" End Operator")
Return builder.ToString()
End Get
End Property
Public Function AssignTypes(typeFrom As String, typeTo As String) As String
Me.TypeFrom = typeFrom
Me.TypeTo = typeTo
Return String.Format("{1}{3} -> {2}{4}", Keyword, Me.TypeFrom, Me.TypeTo,
If(TypeFromLifted, "?", ""), If(TypeToLifted, "?", ""))
End Function
End Class
Private Class TypeDescriptor
Public Type As String = ""
Public IsStructure As Boolean
Private ReadOnly _operators As New List(Of OperatorDescriptor)
Public Function WithOperators(ParamArray ops() As OperatorDescriptor) As TypeDescriptor
_operators.Clear()
_operators.AddRange(ops)
Return Me
End Function
Public ReadOnly Property Keyword As String
Get
Return If(IsStructure, "Structure", "Class")
End Get
End Property
Public ReadOnly Property Code As String
Get
Dim builder As New StringBuilder
builder.AppendFormat("Public {0} {1}", Keyword, Type)
builder.AppendLine()
For Each op In _operators
builder.Append(op.Code)
Next
builder.AppendFormat("End {0}", Keyword)
builder.AppendLine()
Return builder.ToString()
End Get
End Property
Public Function AssignTypes(type As String, typeFrom As String, typeTo As String) As String
Dim builder As New StringBuilder
Me.Type = type
builder.Append(Keyword).Append(" ").Append(Me.Type).Append("{")
For i = 0 To _operators.Count - 1
builder.Append(If(i > 0, ", ", "")).Append(_operators(i).AssignTypes(typeFrom, typeTo))
Next
builder.Append("}")
Return builder.ToString()
End Function
End Class
Private Sub TestConversion_UserDefinedTypes_StructStruct(isNarrowing As Boolean, list As List(Of ExpressionTreeTest))
Dim type1 As New TypeDescriptor With {.IsStructure = True}
Dim type2 As New TypeDescriptor With {.IsStructure = True}
Dim ops = {New OperatorDescriptor With {.IsWidenning = Not isNarrowing},
New OperatorDescriptor With {.IsWidenning = Not isNarrowing, .TypeToLifted = True},
New OperatorDescriptor With {.IsWidenning = Not isNarrowing, .TypeFromLifted = True},
New OperatorDescriptor With {.IsWidenning = Not isNarrowing, .TypeFromLifted = True, .TypeToLifted = True}}
For i = 0 To ops.Count - 1
TestConversion_UserDefinedTypes_OneOp(isNarrowing, type1, type2, ops(i), list)
For j = i + 1 To ops.Count - 1
TestConversion_UserDefinedTypes_TwoOps(isNarrowing, type1, type2, ops(i), ops(j), list)
Next
Next
End Sub
Private Sub TestConversion_UserDefinedTypes_ClassStruct(isNarrowing As Boolean, list As List(Of ExpressionTreeTest))
TestConversion_UserDefinedTypes_TwoOps(isNarrowing,
New TypeDescriptor With {.IsStructure = False},
New TypeDescriptor With {.IsStructure = True},
New OperatorDescriptor With {.IsWidenning = Not isNarrowing},
New OperatorDescriptor With {.IsWidenning = Not isNarrowing, .TypeToLifted = True},
list)
End Sub
Private Sub TestConversion_UserDefinedTypes_StructClass(isNarrowing As Boolean, list As List(Of ExpressionTreeTest))
TestConversion_UserDefinedTypes_TwoOps(isNarrowing,
New TypeDescriptor With {.IsStructure = True},
New TypeDescriptor With {.IsStructure = False},
New OperatorDescriptor With {.IsWidenning = Not isNarrowing},
New OperatorDescriptor With {.IsWidenning = Not isNarrowing, .TypeFromLifted = True},
list)
End Sub
Private Sub TestConversion_UserDefinedTypes_ClassClass(isNarrowing As Boolean, list As List(Of ExpressionTreeTest))
TestConversion_UserDefinedTypes_OneOp(isNarrowing,
New TypeDescriptor With {.IsStructure = False},
New TypeDescriptor With {.IsStructure = False},
New OperatorDescriptor With {.IsWidenning = Not isNarrowing},
list)
End Sub
Private Sub TestConversion_UserDefinedTypes_TwoOps(isNarrowing As Boolean,
type1 As TypeDescriptor, type2 As TypeDescriptor,
op1 As OperatorDescriptor, op2 As OperatorDescriptor,
list As List(Of ExpressionTreeTest))
TestConversion_UserDefinedTypes_TypeType(type1.WithOperators(op1), type2.WithOperators(), isNarrowing, list)
TestConversion_UserDefinedTypes_TypeType(type1.WithOperators(), type2.WithOperators(op1), isNarrowing, list)
TestConversion_UserDefinedTypes_TypeType(type1.WithOperators(op2), type2.WithOperators(), isNarrowing, list)
TestConversion_UserDefinedTypes_TypeType(type1.WithOperators(), type2.WithOperators(op2), isNarrowing, list)
TestConversion_UserDefinedTypes_TypeType(type1.WithOperators(op1, op2), type2.WithOperators(), isNarrowing, list)
TestConversion_UserDefinedTypes_TypeType(type1.WithOperators(op1), type2.WithOperators(op2), isNarrowing, list)
TestConversion_UserDefinedTypes_TypeType(type1.WithOperators(), type2.WithOperators(op1, op2), isNarrowing, list)
End Sub
Private Sub TestConversion_UserDefinedTypes_OneOp(isNarrowing As Boolean,
type1 As TypeDescriptor, type2 As TypeDescriptor,
op As OperatorDescriptor, list As List(Of ExpressionTreeTest))
TestConversion_UserDefinedTypes_TypeType(type1.WithOperators(op), type2.WithOperators(), isNarrowing, list)
TestConversion_UserDefinedTypes_TypeType(type1.WithOperators(), type2.WithOperators(op), isNarrowing, list)
End Sub
Private Sub TestConversion_UserDefinedTypes_TypeType(type1 As TypeDescriptor, type2 As TypeDescriptor, isNarrowing As Boolean, list As List(Of ExpressionTreeTest))
Dim index = list.Count
Dim typeFrom = "From" + index.ToString()
Dim typeTo = "To" + index.ToString()
Dim typeFromDescr = type1.AssignTypes(typeFrom, typeFrom, typeTo)
Dim typeToDescr = type2.AssignTypes(typeTo, typeFrom, typeTo)
For Each typeFromInstance In If(type1.IsStructure, {typeFrom, typeFrom & "?"}, {typeFrom})
For Each typeToInstance In If(type2.IsStructure, {typeTo, typeTo & "?"}, {typeTo})
TestConversion_UserDefinedTypes_OneTest(typeFromDescr, typeToDescr, typeFromInstance, typeToInstance, isNarrowing, list)
Next
Next
list(index).Prefix = <![CDATA[]]>
list(index).Prefix.Value = type1.Code & type2.Code
End Sub
Private Sub TestConversion_UserDefinedTypes_OneTest(typeFromDescr As String, typeToDescr As String,
typeFrom As String, typeTo As String,
isNarrowing As Boolean, list As List(Of ExpressionTreeTest))
Dim description = If(isNarrowing,
String.Format("-=-=-=-=-=-=-=-=- CType({0}, {1}) for {2} and {3} -=-=-=-=-=-=-=-=-",
typeFrom, typeTo, typeFromDescr, typeToDescr),
String.Format("-=-=-=-=-=-=-=-=- implicit {0} -> {1} for {2} and {3} -=-=-=-=-=-=-=-=-",
typeFrom, typeTo, typeFromDescr, typeToDescr))
Dim opPattern = If(isNarrowing, ("CType({0}, " & typeTo & ")"), "{0}")
list.Add(New ExpressionTreeTest With {.Description = description,
.ExpressionTypeArgument = String.Format("Func(Of {0}, {1})", typeFrom, typeTo),
.Lambda = String.Format("Function(x As {0}) {1}", typeFrom, String.Format(opPattern, "x", typeTo))})
End Sub
#End Region
#End Region
#Region "Conversions: Type Matrix"
Public Sub TestConversion_TypeMatrix_UserTypes(checked As Boolean, result As String)
' Dim tests As New List(Of ExpressionTreeTest)
' For Each type1 In {"Object", "String", "Struct1", "Struct1?", "Clazz1", "Clazz2"}
' For Each type2 In {"Object", "String", "Struct1", "Struct1?", "Clazz1", "Clazz2"}
' TestConversion_TypeMatrix_Implicit(type1, type2, tests)
' TestConversion_TypeMatrix_CType(type1, type2, tests)
' TestConversion_TypeMatrix_DirectCast(type1, type2, tests)
' TestConversion_TypeMatrix_TryCast(type1, type2, tests)
' TestConversion_TypeMatrix_Specific(type1, type2, tests)
' Next
' Next
' tests(0).Prefix = <![CDATA[
'Public Class Clazz1
'End Class
'Public Class Clazz2
' Inherits Clazz1
'End Class
'Public Structure Struct1
'End Structure
']]>
' tests(0).Prefix.Value = tests(0).Prefix.Value & vbLf & EnumDeclarations.Value
' TestExpressionTrees(checked, result, tests.ToArray())
Dim source = <compilation>
<file name="a.vb">
<%= ExpTreeTestResources.TestConversion_TypeMatrix_UserTypes %>
</file>
<%= _exprTesting %>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
options:=TestOptions.ReleaseExe.WithOverflowChecks(checked),
expectedOutput:=result.Trim
).VerifyDiagnostics(Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"))
End Sub
Public Sub TestConversion_TypeMatrix_Standard_ImplicitAndCType(checked As Boolean, result As String, even As Boolean)
Dim tests As New List(Of ExpressionTreeTest)
' Primitive types
For Each type1 In _allTypes
Dim i As Integer = 0 ' Generate only calls to even or odd types from type2
For Each type2 In _allTypes
i += 1
If (i Mod 2) = If(even, 0, 1) Then
Dim isFloatingType = (type2 = "Single") OrElse (type2 = "Double")
Dim isEven = ((i >> 1) Mod 2) = 0
If isEven OrElse isFloatingType Then
TestConversion_TypeMatrix_Implicit(type1, type2, tests)
End If
If Not isEven OrElse isFloatingType Then
TestConversion_TypeMatrix_CType(type1, type2, tests)
End If
End If
Next
Next
tests(0).Prefix = s_enumDeclarations
TestExpressionTrees(checked, result, tests.ToArray())
End Sub
Public Sub TestConversion_TypeMatrix_Standard_DirectTrySpecialized(checked As Boolean, result As String)
Dim tests As New List(Of ExpressionTreeTest)
' Primitive types
For Each type1 In _allTypes
For Each type2 In _allTypes
TestConversion_TypeMatrix_DirectCast(type1, type2, tests)
TestConversion_TypeMatrix_TryCast(type1, type2, tests)
TestConversion_TypeMatrix_Specific(type1, type2, tests)
Next
Next
tests(0).Prefix = s_enumDeclarations
TestExpressionTrees(checked, result, tests.ToArray(),
diagnostics:={
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "x")})
End Sub
Private Function IsDateVersusPrimitive(type1 As String, type2 As String) As Boolean
Return type1 <> type2 AndAlso
((type2 = "Date" OrElse type2 = "Date?") AndAlso IsPrimitiveStructType(type1) OrElse
(type1 = "Date" OrElse type1 = "Date?") AndAlso IsPrimitiveStructType(type2))
End Function
Private Sub TestConversion_TypeMatrix_Implicit(type1 As String, type2 As String, list As List(Of ExpressionTreeTest))
If IsDateVersusPrimitive(type1, type2) Then
Return
End If
TestConversion_TwoTypesAndExpression(type1, type2, "{0}", list)
End Sub
Private Sub TestConversion_TypeMatrix_CType(type1 As String, type2 As String, list As List(Of ExpressionTreeTest))
If IsDateVersusPrimitive(type1, type2) Then
Return
End If
TestConversion_TwoTypesAndExpression(type1, type2, "CType({0}, {1})", list)
End Sub
Private Sub TestConversion_TypeMatrix_DirectCast(type1 As String, type2 As String, list As List(Of ExpressionTreeTest))
If IsPrimitiveStructType(type1) Then
If Not IsPrimitiveStructType(type1) OrElse (type1 = type2 AndAlso type1 <> "Single" AndAlso type1 <> "Double") Then
TestConversion_TwoTypesAndExpression(type1, type2, "DirectCast({0}, {1})", list)
End If
ElseIf type1 = "String" Then
If Not IsPrimitiveStructType(type2) Then
TestConversion_TwoTypesAndExpression(type1, type2, "DirectCast({0}, {1})", list)
End If
Else
TestConversion_TwoTypesAndExpression(type1, type2, "DirectCast({0}, {1})", list)
End If
End Sub
Private Sub TestConversion_TypeMatrix_TryCast(type1 As String, type2 As String, list As List(Of ExpressionTreeTest))
Select Case type2
Case "Struct1", "Struct1?"
lNothing:
' Nothing
Case "String"
If IsPrimitiveStructType(type1) Then
GoTo lNothing
End If
Case Else
If IsPrimitiveStructType(type2) Then
GoTo lNothing
End If
TestConversion_TwoTypesAndExpression(type1, type2, "TryCast({0}, {1})", list)
End Select
End Sub
Private Sub TestConversion_TypeMatrix_Specific(type1 As String, type2 As String, list As List(Of ExpressionTreeTest))
Select Case type2
Case "Boolean"
If type1.StartsWith("Date", StringComparison.Ordinal) Then
GoTo lNothing
End If
TestConversion_TwoTypesAndExpression(type1, type2, "CBool({0})", list)
Case "Byte"
If type1.StartsWith("Date", StringComparison.Ordinal) Then
GoTo lNothing
End If
TestConversion_TwoTypesAndExpression(type1, type2, "CByte({0})", list)
Case "Char"
TestConversion_TwoTypesAndExpression(type1, type2, "CChar({0})", list)
Case "Date"
If IsPrimitiveStructType(type1) Then
GoTo lNothing
End If
TestConversion_TwoTypesAndExpression(type1, type2, "CDate({0})", list)
Case "Double"
If type1.StartsWith("Date", StringComparison.Ordinal) Then
GoTo lNothing
End If
TestConversion_TwoTypesAndExpression(type1, type2, "CDbl({0})", list)
Case "Decimal"
If type1.StartsWith("Date", StringComparison.Ordinal) Then
GoTo lNothing
End If
TestConversion_TwoTypesAndExpression(type1, type2, "CDec({0})", list)
Case "Integer"
If type1.StartsWith("Date", StringComparison.Ordinal) Then
GoTo lNothing
End If
TestConversion_TwoTypesAndExpression(type1, type2, "CInt({0})", list)
Case "Long"
If type1.StartsWith("Date", StringComparison.Ordinal) Then
GoTo lNothing
End If
TestConversion_TwoTypesAndExpression(type1, type2, "CLng({0})", list)
Case "Object"
TestConversion_TwoTypesAndExpression(type1, type2, "CObj({0})", list)
Case "Short"
If type1.StartsWith("Date", StringComparison.Ordinal) Then
GoTo lNothing
End If
TestConversion_TwoTypesAndExpression(type1, type2, "CShort({0})", list)
Case "Single"
If type1.StartsWith("Date", StringComparison.Ordinal) Then
GoTo lNothing
End If
TestConversion_TwoTypesAndExpression(type1, type2, "CSng({0})", list)
Case "String"
TestConversion_TwoTypesAndExpression(type1, type2, "CStr({0})", list)
Case Else
lNothing:
' Nothing
End Select
End Sub
#End Region
#Region "Conversions: Type Parameters"
Public Sub TestConversion_TypeParameters(checked As Boolean, result As String)
Dim tests As New List(Of ExpressionTreeTest)
Dim typeParameters = "(Of T, O As Clazz1, S As Structure, D As {Class, O})"
Dim typeArguments = "(Of Object, Clazz1, Struct1, Clazz2)"
' Type Parameters <--> Type Parameter
TestConversion_TypeParameters("O", "D", tests)
TestConversion_TypeParameters("D", "O", tests)
' Type parameter -> Type
For Each type1 In {"T", "S", "S?", "O", "D"}
TestConversion_TypeParameters(type1, "Object", tests)
Next
TestConversion_TypeParameters("O", "Clazz1", tests)
TestConversion_TwoTypesAndExpression("O", "Clazz2", "TryCast({0}, {1})", tests)
TestConversion_TypeParameters("D", "Clazz1", tests)
TestConversion_TwoTypesAndExpression("D", "Clazz2", "TryCast({0}, {1})", tests)
' Type -> Type parameter
For Each type1 In {"T", "S", "S?", "O", "D"}
TestConversion_TypeParameters(type1, "Object", tests)
Next
TestConversion_TypeParameters("Object", "T", tests, False)
TestConversion_TypeParameters("Object", "O", tests)
TestConversion_TypeParameters("Clazz1", "O", tests)
TestConversion_TwoTypesAndExpression("Clazz2", "O", "TryCast({0}, {1})", tests)
TestConversion_TypeParameters("Object", "D", tests)
TestConversion_TypeParameters("Clazz1", "D", tests)
TestConversion_TwoTypesAndExpression("Clazz2", "D", "TryCast({0}, {1})", tests)
' Nothing -> Type parameter
For Each type1 In {"T", "S", "S?", "O", "D"}
TestConversion_TwoTypesAndExpression("Object", type1, "Nothing", tests)
TestConversion_TwoTypesAndExpression("Object", type1, "CType(Nothing, {1})", tests)
TestConversion_TwoTypesAndExpression("Object", type1, "DirectCast(Nothing, {1})", tests)
If type1 = "O" OrElse type1 = "D" Then
TestConversion_TwoTypesAndExpression("Object", type1, "TryCast(Nothing, {1})", tests)
End If
Next
tests(0).Prefix = <![CDATA[
Public Class Clazz1
End Class
Public Class Clazz2
Inherits Clazz1
End Class
Public Structure Struct1
End Structure
]]>
tests(0).Prefix.Value = tests(0).Prefix.Value & vbLf & s_enumDeclarations.Value
TestExpressionTrees(checked, result, tests.ToArray(), typeParameters, typeArguments)
End Sub
Private Sub TestConversion_TypeParameters(type1 As String, type2 As String, list As List(Of ExpressionTreeTest), Optional useTryCast As Boolean = True)
TestConversion_TwoTypesAndExpression(type1, type2, "{0}", list)
TestConversion_TwoTypesAndExpression(type1, type2, "CType({0}, {1})", list)
TestConversion_TwoTypesAndExpression(type1, type2, "DirectCast({0}, {1})", list)
If useTryCast Then
TestConversion_TwoTypesAndExpression(type1, type2, "TryCast({0}, {1})", list)
End If
End Sub
Private Sub TestConversion_TwoTypesAndExpression(type1 As String, type2 As String, pattern As String, list As List(Of ExpressionTreeTest))
list.Add(New ExpressionTreeTest With {.Description =
String.Format("-=-=-=-=-=-=-=-=- {0} -> {1} -=-=-=-=-=-=-=-=-",
String.Format(pattern, type1, type2), type2),
.ExpressionTypeArgument =
String.Format("Func(Of {0}, {1})", type1, type2),
.Lambda = String.Format("Function(x As {0}) {1}",
type1, String.Format(pattern, "x", type2))})
End Sub
#End Region
#Region "Conversions: Nothing Literal"
Public Sub TestConversion_NothingLiteral(checked As Boolean, result As String)
Dim tests As New List(Of ExpressionTreeTest)
For Each type1 In _allTypesWithoutDate.Concat({"Clazz1", "Struct1", "Clazz2(Of Clazz1, String)", "Struct2(Of Struct1)"})
TestConversion_NothingLiteral(type1, "Nothing", tests)
TestConversion_NothingLiteral(type1, "CType(Nothing, " + type1 + ")", tests)
TestConversion_NothingLiteral(type1, "DirectCast(Nothing, " + type1 + ")", tests)
Next
For Each type1 In {"String", "Object", "Clazz1", "Clazz2(Of Clazz1, String)"}
TestConversion_NothingLiteral(type1, "TryCast(Nothing, " + type1 + ")", tests)
Next
tests(0).Prefix = <![CDATA[
Class Clazz1
End Class
Class Clazz2(Of T, U)
End Class
Structure Struct1
End Structure
Structure Struct2(Of T)
End Structure
]]>
tests(0).Prefix.Value = tests(0).Prefix.Value & vbLf & s_enumDeclarations.Value
TestExpressionTrees(checked, result, tests.ToArray())
End Sub
Private Sub TestConversion_NothingLiteral(type As String, nothingLiteral As String, list As List(Of ExpressionTreeTest))
Dim descr1 = String.Format("-=-=-=-=-=-=-=-=- {0} -> {{0}} -=-=-=-=-=-=-=-=-", nothingLiteral)
list.Add(New ExpressionTreeTest With {.Description = String.Format(descr1, type),
.ExpressionTypeArgument =
String.Format("Func(Of {0})", type),
.Lambda = String.Format("Function() {0}", nothingLiteral)})
End Sub
#End Region
#End Region
#Region "Operators Test Utils"
Private Sub VerifyExpressionTreesDiagnostics(sourceFile As XElement, diagnostics As XElement,
Optional checked As Boolean = True,
Optional optimize As Boolean = True,
Optional addXmlReferences As Boolean = False)
Dim compilation =
CompilationUtils.CreateCompilationWithReferences(
<compilation>
<%= sourceFile %>
<%= _exprTesting %>
<%= _queryTesting %>
</compilation>,
references:=If(addXmlReferences, DefaultReferences.Concat(XmlReferences), DefaultReferences),
options:=If(optimize, TestOptions.ReleaseDll, TestOptions.DebugDll).WithOverflowChecks(checked))
CompilationUtils.AssertTheseDiagnostics(compilation, diagnostics)
End Sub
Private Function TestExpressionTreesVerifier(sourceFile As XElement, result As String,
Optional checked As Boolean = True,
Optional optimize As Boolean = True,
Optional latestReferences As Boolean = False,
Optional addXmlReferences As Boolean = False) As CompilationVerifier
Debug.Assert(Not latestReferences OrElse Not addXmlReferences) ' NYI
Return CompileAndVerify(
<compilation>
<%= sourceFile %>
<%= _exprTesting %>
<%= _queryTesting %>
</compilation>,
options:=If(optimize, TestOptions.ReleaseExe, TestOptions.DebugExe).WithOverflowChecks(checked),
expectedOutput:=If(result IsNot Nothing, result.Trim, Nothing),
additionalRefs:=If(addXmlReferences, XmlReferences, {}),
useLatestFramework:=latestReferences)
End Function
Private Sub TestExpressionTrees(sourceFile As XElement, result As String,
Optional checked As Boolean = True,
Optional optimize As Boolean = True,
Optional latestReferences As Boolean = False,
Optional addXmlReferences As Boolean = False,
Optional diagnostics() As DiagnosticDescription = Nothing)
TestExpressionTreesVerifier(sourceFile, result, checked, optimize, latestReferences, addXmlReferences).VerifyDiagnostics(If(diagnostics, {}))
End Sub
Private Sub TestExpressionTrees(sourceFile As XElement, result As XCData,
Optional checked As Boolean = True,
Optional optimize As Boolean = True,
Optional latestReferences As Boolean = False,
Optional addXmlReferences As Boolean = False,
Optional diagnostics() As DiagnosticDescription = Nothing)
TestExpressionTrees(sourceFile, result.Value.Replace(vbLf, vbCrLf), checked, optimize, latestReferences, addXmlReferences, diagnostics)
End Sub
Private Class ExpressionTreeTest
Public Description As String
Public ExpressionTypeArgument As String
Public Lambda As String
Public Prefix As XCData
End Class
Private Sub TestExpressionTrees(checked As Boolean, result As String, tests() As ExpressionTreeTest,
Optional typeParameters As String = "",
Optional typeArguments As String = "",
Optional diagnostics() As DiagnosticDescription = Nothing)
Dim prefixbuilder As New StringBuilder
Dim testbuilder As New StringBuilder
Dim procIndex As Integer = 0
Dim count As Integer = 0
For Each tst In tests
count += 1
Debug.Assert(tst.Description IsNot Nothing)
Debug.Assert(tst.ExpressionTypeArgument IsNot Nothing)
Debug.Assert(tst.Lambda IsNot Nothing)
If tst.Prefix IsNot Nothing Then
prefixbuilder.AppendLine()
prefixbuilder.AppendLine(tst.Prefix.Value)
End If
testbuilder.AppendLine(String.Format("Console.WriteLine(""{0}"")", tst.Description))
testbuilder.AppendLine(String.Format("Dim exprtree{0} As Expression(Of {1}) = {2}", count, tst.ExpressionTypeArgument, tst.Lambda))
testbuilder.AppendLine(String.Format("Console.WriteLine(exprtree{0}.Dump)", count))
Next
Dim source = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Linq.Expressions
{0}
Public Class TestClass{2}
Public Sub Test()
{1}
End Sub
End Class
Module Form1
Sub Main()
Dim inst As New TestClass{3}()
inst.Test()
End Sub
End Module
]]></file>
<%= _exprTesting %>
</compilation>
source...<file>.Value = String.Format(source...<file>.Value,
prefixbuilder.ToString(),
testbuilder.ToString(),
typeParameters,
typeArguments)
Dim src = source...<file>.Value
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
options:=TestOptions.ReleaseExe.WithOverflowChecks(checked),
expectedOutput:=result.Trim
).VerifyDiagnostics(If(diagnostics, {}))
End Sub
Private Shared ReadOnly s_enumDeclarations As XCData = <![CDATA[
Public Enum E_Byte As Byte : Dummy : End Enum
Public Enum E_SByte As SByte : Dummy : End Enum
Public Enum E_UShort As UShort : Dummy : End Enum
Public Enum E_Short As Short : Dummy : End Enum
Public Enum E_UInteger As UInteger : Dummy : End Enum
Public Enum E_Integer As Integer : Dummy : End Enum
Public Enum E_ULong As ULong : Dummy : End Enum
Public Enum E_Long As Long : Dummy : End Enum
]]>
Private ReadOnly _allTypes() As String =
{
"SByte", "SByte?", GetEnumTypeName("SByte"), GetEnumTypeName("SByte") + "?",
"Byte", "Byte?", GetEnumTypeName("Byte"), GetEnumTypeName("Byte") + "?",
"Short", "Short?", GetEnumTypeName("Short"), GetEnumTypeName("Short") + "?",
"UShort", "UShort?", GetEnumTypeName("UShort"), GetEnumTypeName("UShort") + "?",
"Integer", "Integer?", GetEnumTypeName("Integer"), GetEnumTypeName("Integer") + "?",
"UInteger", "UInteger?", GetEnumTypeName("UInteger"), GetEnumTypeName("UInteger") + "?",
"Long", "Long?", GetEnumTypeName("Long"), GetEnumTypeName("Long") + "?",
"Boolean", "Boolean?",
"Single", "Single?",
"Double", "Double?",
"Decimal", "Decimal?",
"Date", "Date?",
"String",
"Object"
}
Private ReadOnly _allTypesWithoutDate() As String =
{
"SByte", "SByte?", GetEnumTypeName("SByte"), GetEnumTypeName("SByte") + "?",
"Byte", "Byte?", GetEnumTypeName("Byte"), GetEnumTypeName("Byte") + "?",
"Short", "Short?", GetEnumTypeName("Short"), GetEnumTypeName("Short") + "?",
"UShort", "UShort?", GetEnumTypeName("UShort"), GetEnumTypeName("UShort") + "?",
"Integer", "Integer?", GetEnumTypeName("Integer"), GetEnumTypeName("Integer") + "?",
"UInteger", "UInteger?", GetEnumTypeName("UInteger"), GetEnumTypeName("UInteger") + "?",
"Long", "Long?", GetEnumTypeName("Long"), GetEnumTypeName("Long") + "?",
"Boolean", "Boolean?",
"Single", "Single?",
"Double", "Double?",
"Decimal", "Decimal?",
"String",
"Object"
}
Private Shared Function IsPrimitiveStructType(type As String) As Boolean
Select Case type
Case "SByte", "Byte", "SByte?", "Byte?", "E_SByte", "E_Byte", "E_SByte?", "E_Byte?",
"Short", "UShort", "Short?", "UShort?", "E_Short", "E_UShort", "E_Short?", "E_UShort?",
"Integer", "UInteger", "Integer?", "UInteger?", "E_Integer", "E_UInteger", "E_Integer?", "E_UInteger?",
"Long", "ULong", "Long?", "ULong?", "E_Long", "E_ULong", "E_Long?", "E_ULong?",
"Boolean", "Boolean?", "Decimal", "Decimal?", "Date", "Date?", "Double", "Double?", "Single", "Single?"
Return True
Case Else
Return False
End Select
End Function
Private Function GetEnumTypeName(type As String) As String
Return "E_" & type
End Function
#End Region
#Region "Lambdas"
<Fact, WorkItem(530883, "DevDiv")>
Public Sub ExpressionTreeParameterWithLambdaArgumentAndTypeInference()
Dim source = <compilation>
<file name="expr.vb"><![CDATA[
Option Strict Off
Imports System.Linq.Expressions
Friend Module LambdaParam05mod
Function Moo(Of T)(ByVal x As Expression(Of T)) As Integer
Return 5
End Function
Sub LambdaParam05()
Dim ret = Moo(Function(v, w, x, y, z) z)
End Sub
End Module
]]></file>
</compilation>
CompileAndVerify(source, additionalRefs:={SystemCoreRef}).VerifyDiagnostics()
End Sub
<Fact, WorkItem(577271, "DevDiv")>
Public Sub Bug577271()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict On
Imports System
Imports System.Linq.Expressions
Imports System.Linq.Enumerable
Imports System.Xml.Linq
Imports System.Xml
Module Program
Sub Main()
Dim x As Expression(Of Func(Of XElement)) = Function() <e a=<%= Sub() Return %>/>
Console.WriteLine(x)
End Sub
End Module
]]></file>
VerifyExpressionTreesDiagnostics(file,
<errors>
BC36675: Statement lambdas cannot be converted to expression trees.
Dim x As Expression(Of Func(Of XElement)) = Function() <e a=<%= Sub() Return %>/>
~~~~~~~~~~~~
</errors>, addXmlReferences:=True)
End Sub
<WorkItem(577272, "DevDiv")>
<Fact>
Public Sub Bug577272()
Dim file = <file name="expr.vb"><![CDATA[
Imports System.Linq.Expressions
Imports System
<Serializable()>
Public Structure AStruct
Public x As Byte
Public y As Byte
Public Overrides Function ToString() As String
Return x & "," & y
End Function
End Structure
Module Module1
Sub Main
Dim NOT_USED As Expression(Of Func(Of AStruct)) = Function() New AStruct() With {.y = 255}
Console.WriteLine(NOT_USED.Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file,
<![CDATA[
Lambda(
body {
MemberInit(
NewExpression(
New(
<.ctor>(
)
type: AStruct
)
)
bindings:
MemberAssignment(
member: Byte y
expression: {
Constant(
255
type: System.Byte
)
}
)
type: AStruct
)
}
return type: AStruct
type: System.Func`1[AStruct]
)
]]>)
End Sub
<Fact()>
Public Sub LambdaConversion1()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Friend Module Program
Sub Main()
Dim ret as Expression(Of Func(Of Func(Of Object, Object, Object, Object))) = Function() Function(v, w, z) z
Console.WriteLine(ret.Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file,
<![CDATA[
Lambda(
body {
Lambda(
Parameter(
v
type: System.Object
)
Parameter(
w
type: System.Object
)
Parameter(
z
type: System.Object
)
body {
Parameter(
z
type: System.Object
)
}
return type: System.Object
type: System.Func`4[System.Object,System.Object,System.Object,System.Object]
)
}
return type: System.Func`4[System.Object,System.Object,System.Object,System.Object]
type: System.Func`1[System.Func`4[System.Object,System.Object,System.Object,System.Object]]
)
]]>)
End Sub
<Fact()>
Public Sub LambdaConversion2()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Friend Module Program
Sub Main()
Dim ret As Func(Of Expression(Of Func(Of Object, Object, Object, Object))) = Function() Function(v, w, z) z
Console.WriteLine(ret().Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file,
<![CDATA[
Lambda(
Parameter(
v
type: System.Object
)
Parameter(
w
type: System.Object
)
Parameter(
z
type: System.Object
)
body {
Parameter(
z
type: System.Object
)
}
return type: System.Object
type: System.Func`4[System.Object,System.Object,System.Object,System.Object]
)
]]>)
End Sub
<Fact()>
Public Sub LambdaConversion3()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Module Form1
Private Function Foo(p As Expression(Of Func(Of Object, Object))) As Expression(Of Func(Of Object, Object))
Return p
End Function
Public Sub Main()
Dim ret As Expression(Of Func(Of Object, Object, Object, Object)) = Function(x, y, z) Foo(Function() Function(w) w)
Console.WriteLine(ret.Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file,
<![CDATA[
Lambda(
Parameter(
x
type: System.Object
)
Parameter(
y
type: System.Object
)
Parameter(
z
type: System.Object
)
body {
Convert(
Call(
<NULL>
method: System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Object]] Foo(System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Object]]) in Form1 (
Quote(
Lambda(
Parameter(
a0
type: System.Object
)
body {
Invoke(
Lambda(
body {
Convert(
Lambda(
Parameter(
w
type: System.Object
)
body {
Parameter(
w
type: System.Object
)
}
return type: System.Object
type: VB$AnonymousDelegate_1`2[System.Object,System.Object]
)
type: System.Object
)
}
return type: System.Object
type: VB$AnonymousDelegate_0`1[System.Object]
)
(
)
type: System.Object
)
}
return type: System.Object
type: System.Func`2[System.Object,System.Object]
)
type: System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Object]]
)
)
type: System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Object]]
)
type: System.Object
)
}
return type: System.Object
type: System.Func`4[System.Object,System.Object,System.Object,System.Object]
)
]]>)
End Sub
<Fact()>
Public Sub LambdaConversion4()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Module Form1
Private Function Foo(p As Expression(Of Func(Of Object, Object))) As Expression(Of Func(Of Object, Object))
Return p
End Function
Public Sub Main()
Dim ret As Expression(Of Func(Of Object, Object, Object, Object)) = Function(x, y, z) Foo(Function(w) w)
Console.WriteLine(ret.Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file,
<![CDATA[
Lambda(
Parameter(
x
type: System.Object
)
Parameter(
y
type: System.Object
)
Parameter(
z
type: System.Object
)
body {
Convert(
Call(
<NULL>
method: System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Object]] Foo(System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Object]]) in Form1 (
Quote(
Lambda(
Parameter(
w
type: System.Object
)
body {
Parameter(
w
type: System.Object
)
}
return type: System.Object
type: System.Func`2[System.Object,System.Object]
)
type: System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Object]]
)
)
type: System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Object]]
)
type: System.Object
)
}
return type: System.Object
type: System.Func`4[System.Object,System.Object,System.Object,System.Object]
)
]]>)
End Sub
<Fact()>
Public Sub LambdaConversion5()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Module Form1
Private Function Foo(p As Expression(Of Func(Of Object, Func(Of Object, Object)))) As Func(Of Object, Object)
Return p.Compile.Invoke(Nothing)
End Function
Private Function Bar(p As Object) As Expression(Of Func(Of Object, Object))
Return p
End Function
Public Sub Main()
Dim ret As Expression(Of Func(Of Object, Object, Object, Object)) = Function(x, y, z) Foo(Function() AddressOf Bar)
Console.WriteLine(ret.Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file,
<![CDATA[
Lambda(
Parameter(
x
type: System.Object
)
Parameter(
y
type: System.Object
)
Parameter(
z
type: System.Object
)
body {
Convert(
Call(
<NULL>
method: System.Func`2[System.Object,System.Object] Foo(System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Func`2[System.Object,System.Object]]]) in Form1 (
Quote(
Lambda(
Parameter(
a0
type: System.Object
)
body {
Invoke(
Lambda(
body {
Convert(
Call(
<NULL>
method: System.Delegate CreateDelegate(System.Type, System.Object, System.Reflection.MethodInfo, Boolean) in System.Delegate (
Constant(
System.Func`2[System.Object,System.Object]
type: System.Type
)
Constant(
null
type: System.Object
)
Constant(
System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Object]] Bar(System.Object)
type: System.Reflection.MethodInfo
)
Constant(
False
type: System.Boolean
)
)
type: System.Delegate
)
type: System.Func`2[System.Object,System.Object]
)
}
return type: System.Func`2[System.Object,System.Object]
type: VB$AnonymousDelegate_0`1[System.Func`2[System.Object,System.Object]]
)
(
)
type: System.Func`2[System.Object,System.Object]
)
}
return type: System.Func`2[System.Object,System.Object]
type: System.Func`2[System.Object,System.Func`2[System.Object,System.Object]]
)
type: System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Func`2[System.Object,System.Object]]]
)
)
type: System.Func`2[System.Object,System.Object]
)
type: System.Object
)
}
return type: System.Object
type: System.Func`4[System.Object,System.Object,System.Object,System.Object]
)
]]>)
End Sub
<Fact()>
Public Sub LambdaConversion5_45()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Module Form1
Private Function Foo(p As Expression(Of Func(Of Object, Func(Of Object, Object)))) As Func(Of Object, Object)
Return p.Compile.Invoke(Nothing)
End Function
Private Function Bar(p As Object) As Expression(Of Func(Of Object, Object))
Return p
End Function
Public Sub Main()
Dim ret As Expression(Of Func(Of Object, Object, Object, Object)) = Function(x, y, z) Foo(Function() AddressOf Bar)
Console.WriteLine(ret.Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file,
<![CDATA[
Lambda(
Parameter(
x
type: System.Object
)
Parameter(
y
type: System.Object
)
Parameter(
z
type: System.Object
)
body {
Convert(
Call(
<NULL>
method: System.Func`2[System.Object,System.Object] Foo(System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Func`2[System.Object,System.Object]]]) in Form1 (
Quote(
Lambda(
Parameter(
a0
type: System.Object
)
body {
Invoke(
Lambda(
body {
Convert(
Call(
Constant(
System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Object]] Bar(System.Object)
type: System.Reflection.MethodInfo
)
method: System.Delegate CreateDelegate(System.Type, System.Object) in System.Reflection.MethodInfo (
Constant(
System.Func`2[System.Object,System.Object]
type: System.Type
)
Constant(
null
type: System.Object
)
)
type: System.Delegate
)
type: System.Func`2[System.Object,System.Object]
)
}
return type: System.Func`2[System.Object,System.Object]
type: VB$AnonymousDelegate_0`1[System.Func`2[System.Object,System.Object]]
)
(
)
type: System.Func`2[System.Object,System.Object]
)
}
return type: System.Func`2[System.Object,System.Object]
type: System.Func`2[System.Object,System.Func`2[System.Object,System.Object]]
)
type: System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Func`2[System.Object,System.Object]]]
)
)
type: System.Func`2[System.Object,System.Object]
)
type: System.Object
)
}
return type: System.Object
type: System.Func`4[System.Object,System.Object,System.Object,System.Object]
)
]]>, latestReferences:=True)
End Sub
<Fact()>
Public Sub LambdaConversion6()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Module Form1
Private Function Foo(p As Expression(Of Func(Of Object, Func(Of Object, Object)))) As Func(Of Object, Object)
Return p.Compile.Invoke(Nothing)
End Function
Public Sub Main()
Dim ret1 = DirectCast(Function(x, y, z) Foo(Function() Function(w) w), Expression(Of Func(Of Object, Object, Object, Object)))
Console.WriteLine(ret1.Dump)
Dim ret2 = TryCast(Function(x, y, z) Foo(Function() Function(w) w), Expression(Of Func(Of Object, Object, Object, Object)))
Console.WriteLine(ret2.Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file,
<![CDATA[
Lambda(
Parameter(
x
type: System.Object
)
Parameter(
y
type: System.Object
)
Parameter(
z
type: System.Object
)
body {
Convert(
Call(
<NULL>
method: System.Func`2[System.Object,System.Object] Foo(System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Func`2[System.Object,System.Object]]]) in Form1 (
Quote(
Lambda(
Parameter(
a0
type: System.Object
)
body {
Invoke(
Lambda(
body {
Lambda(
Parameter(
w
type: System.Object
)
body {
Parameter(
w
type: System.Object
)
}
return type: System.Object
type: System.Func`2[System.Object,System.Object]
)
}
return type: System.Func`2[System.Object,System.Object]
type: VB$AnonymousDelegate_0`1[System.Func`2[System.Object,System.Object]]
)
(
)
type: System.Func`2[System.Object,System.Object]
)
}
return type: System.Func`2[System.Object,System.Object]
type: System.Func`2[System.Object,System.Func`2[System.Object,System.Object]]
)
type: System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Func`2[System.Object,System.Object]]]
)
)
type: System.Func`2[System.Object,System.Object]
)
type: System.Object
)
}
return type: System.Object
type: System.Func`4[System.Object,System.Object,System.Object,System.Object]
)
Lambda(
Parameter(
x
type: System.Object
)
Parameter(
y
type: System.Object
)
Parameter(
z
type: System.Object
)
body {
Convert(
Call(
<NULL>
method: System.Func`2[System.Object,System.Object] Foo(System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Func`2[System.Object,System.Object]]]) in Form1 (
Quote(
Lambda(
Parameter(
a0
type: System.Object
)
body {
Invoke(
Lambda(
body {
Lambda(
Parameter(
w
type: System.Object
)
body {
Parameter(
w
type: System.Object
)
}
return type: System.Object
type: System.Func`2[System.Object,System.Object]
)
}
return type: System.Func`2[System.Object,System.Object]
type: VB$AnonymousDelegate_0`1[System.Func`2[System.Object,System.Object]]
)
(
)
type: System.Func`2[System.Object,System.Object]
)
}
return type: System.Func`2[System.Object,System.Object]
type: System.Func`2[System.Object,System.Func`2[System.Object,System.Object]]
)
type: System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Func`2[System.Object,System.Object]]]
)
)
type: System.Func`2[System.Object,System.Object]
)
type: System.Object
)
}
return type: System.Object
type: System.Func`4[System.Object,System.Object,System.Object,System.Object]
)
]]>)
End Sub
<Fact()>
Public Sub LambdaConversion7()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Module Form1
Private Function Foo(p As Expression(Of Func(Of Object, Object))) As Expression(Of Func(Of Object, Object))
Return p
End Function
Public Sub Main()
Dim a As Integer = 1
Dim b As Double = 2
Dim ret As Expression(Of Func(Of Object, Object, Object, Object)) = Function(x, y, z) Foo(Function(w) a + b + w)
Console.WriteLine(ret.Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file,
<![CDATA[
Lambda(
Parameter(
x
type: System.Object
)
Parameter(
y
type: System.Object
)
Parameter(
z
type: System.Object
)
body {
Convert(
Call(
<NULL>
method: System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Object]] Foo(System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Object]]) in Form1 (
Quote(
Lambda(
Parameter(
w
type: System.Object
)
body {
Add(
Convert(
Add(
Convert(
MemberAccess(
Constant(
Form1+_Closure$__1-0
type: Form1+_Closure$__1-0
)
-> $VB$Local_a
type: System.Int32
)
type: System.Double
)
MemberAccess(
Constant(
Form1+_Closure$__1-0
type: Form1+_Closure$__1-0
)
-> $VB$Local_b
type: System.Double
)
type: System.Double
)
type: System.Object
)
Parameter(
w
type: System.Object
)
method: System.Object AddObject(System.Object, System.Object) in Microsoft.VisualBasic.CompilerServices.Operators
type: System.Object
)
}
return type: System.Object
type: System.Func`2[System.Object,System.Object]
)
type: System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Object]]
)
)
type: System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Object]]
)
type: System.Object
)
}
return type: System.Object
type: System.Func`4[System.Object,System.Object,System.Object,System.Object]
)
]]>)
End Sub
#End Region
#Region "Xml Literals"
<Fact()>
Public Sub XmlLiteralsInExprLambda01()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Imports System.Linq.Enumerable
Imports System.Xml.Linq
Imports <xmlns="http://roslyn/default1">
Imports <xmlns:r1="http://roslyn">
Imports <xmlns:p="http://roslyn/p">
Imports <xmlns:q="http://roslyn/q">
Module Form1
Private Sub F(p As Expression(Of Func(Of Object)))
System.Console.WriteLine(p.Dump)
End Sub
Public Sub Main()
F(Function() <!-- comment -->)
F(Function() <?xml version="1.0"?><!-- A --><?p?><x><!-- B --><?q?></x><?r?><!-- C-->)
F(Function() <x a="1"><!-- B --><?q?></x>)
F(Function() <x a="1"/>)
F(Function() <x xmlns="http://roslyn/default2" a="2"/>)
F(Function() <p:x xmlns:p="http://roslyn/p4" a="4"/>)
F(Function() <x xmlns="http://roslyn/default5" xmlns:p="http://roslyn/p5" p:a="5"/>)
F(Function() <x a="0"/>)
F(Function() <p:x xmlns:p="http://roslyn/p3" a="3"/>)
Dim x = <a xmlns:r2="http://roslyn" r1:b="a.b"><b>1</b><r2:c>2</r2:c><c d="c.d">3</c><b>4</b><b/></a>
F(Function() <a xmlns:r2="http://roslyn" r1:b="a.b"><b>1</b><r2:c>2</r2:c><c d="c.d">3</c><b>4</b><b/></a>)
F(Function() x.<b>)
F(Function() x.<c>)
F(Function() x.<r1:c>)
F(Function() x.@r1:b)
F(Function() x.@xmlns:r2)
Dim f1 As XElement = <x xmlns="http://roslyn/p" a="a1" p:b="b1"/>
F(Function() <x xmlns="http://roslyn/p" a="a1" p:b="b1"/>)
F(Function() <p:x a="a1" q:b="b1"/>)
F(Function() f1.@<a>)
F(Function() f1.@<p:a>)
F(Function() f1.@<q:a>)
F(Function() f1.@<b>)
F(Function() f1.@<p:b>)
F(Function() f1.@<q:b>)
F(Function() <x/>.<xmlns>.Count())
F(Function() <x/>.@xmlns)
F(Function() <x xmlns="http://roslyn/default"/>.@xmlns)
F(Function() <x xmlns:p="http://roslyn/p"/>.@<xmlns:p>)
End Sub
End Module
]]></file>
TestExpressionTrees(file, ExpTreeTestResources.XmlLiteralsInExprLambda01_Result, addXmlReferences:=True)
End Sub
<Fact()>
Public Sub XmlLiteralsInExprLambda02()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Collections.Generic
Imports System.Linq.Expressions
Imports System.Xml.Linq
Imports <xmlns:p="http://roslyn/p">
Imports <xmlns:q="http://roslyn/q">
Imports <xmlns="http://roslyn/default">
Imports <xmlns:qq="">
Imports <xmlns:p1="http://roslyn/1">
Imports <xmlns:p2="http://roslyn/2">
Module Form1
Private Sub F(p As Expression(Of Func(Of Object)))
System.Console.WriteLine(p.Dump)
End Sub
Function FF(x As XElement) As XElement
Return x
End Function
Public Sub Main()
F(Function() DirectCast(<a><b c="1"/><b c="2"/></a>.<b>, IEnumerable(Of XElement)))
F(Function() DirectCast(<a><b><c>1</c></b><b><c>2</c></b></a>.<b>, IEnumerable(Of XElement)))
Dim P1 = <a><b c="1"/><b c="2"/></a>
F(Function() P1.<b>.@c)
Dim P2 As IEnumerable(Of XElement) = P1.<b>
F(Function() P2.@c)
Dim P3 = <a><b><c>1</c></b><b><c>2</c></b></a>
F(Function() P3.<b>.<c>)
Dim P4 As IEnumerable(Of XElement) = P1.<b>
F(Function() P4.<c>)
F(Function() <a><c>1</c><b><q:c>2</q:c><p3:c xmlns:p3="http://roslyn/p">3</p3:c></b><b><c>4</c><p5:c xmlns:p5="http://roslyn/p">5</p5:c></b></a>)
Dim P5 = <a><c>1</c><b><q:c>2</q:c><p3:c xmlns:p3="http://roslyn/p">3</p3:c></b><b><c>4</c><p5:c xmlns:p5="http://roslyn/p">5</p5:c></b></a>
F(Function() P5...<c>)
F(Function() P5...<b>...<p:c>)
F(Function() <pa:a xmlns:pa="http://roslyn"><pb:b xmlns:pb="http://roslyn"/><pa:c/><p:d/></pa:a>)
Dim P6 = <pa:a xmlns:pa="http://roslyn"><pb:b xmlns:pb="http://roslyn"/><pa:c/><p:d/></pa:a>
F(Function() P6.<p:b>)
F(Function() P6.<p:c>)
F(Function() P6.<p:d>)
F(Function() DirectCast(AddressOf <x a="b"/>.@a.ToString, Func(Of String)))
F(Function() <p:x><y/><qq:z/></p:x>)
Dim P7 As Object = <p:y/>
F(Function() <x><%= <p:y1/> %><%= <p:y2/> %><%= <q:y3/> %></x>)
F(Function() <x><%= P7 %></x>)
F(Function() <p:x><%= <<%= <q:y/> %>/> %></p:x>)
F(Function() <p:x><%= (Function() <y/>)() %></p:x>)
F(Function() <a><b><%= FF(<c><p1:d/></c>) %></b><b><%= FF(<c><p1:d/><p2:d/></c>) %></b></a>)
F(Function() <a><b xmlns:p1="http://roslyn/3"><%= FF(<c><p1:d/><p2:d/></c>) %></b><b xmlns:p2="http://roslyn/4"><%= FF(<c><p1:d/><p2:d/></c>) %></b></a>)
F(Function() <a xmlns:p1="http://roslyn/3"><b xmlns:p2="http://roslyn/4"><%= FF(<c><p1:d/><p2:d/></c>) %></b></a>)
End Sub
End Module
]]></file>
TestExpressionTrees(file, ExpTreeTestResources.XmlLiteralsInExprLambda02_Result, addXmlReferences:=True)
End Sub
<Fact()>
Public Sub XmlLiteralsInExprLambda03()
Dim file = <file name="expr.vb"><![CDATA[
imports System
Imports System.Xml.Linq
Imports System.Linq.Expressions
Imports <xmlns:p="http://roslyn/p">
Imports <xmlns:q="http://roslyn/q1">
Imports <xmlns:r="http://roslyn/r">
Imports <xmlns:s="http://roslyn/r">
Module Form1
Private Sub F(p As Expression(Of Func(Of Object)))
System.Console.WriteLine(p.Dump)
End Sub
Public Sub Main()
F(Function() <x><y><p:z q:a="b" r:c="d"/><%= N.F %></y></x>)
F(Function() <x <%= <p:y/> %>/>)
F(Function() <<%= <p:y/> %>/>)
F(Function() <?xml version="1.0"?><%= <p:y/> %>)
Dim F1 = <q:y/>
F(Function() <p:x><%= F1 %></p:x>)
F(Function() <p:x><%= F1 %></p:x>)
Dim F2 As String = "x"
F(Function() <<%= F2 %> <%= F2 %>="..."/>)
F(Function() <x a1="b1"/>)
F(Function() <x a2=<%= "b2" %>/>)
F(Function() <x a3=<%= 3 %>/>)
F(Function() <x a4=<%= Nothing %>/>)
F(Function() <r:h xmlns:r="http://roslyn"/>)
F(Function() <w w=<%= F2 %>/>)
F(Function() <x><%= F2 %></x>)
Dim F3 As XElement = <g/>
F(Function() <y><%= F3 %></y>)
Dim F4 As XElement = <y><%= F3 %></y>
F(Function() <z><%= F2 %><%= F3 %><%= F4 %></z>)
End Sub
End Module
Module N
Public F As Object = <p:z q:a="b" s:c="d"/>
End Module
]]></file>
TestExpressionTrees(file, ExpTreeTestResources.XmlLiteralsInExprLambda03_Result, addXmlReferences:=True)
End Sub
<WorkItem(545738, "DevDiv")>
<Fact()>
Public Sub Bug_14377b()
' Expression Trees: Xml literals NYI
Dim file = <file name="a.vb"><![CDATA[
imports System
Imports System.Linq.Expressions
Module Module1
Sub Main()
Dim val As String = "val"
apCompareLambdaToExpression(Function() <e1><%= val %></e1>, Function() <e1><%= val %></e1>)
End Sub
Public Sub apCompareLambdaToExpression(Of T)(ByVal func As Func(Of T), ByVal expr As Expression(Of Func(Of T)))
func()
Console.WriteLine(expr.Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file, <![CDATA[
Lambda(
body {
New(
Void .ctor(System.Xml.Linq.XName, System.Object)(
Call(
<NULL>
method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName (
Constant(
e1
type: System.String
)
Constant(
type: System.String
)
)
type: System.Xml.Linq.XName
)
Convert(
MemberAccess(
Constant(
Module1+_Closure$__0-0
type: Module1+_Closure$__0-0
)
-> $VB$Local_val
type: System.String
)
type: System.Object
)
)
type: System.Xml.Linq.XElement
)
}
return type: System.Xml.Linq.XElement
type: System.Func`1[System.Xml.Linq.XElement]
)]]>, addXmlReferences:=True)
End Sub
#End Region
#Region "Miscellaneous"
<Fact()>
Public Sub ExprTree_LegacyTests01()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Module Form1
Class Class1
End Class
Class Class2 : Inherits Class1
End Class
Delegate Sub DeleSub1(ByVal x As Integer)
Sub Sub1(ByVal x As Long)
End Sub
Delegate Function DeleFunc1(ByVal x As Class2) As Integer
Delegate Function DeleFunc2() As Decimal
Function Func1(ByVal x As Class1) As UShort
Return Nothing
End Function
Function Func2() As Boolean
Return Nothing
End Function
Function Func3(Optional ByVal x As Integer = 42) As Long
Return Nothing
End Function
Function Foo(ByVal ds As DeleSub1) As Boolean
Return Nothing
End Function
Sub Main()
Dim l1 As Expression(Of Func(Of DeleSub1)) = Function() CType(AddressOf Sub1, DeleSub1)
Console.WriteLine(l1.Dump)
Dim l2 As Expression(Of Func(Of DeleFunc1)) = Function() New DeleFunc1(AddressOf Func1)
Console.WriteLine(l2.Dump)
Dim l3 As Expression(Of Func(Of Boolean)) = Function() Foo(AddressOf Func2)
Console.WriteLine(l3.Dump)
Dim l4 As Expression(Of Func(Of DeleFunc2)) = Function() CType(AddressOf Func3, DeleFunc2)
Console.WriteLine(l4.Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file, <![CDATA[
Lambda(
body {
Lambda(
Parameter(
a0
type: System.Int32
)
body {
Call(
<NULL>
method: Void Sub1(Int64) in Form1 (
ConvertChecked(
Parameter(
a0
type: System.Int32
)
type: System.Int64
)
)
type: System.Void
)
}
return type: System.Void
type: Form1+DeleSub1
)
}
return type: Form1+DeleSub1
type: System.Func`1[Form1+DeleSub1]
)
Lambda(
body {
Lambda(
Parameter(
a0
type: Form1+Class2
)
body {
ConvertChecked(
Call(
<NULL>
method: UInt16 Func1(Class1) in Form1 (
Convert(
Parameter(
a0
type: Form1+Class2
)
type: Form1+Class1
)
)
type: System.UInt16
)
type: System.Int32
)
}
return type: System.Int32
type: Form1+DeleFunc1
)
}
return type: Form1+DeleFunc1
type: System.Func`1[Form1+DeleFunc1]
)
Lambda(
body {
Call(
<NULL>
method: Boolean Foo(DeleSub1) in Form1 (
Lambda(
Parameter(
a0
type: System.Int32
)
body {
Call(
<NULL>
method: Boolean Func2() in Form1 (
)
type: System.Boolean
)
}
return type: System.Void
type: Form1+DeleSub1
)
)
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`1[System.Boolean]
)
Lambda(
body {
Lambda(
body {
Convert(
Call(
<NULL>
method: Int64 Func3(Int32) in Form1 (
Constant(
42
type: System.Int32
)
)
type: System.Int64
)
method: System.Decimal op_Implicit(Int64) in System.Decimal
type: System.Decimal
)
}
return type: System.Decimal
type: Form1+DeleFunc2
)
}
return type: Form1+DeleFunc2
type: System.Func`1[Form1+DeleFunc2]
)]]>)
End Sub
<Fact()>
Public Sub ExprTree_LegacyTests02_v40()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Module Form1
Delegate Sub DeleSub(ByVal x As Integer)
Sub Sub1(ByVal x As Integer)
End Sub
Delegate Function DeleFunc(ByVal x As DeleSub) As Boolean
Class Class1
Function Func1(ByVal x As DeleSub) As Boolean
Return Nothing
End Function
End Class
<Runtime.CompilerServices.Extension()>
Function ExtensionMethod1(ByVal target As Class1, ByVal x As DeleSub) As Boolean
Return Nothing
End Function
Sub Main()
'Dim l1 As Expression(Of Func(Of DeleSub1)) = Function() CType(AddressOf Sub1, DeleSub1)
'Console.WriteLine(l1.Dump)
Dim queryObj As New QueryHelper(Of String)
Dim c1 As New Class1
Dim scenario1 = From s In queryObj Where New DeleSub(AddressOf Sub1) Is Nothing Select s
Dim scenario3 = From s In queryObj Where CType(AddressOf c1.Func1, DeleFunc) Is Nothing Select s
Dim d1 As New DeleSub(AddressOf Sub1)
Dim d2 As New DeleFunc(AddressOf c1.Func1)
Dim scenario4 = From s In queryObj Where d2(d1) Select s
Dim scenario5 = From s In queryObj Where d2.Invoke(d1) Select s
Dim callback As AsyncCallback = Nothing
Dim scenario6 = From s In queryObj Where d2.BeginInvoke(d1, callback, Nothing).IsCompleted Select s
Dim d3 = CType(AddressOf c1.ExtensionMethod1, DeleFunc)
Dim scenario7 = From s In queryObj Where CType(AddressOf c1.ExtensionMethod1, DeleFunc) Is Nothing Select s
Dim scenario8 = From s In queryObj Where d3(d1) Select s
End Sub
End Module
]]></file>
TestExpressionTrees(file, ExpTreeTestResources.ExprTree_LegacyTests02_v40_Result)
End Sub
<Fact()>
Public Sub ExprTree_LegacyTests02_v45()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Module Form1
Delegate Sub DeleSub(ByVal x As Integer)
Sub Sub1(ByVal x As Integer)
End Sub
Delegate Function DeleFunc(ByVal x As DeleSub) As Boolean
Class Class1
Function Func1(ByVal x As DeleSub) As Boolean
Return Nothing
End Function
End Class
<Runtime.CompilerServices.Extension()>
Function ExtensionMethod1(ByVal target As Class1, ByVal x As DeleSub) As Boolean
Return Nothing
End Function
Sub Main()
Dim queryObj As New QueryHelper(Of String)
Dim c1 As New Class1
Dim scenario1 = From s In queryObj Where New DeleSub(AddressOf Sub1) Is Nothing Select s
Dim scenario3 = From s In queryObj Where CType(AddressOf c1.Func1, DeleFunc) Is Nothing Select s
Dim d1 As New DeleSub(AddressOf Sub1)
Dim d2 As New DeleFunc(AddressOf c1.Func1)
Dim scenario4 = From s In queryObj Where d2(d1) Select s
Dim scenario5 = From s In queryObj Where d2.Invoke(d1) Select s
Dim callback As AsyncCallback = Nothing
Dim scenario6 = From s In queryObj Where d2.BeginInvoke(d1, callback, Nothing).IsCompleted Select s
Dim d3 = CType(AddressOf c1.ExtensionMethod1, DeleFunc)
Dim scenario7 = From s In queryObj Where CType(AddressOf c1.ExtensionMethod1, DeleFunc) Is Nothing Select s
Dim scenario8 = From s In queryObj Where d3(d1) Select s
End Sub
End Module
]]></file>
TestExpressionTrees(file, ExpTreeTestResources.ExprTree_LegacyTests02_v45_Result, latestReferences:=True)
End Sub
<Fact()>
Public Sub ExprTree_LegacyTests03()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Module Form1
Dim queryObj As New QueryHelper(Of String)
Class Class1
Const x As Integer = -3
ReadOnly y As ULong = 3
Function GetX() As Object
Return From s In queryObj Where x Select s
End Function
Function GetY() As Object
Return From s In queryObj Where y Select s
End Function
Function FooToTheX() As Object
Return From s In queryObj Where Foo(x) Select s
End Function
Function FooToTheY() As Object
Return From s In queryObj Where Foo(y) Select s
End Function
Function FooToTheLocal() As Object
Dim t As Integer = 1
Return From s In queryObj Where Foo(t) Select s
End Function
Function FooToTheLocalAndCopyBack() As Object
Dim t As String = "1"
Return From s In queryObj Where Foo(t) Select s
End Function
End Class
Function Foo(ByRef x As Integer) As Boolean
x = 42
Return Nothing
End Function
Sub Main()
Dim c1 As New Class1
c1.GetX()
c1.GetY()
c1.FooToTheX()
c1.FooToTheY()
c1.FooToTheLocal()
c1.FooToTheLocalAndCopyBack()
End Sub
End Module
]]></file>
TestExpressionTrees(file, <![CDATA[
Lambda(
Parameter(
s
type: System.String
)
body {
Constant(
True
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Convert(
MemberAccess(
Constant(
Form1+Class1
type: Form1+Class1
)
-> y
type: System.UInt64
)
method: Boolean ToBoolean(UInt64) in System.Convert
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Call(
<NULL>
method: Boolean Foo(Int32 ByRef) in Form1 (
Constant(
-3
type: System.Int32
)
)
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Call(
<NULL>
method: Boolean Foo(Int32 ByRef) in Form1 (
ConvertChecked(
MemberAccess(
Constant(
Form1+Class1
type: Form1+Class1
)
-> y
type: System.UInt64
)
type: System.Int32
)
)
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Call(
<NULL>
method: Boolean Foo(Int32 ByRef) in Form1 (
MemberAccess(
Constant(
Form1+Class1+_Closure$__7-0
type: Form1+Class1+_Closure$__7-0
)
-> $VB$Local_t
type: System.Int32
)
)
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Call(
<NULL>
method: Boolean Foo(Int32 ByRef) in Form1 (
ConvertChecked(
MemberAccess(
Constant(
Form1+Class1+_Closure$__8-0
type: Form1+Class1+_Closure$__8-0
)
-> $VB$Local_t
type: System.String
)
method: Int32 ToInteger(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions
type: System.Int32
)
)
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)]]>)
End Sub
<Fact()>
Public Sub ExprTree_LegacyTests04()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Option Explicit Off
Imports System
Module Form1
Dim queryObj As New QueryHelper(Of String)
Class Class1
End Class
Class Class2(Of T)
Shared Sub Scenario4()
Dim scenario4 = From s In queryObj Where GetType(Class2(Of T)) Is t3 Select s
End Sub
Shared Sub Scenario6()
Dim scenario6 = From s In queryObj Where GetType(T) Is t1 Select s
End Sub
End Class
Structure Struct1
Dim a
End Structure
Enum Enum1
a
End Enum
Sub Main()
Dim t1 = GetType(Integer)
Dim t2 = GetType(Class1)
Dim t3 = GetType(Nullable(Of IntPtr))
Dim scenario1 = From s In queryObj Where GetType(Integer) Is t1 Select s
Dim scenario2 = From s In queryObj Where GetType(Class1) Is t2 Select s
Dim scenario3 = From s In queryObj Where GetType(Nullable(Of IntPtr)) Is t3 Select s
Class2(Of String).Scenario4()
Dim scenario5 = From s In queryObj Where GetType(System.Void) Is t3 Select s
Class2(Of Integer).Scenario6()
Dim scenario7 = From s In queryObj Where GetType(Struct1) Is t3 Select s
Dim scenario8 = From s In queryObj Where GetType(Enum1) Is t3 Select s
End Sub
End Module
]]></file>
TestExpressionTrees(file, <![CDATA[
Lambda(
Parameter(
s
type: System.String
)
body {
Equal(
Convert(
Constant(
System.Int32
type: System.Type
)
type: System.Object
)
Convert(
MemberAccess(
Constant(
Form1+_Closure$__6-0
type: Form1+_Closure$__6-0
)
-> $VB$Local_t1
type: System.Type
)
type: System.Object
)
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Equal(
Convert(
Constant(
Form1+Class1
type: System.Type
)
type: System.Object
)
Convert(
MemberAccess(
Constant(
Form1+_Closure$__6-0
type: Form1+_Closure$__6-0
)
-> $VB$Local_t2
type: System.Type
)
type: System.Object
)
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Equal(
Convert(
Constant(
System.Nullable`1[System.IntPtr]
type: System.Type
)
type: System.Object
)
Convert(
MemberAccess(
Constant(
Form1+_Closure$__6-0
type: Form1+_Closure$__6-0
)
-> $VB$Local_t3
type: System.Type
)
type: System.Object
)
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Equal(
Convert(
Constant(
Form1+Class2`1[System.String]
type: System.Type
)
type: System.Object
)
MemberAccess(
Constant(
Form1+Class2`1+_Closure$__1-0[System.String]
type: Form1+Class2`1+_Closure$__1-0[System.String]
)
-> $VB$Local_t3
type: System.Object
)
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Equal(
Convert(
Constant(
System.Void
type: System.Type
)
type: System.Object
)
Convert(
MemberAccess(
Constant(
Form1+_Closure$__6-0
type: Form1+_Closure$__6-0
)
-> $VB$Local_t3
type: System.Type
)
type: System.Object
)
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Equal(
Convert(
Constant(
System.Int32
type: System.Type
)
type: System.Object
)
MemberAccess(
Constant(
Form1+Class2`1+_Closure$__2-0[System.Int32]
type: Form1+Class2`1+_Closure$__2-0[System.Int32]
)
-> $VB$Local_t1
type: System.Object
)
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Equal(
Convert(
Constant(
Form1+Struct1
type: System.Type
)
type: System.Object
)
Convert(
MemberAccess(
Constant(
Form1+_Closure$__6-0
type: Form1+_Closure$__6-0
)
-> $VB$Local_t3
type: System.Type
)
type: System.Object
)
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Equal(
Convert(
Constant(
Form1+Enum1
type: System.Type
)
type: System.Object
)
Convert(
MemberAccess(
Constant(
Form1+_Closure$__6-0
type: Form1+_Closure$__6-0
)
-> $VB$Local_t3
type: System.Type
)
type: System.Object
)
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)]]>, diagnostics:={
Diagnostic(ERRID.WRN_DefAsgUseNullRef, "t3").WithArguments("t3"),
Diagnostic(ERRID.WRN_DefAsgUseNullRef, "t1").WithArguments("t1")})
End Sub
<Fact()>
Public Sub ExprTree_LegacyTests05()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Option Explicit Off
Imports System
Imports System.Linq.Expressions
Module Form1
Dim queryObj As New QueryHelper(Of String)
Class Class1
Private x
Function GetMyClass() As Object
Return From s In queryObj Where MyClass.Bar() Select s
End Function
Function GetMe() As Object
Return From s In queryObj Where Me.x Select s
End Function
Function GetMyClassV() As Object
Return From s In queryObj Where MyClass.VBar() Select s
End Function
Function Bar() As Integer
Return Nothing
End Function
Overridable Function VBar() As Integer
Return Nothing
End Function
Function GetMyClassAsExpression() As Expression(Of Func(Of Integer))
Return Function() MyClass.Bar()
End Function
Function GetMyClassAsExpressionV() As Expression(Of Func(Of Integer))
Return Function() MyClass.VBar()
End Function
Function GetMyClassAddressOfAsExpressionV() As Expression(Of Func(Of Func(Of Integer)))
Return Function() AddressOf MyClass.VBar
End Function
End Class
Class Class2 : Inherits Class1
Overloads Function Bar() As Integer
Return Nothing
End Function
Function GetMyBase() As Object
Return From s In queryObj Where MyBase.Bar() Select s
End Function
Function GetMyBaseV() As Object
Return From s In queryObj Where MyBase.VBar() Select s
End Function
Function GetMyBaseAsExpression() As Expression(Of Func(Of Integer))
Return Function() MyBase.Bar()
End Function
Function GetMyBaseAsExpressionV() As Expression(Of Func(Of Integer))
Return Function() MyBase.VBar()
End Function
Function GetMyBaseAddressOfAsExpressionV() As Expression(Of Func(Of Func(Of Integer)))
Return Function() AddressOf MyBase.VBar
End Function
End Class
Sub Main()
Dim c1 As Class1 = New Class2
Dim c2 As New Class2
c1.GetMyClass()
c1.GetMyClassV()
c1.GetMe()
c2.GetMyBase()
c2.GetMyBaseV()
Dim l1 = c2.GetMyBaseAsExpression
Console.WriteLine(l1.Dump)
Dim l2 = c2.GetMyBaseAsExpressionV
Console.WriteLine(l2.Dump)
Dim l3 = c1.GetMyClassAsExpression
Console.WriteLine(l3.Dump)
Dim l4 = c1.GetMyClassAsExpressionV
Console.WriteLine(l4.Dump)
Dim l5 = c1.GetMyClassAddressOfAsExpressionV
Console.WriteLine(l5.Dump)
Dim l6 = c2.GetMyBaseAddressOfAsExpressionV
Console.WriteLine(l6.Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file, <![CDATA[
Lambda(
Parameter(
s
type: System.String
)
body {
Convert(
Call(
Constant(
Form1+Class2
type: Form1+Class1
)
method: Int32 $VB$ClosureStub_Bar_MyClass() in Form1+Class1 (
)
type: System.Int32
)
method: Boolean ToBoolean(Int32) in System.Convert
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Convert(
Call(
Constant(
Form1+Class2
type: Form1+Class1
)
method: Int32 $VB$ClosureStub_VBar_MyClass() in Form1+Class1 (
)
type: System.Int32
)
method: Boolean ToBoolean(Int32) in System.Convert
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Convert(
MemberAccess(
Constant(
Form1+Class2
type: Form1+Class1
)
-> x
type: System.Object
)
method: Boolean ToBoolean(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Convert(
Call(
Constant(
Form1+Class2
type: Form1+Class2
)
method: Int32 $VB$ClosureStub_Bar_MyBase() in Form1+Class2 (
)
type: System.Int32
)
method: Boolean ToBoolean(Int32) in System.Convert
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Convert(
Call(
Constant(
Form1+Class2
type: Form1+Class2
)
method: Int32 $VB$ClosureStub_VBar_MyBase() in Form1+Class2 (
)
type: System.Int32
)
method: Boolean ToBoolean(Int32) in System.Convert
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)
Lambda(
body {
Call(
Constant(
Form1+Class2
type: Form1+Class2
)
method: Int32 $VB$ClosureStub_Bar_MyBase() in Form1+Class2 (
)
type: System.Int32
)
}
return type: System.Int32
type: System.Func`1[System.Int32]
)
Lambda(
body {
Call(
Constant(
Form1+Class2
type: Form1+Class2
)
method: Int32 $VB$ClosureStub_VBar_MyBase() in Form1+Class2 (
)
type: System.Int32
)
}
return type: System.Int32
type: System.Func`1[System.Int32]
)
Lambda(
body {
Call(
Constant(
Form1+Class2
type: Form1+Class1
)
method: Int32 $VB$ClosureStub_Bar_MyClass() in Form1+Class1 (
)
type: System.Int32
)
}
return type: System.Int32
type: System.Func`1[System.Int32]
)
Lambda(
body {
Call(
Constant(
Form1+Class2
type: Form1+Class1
)
method: Int32 $VB$ClosureStub_VBar_MyClass() in Form1+Class1 (
)
type: System.Int32
)
}
return type: System.Int32
type: System.Func`1[System.Int32]
)
Lambda(
body {
Convert(
Call(
<NULL>
method: System.Delegate CreateDelegate(System.Type, System.Object, System.Reflection.MethodInfo, Boolean) in System.Delegate (
Constant(
System.Func`1[System.Int32]
type: System.Type
)
Convert(
Constant(
Form1+Class2
type: Form1+Class1
)
type: System.Object
)
Constant(
Int32 $VB$ClosureStub_VBar_MyClass()
type: System.Reflection.MethodInfo
)
Constant(
False
type: System.Boolean
)
)
type: System.Delegate
)
type: System.Func`1[System.Int32]
)
}
return type: System.Func`1[System.Int32]
type: System.Func`1[System.Func`1[System.Int32]]
)
Lambda(
body {
Convert(
Call(
<NULL>
method: System.Delegate CreateDelegate(System.Type, System.Object, System.Reflection.MethodInfo, Boolean) in System.Delegate (
Constant(
System.Func`1[System.Int32]
type: System.Type
)
Convert(
Constant(
Form1+Class2
type: Form1+Class2
)
type: System.Object
)
Constant(
Int32 $VB$ClosureStub_VBar_MyBase()
type: System.Reflection.MethodInfo
)
Constant(
False
type: System.Boolean
)
)
type: System.Delegate
)
type: System.Func`1[System.Int32]
)
}
return type: System.Func`1[System.Int32]
type: System.Func`1[System.Func`1[System.Int32]]
)]]>)
End Sub
<Fact()>
Public Sub ExprTree_LegacyTests06()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Option Explicit Off
Module Form1
Dim queryObj As New QueryHelper(Of String)
Function Foo(ByVal x As Integer) As String
Return Nothing
End Function
Sub Main()
Dim scenario3 = From var1 In queryObj, var2 In queryObj From var3 In queryObj Select expr3 = Foo(var1) & var3
End Sub
End Module
]]></file>
TestExpressionTrees(file, <![CDATA[
Lambda(
Parameter(
var1
type: System.String
)
Parameter(
var2
type: System.String
)
body {
New(
Void .ctor(System.String, System.String)(
Parameter(
var1
type: System.String
)
Parameter(
var2
type: System.String
)
)
members: {
System.String var1
System.String var2
}
type: VB$AnonymousType_0`2[System.String,System.String]
)
}
return type: VB$AnonymousType_0`2[System.String,System.String]
type: System.Func`3[System.String,System.String,VB$AnonymousType_0`2[System.String,System.String]]
)
Lambda(
Parameter(
$VB$It1
type: VB$AnonymousType_0`2[System.String,System.String]
)
Parameter(
var3
type: System.String
)
body {
Call(
<NULL>
method: System.String Concat(System.String, System.String) in System.String (
Call(
<NULL>
method: System.String Foo(Int32) in Form1 (
ConvertChecked(
MemberAccess(
Parameter(
$VB$It1
type: VB$AnonymousType_0`2[System.String,System.String]
)
-> var1
type: System.String
)
method: Int32 ToInteger(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions
type: System.Int32
)
)
type: System.String
)
Parameter(
var3
type: System.String
)
)
type: System.String
)
}
return type: System.String
type: System.Func`3[VB$AnonymousType_0`2[System.String,System.String],System.String,System.String]
)
]]>)
End Sub
<Fact, WorkItem(651996, "DevDiv")>
Public Sub ExprTree_LegacyTests06_IL()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Option Explicit Off
Imports System
Imports System.Linq.Expressions
Imports System.Collections.Generic
Module Form1
Dim queryObj As New QueryHelper(Of String)
Function Foo(ByVal x As Integer) As String
Return Nothing
End Function
Sub Main()
Dim scenario3 = From var1 In queryObj, var2 In queryObj From var3 In queryObj Select expr3 = Foo(var1) & var3
End Sub
End Module
]]></file>
TestExpressionTreesVerifier(file, Nothing).VerifyIL("Form1.Main",
<![CDATA[
{
// Code size 484 (0x1e4)
.maxstack 15
.locals init (System.Linq.Expressions.ParameterExpression V_0,
System.Linq.Expressions.ParameterExpression V_1)
IL_0000: ldsfld "Form1.queryObj As QueryHelper(Of String)"
IL_0005: ldtoken "String"
IL_000a: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_000f: ldstr "var1"
IL_0014: call "Function System.Linq.Expressions.Expression.Parameter(System.Type, String) As System.Linq.Expressions.ParameterExpression"
IL_0019: stloc.0
IL_001a: ldnull
IL_001b: ldtoken "Form1.queryObj As QueryHelper(Of String)"
IL_0020: call "Function System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle) As System.Reflection.FieldInfo"
IL_0025: call "Function System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo) As System.Linq.Expressions.MemberExpression"
IL_002a: ldtoken "System.Collections.Generic.IEnumerable(Of String)"
IL_002f: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_0034: call "Function System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type) As System.Linq.Expressions.UnaryExpression"
IL_0039: ldc.i4.1
IL_003a: newarr "System.Linq.Expressions.ParameterExpression"
IL_003f: dup
IL_0040: ldc.i4.0
IL_0041: ldloc.0
IL_0042: stelem.ref
IL_0043: call "Function System.Linq.Expressions.Expression.Lambda(Of System.Func(Of String, System.Collections.Generic.IEnumerable(Of String)))(System.Linq.Expressions.Expression, ParamArray System.Linq.Expressions.ParameterExpression()) As System.Linq.Expressions.Expression(Of System.Func(Of String, System.Collections.Generic.IEnumerable(Of String)))"
IL_0048: ldtoken "String"
IL_004d: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_0052: ldstr "var1"
IL_0057: call "Function System.Linq.Expressions.Expression.Parameter(System.Type, String) As System.Linq.Expressions.ParameterExpression"
IL_005c: stloc.0
IL_005d: ldtoken "String"
IL_0062: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_0067: ldstr "var2"
IL_006c: call "Function System.Linq.Expressions.Expression.Parameter(System.Type, String) As System.Linq.Expressions.ParameterExpression"
IL_0071: stloc.1
IL_0072: ldtoken "Sub VB$AnonymousType_0(Of String, String)..ctor(String, String)"
IL_0077: ldtoken "VB$AnonymousType_0(Of String, String)"
IL_007c: call "Function System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle, System.RuntimeTypeHandle) As System.Reflection.MethodBase"
IL_0081: castclass "System.Reflection.ConstructorInfo"
IL_0086: ldc.i4.2
IL_0087: newarr "System.Linq.Expressions.Expression"
IL_008c: dup
IL_008d: ldc.i4.0
IL_008e: ldloc.0
IL_008f: stelem.ref
IL_0090: dup
IL_0091: ldc.i4.1
IL_0092: ldloc.1
IL_0093: stelem.ref
IL_0094: ldc.i4.2
IL_0095: newarr "System.Reflection.MemberInfo"
IL_009a: dup
IL_009b: ldc.i4.0
IL_009c: ldtoken "Function VB$AnonymousType_0(Of String, String).get_var1() As String"
IL_00a1: ldtoken "VB$AnonymousType_0(Of String, String)"
IL_00a6: call "Function System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle, System.RuntimeTypeHandle) As System.Reflection.MethodBase"
IL_00ab: castclass "System.Reflection.MethodInfo"
IL_00b0: stelem.ref
IL_00b1: dup
IL_00b2: ldc.i4.1
IL_00b3: ldtoken "Function VB$AnonymousType_0(Of String, String).get_var2() As String"
IL_00b8: ldtoken "VB$AnonymousType_0(Of String, String)"
IL_00bd: call "Function System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle, System.RuntimeTypeHandle) As System.Reflection.MethodBase"
IL_00c2: castclass "System.Reflection.MethodInfo"
IL_00c7: stelem.ref
IL_00c8: call "Function System.Linq.Expressions.Expression.New(System.Reflection.ConstructorInfo, System.Collections.Generic.IEnumerable(Of System.Linq.Expressions.Expression), ParamArray System.Reflection.MemberInfo()) As System.Linq.Expressions.NewExpression"
IL_00cd: ldc.i4.2
IL_00ce: newarr "System.Linq.Expressions.ParameterExpression"
IL_00d3: dup
IL_00d4: ldc.i4.0
IL_00d5: ldloc.0
IL_00d6: stelem.ref
IL_00d7: dup
IL_00d8: ldc.i4.1
IL_00d9: ldloc.1
IL_00da: stelem.ref
IL_00db: call "Function System.Linq.Expressions.Expression.Lambda(Of System.Func(Of String, String, <anonymous type: Key var1 As String, Key var2 As String>))(System.Linq.Expressions.Expression, ParamArray System.Linq.Expressions.ParameterExpression()) As System.Linq.Expressions.Expression(Of System.Func(Of String, String, <anonymous type: Key var1 As String, Key var2 As String>))"
IL_00e0: call "Function ExpressionTreeHelpers.SelectMany(Of String, String, <anonymous type: Key var1 As String, Key var2 As String>)(QueryHelper(Of String), System.Linq.Expressions.Expression(Of System.Func(Of String, System.Collections.Generic.IEnumerable(Of String))), System.Linq.Expressions.Expression(Of System.Func(Of String, String, <anonymous type: Key var1 As String, Key var2 As String>))) As QueryHelper(Of <anonymous type: Key var1 As String, Key var2 As String>)"
IL_00e5: ldtoken "VB$AnonymousType_0(Of String, String)"
IL_00ea: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_00ef: ldstr "$VB$It"
IL_00f4: call "Function System.Linq.Expressions.Expression.Parameter(System.Type, String) As System.Linq.Expressions.ParameterExpression"
IL_00f9: stloc.1
IL_00fa: ldnull
IL_00fb: ldtoken "Form1.queryObj As QueryHelper(Of String)"
IL_0100: call "Function System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle) As System.Reflection.FieldInfo"
IL_0105: call "Function System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo) As System.Linq.Expressions.MemberExpression"
IL_010a: ldtoken "System.Collections.Generic.IEnumerable(Of String)"
IL_010f: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_0114: call "Function System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type) As System.Linq.Expressions.UnaryExpression"
IL_0119: ldc.i4.1
IL_011a: newarr "System.Linq.Expressions.ParameterExpression"
IL_011f: dup
IL_0120: ldc.i4.0
IL_0121: ldloc.1
IL_0122: stelem.ref
IL_0123: call "Function System.Linq.Expressions.Expression.Lambda(Of System.Func(Of <anonymous type: Key var1 As String, Key var2 As String>, System.Collections.Generic.IEnumerable(Of String)))(System.Linq.Expressions.Expression, ParamArray System.Linq.Expressions.ParameterExpression()) As System.Linq.Expressions.Expression(Of System.Func(Of <anonymous type: Key var1 As String, Key var2 As String>, System.Collections.Generic.IEnumerable(Of String)))"
IL_0128: ldtoken "VB$AnonymousType_0(Of String, String)"
IL_012d: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_0132: ldstr "$VB$It1"
IL_0137: call "Function System.Linq.Expressions.Expression.Parameter(System.Type, String) As System.Linq.Expressions.ParameterExpression"
IL_013c: stloc.1
IL_013d: ldtoken "String"
IL_0142: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_0147: ldstr "var3"
IL_014c: call "Function System.Linq.Expressions.Expression.Parameter(System.Type, String) As System.Linq.Expressions.ParameterExpression"
IL_0151: stloc.0
IL_0152: ldnull
IL_0153: ldtoken "Function String.Concat(String, String) As String"
IL_0158: call "Function System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle) As System.Reflection.MethodBase"
IL_015d: castclass "System.Reflection.MethodInfo"
IL_0162: ldc.i4.2
IL_0163: newarr "System.Linq.Expressions.Expression"
IL_0168: dup
IL_0169: ldc.i4.0
IL_016a: ldnull
IL_016b: ldtoken "Function Form1.Foo(Integer) As String"
IL_0170: call "Function System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle) As System.Reflection.MethodBase"
IL_0175: castclass "System.Reflection.MethodInfo"
IL_017a: ldc.i4.1
IL_017b: newarr "System.Linq.Expressions.Expression"
IL_0180: dup
IL_0181: ldc.i4.0
IL_0182: ldloc.1
IL_0183: ldtoken "Function VB$AnonymousType_0(Of String, String).get_var1() As String"
IL_0188: ldtoken "VB$AnonymousType_0(Of String, String)"
IL_018d: call "Function System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle, System.RuntimeTypeHandle) As System.Reflection.MethodBase"
IL_0192: castclass "System.Reflection.MethodInfo"
IL_0197: call "Function System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo) As System.Linq.Expressions.MemberExpression"
IL_019c: ldtoken "Integer"
IL_01a1: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_01a6: ldtoken "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String) As Integer"
IL_01ab: call "Function System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle) As System.Reflection.MethodBase"
IL_01b0: castclass "System.Reflection.MethodInfo"
IL_01b5: call "Function System.Linq.Expressions.Expression.ConvertChecked(System.Linq.Expressions.Expression, System.Type, System.Reflection.MethodInfo) As System.Linq.Expressions.UnaryExpression"
IL_01ba: stelem.ref
IL_01bb: call "Function System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, ParamArray System.Linq.Expressions.Expression()) As System.Linq.Expressions.MethodCallExpression"
IL_01c0: stelem.ref
IL_01c1: dup
IL_01c2: ldc.i4.1
IL_01c3: ldloc.0
IL_01c4: stelem.ref
IL_01c5: call "Function System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, ParamArray System.Linq.Expressions.Expression()) As System.Linq.Expressions.MethodCallExpression"
IL_01ca: ldc.i4.2
IL_01cb: newarr "System.Linq.Expressions.ParameterExpression"
IL_01d0: dup
IL_01d1: ldc.i4.0
IL_01d2: ldloc.1
IL_01d3: stelem.ref
IL_01d4: dup
IL_01d5: ldc.i4.1
IL_01d6: ldloc.0
IL_01d7: stelem.ref
IL_01d8: call "Function System.Linq.Expressions.Expression.Lambda(Of System.Func(Of <anonymous type: Key var1 As String, Key var2 As String>, String, String))(System.Linq.Expressions.Expression, ParamArray System.Linq.Expressions.ParameterExpression()) As System.Linq.Expressions.Expression(Of System.Func(Of <anonymous type: Key var1 As String, Key var2 As String>, String, String))"
IL_01dd: call "Function ExpressionTreeHelpers.SelectMany(Of <anonymous type: Key var1 As String, Key var2 As String>, String, String)(QueryHelper(Of <anonymous type: Key var1 As String, Key var2 As String>), System.Linq.Expressions.Expression(Of System.Func(Of <anonymous type: Key var1 As String, Key var2 As String>, System.Collections.Generic.IEnumerable(Of String))), System.Linq.Expressions.Expression(Of System.Func(Of <anonymous type: Key var1 As String, Key var2 As String>, String, String))) As QueryHelper(Of String)"
IL_01e2: pop
IL_01e3: ret
}
]]>)
End Sub
<Fact()>
Public Sub ExprTree_LegacyTests07()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Option Explicit Off
Imports System
Imports System.Linq.Expressions
Module Form1
Class Class1
Shared Widening Operator CType(ByVal x As Double) As Class1
Return Nothing
End Operator
Shared Widening Operator CType(ByVal x As Class1) As ULong?
Return Nothing
End Operator
End Class
Interface Interface1
End Interface
Class Class2 : Inherits Class1 : Implements Interface1
End Class
Structure Struct1 : Implements Interface1
Dim a As Integer
Shared Widening Operator CType(ByVal x As Struct1) As ULong
Return Nothing
End Operator
Shared Operator <>(ByVal x As Struct1, ByVal y As Struct1) As Boolean
Return x.a <> y.a
End Operator
Shared Operator =(ByVal x As Struct1, ByVal y As Struct1) As Boolean
Return x.a = y.a
End Operator
End Structure
Dim n1 As Double
Dim n2? As ULong
Dim n3? As Decimal
Dim n4? As UInteger
Dim c1 As Class1 = Nothing
Dim s1 As New Struct1
Dim s2? As Struct1 = New Struct1
Dim i1 As Interface1 = Nothing
Dim c2 As New Class2
Sub F(Of T)(p As Expression(Of Func(Of T)))
Console.WriteLine(p.Dump)
End Sub
Sub Main()
F(Function() If(c1, n1))
F(Function() If(c1, c1))
F(Function() If(c1, n2))
F(Function() If(n2, n1))
F(Function() If(n2, n2))
F(Function() If(n2, n3))
F(Function() If(n2, s2))
F(Function() If(s2, s1))
F(Function() If(s2, s2))
F(Function() If(s2, n1))
F(Function() If(s2, n2))
F(Function() If(i1, c2))
F(Function() If(c2, i1))
F(Function() If(c2, c1))
F(Function() If(c1, c2))
F(Function() If(i1, s1))
F(Function() If(s2, i1))
F(Function() If(n2, n4))
F(Function() If(n4, n2))
F(Function() If(CType(n2, Boolean?), False))
'F(Function() If(n3, 3.3))
End Sub
End Module
]]></file>
TestExpressionTrees(file, ExpTreeTestResources.ExprTree_LegacyTests07_Result)
End Sub
<Fact()>
Public Sub ExprTree_LegacyTests07_Decimal()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Option Explicit Off
Imports System
Imports System.Linq.Expressions
Module Form1
Dim n3? As Decimal
Sub F(Of T)(p As Expression(Of Func(Of T)))
Console.WriteLine(p.Dump)
End Sub
Sub Main()
F(Function() If(n3, 3.3))
End Sub
End Module
]]></file>
TestExpressionTrees(file,
<![CDATA[Lambda(
body {
Coalesce(
MemberAccess(
<NULL>
-> n3
type: System.Nullable`1[System.Decimal]
)
Constant(
3.3
type: System.Double
)
conversion:
Lambda(
Parameter(
CoalesceLHS
type: System.Nullable`1[System.Decimal]
)
body {
Convert(
Convert(
Parameter(
CoalesceLHS
type: System.Nullable`1[System.Decimal]
)
method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal]
type: System.Decimal
)
method: Double op_Explicit(System.Decimal) in System.Decimal
type: System.Double
)
}
return type: System.Double
type: System.Func`2[System.Nullable`1[System.Decimal],System.Double]
)
type: System.Double
)
}
return type: System.Double
type: System.Func`1[System.Double]
)]]>)
End Sub
<Fact()>
Public Sub ExprTree_LegacyTests08()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Option Explicit Off
Imports System
Imports System.Linq
Imports System.Linq.Expressions
Module Form1
Structure Struct1(Of T As Structure)
Dim a As T
Shared Operator -(ByVal y As Struct1(Of T), ByVal x As T) As T
Return Nothing
End Operator
End Structure
Class Class1
Public field1 As Boolean
Public field2 As Decimal
Public ReadOnly Property Prop() As Boolean
Get
Return Nothing
End Get
End Property
Default Public ReadOnly Property MyProperty(ByVal x As String) As Boolean
Get
Return Nothing
End Get
End Property
End Class
Class class2
Public datetime2 As DateTime
Default Public ReadOnly Property MyProperty2(ByVal x As String) As DateTime
Get
Return Nothing
End Get
End Property
Public Property MyProperty3() As DateTime
Get
Return Nothing
End Get
Set(ByVal value As DateTime)
End Set
End Property
End Class
Function RefParam(ByRef p As DateTime) As Boolean
Return Nothing
End Function
Dim queryObj As New QueryHelper(Of String)
Dim c1 As New Class1
Dim c2 As New class2
Dim x1 As Short = 3
Dim x2? As Integer = 3.2
Dim s1 As New Struct1(Of Long)
Dim s2? As Struct1(Of Decimal) = Nothing
Dim i2 As SByte = -2
Dim d3? As Decimal = 3.3
Delegate Sub Foo()
Function Bar(ByVal s As Foo) As Boolean
Return Nothing
End Function
Sub SubRoutine()
End Sub
Sub F(Of T)(p As Expression(Of Func(Of T)))
Console.WriteLine(p.Dump)
End Sub
Sub Main()
F(Function() s1 - x1)
F(Function() s1 - x2)
F(Function() s2 - x1)
F(Function() s2 - x2)
F(Function() -d3)
Dim a = Function() -d3 ' BUG
F(Function() i2 Mod d3)
Dim scenario1 = From s In queryObj Where c1.Prop Select s
Dim scenario2 = From s In queryObj Where c1.Prop And c1.field2 Select s
Dim scenario3 = From s In queryObj Where c1!Foo Select s
Dim scenario4 = From s In queryObj Where c2!Day = c2.datetime2 Select s
Dim scenario5 = From s In queryObj Where RefParam(c2.MyProperty3) Select s
Dim scenario6 = From s In queryObj Where RefParam((c2.MyProperty3)) Select s
Dim col = GetQueryCollection(1, 2, 3)
Dim col1 = GetQueryCollection(1, 2, 3)
Dim q1 = From i In col Where i > 2 Select i Group Join j In col1 On i Equals j Into Count(), Sum(i), Average(i)
Dim q2 = From i In col Where i > 2 Select i Group Join j In col1 On i Equals j Into Count(), Sum(j)
Dim q3 = From i In col Where i > 2 Select i Group Join j In col1 On i Equals j Into Count() From k In col Where k > 2 Select k
Dim d As Foo = Nothing
Dim scenario7 = From s In queryObj Where Bar(AddressOf SubRoutine) Select s
Dim scenario8 = From s In queryObj Where Bar(d) Select s
End Sub
End Module
]]></file>
TestExpressionTrees(file, ExpTreeTestResources.ExprTree_LegacyTests08_Result)
End Sub
<Fact()>
Public Sub ExprTree_LegacyTests09()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Option Explicit Off
Imports System
Imports System.Linq.Expressions
Module Form1
Structure Struct1
Public Shared Operator =(ByVal x As Struct1, ByVal y As Struct1) As Boolean
Return True
End Operator
Public Shared Operator <>(ByVal x As Struct1, ByVal y As Struct1) As Boolean
Return False
End Operator
End Structure
Class Class1
End Class
Class Class2 : Inherits Class1
End Class
Sub Foo1(Of T As Structure)(ByVal x As T?)
F(Function() If(x, Nothing))
F(Function() x is Nothing)
End Sub
'Sub Foo2(Of T As Structure)(ByVal x As T?)
' F(Function() If(x, CObj(3.3)))
'End Sub
Sub Bar(Of T As Class2)(ByVal y As T)
Dim c1 As New Class1
F(Function() If(y, c1))
FF(Function() If(y, c1))
End Sub
Sub Moo(Of U As Class, V As U)(ByVal z1 As U)
Dim z2 As V = Nothing
F(Function() If(z1, z2))
End Sub
Sub F(Of T)(p As Expression(Of Func(Of T)))
Console.WriteLine(p.Dump)
End Sub
Sub FF(Of T)(p As Func(Of T))
End Sub
Sub Main()
Dim x? As Struct1 = New Struct1()
Dim c2 As Class2 = New Class2()
Foo1(Of Struct1)(Nothing)
Foo1(x)
'Foo2(Of Struct1)(Nothing)
'Foo2(x)
Bar(Of Class2)(Nothing)
Bar(c2)
Moo(Of Class2, Class2)(Nothing)
Moo(Of Class2, Class2)(c2)
End Sub
End Module
]]></file>
TestExpressionTrees(file, ExpTreeTestResources.ExprTree_LegacyTests09_Result)
End Sub
<Fact()>
Public Sub ExprTree_LegacyTests09_Decimal()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Option Explicit Off
Imports System
Imports System.Linq.Expressions
Module Form1
Structure Struct1
Public Shared Operator =(ByVal x As Struct1, ByVal y As Struct1) As Boolean
Return True
End Operator
Public Shared Operator <>(ByVal x As Struct1, ByVal y As Struct1) As Boolean
Return False
End Operator
End Structure
Sub Foo2(Of T As Structure)(ByVal x As T?)
F(Function() If(x, CObj(3.3)))
End Sub
Sub F(Of T)(p As Expression(Of Func(Of T)))
Console.WriteLine(p.Dump)
End Sub
Sub Main()
Dim x? As Struct1 = New Struct1()
Foo2(Of Struct1)(Nothing)
Foo2(x)
End Sub
End Module
]]></file>
TestExpressionTrees(file, <![CDATA[
Lambda(
body {
Coalesce(
MemberAccess(
Constant(
Form1+_Closure$__1-0`1[Form1+Struct1]
type: Form1+_Closure$__1-0`1[Form1+Struct1]
)
-> $VB$Local_x
type: System.Nullable`1[Form1+Struct1]
)
Convert(
Constant(
3.3
type: System.Double
)
type: System.Object
)
conversion:
Lambda(
Parameter(
CoalesceLHS
type: System.Nullable`1[Form1+Struct1]
)
body {
Convert(
Convert(
Parameter(
CoalesceLHS
type: System.Nullable`1[Form1+Struct1]
)
method: Struct1 op_Explicit(System.Nullable`1[Form1+Struct1]) in System.Nullable`1[Form1+Struct1]
type: Form1+Struct1
)
type: System.Object
)
}
return type: System.Object
type: System.Func`2[System.Nullable`1[Form1+Struct1],System.Object]
)
type: System.Object
)
}
return type: System.Object
type: System.Func`1[System.Object]
)
Lambda(
body {
Coalesce(
MemberAccess(
Constant(
Form1+_Closure$__1-0`1[Form1+Struct1]
type: Form1+_Closure$__1-0`1[Form1+Struct1]
)
-> $VB$Local_x
type: System.Nullable`1[Form1+Struct1]
)
Convert(
Constant(
3.3
type: System.Double
)
type: System.Object
)
conversion:
Lambda(
Parameter(
CoalesceLHS
type: System.Nullable`1[Form1+Struct1]
)
body {
Convert(
Convert(
Parameter(
CoalesceLHS
type: System.Nullable`1[Form1+Struct1]
)
method: Struct1 op_Explicit(System.Nullable`1[Form1+Struct1]) in System.Nullable`1[Form1+Struct1]
type: Form1+Struct1
)
type: System.Object
)
}
return type: System.Object
type: System.Func`2[System.Nullable`1[Form1+Struct1],System.Object]
)
type: System.Object
)
}
return type: System.Object
type: System.Func`1[System.Object]
)
]]>)
End Sub
<Fact()>
Public Sub ExprTree_LegacyTests10()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Option Explicit Off
Imports System
Imports System.Linq.Expressions
Module Form1
Sub F(Of T)(p As Expression(Of Func(Of T)))
Console.WriteLine(p.Dump)
End Sub
Structure Struct1
Public a As Integer
End Structure
Public Function Foo(Of T As Structure)(ByVal x As T?) As Integer
Return Nothing
End Function
<System.Runtime.CompilerServices.Extension()>
Sub Foo(ByVal x As Integer)
Console.WriteLine("Printed From 'Sub Foo(ByVal x As Integer)'")
Console.WriteLine()
End Sub
Sub Main()
Dim q0 As Expression(Of Func(Of Integer)) = Function() Foo(Of Struct1)(Nothing)
Console.WriteLine(q0.Dump)
Console.WriteLine("Result: " + q0.Compile()().ToString())
Dim q1 As Expression(Of Func(Of Func(Of Func(Of Object, Boolean)))) = Function() If(4 > 3, Function() Function(s) True, Function() Function() False)
Console.WriteLine(q1.Dump)
Console.WriteLine("Result: " + q1.Compile()()()(Nothing).ToString())
Dim q2 As Expression(Of Func(Of Func(Of String))) = Function() If(4 > 3, Function() 1UI, Function() 5.0)
Console.WriteLine(q2.Dump)
Console.WriteLine("Result: " + q2.Compile()()().ToString())
Dim q3 As Expression(Of Func(Of Func(Of Long))) = Function() If(4 > 3, Function() 1UI, Function() 1US)
Console.WriteLine(q3.Dump)
Console.WriteLine("Result: " + q3.Compile()()().ToString())
Dim q4 As Expression(Of Func(Of Action(Of String))) = Function() If(4 > 3, Function() 1UI, Function() 5.0)
Console.WriteLine(q4.Dump)
Call q4.Compile()()("11")
Dim q5 As Expression(Of Func(Of Action)) = Function() AddressOf 0.Foo
Console.WriteLine(q5.Dump)
Call q5.Compile()()()
End Sub
End Module
]]></file>
TestExpressionTrees(file, ExpTreeTestResources.ExprTree_LegacyTests10_Result)
End Sub
<Fact()>
Public Sub ExprTreeLiftedUserDefinedConversionsWithNullableResult()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Module Program
Sub Main()
Dim l1 As Expression(Of Func(Of Test1?, Test2, Test2)) = Function(x, y) If(x, y)
Console.WriteLine(l1.Dump)
Dim l2 As Expression(Of Func(Of Test1?, Test2?, Test2?)) = Function(x, y) If(x, y)
Console.WriteLine(l2.Dump)
Dim l1x As Expression(Of Func(Of Test3?, Test1, Test1)) = Function(x, y) If(x, y)
Console.WriteLine(l1x.Dump)
Dim l2x As Expression(Of Func(Of Test3?, Test1?, Test1?)) = Function(x, y) If(x, y)
Console.WriteLine(l2x.Dump)
End Sub
End Module
Structure Test1
Public Shared Widening Operator CType(x As Test1) As Test2?
Return Nothing
End Operator
End Structure
Structure Test2
End Structure
Structure Test3
Public Shared Widening Operator CType(x As Test3?) As Test1
Return Nothing
End Operator
End Structure
]]></file>
TestExpressionTrees(file, <![CDATA[
Lambda(
Parameter(
x
type: System.Nullable`1[Test1]
)
Parameter(
y
type: Test2
)
body {
Coalesce(
Parameter(
x
type: System.Nullable`1[Test1]
)
Parameter(
y
type: Test2
)
conversion:
Lambda(
Parameter(
CoalesceLHS
type: System.Nullable`1[Test1]
)
body {
Convert(
Convert(
Convert(
Parameter(
CoalesceLHS
type: System.Nullable`1[Test1]
)
Lifted
type: Test1
)
method: System.Nullable`1[Test2] op_Implicit(Test1) in Test1
type: System.Nullable`1[Test2]
)
Lifted
type: Test2
)
}
return type: Test2
type: System.Func`2[System.Nullable`1[Test1],Test2]
)
type: Test2
)
}
return type: Test2
type: System.Func`3[System.Nullable`1[Test1],Test2,Test2]
)
Lambda(
Parameter(
x
type: System.Nullable`1[Test1]
)
Parameter(
y
type: System.Nullable`1[Test2]
)
body {
Coalesce(
Parameter(
x
type: System.Nullable`1[Test1]
)
Parameter(
y
type: System.Nullable`1[Test2]
)
conversion:
Lambda(
Parameter(
CoalesceLHS
type: System.Nullable`1[Test1]
)
body {
Convert(
Convert(
Parameter(
CoalesceLHS
type: System.Nullable`1[Test1]
)
Lifted
type: Test1
)
method: System.Nullable`1[Test2] op_Implicit(Test1) in Test1
type: System.Nullable`1[Test2]
)
}
return type: System.Nullable`1[Test2]
type: System.Func`2[System.Nullable`1[Test1],System.Nullable`1[Test2]]
)
type: System.Nullable`1[Test2]
)
}
return type: System.Nullable`1[Test2]
type: System.Func`3[System.Nullable`1[Test1],System.Nullable`1[Test2],System.Nullable`1[Test2]]
)
Lambda(
Parameter(
x
type: System.Nullable`1[Test3]
)
Parameter(
y
type: Test1
)
body {
Coalesce(
Parameter(
x
type: System.Nullable`1[Test3]
)
Parameter(
y
type: Test1
)
conversion:
Lambda(
Parameter(
CoalesceLHS
type: System.Nullable`1[Test3]
)
body {
Convert(
Parameter(
CoalesceLHS
type: System.Nullable`1[Test3]
)
method: Test1 op_Implicit(System.Nullable`1[Test3]) in Test3
type: Test1
)
}
return type: Test1
type: System.Func`2[System.Nullable`1[Test3],Test1]
)
type: Test1
)
}
return type: Test1
type: System.Func`3[System.Nullable`1[Test3],Test1,Test1]
)
Lambda(
Parameter(
x
type: System.Nullable`1[Test3]
)
Parameter(
y
type: System.Nullable`1[Test1]
)
body {
Coalesce(
Parameter(
x
type: System.Nullable`1[Test3]
)
Parameter(
y
type: System.Nullable`1[Test1]
)
conversion:
Lambda(
Parameter(
CoalesceLHS
type: System.Nullable`1[Test3]
)
body {
Convert(
Convert(
Parameter(
CoalesceLHS
type: System.Nullable`1[Test3]
)
method: Test1 op_Implicit(System.Nullable`1[Test3]) in Test3
type: Test1
)
Lifted
LiftedToNull
type: System.Nullable`1[Test1]
)
}
return type: System.Nullable`1[Test1]
type: System.Func`2[System.Nullable`1[Test3],System.Nullable`1[Test1]]
)
type: System.Nullable`1[Test1]
)
}
return type: System.Nullable`1[Test1]
type: System.Func`3[System.Nullable`1[Test3],System.Nullable`1[Test1],System.Nullable`1[Test1]]
)]]>)
End Sub
<Fact()>
Public Sub ExprTreeMiscellaneous_A()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Module Form1
Sub Main()
Call (New Clazz(Of C)()).Main()
End Sub
End Module
Class C
Public Property P As Object
End Class
Class Clazz(Of T As {C, New})
Sub Main()
Console.WriteLine((DirectCast(Function() Me.ToString(), Expression(Of Func(Of Object)))).Dump)
Console.WriteLine((DirectCast(Function() New T(), Expression(Of Func(Of Object)))).Dump)
Console.WriteLine((DirectCast(Function() New T() With {.P = New T()}, Expression(Of Func(Of Object)))).Dump)
Console.WriteLine((DirectCast(Function() Nothing, Expression(Of Func(Of T)))).Dump)
Console.WriteLine((DirectCast(Function() Sub() AddHandler Me.EV, Nothing, Expression(Of Func(Of Action)))).Dump)
Console.WriteLine((DirectCast(Function() Sub() RemoveHandler Me.EV, Nothing, Expression(Of Func(Of Action)))).Dump)
Console.WriteLine((DirectCast(Function(x) (TypeOf Me Is Object) = (TypeOf x Is String), Expression(Of Func(Of String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x) Me(x), Expression(Of Func(Of String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x) (New Clazz(Of T))(x), Expression(Of Func(Of String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x) x("aaa"), Expression(Of Func(Of Clazz(Of T), Object)))).Dump)
Console.WriteLine((DirectCast(Function(x) x.P, Expression(Of Func(Of C, Object)))).Dump)
End Sub
Event EV(i As Integer)
Default Public Property IND(s As String) As String
Get
Return Nothing
End Get
Set(value As String)
End Set
End Property
End Class
]]></file>
TestExpressionTrees(file, ExpTreeTestResources.CheckedMiscellaneousA)
End Sub
<Fact()>
Public Sub ExprTreeNothingIsNothing()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Module Form1
Sub Main()
Dim l1 As Expression(Of Func(Of Object)) = Function() Nothing Is Nothing
Console.WriteLine(l1.Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file, <![CDATA[
Lambda(
body {
Convert(
Equal(
Constant(
null
type: System.Object
)
Constant(
null
type: System.Object
)
type: System.Boolean
)
type: System.Object
)
}
return type: System.Object
type: System.Func`1[System.Object]
)
]]>)
End Sub
<Fact()>
Public Sub CheckedCoalesceWithNullableBoolean()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Module Form1
Sub Main()
Dim ret1n As Expression(Of Func(Of Boolean?, Object)) = Function(x) If(x, True)
Console.WriteLine(ret1n.Dump)
Dim ret1na As Expression(Of Func(Of Boolean?, Boolean)) = Function(x) x
Console.WriteLine(ret1na.Dump)
Dim ret2n As Expression(Of Func(Of Boolean?, Boolean?, Object)) = Function(x, y) If(x AndAlso y, True, False)
Console.WriteLine(ret2n.Dump)
Dim ret2na As Expression(Of Func(Of Boolean?, Boolean?, Object)) = Function(x, y) If(CType(x AndAlso y, Boolean), True, False)
Console.WriteLine(ret2na.Dump)
Dim ret2nb As Expression(Of Func(Of Boolean?, Object)) = Function(x) If(x, True, False)
Console.WriteLine(ret2nb.Dump)
Dim ret3n As Expression(Of Func(Of Boolean?, Boolean, Object)) = Function(x, y) If(x AndAlso y, True, False)
Console.WriteLine(ret3n.Dump)
Dim ret3na As Expression(Of Func(Of Boolean, Boolean?, Object)) = Function(x, y) If(x AndAlso y, True, False)
Console.WriteLine(ret3na.Dump)
Dim ret3nb As Expression(Of Func(Of Boolean, Boolean, Object)) = Function(x, y) If(x AndAlso y, True, False)
Console.WriteLine(ret3nb.Dump)
Dim ret4n As Expression(Of Func(Of Integer, Object)) = Function(x) If("const", x)
Console.WriteLine(ret4n.Dump)
Dim ret5n As Expression(Of Func(Of Integer?, Object)) = Function(x) If(x, "const")
Console.WriteLine(ret5n.Dump)
Dim ret6n As Expression(Of Func(Of Boolean?, Object)) = Function(x) If(x, "const")
Console.WriteLine(ret6n.Dump)
Dim ret7n As Expression(Of Func(Of Boolean?, String)) = Function(x) If(x, "const")
Console.WriteLine(ret7n.Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file, ExpTreeTestResources.CheckedCoalesceWithNullableBoolean)
End Sub
<Fact()>
Public Sub ExprTreeWithCollectionIntializer()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Imports System.Collections
Imports System.Collections.Generic
Structure Custom
Implements IEnumerable
Public Shared list As New List(Of String)()
Public Overloads Sub Add(p As Object)
End Sub
Public Overloads Sub Add(p As String, p2 As Object)
End Sub
Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return Nothing
End Function
End Structure
Class Clazz
Public Property P() As List(Of Object)
Public F() As Custom
End Class
Module Form1
Sub Main()
Console.WriteLine((DirectCast(Function(x, y) New List(Of String)() From {x, "a", y.ToString()}, Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) New List(Of Object)() From {{{x}}, {"a"}}, Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) New Custom() From {{{x}}, {x, {"a"}}}, Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) New List(Of List(Of String))() From {New List(Of String)() From {"Hello", " "}, New List(Of String)() From {"World!"}}, Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) New List(Of Action) From {Sub() Console.Write("hello"), Sub() Console.Write("world")}, Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) New Clazz() With {.F = {New Custom() From {{{x}}, {x, {"a"}}}, New Custom() From {{{x}}}, New Custom()},
.P = New List(Of Object) From {New List(Of Action) From {Sub() Console.Write("hello"), Sub() Console.Write("world")}}},
Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) {x, y}, Expression(Of Func(Of Integer, String, Object)))).Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file, ExpTreeTestResources.CheckedCollectionInitializers)
End Sub
<Fact()>
Public Sub ArrayCreationAndInitialization()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Module Form1
Sub Main()
Console.WriteLine((DirectCast(Function(x, y) (Function(a) a)((New String(11) {}).Length), Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) (Function(a) a)((New String(11) {}).LongLength), Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) (Function(a) a)((New String(2) {x, y, ""})(x)), Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) (Function(a) a)((New String(2) {x, y, ""})(x)), Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) (Function(a) a)((New String(1, 2) {})(x, 0)), Expression(Of Func(Of Integer, String, Object)))).Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file, ExpTreeTestResources.CheckedArrayInitializers)
End Sub
<Fact()>
Public Sub SimpleObjectCreation()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Public Structure SSS
Public Sub New(i As Object)
End Sub
End Structure
Public Class Clazz
Public Sub New()
End Sub
Public Sub New(i As Object)
End Sub
End Class
Module Form1
Sub Main()
Console.WriteLine((DirectCast(Function(x, y) New SSS(New SSS()), Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) New Clazz(New Clazz()), Expression(Of Func(Of Integer, String, Object)))).Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file, <![CDATA[
Lambda(
Parameter(
x
type: System.Int32
)
Parameter(
y
type: System.String
)
body {
Convert(
New(
Void .ctor(System.Object)(
Convert(
New(
<.ctor>(
)
type: SSS
)
type: System.Object
)
)
type: SSS
)
type: System.Object
)
}
return type: System.Object
type: System.Func`3[System.Int32,System.String,System.Object]
)
Lambda(
Parameter(
x
type: System.Int32
)
Parameter(
y
type: System.String
)
body {
Convert(
New(
Void .ctor(System.Object)(
Convert(
New(
Void .ctor()(
)
type: Clazz
)
type: System.Object
)
)
type: Clazz
)
type: System.Object
)
}
return type: System.Object
type: System.Func`3[System.Int32,System.String,System.Object]
)
]]>)
End Sub
<Fact()>
Public Sub ObjectCreationInitializers()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Public Structure SSS
Public ReadOnly I As Integer
Public F As Object
Public Sub New(i As Integer)
Me.I = i
End Sub
End Structure
Public Class Clazz
Public Shared Property P0 As Object
Public Property P1 As Object
Public Property P2 As Object
Public Property P3 As SSS
Public Shared F0 As Object
Public F1 As Object
Public F2 As Object
Public F3 As SSS
Public Sub New()
End Sub
Public Sub New(i As Integer)
End Sub
End Class
Module Form1
Sub Main()
Console.WriteLine((DirectCast(Function(x, y) New Clazz(x) With {.F1 = New Clazz(y)}, Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) New Clazz(x) With {.P1 = New Clazz(y)}, Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) New Clazz(x) With {.F3 = New SSS(1)}, Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) New Clazz(x) With {.P3 = New SSS(1)}, Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) New Clazz(x) With {.F1 = Nothing, .F2 = .F0}, Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) New Clazz(x) With {.P1 = Nothing, .P2 = .P0}, Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) New Clazz() With {.F1 = Sub() Console.WriteLine()}, Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) New Clazz() With {.P1 = Sub() Console.WriteLine()}, Expression(Of Func(Of Integer, String, Object)))).Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file, ExpTreeTestResources.CheckedObjectInitializers)
End Sub
<Fact()>
Public Sub ObjectCreationInitializers_BC36534a()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Public Structure SSS
Public F As Object
Public Property P As Object
Public Sub New(i As Integer)
End Sub
End Structure
Public Class Clazz
Public Property P1 As Object
Public Property P2 As Object
Public F1 As Object
Public F2 As Object
Public Sub New(i As Integer)
End Sub
End Class
Module Form1
Sub Main()
Console.WriteLine((DirectCast(Function(x, y) New SSS(x) With {.F = New SSS(1)}, Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) New SSS(x) With {.P = New SSS(1)}, Expression(Of Func(Of Integer, String, Object)))).Dump)
End Sub
End Module
]]></file>
VerifyExpressionTreesDiagnostics(file,
<errors>
BC36534: Expression cannot be converted into an expression tree.
Console.WriteLine((DirectCast(Function(x, y) New SSS(x) With {.F = New SSS(1)}, Expression(Of Func(Of Integer, String, Object)))).Dump)
~~~~~~~~~~~~~~~~~~~~~~
BC36534: Expression cannot be converted into an expression tree.
Console.WriteLine((DirectCast(Function(x, y) New SSS(x) With {.P = New SSS(1)}, Expression(Of Func(Of Integer, String, Object)))).Dump)
~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub ObjectCreationInitializers_BC36534b()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Public Structure SSS
Public F As Object
Public Property P As Object
Public Sub New(i As Integer)
End Sub
End Structure
Public Class Clazz
Public Property P1 As Object
Public Property P2 As Object
Public F1 As Object
Public F2 As Object
Public Sub New(i As Integer)
End Sub
End Class
Module Form1
Sub Main()
Console.WriteLine((DirectCast(Function(x, y) New Clazz(x) With {.P1 = Nothing, .P2 = .P1}, Expression(Of Func(Of Integer, String, Object)))).Dump)
Console.WriteLine((DirectCast(Function(x, y) New Clazz(x) With {.F1 = Nothing, .F2 = .F1}, Expression(Of Func(Of Integer, String, Object)))).Dump)
End Sub
End Module
]]></file>
VerifyExpressionTreesDiagnostics(file,
<errors>
BC36534: Expression cannot be converted into an expression tree.
Console.WriteLine((DirectCast(Function(x, y) New Clazz(x) With {.P1 = Nothing, .P2 = .P1}, Expression(Of Func(Of Integer, String, Object)))).Dump)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36534: Expression cannot be converted into an expression tree.
Console.WriteLine((DirectCast(Function(x, y) New Clazz(x) With {.F1 = Nothing, .F2 = .F1}, Expression(Of Func(Of Integer, String, Object)))).Dump)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub AnonymousObjectCreationExpression()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Module Form1
Sub Main()
Dim ret1 As Expression(Of Func(Of Integer, String, Object)) = Function(x, y) New With {.A = x, .B = y}.B + x
Console.WriteLine(ret1.Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file, <![CDATA[
Lambda(
Parameter(
x
type: System.Int32
)
Parameter(
y
type: System.String
)
body {
Convert(
Add(
Convert(
MemberAccess(
New(
Void .ctor(Int32, System.String)(
Parameter(
x
type: System.Int32
)
Parameter(
y
type: System.String
)
)
members: {
Int32 A
System.String B
}
type: VB$AnonymousType_0`2[System.Int32,System.String]
)
-> B
type: System.String
)
method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions
type: System.Double
)
Convert(
Parameter(
x
type: System.Int32
)
type: System.Double
)
type: System.Double
)
type: System.Object
)
}
return type: System.Object
type: System.Func`3[System.Int32,System.String,System.Object]
)
]]>)
End Sub
<Fact()>
Public Sub CheckedCoalesceWithUserDefinedConversion()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Structure Str1
Public F As Boolean?
Public Shared Narrowing Operator CType(s As Str1) As String
Return ""
End Operator
Public Shared Narrowing Operator CType(s As Str1) As Str2
Return Nothing
End Operator
End Structure
Structure Str2
Public F As Boolean?
Public Shared Narrowing Operator CType(s As Str2?) As String
Return ""
End Operator
End Structure
Module Form1
Sub Main()
Dim ret1 As Expression(Of Func(Of Str1?, Object)) = Function(x) If(x, True)
Console.WriteLine(ret1.Dump)
Dim ret2 As Expression(Of Func(Of Str1?, Str2?)) = Function(x) If(x, Nothing)
Console.WriteLine(ret2.Dump)
Dim ret3 As Expression(Of Func(Of Str1?, Str2)) = Function(x) If(x, Nothing)
Console.WriteLine(ret3.Dump)
Dim ret4 As Expression(Of Func(Of Str2?, Object)) = Function(x) If(x, True)
Console.WriteLine(ret4.Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file, ExpTreeTestResources.CheckedCoalesceWithUserDefinedConversions)
End Sub
<Fact()>
Public Sub CheckedExpressionInCoalesceWitSideEffects()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Structure str
Public F As Boolean?
End Structure
Module Form1
Function A(p As Object) As str()
Return New str(5) {}
End Function
Sub Main()
Dim ret As Expression(Of Func(Of Object, Object)) = Function(x) If(A(x)(1).F, True)
Console.WriteLine(ret.Dump)
End Sub
End Module
]]></file>
TestExpressionTrees(file,
<![CDATA[
Lambda(
Parameter(
x
type: System.Object
)
body {
Convert(
Coalesce(
MemberAccess(
ArrayIndex(
Call(
<NULL>
method: str[] A(System.Object) in Form1 (
Parameter(
x
type: System.Object
)
)
type: str[]
)
Constant(
1
type: System.Int32
)
type: str
)
-> F
type: System.Nullable`1[System.Boolean]
)
Constant(
True
type: System.Boolean
)
type: System.Boolean
)
type: System.Object
)
}
return type: System.Object
type: System.Func`2[System.Object,System.Object]
)
]]>)
End Sub
<Fact, WorkItem(651996, "DevDiv")>
Public Sub ExprTreeIL()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Imports System.Linq.Expressions
Module Module1
Sub Main()
Dim exprTree As Expression(Of Func(Of Integer, Integer, Integer)) = Function(x, y) x + y
End Sub
End Module
</file>
</compilation>).
VerifyIL("Module1.Main",
<![CDATA[
{
// Code size 70 (0x46)
.maxstack 5
.locals init (System.Linq.Expressions.ParameterExpression V_0,
System.Linq.Expressions.ParameterExpression V_1)
IL_0000: ldtoken "Integer"
IL_0005: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_000a: ldstr "x"
IL_000f: call "Function System.Linq.Expressions.Expression.Parameter(System.Type, String) As System.Linq.Expressions.ParameterExpression"
IL_0014: stloc.0
IL_0015: ldtoken "Integer"
IL_001a: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_001f: ldstr "y"
IL_0024: call "Function System.Linq.Expressions.Expression.Parameter(System.Type, String) As System.Linq.Expressions.ParameterExpression"
IL_0029: stloc.1
IL_002a: ldloc.0
IL_002b: ldloc.1
IL_002c: call "Function System.Linq.Expressions.Expression.AddChecked(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression) As System.Linq.Expressions.BinaryExpression"
IL_0031: ldc.i4.2
IL_0032: newarr "System.Linq.Expressions.ParameterExpression"
IL_0037: dup
IL_0038: ldc.i4.0
IL_0039: ldloc.0
IL_003a: stelem.ref
IL_003b: dup
IL_003c: ldc.i4.1
IL_003d: ldloc.1
IL_003e: stelem.ref
IL_003f: call "Function System.Linq.Expressions.Expression.Lambda(Of System.Func(Of Integer, Integer, Integer))(System.Linq.Expressions.Expression, ParamArray System.Linq.Expressions.ParameterExpression()) As System.Linq.Expressions.Expression(Of System.Func(Of Integer, Integer, Integer))"
IL_0044: pop
IL_0045: ret
}]]>)
End Sub
<Fact()>
Public Sub MissingHelpers()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Imports System.Linq.Expressions
Module Module1
Sub Main()
Dim exprTree As Expression(Of Func(Of Integer, Integer, Integer)) = Function(x, y) x + y
End Sub
End Module
</file>
<file name="b.vb">
Namespace System.Linq.Expressions
Public Class Expression
End Class
Public Class Expression(Of T)
Inherits Expression
Public Function Lambda(Of U)(e As Expression, ParamArray p As ParameterExpression()) As Expression(Of U)
Return Nothing
End Function
End Class
Public Class ParameterExpression
Inherits Expression
End Class
End Namespace
</file>
</compilation>)
Using stream = New MemoryStream()
Dim emitResult = compilation.Emit(stream)
Assert.False(emitResult.Success)
CompilationUtils.AssertTheseDiagnostics(emitResult.Diagnostics, <expected>
BC30456: 'Lambda' is not a member of 'Expression'.
Dim exprTree As Expression(Of Func(Of Integer, Integer, Integer)) = Function(x, y) x + y
~~~~~~~~~~~~~~~~~~~~
BC30456: 'Parameter' is not a member of 'Expression'.
Dim exprTree As Expression(Of Func(Of Integer, Integer, Integer)) = Function(x, y) x + y
~~~~~~~~~~~~~~~~~~~~
BC30456: 'Parameter' is not a member of 'Expression'.
Dim exprTree As Expression(Of Func(Of Integer, Integer, Integer)) = Function(x, y) x + y
~~~~~~~~~~~~~~~~~~~~
BC30456: 'AddChecked' is not a member of 'Expression'.
Dim exprTree As Expression(Of Func(Of Integer, Integer, Integer)) = Function(x, y) x + y
~~~~~
</expected>)
End Using
End Sub
<Fact()>
Public Sub LocalVariableAccess()
Dim source = <compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports System.Linq.Expressions
Module Module1
Sub Main()
Dim y As Integer = 12
Dim exprTree1 As Expression(Of Func(Of Integer, Integer)) = Function(x) x + y
Console.WriteLine(exprtree1.Dump)
End Sub
End Module
]]></file>
<%= _exprTesting %>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
expectedOutput:=<![CDATA[
Lambda(
Parameter(
x
type: System.Int32
)
body {
AddChecked(
Parameter(
x
type: System.Int32
)
MemberAccess(
Constant(
Module1+_Closure$__0-0
type: Module1+_Closure$__0-0
)
-> $VB$Local_y
type: System.Int32
)
type: System.Int32
)
}
return type: System.Int32
type: System.Func`2[System.Int32,System.Int32]
)]]>).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub LocalVariableAccessInGeneric()
Dim source = <compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports System.Linq.Expressions
Module Module1
Sub Main()
Dim y As Integer = 7
Dim exprTree As Expression(Of Func(Of Decimal, String)) = (New Gen(Of Long, String, Decimal)()).F("hello")
Console.WriteLine(exprTree.Dump)
End Sub
End Module
Public Class Gen(Of U, V, W)
Public Function F(val As V) As Expression(Of Func(Of W, V))
Dim y As V = val
Return Function(x) y
End Function
End Class
]]></file>
<%= _exprTesting %>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
expectedOutput:=<![CDATA[
Lambda(
Parameter(
x
type: System.Decimal
)
body {
MemberAccess(
Constant(
Gen`3+_Closure$__1-0[System.Int64,System.String,System.Decimal]
type: Gen`3+_Closure$__1-0[System.Int64,System.String,System.Decimal]
)
-> $VB$Local_y
type: System.String
)
}
return type: System.String
type: System.Func`2[System.Decimal,System.String]
)]]>).VerifyDiagnostics()
End Sub
<Fact, WorkItem(651996, "DevDiv")>
Public Sub LocalVariableAccessIL()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Imports System.Linq.Expressions
Module Module1
Sub Main()
Dim y As Integer = 7
Dim exprTree As Expression(Of Func(Of Integer, Integer)) = Function(x) x + y
End Sub
End Module
</file>
</compilation>)
c.VerifyIL("Module1.Main", <![CDATA[
{
// Code size 88 (0x58)
.maxstack 5
.locals init (Module1._Closure$__0-0 V_0, //$VB$Closure_0
System.Linq.Expressions.ParameterExpression V_1)
IL_0000: newobj "Sub Module1._Closure$__0-0..ctor()"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.7
IL_0008: stfld "Module1._Closure$__0-0.$VB$Local_y As Integer"
IL_000d: ldtoken "Integer"
IL_0012: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_0017: ldstr "x"
IL_001c: call "Function System.Linq.Expressions.Expression.Parameter(System.Type, String) As System.Linq.Expressions.ParameterExpression"
IL_0021: stloc.1
IL_0022: ldloc.1
IL_0023: ldloc.0
IL_0024: ldtoken "Module1._Closure$__0-0"
IL_0029: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_002e: call "Function System.Linq.Expressions.Expression.Constant(Object, System.Type) As System.Linq.Expressions.ConstantExpression"
IL_0033: ldtoken "Module1._Closure$__0-0.$VB$Local_y As Integer"
IL_0038: call "Function System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle) As System.Reflection.FieldInfo"
IL_003d: call "Function System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo) As System.Linq.Expressions.MemberExpression"
IL_0042: call "Function System.Linq.Expressions.Expression.AddChecked(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression) As System.Linq.Expressions.BinaryExpression"
IL_0047: ldc.i4.1
IL_0048: newarr "System.Linq.Expressions.ParameterExpression"
IL_004d: dup
IL_004e: ldc.i4.0
IL_004f: ldloc.1
IL_0050: stelem.ref
IL_0051: call "Function System.Linq.Expressions.Expression.Lambda(Of System.Func(Of Integer, Integer))(System.Linq.Expressions.Expression, ParamArray System.Linq.Expressions.ParameterExpression()) As System.Linq.Expressions.Expression(Of System.Func(Of Integer, Integer))"
IL_0056: pop
IL_0057: ret
}
]]>)
End Sub
<Fact>
Public Sub TypeInference()
Dim source = <compilation>
<%= _exprTesting %>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports System.Linq.Expressions
Module Module1
Sub Foo(Of A, B, C)(q As Expression(Of Func(Of A, B, C)))
Console.WriteLine("Infer A={0}", GetType(A))
Console.WriteLine("Infer B={0}", GetType(B))
Console.WriteLine("Infer C={0}", GetType(C))
End Sub
Sub Main()
Foo(Function(x As Decimal, y As String) 4)
End Sub
End Module
]]></file>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
expectedOutput:=<![CDATA[
Infer A=System.Decimal
Infer B=System.String
Infer C=System.Int32
]]>).VerifyDiagnostics()
End Sub
<Fact>
Public Sub QueryWhereSelect()
Dim source = <compilation>
<%= _exprTesting %>
<file name="a.vb"><)) As Queryable
System.Console.Write("Select ")
'TODO: Check expression tree
Return Me
End Function
Public Function Where(x As Expression(Of Func(Of Integer, Boolean))) As Queryable
System.Console.Write("Where ")
'TODO: Check expression tree
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim r = From a In q Where a > 0 Select a
End Sub
End Module
]]></file>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
expectedOutput:=<![CDATA[Where Select]]>).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub QueryGroupBy()
Dim source = <compilation>
<%= _exprTesting %>
<file name="a.vb"><(x As Expression(Of Func(Of T, S))) As QueryAble(Of S)
Console.Write("Select;")
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Expression(Of Func(Of T, K)), item As Expression(Of Func(Of T, I)), into As Expression(Of Func(Of K, QueryAble(Of I), R))) As QueryAble(Of R)
System.Console.Write("GroupBy 1;")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Expression(Of Func(Of T, K)), into As Expression(Of Func(Of K, QueryAble(Of T), R))) As QueryAble(Of R)
System.Console.Write("GroupBy 2;")
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of Integer)(4)
Dim r = From a In q Group x = a By a Into Group Select a
Dim s = From a In q Group By a Into Group Select a
End Sub
End Module
]]></file>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
expectedOutput:="GroupBy 1;Select;GroupBy 2;Select;").VerifyDiagnostics()
End Sub
<Fact()>
Public Sub QueryGroupJoin()
Dim source = <compilation>
<%= _exprTesting %>
<file name="a.vb"><(x As Expression(Of Func(Of T, S))) As QueryAble(Of S)
Console.Write("Select;")
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Expression(Of Func(Of T, K)), innerKey As Expression(Of Func(Of I, K)), x As Expression(Of Func(Of T, QueryAble(Of I), R))) As QueryAble(Of R)
System.Console.Write("GroupJoin;")
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of Integer)(4)
Dim r = From a In q Group Join b In q On a Equals b Into Group
End Sub
End Module]]></file>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
expectedOutput:="GroupJoin;").VerifyDiagnostics()
End Sub
<Fact>
Public Sub OverloadResolutionDisambiguation1()
Dim source = <compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System
Imports System.Linq.Expressions
Delegate Function MyFunc(Of U)() As U
Class X(Of T)
Public Sub A(p As Func(Of T), q As Integer)
Console.Write("A1 ")
End Sub
Public Sub A(p As Func(Of T), q As T)
Console.Write("A2 ")
End Sub
Public Sub B(p As Func(Of T), q As T)
Console.Write("B1 ")
End Sub
Public Sub B(p As Func(Of T), q As Integer)
Console.Write("B2 ")
End Sub
Public Sub C(p As MyFunc(Of T), q As Integer)
Console.Write("C1 ")
End Sub
Public Sub C(p As Func(Of T), q As T)
Console.Write("C2 ")
End Sub
Public Sub D(p As MyFunc(Of T), q As T)
Console.Write("D1 ")
End Sub
Public Sub D(p As Func(Of T), q As Integer)
Console.Write("D2 ")
End Sub
Public Sub E(p As MyFunc(Of T), q As Integer)
Console.Write("E1 ")
End Sub
Public Sub E(p As Expression(Of Func(Of T)), q As T)
Console.Write("E2 ")
End Sub
Public Sub F(p As MyFunc(Of T), q As T)
Console.Write("F1 ")
End Sub
Public Sub F(p As Expression(Of Func(Of T)), q As Integer)
Console.Write("F2 ")
End Sub
End Class
Module Module1
Sub Main()
Dim instance As New X(Of Integer)
instance.A(Function() 1, 7)
instance.B(Function() 1, 7)
instance.C(Function() 1, 7)
instance.D(Function() 1, 7)
instance.E(Function() 1, 7)
instance.F(Function() 1, 7)
End Sub
End Module
]]></file>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
expectedOutput:=<![CDATA[A1 B2 C1 D2 E1 F2]]>)
End Sub
<Fact>
Public Sub OverloadResolutionDisambiguation2()
Dim source = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Linq.Expressions
Delegate Function D1(x As Integer) As Integer
Delegate Function D2(y As Integer) As Long
Module Module1
Sub Main()
f(Nothing)
f(Function(a) 4)
g(Function(a) 4)
End Sub
Sub f(x As Expression(Of D1))
Console.Write("f1 ")
End Sub
Sub f(x As Expression(Of D2))
Console.Write("f2 ")
End Sub
Sub g(x As Expression(Of D1))
Console.Write("g1 ")
End Sub
Sub g(x As D2)
Console.Write("g2 ")
End Sub
End Module]]></file>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
expectedOutput:=<![CDATA[f1 f1 g1]]>)
End Sub
<WorkItem(545757, "DevDiv")>
<Fact()>
Public Sub Bug_14402()
Dim source = <compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Module Form1
Sub Main()
'System.Console.WriteLine("Dev10 #531876 regression test.")
Dim s1_a As Boolean?
Dim s1_b As Char? = "1"c
Dim s1_c As Object = If(s1_a, s1_b)
Dim expr As Expression(Of Func(Of Object)) = Function() If(s1_a, s1_b)
System.Console.WriteLine(expr)
End Sub
End Module
]]></file>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
expectedOutput:="() => (value(Form1+_Closure$__0-0).$VB$Local_s1_a ?? Convert(value(Form1+_Closure$__0-0).$VB$Local_s1_b))").VerifyDiagnostics()
End Sub
<WorkItem(531513, "DevDiv")>
<Fact()>
Public Sub Bug_18234()
Dim file = <file name="a.vb"><![CDATA[
Option Strict Off
Module Program
Private d As Date
Private v As Integer
Private x As Decimal
Sub Main(args As String())
Dim queryObj As New QueryHelper(Of String)
Dim scenario4 = From s In queryObj
Where Not TypeOf CObj(d) Is Double = (x + v) AndAlso True
Select s
End Sub
End Module
]]></file>
TestExpressionTrees(file, <![CDATA[
Lambda(
Parameter(
s
type: System.String
)
body {
AndAlso(
Not(
Equal(
Convert(
TypeIs(
Convert(
MemberAccess(
<NULL>
-> d
type: System.DateTime
)
type: System.Object
)
Type Operand: System.Double
type: System.Boolean
)
method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions
type: System.Decimal
)
Add(
MemberAccess(
<NULL>
-> x
type: System.Decimal
)
Convert(
MemberAccess(
<NULL>
-> v
type: System.Int32
)
method: System.Decimal op_Implicit(Int32) in System.Decimal
type: System.Decimal
)
method: System.Decimal Add(System.Decimal, System.Decimal) in System.Decimal
type: System.Decimal
)
method: Boolean op_Equality(System.Decimal, System.Decimal) in System.Decimal
type: System.Boolean
)
type: System.Boolean
)
Constant(
True
type: System.Boolean
)
type: System.Boolean
)
}
return type: System.Boolean
type: System.Func`2[System.String,System.Boolean]
)
Lambda(
Parameter(
s
type: System.String
)
body {
Parameter(
s
type: System.String
)
}
return type: System.String
type: System.Func`2[System.String,System.String]
)
]]>)
End Sub
<WorkItem(545738, "DevDiv")>
<Fact()>
Public Sub Bug_14377a()
Dim source = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Linq.Expressions
Imports System
Module Module1
Sub Main()
Dim e As Expression(Of Func(Of Integer, Integer)) = Function(ByVal x) x + 1
Dim f As Func(Of Integer, Integer) = Function(ByVal x) x + 1
Console.WriteLine(f(9))
End Sub
End Module
]]></file>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
expectedOutput:="10").VerifyDiagnostics()
End Sub
<WorkItem(547151, "DevDiv")>
<Fact()>
Public Sub Bug_18156()
Dim file = <file name="expr.vb"><![CDATA[
Imports System
Imports System.Linq.Expressions
Friend Module ExprTreeAdd01mod
Sub ExprTreeAdd01()
Dim queryObj As New QueryHelper(Of String)
Dim str As String = "abc"
Dim b As Boolean = False
Dim scenario1 = From s In queryObj Where str + b Select s
Dim byteVal As Byte = 7
Dim scenario2 = From s In queryObj Where str + byteVal Select s
Dim c As Char = "c"
Dim scenario3 = From s In queryObj Where c + str Select s
Dim dt As DateTime = #1/1/2006#
Dim scenario4 = From s In queryObj Where str + dt Select s
Dim d As Decimal = 5.77
Dim scenario5 = From s In queryObj Where d + str Select s
Dim dbl As Double = 5.99
Dim scenario6 = From s In queryObj Where str + dbl Select s
Dim i As Integer = 5
Dim scenario7 = From s In queryObj Where str + i Select s
Dim lng As Long = 9999999
Dim scenario8 = From s In queryObj Where str + lng Select s
Dim sb As SByte = 9
Dim scenario9 = From s In queryObj Where str + sb Select s
Dim sh As Short = 5
Dim scenario10 = From s In queryObj Where str + sh Select s
Dim sng As Single = 5.5
Dim scenario11 = From s In queryObj Where str + sng Select s
Dim str2 As String = "string2"
Dim scenario12 = From s In queryObj Where CBool(str + str2) Select s
Dim ui As UInteger = 8
Dim scenario13 = From s In queryObj Where str + ui Select s
Dim ul As ULong = 555
Dim scenario14 = From s In queryObj Where str + ul Select s
Dim us As UShort = 7
Dim scenario15 = From s In queryObj Where str + us Select s
Dim obj As Object = New Object
Dim scenario16 = From s In queryObj Where str + obj Select s
End Sub
End Module
]]></file>
VerifyExpressionTreesDiagnostics(file, <errors></errors>)
End Sub
<WorkItem(957927, "DevDiv")>
<Fact()>
Public Sub Bug957927()
Dim source = <compilation>
<file name="a.vb"><![CDATA[
imports System
imports System.Linq.Expressions
class Test
shared Sub Main()
System.Console.WriteLine(GetFunc(Of Integer)()().ToString())
End Sub
shared Function GetFunc(Of T)() As Func(Of Expression(Of Func(Of T,T)))
Dim x = 10
return Function()
Dim y = x
return Function(m As T) m
End Function
End Function
end class
]]></file>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
expectedOutput:="m => m").VerifyDiagnostics()
End Sub
<WorkItem(3906, "https://github.com/dotnet/roslyn/issues/3906")>
<Fact()>
Public Sub GenericField01()
Dim source = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Public Class Module1
Public Class S(Of T)
Public x As T
End Class
Public Shared Function SomeFunc(Of A)(selector As System.Linq.Expressions.Expression(Of Func(Of Object, A))) As Object
Return Nothing
End Function
Public Shared Sub CallIt(Of T)(p As T)
Dim goodF As Func(Of Object, Object) = Function(xs) SomeFunc(Of S(Of T))(Function(e) New S(Of T)())
Dim z1 = goodF(3)
Dim badF As Func(Of Object, Object) = Function(xs)
Return SomeFunc(Of S(Of T))(Function(e) New S(Of T) With {.x = p})
End Function
Dim z2 = badF(3)
End Sub
Public Shared Sub Main()
CallIt(Of Integer)(3)
End Sub
End Class
]]></file>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
expectedOutput:="").VerifyDiagnostics()
End Sub
<Fact()>
Public Sub ExpressionTrees_MyBaseMyClass()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Module Form1
Sub Main()
Call (New Clazz(Of Object)()).Main()
Call (New Derived()).Main()
End Sub
End Module
Public Class Base
Public F As Integer
Public Property P1 As String
Default Public Property P2(i As Integer) As String
Get
Return Nothing
End Get
Set(value As String)
End Set
End Property
End Class
Public Class Derived
Inherits Base
Public Shadows F As Integer
Public Shadows Property P1 As String
Default Public Shadows Property P2(i As Integer) As String
Get
Return Nothing
End Get
Set(value As String)
End Set
End Property
Sub Main()
Console.WriteLine((DirectCast(Function() Me.F.ToString(), Expression(Of Func(Of Object)))).Dump)
Console.WriteLine((DirectCast(Function() MyClass.F.ToString(), Expression(Of Func(Of Object)))).Dump)
Console.WriteLine((DirectCast(Function() MyBase.F.ToString(), Expression(Of Func(Of Object)))).Dump)
Console.WriteLine((DirectCast(Function() Me.P1.ToString(), Expression(Of Func(Of Object)))).Dump)
Console.WriteLine((DirectCast(Function() MyClass.P1.ToString(), Expression(Of Func(Of Object)))).Dump)
Console.WriteLine((DirectCast(Function() MyBase.P1.ToString(), Expression(Of Func(Of Object)))).Dump)
Console.WriteLine((DirectCast(Function() Me.P2(1).ToString(), Expression(Of Func(Of Object)))).Dump)
Console.WriteLine((DirectCast(Function() MyClass.P2(1).ToString(), Expression(Of Func(Of Object)))).Dump)
Console.WriteLine((DirectCast(Function() MyBase.P2(1).ToString(), Expression(Of Func(Of Object)))).Dump)
End Sub
End Class
Class Clazz(Of T As {Class, New})
Sub Main()
Console.WriteLine((DirectCast(Function() MyBase.ToString(), Expression(Of Func(Of Object)))).Dump)
Console.WriteLine((DirectCast(Function() MyClass.ToString(), Expression(Of Func(Of Object)))).Dump)
End Sub
End Class
]]></file>
TestExpressionTrees(file, <![CDATA[
Lambda(
body {
Convert(
Call(
Constant(
Clazz`1[System.Object]
type: Clazz`1[System.Object]
)
method: System.String $VB$ClosureStub_ToString_MyBase() in Clazz`1[System.Object] (
)
type: System.String
)
type: System.Object
)
}
return type: System.Object
type: System.Func`1[System.Object]
)
Lambda(
body {
Convert(
Call(
Constant(
Clazz`1[System.Object]
type: Clazz`1[System.Object]
)
method: System.String $VB$ClosureStub_ToString_MyBase() in Clazz`1[System.Object] (
)
type: System.String
)
type: System.Object
)
}
return type: System.Object
type: System.Func`1[System.Object]
)
Lambda(
body {
Convert(
Call(
MemberAccess(
Constant(
Derived
type: Derived
)
-> F
type: System.Int32
)
method: System.String ToString() in System.Int32 (
)
type: System.String
)
type: System.Object
)
}
return type: System.Object
type: System.Func`1[System.Object]
)
Lambda(
body {
Convert(
Call(
MemberAccess(
Constant(
Derived
type: Derived
)
-> F
type: System.Int32
)
method: System.String ToString() in System.Int32 (
)
type: System.String
)
type: System.Object
)
}
return type: System.Object
type: System.Func`1[System.Object]
)
Lambda(
body {
Convert(
Call(
MemberAccess(
Constant(
Derived
type: Base
)
-> F
type: System.Int32
)
method: System.String ToString() in System.Int32 (
)
type: System.String
)
type: System.Object
)
}
return type: System.Object
type: System.Func`1[System.Object]
)
Lambda(
body {
Convert(
Call(
MemberAccess(
Constant(
Derived
type: Derived
)
-> P1
type: System.String
)
method: System.String ToString() in System.String (
)
type: System.String
)
type: System.Object
)
}
return type: System.Object
type: System.Func`1[System.Object]
)
Lambda(
body {
Convert(
Call(
Call(
Constant(
Derived
type: Derived
)
method: System.String $VB$ClosureStub_get_P1_MyClass() in Derived (
)
type: System.String
)
method: System.String ToString() in System.String (
)
type: System.String
)
type: System.Object
)
}
return type: System.Object
type: System.Func`1[System.Object]
)
Lambda(
body {
Convert(
Call(
Call(
Constant(
Derived
type: Derived
)
method: System.String $VB$ClosureStub_get_P1_MyBase() in Derived (
)
type: System.String
)
method: System.String ToString() in System.String (
)
type: System.String
)
type: System.Object
)
}
return type: System.Object
type: System.Func`1[System.Object]
)
Lambda(
body {
Convert(
Call(
Call(
Constant(
Derived
type: Derived
)
method: System.String get_P2(Int32) in Derived (
Constant(
1
type: System.Int32
)
)
type: System.String
)
method: System.String ToString() in System.String (
)
type: System.String
)
type: System.Object
)
}
return type: System.Object
type: System.Func`1[System.Object]
)
Lambda(
body {
Convert(
Call(
Call(
Constant(
Derived
type: Derived
)
method: System.String $VB$ClosureStub_get_P2_MyClass(Int32) in Derived (
Constant(
1
type: System.Int32
)
)
type: System.String
)
method: System.String ToString() in System.String (
)
type: System.String
)
type: System.Object
)
}
return type: System.Object
type: System.Func`1[System.Object]
)
Lambda(
body {
Convert(
Call(
Call(
Constant(
Derived
type: Derived
)
method: System.String $VB$ClosureStub_get_P2_MyBase(Int32) in Derived (
Constant(
1
type: System.Int32
)
)
type: System.String
)
method: System.String ToString() in System.String (
)
type: System.String
)
type: System.Object
)
}
return type: System.Object
type: System.Func`1[System.Object]
)
]]>)
End Sub
#End Region
#Region "Errors"
<Fact()>
Public Sub ArrayCreationAndInitialization_BC36603()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Module Form1
Sub Main()
Console.WriteLine((DirectCast(Function(x, y) (Function(a) a)((New String(1, 2) {{x, y, ""}, {x, y, ""}})(x, 0)), Expression(Of Func(Of Integer, String, Object)))).Dump)
End Sub
End Module
]]></file>
VerifyExpressionTreesDiagnostics(file,
<errors>
BC36603: Multi-dimensional array cannot be converted to an expression tree.
Console.WriteLine((DirectCast(Function(x, y) (Function(a) a)((New String(1, 2) {{x, y, ""}, {x, y, ""}})(x, 0)), Expression(Of Func(Of Integer, String, Object)))).Dump)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<WorkItem(531526, "DevDiv")>
<Fact()>
Public Sub ByRefParamsInExpressionLambdas_BC36538()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Module Program
Delegate Function MyFunc(Of T)(ByRef x As T, ByVal y As T) As T
Delegate Function MyFunc2(Of T)(ByRef x As T) As T
Delegate Function MyFuncV(Of T)(ByVal x As T, ByVal y As T) As T
Delegate Function MyFunc2V(Of T)(ByVal x As T) As T
Sub Foo(Of T)(ByVal x As Expression(Of MyFunc(Of T)))
End Sub
Sub Foo2(Of T)(ByVal x As Expression(Of MyFunc2(Of T)))
End Sub
Sub Foo3(Of T)(ByVal x As Expression(Of MyFuncV(Of T)))
End Sub
Sub Foo4(Of T)(ByVal x As Expression(Of MyFunc2V(Of T)))
End Sub
Sub Main(args As String())
'COMPILEERROR: BC36538, "Function(ByRef x As Double, y As Integer) 1.1"
Foo(Function(ByRef x As Double, y As Integer) 1.1) 'Causes compile time error
'COMPILEERROR: BC36538, "Function(ByRef x As Double) 1.1"
Foo2(Function(ByRef x As Double) 1.1) 'Regression Scenario - Previously No compile time error
'COMPILEERROR: BC36538, "Function() 1.1"
Foo(Function() 1.1)
End Sub
End Module
]]></file>
VerifyExpressionTreesDiagnostics(file,
<errors>
BC36538: References to 'ByRef' parameters cannot be converted to an expression tree.
Foo(Function(ByRef x As Double, y As Integer) 1.1) 'Causes compile time error
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36538: References to 'ByRef' parameters cannot be converted to an expression tree.
Foo2(Function(ByRef x As Double) 1.1) 'Regression Scenario - Previously No compile time error
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36538: References to 'ByRef' parameters cannot be converted to an expression tree.
Foo(Function() 1.1)
~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub AnonymousObjectCreationExpression_BC36548()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Module Form1
Sub Main()
Dim ret0 As Expression(Of Func(Of Integer, String, Object)) = Function(x, y) New With {.A = x, .B = y, .C = .A + .B}.C
Console.WriteLine(ret0.Dump)
End Sub
End Module
]]></file>
VerifyExpressionTreesDiagnostics(file,
<errors>
BC36548: Cannot convert anonymous type to an expression tree because a property of the type is used to initialize another property.
Dim ret0 As Expression(Of Func(Of Integer, String, Object)) = Function(x, y) New With {.A = x, .B = y, .C = .A + .B}.C
~~
BC36548: Cannot convert anonymous type to an expression tree because a property of the type is used to initialize another property.
Dim ret0 As Expression(Of Func(Of Integer, String, Object)) = Function(x, y) New With {.A = x, .B = y, .C = .A + .B}.C
~~
</errors>)
End Sub
<Fact()>
Public Sub MultiStatementLambda_BC36675a()
Dim file = <file name="expr.vb"><![CDATA[
Imports System
Imports Microsoft.VisualBasic
Imports System.Linq
Imports System.Linq.Expressions
Imports System.Collections.Generic
Module Program
Sub Main()
Dim l1 As Expression(Of Func(Of Object)) = Function() Function() Function()
Return Nothing
End Function
Dim l2 As Expression(Of Func(Of Object)) = Function() Function() Sub()
Console.WriteLine()
End Sub
End Sub
End Module
]]></file>
VerifyExpressionTreesDiagnostics(file,
<errors>
BC36675: Statement lambdas cannot be converted to expression trees.
Dim l1 As Expression(Of Func(Of Object)) = Function() Function() Function()
~~~~~~~~~~~
BC36675: Statement lambdas cannot be converted to expression trees.
Dim l2 As Expression(Of Func(Of Object)) = Function() Function() Sub()
~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub MultiStatementLambda_BC36675b()
Dim file = <file name="expr.vb"><![CDATA[
Imports System
Imports Microsoft.VisualBasic
Imports System.Linq
Imports System.Linq.Expressions
Imports System.Collections.Generic
Module Program
Sub Main()
Dim l3 As Expression(Of Func(Of Object)) = Function() Sub() If True Then Console.WriteLine()
End Sub
End Module
]]></file>
VerifyExpressionTreesDiagnostics(file,
<errors>
BC36675: Statement lambdas cannot be converted to expression trees.
Dim l3 As Expression(Of Func(Of Object)) = Function() Sub() If True Then Console.WriteLine()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<WorkItem(545804, "DevDiv")>
<Fact()>
Public Sub Bug_14469()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports System.Linq.Expressions
Module Module1
Sub Main()
Dim x15 As Expression(Of Action) = Sub() glob = Function()
Return Sub()
End Sub
End Function
End Sub
Public glob As Object = Nothing
End Module
]]></file>
VerifyExpressionTreesDiagnostics(file,
<errors>
BC36534: Expression cannot be converted into an expression tree.
Dim x15 As Expression(Of Action) = Sub() glob = Function()
~~~~~~~~~~~~~~~~~~
BC36675: Statement lambdas cannot be converted to expression trees.
Dim x15 As Expression(Of Action) = Sub() glob = Function()
~~~~~~~~~~~
BC36675: Statement lambdas cannot be converted to expression trees.
Return Sub()
~~~~~~
</errors>)
End Sub
<WorkItem(531420, "DevDiv")>
<Fact()>
Public Sub ExprTreeLiftedUserDefinedOperatorsWithNullableResult_Binary_BC36534()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Imports System.Linq.Expressions
Imports System.Collections.Generic
Module Program
Sub Main()
Dim l2 As Expression(Of Func(Of Test1?, Test1, Test1)) = Function(x, y) x = y
Console.WriteLine(l2.Dump)
Dim l3 As Expression(Of Func(Of Test1?, Test1, Test1)) = Function(x, y) x + y
Console.WriteLine(l3.Dump)
End Sub
End Module
Structure Test1
Public Shared Operator +(x As Test1, y As Test1) As Test1?
Return Nothing
End Operator
Public Shared Operator =(x As Test1, y As Test1) As Test1?
Return Nothing
End Operator
Public Shared Operator <>(x As Test1, y As Test1) As Test1?
Return Nothing
End Operator
End Structure
]]></file>
VerifyExpressionTreesDiagnostics(file,
<errors>
BC36534: Expression cannot be converted into an expression tree.
Dim l2 As Expression(Of Func(Of Test1?, Test1, Test1)) = Function(x, y) x = y
~~~~~
BC36534: Expression cannot be converted into an expression tree.
Dim l3 As Expression(Of Func(Of Test1?, Test1, Test1)) = Function(x, y) x + y
~~~~~
</errors>)
End Sub
<WorkItem(531423, "DevDiv")>
<Fact()>
Public Sub ExprTreeUserDefinedAndAlsoOrElseWithNullableResult_BC36534()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Imports System.Linq.Expressions
Imports System.Collections.Generic
Module Program
Sub Main()
Dim l2 As Expression(Of Func(Of Test1?, Test1, Test1)) = Function(x, y) if(x AndAlso y, x, y)
Console.WriteLine(l2.Dump)
Dim l3 As Expression(Of Func(Of Test1?, Test1, Test1)) = Function(x, y) if(x OrElse y, x, y)
Console.WriteLine(l3.Dump)
End Sub
End Module
Structure Test1
Public Shared Operator And(x As Test1, y As Test1) As Test1?
Return Nothing
End Operator
Public Shared Operator Or(x As Test1, y As Test1) As Test1?
Return Nothing
End Operator
Public Shared Operator IsTrue(x As Test1) As Boolean
Return Nothing
End Operator
Public Shared Operator IsFalse(x As Test1) As Boolean
Return Nothing
End Operator
End Structure
]]></file>
VerifyExpressionTreesDiagnostics(file,
<errors>
BC36534: Expression cannot be converted into an expression tree.
Dim l2 As Expression(Of Func(Of Test1?, Test1, Test1)) = Function(x, y) if(x AndAlso y, x, y)
~~~~~~~~~~~
BC36534: Expression cannot be converted into an expression tree.
Dim l3 As Expression(Of Func(Of Test1?, Test1, Test1)) = Function(x, y) if(x OrElse y, x, y)
~~~~~~~~~~
</errors>)
End Sub
<WorkItem(531424, "DevDiv")>
<Fact()>
Public Sub ExprTreeUserDefinedUnaryWithNullableResult_BC36534()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Imports System.Linq.Expressions
Imports System.Collections.Generic
Module Program
Sub Main()
Dim l9 As Expression(Of Func(Of Test1?, Test1)) = Function(x) -x
Console.WriteLine(l9.Dump)
Dim l10 As Expression(Of Func(Of Test1?, Test1?)) = Function(x) -x
Console.WriteLine(l10.Dump)
End Sub
End Module
Structure Test1
Public Shared Operator -(x As Test1) As Test1?
Return Nothing
End Operator
End Structure
]]></file>
VerifyExpressionTreesDiagnostics(file,
<errors>
BC36534: Expression cannot be converted into an expression tree.
Dim l9 As Expression(Of Func(Of Test1?, Test1)) = Function(x) -x
~~
BC36534: Expression cannot be converted into an expression tree.
Dim l10 As Expression(Of Func(Of Test1?, Test1?)) = Function(x) -x
~~
</errors>)
End Sub
<Fact()>
Public Sub ExprTree_LateBinding_BC36604()
Dim file = <file name="expr.vb"><![CDATA[
Option Strict Off
Imports System
Imports Microsoft.VisualBasic
Imports System.Linq.Expressions
Imports System.Collections.Generic
Module Form1
Dim queryObj As New QueryHelper(Of String)
Public x
Function Foo(ByVal x As Long)
Return Nothing
End Function
Function Foo(ByVal x As Short)
Return Nothing
End Function
Sub Main()
Dim scenario1 = From s In queryObj Where x.Foo() Select s
Dim scenario2 = From s In queryObj Where Foo(x) Select s
Dim scenario3 = From s In queryObj Where CBool(Foo(x)) Select s
End Sub
End Module
]]></file>
VerifyExpressionTreesDiagnostics(file,
<errors>
BC36604: Late binding operations cannot be converted to an expression tree.
Dim scenario1 = From s In queryObj Where x.Foo() Select s
~~~~~~~
BC36604: Late binding operations cannot be converted to an expression tree.
Dim scenario2 = From s In queryObj Where Foo(x) Select s
~~~~~~
BC36604: Late binding operations cannot be converted to an expression tree.
Dim scenario3 = From s In queryObj Where CBool(Foo(x)) Select s
~~~~~~
</errors>)
End Sub
<WorkItem(797996, "DevDiv")>
<Fact()>
Public Sub MissingMember_System_Type__GetTypeFromHandle()
Dim compilation = CreateCompilationWithoutReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Linq.Expressions
Namespace System
Public Class [Object]
End Class
Public Structure Void
End Structure
Public Class ValueType
End Class
Public Class MulticastDelegate
End Class
Public Structure IntPtr
End Structure
Public Structure Int32
End Structure
Public Structure Nullable(Of T)
End Structure
Public Class [Type]
End Class
Public Interface IAsyncResult
End Interface
Public Class AsyncCallback
End Class
End Namespace
Namespace System.Collections.Generic
Public Interface IEnumerable(Of T)
End Interface
End Namespace
Namespace System.Linq.Expressions
Public Class Expression
Public Shared Function [New](t As Type) As Expression
Return Nothing
End Function
Public Shared Function Lambda(Of T)(e As Expression, args As Expression()) As Expression(Of T)
Return Nothing
End Function
End Class
Public Class Expression(Of T)
End Class
Public Class ParameterExpression
Inherits Expression
End Class
End Namespace
Delegate Function D() As C
Class C
Shared E As Expression(Of D) = Function() New C()
End Class
]]></file>
</compilation>)
AssertTheseEmitDiagnostics(compilation,
<errors>
BC35000: Requested operation is not available because the runtime library function 'System.Type.GetTypeFromHandle' is not defined.
Shared E As Expression(Of D) = Function() New C()
~~~~~~~
</errors>)
End Sub
<WorkItem(797996, "DevDiv")>
<Fact()>
Public Sub MissingMember_System_Reflection_FieldInfo__GetFieldFromHandle()
Dim compilation = CreateCompilationWithoutReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Linq.Expressions
Imports System.Reflection
Namespace System
Public Class [Object]
End Class
Public Structure Void
End Structure
Public Class ValueType
End Class
Public Class MulticastDelegate
End Class
Public Structure IntPtr
End Structure
Public Structure Int32
End Structure
Public Structure Nullable(Of T)
End Structure
Public Class [Type]
End Class
Public Class Array
End Class
Public Interface IAsyncResult
End Interface
Public Class AsyncCallback
End Class
End Namespace
Namespace System.Collections.Generic
Public Interface IEnumerable(Of T)
End Interface
End Namespace
Namespace System.Linq.Expressions
Public Class Expression
Public Shared Function Field(e As Expression, f As FieldInfo) As Expression
Return Nothing
End Function
Public Shared Function Lambda(Of T)(e As Expression, args As Expression()) As Expression(Of T)
Return Nothing
End Function
End Class
Public Class Expression(Of T)
End Class
Public Class ParameterExpression
Inherits Expression
End Class
End Namespace
Namespace System.Reflection
Public Class FieldInfo
End Class
End Namespace
Delegate Function D() As Object
Class A
Shared F As Object = Nothing
Shared G As Expression(Of D) = Function() F
End Class
Class B(Of T)
Shared F As Object = Nothing
Shared G As Expression(Of D) = Function() F
End Class
]]></file>
</compilation>)
AssertTheseEmitDiagnostics(compilation,
<errors>
BC35000: Requested operation is not available because the runtime library function 'System.Reflection.FieldInfo.GetFieldFromHandle' is not defined.
Shared G As Expression(Of D) = Function() F
~
BC35000: Requested operation is not available because the runtime library function 'System.Reflection.FieldInfo.GetFieldFromHandle' is not defined.
Shared G As Expression(Of D) = Function() F
~
</errors>)
End Sub
<WorkItem(797996, "DevDiv")>
<Fact()>
Public Sub MissingMember_System_Reflection_MethodBase__GetMethodFromHandle()
Dim compilation = CreateCompilationWithoutReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Imports System.Linq.Expressions
Imports System.Reflection
Namespace System
Public Class [Object]
End Class
Public Structure Void
End Structure
Public Class ValueType
End Class
Public Class MulticastDelegate
End Class
Public Structure IntPtr
End Structure
Public Structure Int32
End Structure
Public Structure Nullable(Of T)
End Structure
Public Class [Type]
Public Shared Function GetTypeFromHandle(h As RuntimeTypeHandle) As [Type]
Return Nothing
End Function
End Class
Public Structure RuntimeTypeHandle
End Structure
Public Class Array
End Class
Public Interface IAsyncResult
End Interface
Public Class AsyncCallback
End Class
End Namespace
Namespace System.Collections.Generic
Public Interface IEnumerable(Of T)
End Interface
End Namespace
Namespace System.Linq.Expressions
Public Class Expression
Public Shared Function [Call](e As Expression, m As MethodInfo, args As Expression()) As Expression
Return Nothing
End Function
Public Shared Function Constant(o As Object, t As Type) As Expression
Return Nothing
End Function
Public Shared Function Convert(e As Expression, t As Type) As Expression
Return Nothing
End Function
Public Shared Function Lambda(Of T)(e As Expression, args As Expression()) As Expression(Of T)
Return Nothing
End Function
Public Shared Function [New](c As ConstructorInfo, args As IEnumerable(Of Expression)) As Expression
Return Nothing
End Function
End Class
Public Class Expression(Of T)
End Class
Public Class ParameterExpression
Inherits Expression
End Class
End Namespace
Namespace System.Reflection
Public Class ConstructorInfo
End Class
Public Class MethodInfo
End Class
End Namespace
Delegate Function D() As Object
Class A
Shared F As Expression(Of D) = Function() New A(Nothing)
Shared G As Expression(Of D) = Function() M()
Shared Function M() As Object
Return Nothing
End Function
Sub New(o As Object)
End Sub
End Class
Class B(Of T)
Shared F As Expression(Of D) = Function() New A(Nothing)
Shared G As Expression(Of D) = Function() M()
Shared Function M() As Object
Return Nothing
End Function
Sub New(o As Object)
End Sub
End Class
]]></file>
</compilation>)
AssertTheseEmitDiagnostics(compilation,
<errors>
BC35000: Requested operation is not available because the runtime library function 'System.Reflection.MethodBase.GetMethodFromHandle' is not defined.
Shared G As Expression(Of D) = Function() M()
~~~
BC35000: Requested operation is not available because the runtime library function 'System.Reflection.MethodBase.GetMethodFromHandle' is not defined.
Shared G As Expression(Of D) = Function() M()
~~~
</errors>)
End Sub
#End Region
#Region "Expression Tree Test Helpers"
Private ReadOnly _exprTesting As XElement = <file name="exprlambdatest.vb"><%= ExpTreeTestResources.ExprLambdaUtils %></file>
Private ReadOnly _queryTesting As XElement = <file name="QueryHelper.vb"><%= ExpTreeTestResources.QueryHelper %></file>
#End Region
<Fact, WorkItem(808608, "DevDiv")>
Public Sub Bug808608_01()
Dim source = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Linq.Expressions
Friend Module M
Structure X
Public x As Integer
Public Shared Operator =(ByVal x As X, ByVal y As X) As Boolean
Return x.x = y.x
End Operator
Public Shared Operator <>(ByVal x As X, ByVal y As X) As Boolean
Return x.x <> y.x
End Operator
End Structure
Sub Main()
Foo1(Of X)(Nothing)
Foo1(New X())
Foo2(Of X)()
End Sub
Sub Foo1(Of T As Structure)(ByVal x As T?)
ExprTest(Function() x Is Nothing)
ExprTest(Function() x IsNot Nothing)
ExprTest(Function() Nothing Is x)
ExprTest(Function() Nothing IsNot x)
End Sub
Sub Foo2(Of T As Structure)()
ExprTest(Function() CType(Nothing, X?))
ExprTest(Function() CType(Nothing, X))
ExprTest(Function() CType(Nothing, T?))
ExprTest(Function() CType(Nothing, T))
End Sub
Public Sub ExprTest(Of T)(expr As Expression(Of Func(Of T)))
Console.WriteLine(expr.ToString)
End Sub
End Module
]]></file>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
options:=TestOptions.ReleaseExe,
expectedOutput:=<![CDATA[
() => (value(M+_Closure$__2-0`1[M+X]).$VB$Local_x == null)
() => (value(M+_Closure$__2-0`1[M+X]).$VB$Local_x != null)
() => (null == value(M+_Closure$__2-0`1[M+X]).$VB$Local_x)
() => (null != value(M+_Closure$__2-0`1[M+X]).$VB$Local_x)
() => (value(M+_Closure$__2-0`1[M+X]).$VB$Local_x == null)
() => (value(M+_Closure$__2-0`1[M+X]).$VB$Local_x != null)
() => (null == value(M+_Closure$__2-0`1[M+X]).$VB$Local_x)
() => (null != value(M+_Closure$__2-0`1[M+X]).$VB$Local_x)
() => null
() => new X()
() => Convert(null)
() => default(X)
]]>).VerifyDiagnostics()
End Sub
<Fact, WorkItem(808608, "DevDiv")>
Public Sub Bug808608_02()
Dim source = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Linq.Expressions
Friend Module M
Structure X
Public x As Integer
End Structure
Sub Main()
Foo1(Of X)(Nothing)
Foo1(New X())
Foo2(Of X)()
End Sub
Sub Foo1(Of T As Structure)(ByVal x As T?)
ExprTest(Function() x Is Nothing)
ExprTest(Function() x IsNot Nothing)
ExprTest(Function() Nothing Is x)
ExprTest(Function() Nothing IsNot x)
End Sub
Sub Foo2(Of T As Structure)()
ExprTest(Function() CType(Nothing, X?))
ExprTest(Function() CType(Nothing, X))
ExprTest(Function() CType(Nothing, T?))
ExprTest(Function() CType(Nothing, T))
End Sub
Public Sub ExprTest(Of T)(expr As Expression(Of Func(Of T)))
Console.WriteLine(expr.ToString)
End Sub
End Module
]]></file>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
options:=TestOptions.ReleaseExe,
expectedOutput:=<![CDATA[
() => (value(M+_Closure$__2-0`1[M+X]).$VB$Local_x == null)
() => (value(M+_Closure$__2-0`1[M+X]).$VB$Local_x != null)
() => (null == value(M+_Closure$__2-0`1[M+X]).$VB$Local_x)
() => (null != value(M+_Closure$__2-0`1[M+X]).$VB$Local_x)
() => (value(M+_Closure$__2-0`1[M+X]).$VB$Local_x == null)
() => (value(M+_Closure$__2-0`1[M+X]).$VB$Local_x != null)
() => (null == value(M+_Closure$__2-0`1[M+X]).$VB$Local_x)
() => (null != value(M+_Closure$__2-0`1[M+X]).$VB$Local_x)
() => null
() => new X()
() => Convert(null)
() => default(X)
]]>).VerifyDiagnostics()
End Sub
<Fact, WorkItem(808651, "DevDiv")>
Public Sub Bug808651()
Dim source = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Linq.Expressions
Friend Module M
Sub Main()
Dim str As String = "123"
ExprTest(Function() str & Nothing)
ExprTest(Function() Nothing & str)
End Sub
Public Sub ExprTest(Of T)(expr As Expression(Of Func(Of T)))
Console.WriteLine(expr.ToString)
End Sub
End Module
]]></file>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
options:=TestOptions.ReleaseExe,
expectedOutput:=<![CDATA[
() => Concat(value(M+_Closure$__0-0).$VB$Local_str, null)
() => Concat(null, value(M+_Closure$__0-0).$VB$Local_str)
]]>).VerifyDiagnostics()
End Sub
<Fact, WorkItem(1190, "https://github.com/dotnet/roslyn/issues/1190")>
Public Sub CollectionInitializers()
Dim source = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq.Expressions
Imports System.Runtime.CompilerServices
Namespace ConsoleApplication31
Module Program
Sub Main()
Try
Dim e1 As Expression(Of Func(Of Stack(Of Integer))) = Function() New Stack(Of Integer) From {42}
System.Console.WriteLine("e1 => {0}", e1.ToString())
Catch
System.Console.WriteLine("In catch")
End Try
Dim e2 As Expression(Of Func(Of MyStack(Of Integer))) = Function() New MyStack(Of Integer) From {42}
System.Console.WriteLine("e2 => {0}", e2.ToString())
System.Console.WriteLine(e2.Compile()().Pop())
End Sub
End Module
Module StackExtensions
<Extension()>
Public Sub Add(Of T)(s As Stack(Of T), x As T)
s.Push(x)
End Sub
End Module
Class MyStack(Of T)
Inherits System.Collections.Generic.Stack(Of T)
Public Sub Add(x As T)
Me.Push(x)
End Sub
End Class
End Namespace
]]></file>
</compilation>
CompileAndVerify(source,
additionalRefs:={SystemCoreRef},
options:=TestOptions.ReleaseExe,
expectedOutput:=<![CDATA[
In catch
e2 => () => new MyStack`1() {Void Add(Int32)(42)}
42
]]>).VerifyDiagnostics()
End Sub
End Class
End Namespace
|
droyad/roslyn
|
src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/CodeGenExprLambda.vb
|
Visual Basic
|
apache-2.0
| 263,270
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Text
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Text
Namespace Microsoft.CodeAnalysis.VisualBasic
Public Partial Class VisualBasicSyntaxTree
''' <summary>
''' A SyntaxTree is a tree of nodes that represents an entire file of VB
''' code, and is parsed by the parser.
''' </summary>
Partial Private Class ParsedSyntaxTree
Inherits VisualBasicSyntaxTree
Private ReadOnly _options As VisualBasicParseOptions
Private ReadOnly _path As String
Private ReadOnly _root As VisualBasicSyntaxNode
Private ReadOnly _hasCompilationUnitRoot As Boolean
Private ReadOnly _isMyTemplate As Boolean
Private ReadOnly _encodingOpt As Encoding
Private ReadOnly _checksumAlgorithm As SourceHashAlgorithm
Private _lazyText As SourceText
''' <summary>
''' Used to create new tree incrementally.
''' </summary>
Friend Sub New(textOpt As SourceText,
encodingOpt As Encoding,
checksumAlgorithm As SourceHashAlgorithm,
path As String,
options As VisualBasicParseOptions,
syntaxRoot As VisualBasicSyntaxNode,
isMyTemplate As Boolean,
Optional cloneRoot As Boolean = True)
Debug.Assert(syntaxRoot IsNot Nothing)
Debug.Assert(options IsNot Nothing)
Debug.Assert(textOpt Is Nothing OrElse textOpt.Encoding Is encodingOpt AndAlso textOpt.ChecksumAlgorithm = checksumAlgorithm)
_lazyText = textOpt
_encodingOpt = If(encodingOpt, textOpt?.Encoding)
_checksumAlgorithm = checksumAlgorithm
_options = options
_path = If(path, String.Empty)
_root = If(cloneRoot, Me.CloneNodeAsRoot(syntaxRoot), syntaxRoot)
_hasCompilationUnitRoot = (syntaxRoot.Kind = SyntaxKind.CompilationUnit)
_isMyTemplate = isMyTemplate
End Sub
Public Overrides ReadOnly Property FilePath As String
Get
Return _path
End Get
End Property
Friend Overrides ReadOnly Property IsMyTemplate As Boolean
Get
Return _isMyTemplate
End Get
End Property
Public Overrides Function GetText(Optional cancellationToken As CancellationToken = Nothing) As SourceText
If _lazyText Is Nothing Then
Dim treeText = Me.GetRoot(cancellationToken).GetText(_encodingOpt, _checksumAlgorithm)
Interlocked.CompareExchange(_lazyText, treeText, Nothing)
End If
Return _lazyText
End Function
Public Overrides Function TryGetText(ByRef text As SourceText) As Boolean
text = _lazyText
Return text IsNot Nothing
End Function
Public Overrides ReadOnly Property Encoding As Encoding
Get
Return _encodingOpt
End Get
End Property
Public Overrides ReadOnly Property Length As Integer
Get
Return _root.FullSpan.Length
End Get
End Property
Public Overrides Function GetRoot(Optional cancellationToken As CancellationToken = Nothing) As VisualBasicSyntaxNode
Return _root
End Function
Public Overrides Function GetRootAsync(Optional cancellationToken As CancellationToken = Nothing) As Task(Of VisualBasicSyntaxNode)
Return Task.FromResult(_root)
End Function
Public Overrides Function TryGetRoot(ByRef root As VisualBasicSyntaxNode) As Boolean
root = _root
Return True
End Function
Public Overrides ReadOnly Property HasCompilationUnitRoot As Boolean
Get
Return _hasCompilationUnitRoot
End Get
End Property
Public Overrides ReadOnly Property Options As VisualBasicParseOptions
Get
Return _options
End Get
End Property
''' <summary>
''' Get a reference to the given node.
''' </summary>
Public Overrides Function GetReference(node As SyntaxNode) As SyntaxReference
Return New SimpleSyntaxReference(Me, node)
End Function
Public Overrides Function WithRootAndOptions(root As SyntaxNode, options As ParseOptions) As SyntaxTree
If Me._root Is root AndAlso Me._options Is options Then
Return Me
End If
Return New ParsedSyntaxTree(
Nothing,
Me._encodingOpt,
Me._checksumAlgorithm,
Me._path,
DirectCast(options, VisualBasicParseOptions),
DirectCast(root, VisualBasicSyntaxNode),
Me._isMyTemplate)
End Function
Public Overrides Function WithFilePath(path As String) As SyntaxTree
If String.Equals(Me._path, path) Then
Return Me
End If
Return New ParsedSyntaxTree(
Me._lazyText,
Me._encodingOpt,
Me._checksumAlgorithm,
path,
Me._options,
Me._root,
Me._isMyTemplate)
End Function
End Class
End Class
End Namespace
|
Pvlerick/roslyn
|
src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxTree.ParsedSyntaxTree.vb
|
Visual Basic
|
apache-2.0
| 6,132
|
Namespace VBWinFormDataGridView.EditingControlHosting
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class MainForm
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.label1 = New System.Windows.Forms.Label
Me.dataGridView1 = New System.Windows.Forms.DataGridView
CType(Me.dataGridView1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'label1
'
Me.label1.AutoSize = True
Me.label1.Font = New System.Drawing.Font("Verdana", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.label1.Location = New System.Drawing.Point(20, 27)
Me.label1.Name = "label1"
Me.label1.Size = New System.Drawing.Size(582, 20)
Me.label1.TabIndex = 3
Me.label1.Text = "This sample demonstrates how to host a control in the current DataGridViewCell f" & _
"or editing."
Me.label1.UseCompatibleTextRendering = True
'
'dataGridView1
'
Me.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
Me.dataGridView1.Location = New System.Drawing.Point(23, 64)
Me.dataGridView1.Name = "dataGridView1"
Me.dataGridView1.Size = New System.Drawing.Size(586, 350)
Me.dataGridView1.TabIndex = 2
'
'MainForm
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(628, 441)
Me.Controls.Add(Me.label1)
Me.Controls.Add(Me.dataGridView1)
Me.Name = "MainForm"
Me.Text = "MainForm"
CType(Me.dataGridView1, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Private WithEvents label1 As System.Windows.Forms.Label
Private WithEvents dataGridView1 As System.Windows.Forms.DataGridView
End Class
End Namespace
|
Neo-Desktop/Coleman-Code
|
COM350/Project3/VBWinFormDataGridView/EditingControlHosting/MainForm.Designer.vb
|
Visual Basic
|
mit
| 3,093
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.18034
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Imports System
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("Banner.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
alexgurrola/banner
|
Banner/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,712
|
Imports System.Text.RegularExpressions
Imports System.Net
Imports System.IO
Imports Microsoft.Win32
Public Class UpdaterFrm
Dim CurrentVersion As String = "0.0.0" '--- Change this to Current version, needs changing on every update
Dim ProgramName As String = "BlueSheep" '--- Program Name
Dim SiteName As String = "http://bluesheepbot.com/update.html" '--- Update Page
Dim VersionCHK, GetVer, GetVerLink As String
Dim GetUpd As Integer
Private Sub UpdaterFrm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
' StatusLb.Text = "Vérification des sécurités..."
' For Each Process In Diagnostics.Process.GetProcesses()
' 'Si un des noms de processus correspond
' If Process.ProcessName.Contains("wampserver") Then
' Me.Close()
' ElseIf Process.ProcessName.Contains("wireshark") Then
' Me.Close()
' ' AlertBox1.Visible = True
' ' Close_form()
' 'ElseIf Process.ProcessName.Contains("javaw") Then
' ' Me.Close()
' End If
' Next
' Pbar.Value = 10
' Dim chemin As String = Environment.GetEnvironmentVariable("windir") & "\system32\drivers\etc\hosts"
' If File.Exists(chemin) Then
' Dim X As System.IO.StreamWriter = New System.IO.StreamWriter(chemin)
' Dim Contenu As String = "127.0.0.1 localhost"
' X.WriteLine(Contenu)
' X.Close()
' End If
Pbar.Value = 20
Pbar.Value = 25
If Not Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\BlueSheep") Then
Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\BlueSheep")
End If
If File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\BlueSheep\BlueSheep.exe") Then
AutoUpdate()
Else
Dim Thread As New Threading.Thread(AddressOf Download)
Thread.Start()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Public Sub AutoUpdate()
Dim WebRequest As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(SiteName)
Dim WebResponse As System.Net.HttpWebResponse = WebRequest.GetResponse
Dim STR As System.IO.StreamReader = New System.IO.StreamReader(WebResponse.GetResponseStream())
Dim ReadSource As String = STR.ReadToEnd
Dim Regex As New System.Text.RegularExpressions.Regex(ProgramName & "=(\d+).(\d+).(\d+)=(.*?).exe")
Dim matches As MatchCollection = Regex.Matches(ReadSource)
'Dim reg As RegistryKey
Dim c As Integer
Dim reg As RegistryKey = Registry.CurrentUser.OpenSubKey("Software\BlueSheep")
'If File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\BlueSheep\version.bs") Then
'If cs.Contains("Software\\BlueSheep") Then
If reg IsNot Nothing Then
'reg = Registry.CurrentUser.CreateSubKey("Software\BlueSheep")
CurrentVersion = reg.GetValue("Version").ToString()
c = reg.GetValue("Minor")
'Dim reader As New StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\BlueSheep\version.bs")
'Dim BVer As String = reader.ReadLine()
'Dim decByte As Byte() = Convert.FromBase64String(BVer)
'CurrentVersion = System.Text.Encoding.ASCII.GetString(decByte)
'reader.Close()
Else
File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\BlueSheep\BlueSheep.exe")
Dim Thread As New Threading.Thread(AddressOf Download)
Thread.Start()
Exit Sub
End If
For Each match As Match In matches
Dim RegSplit() As String = Split(match.ToString, "=")
GetVer = RegSplit(1)
GetVerLink = RegSplit(2)
Next
Pbar.Value = 100
Dim major As Integer = Convert.ToInt32(GetVer.Split(".")(0))
Dim minor As Integer = Convert.ToInt32(GetVer.Split(".")(1))
Dim release As Integer = Convert.ToInt32(GetVer.Split(".")(2))
Dim currentmajor As Integer
Dim currentminor As Integer
If (CurrentVersion.Contains(",")) Then
currentmajor = Convert.ToInt32(CurrentVersion.Split(",")(0))
currentminor = Convert.ToInt32(CurrentVersion.Split(",")(1))
Else
currentmajor = Convert.ToInt32(CurrentVersion.Split(".")(0))
currentminor = Convert.ToInt32(CurrentVersion.Split(".")(1))
End If
Dim currentrelease As Integer = c
If major > currentmajor OrElse minor > currentminor OrElse release > currentrelease Then
'My.Computer.Network.DownloadFile(GetVerLink, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & IO.Path.GetFileName(GetVerLink))
File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\BlueSheep\BlueSheep.exe")
Dim Thread As New Threading.Thread(AddressOf Download)
Thread.Start()
Else
client_DownloadCompleted(Nothing, Nothing)
End If
End Sub
Private Sub client_ProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
Me.BeginInvoke(DirectCast(Sub() Pbar.Value = e.ProgressPercentage, MethodInvoker))
Me.BeginInvoke(DirectCast(Sub() StatusLb.Text = "Téléchargement en cours... " & e.ProgressPercentage & " %", MethodInvoker))
End Sub
Private Sub client_DownloadCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
Try
Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\BlueSheep\BlueSheep.exe", "ok")
Me.BeginInvoke(DirectCast(Sub() Me.Close(), MethodInvoker))
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub dll_DownloadCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
Dim Thread As New Threading.Thread(AddressOf Download)
Thread.Start()
End Sub
Private Sub Download()
Try
If Not File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\BlueSheep\ICSharpCode.SharpZipLib.dll") Then
Dim Thread As New Threading.Thread(AddressOf Dll)
Thread.Start()
Exit Sub
End If
Dim Client As WebClient = New WebClient
AddHandler Client.DownloadProgressChanged, AddressOf client_ProgressChanged
AddHandler Client.DownloadFileCompleted, AddressOf client_DownloadCompleted
Client.DownloadFileAsync(New Uri("http://bluesheepbot.com/BlueSheep.exe"), Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\BlueSheep\BlueSheep.exe")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Dll()
Dim Client As WebClient = New WebClient
AddHandler Client.DownloadProgressChanged, AddressOf client_ProgressChanged
AddHandler Client.DownloadFileCompleted, AddressOf dll_DownloadCompleted
Client.DownloadFileAsync(New Uri("http://bluesheepbot.com/ICSharpCode.SharpZipLib.dll"), Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\BlueSheep\ICSharpCode.SharpZipLib.dll")
End Sub
End Class
|
AnonymousSheep/BlueSheep
|
Updater/Updater/Form1.vb
|
Visual Basic
|
mit
| 7,884
|
Imports Microsoft.VisualBasic
Imports System
Imports System.Reflection
Imports System.Resources
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
<Assembly: AssemblyTitle("Microsoft.KeyBindings")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyConfiguration("")>
<Assembly: AssemblyCompany("Microsoft")>
<Assembly: AssemblyProduct("Microsoft.KeyBindings")>
<Assembly: AssemblyCopyright("")>
<Assembly: AssemblyTrademark("")>
<Assembly: AssemblyCulture("")>
<Assembly: ComVisible(False)>
<Assembly: CLSCompliant(false)>
<Assembly: NeutralResourcesLanguage("en-US")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Revision and Build Numbers
' by using the '*' as shown below:
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
chrisdias/VSKeyBindings
|
Properties/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,205
|
Imports System.IO
Imports Aspose.Cells
Namespace Worksheets.Display
Public Class DisplayTab
Public Shared Sub Run()
' ExStart:1
' The path to the documents directory.
Dim dataDir As String = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
' Opening the Excel file
Dim workbook As New Workbook(dataDir & "book1.xls")
' Hiding the tabs of the Excel file
workbook.Settings.ShowTabs = False
' Saving the modified Excel file
workbook.Save(dataDir & "output.xls")
' ExEnd:1
End Sub
End Class
End Namespace
|
maria-shahid-aspose/Aspose.Cells-for-.NET
|
Examples/VisualBasic/Worksheets/Display/DisplayTabs.vb
|
Visual Basic
|
mit
| 686
|
Namespace QNAP
Partial Public Class HardDrive
Implements IMonitorable
#Region " IMonitorable Implementation "
Public ReadOnly Property IsHardDriveHealthy() As Health Implements IMonitorable.IsHealthy
Get
If Status <> HDStatus.READY Then
Return New Health(HealthStatus.Degraded, String.Format(Resources.HEALTH_QNAP_HARDDRIVENOTREADY, Index, Description))
ElseIf Not String.IsNullOrEmpty(SMART) AndAlso SMART.ToUpper <> "GOOD" Then
Return New Health(HealthStatus.Degraded, String.Format(Resources.HEALTH_QNAP_HARDDRIVEBADSMART, Index, Description, SMART))
ElseIf Not Temperature Is Nothing Then
Temperature.WarningLevelHigh = 40
Return Monitoring.CheckHealth(New Health(HealthStatus.Healthy), Temperature)
Else
Return New Health(HealthStatus.Healthy)
End If
End Get
End Property
#End Region
End Class
End Namespace
|
thiscouldbejd/Caerus
|
_QNAP/Partials/HardDrive.vb
|
Visual Basic
|
mit
| 909
|
Imports system.diagnostics
Public NotInheritable Class AboutBox
Private Sub AboutBox1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
PictureBox1.Cursor = Cursors.Hand
PictureBox2.Cursor = Cursors.Hand
PictureBox3.Cursor = Cursors.Hand
Dim ApplicationTitle As String
If My.Application.Info.Title <> "" Then
ApplicationTitle = My.Application.Info.Title
Else
ApplicationTitle = System.IO.Path.GetFileNameWithoutExtension(My.Application.Info.AssemblyName)
End If
TextBox1.Text = My.Application.Info.Description
TextBox1.SelectedText = ""
End Sub
Private Sub OKButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.Close()
End Sub
Private Sub PictureBox2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox2.Click
Process.Start("http://www.zso.krahs-emag.com")
End Sub
Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
Process.Start("http://www.opengl.org")
End Sub
Private Sub PictureBox3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Process.Start("http://www.taoframework.com")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Close()
End Sub
Private Sub PictureBox3_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox3.Click
Process.Start("http://msdn2.microsoft.com/en-us/default.aspx")
End Sub
End Class
|
iterami/uot
|
Utility of Time/AboutBox.vb
|
Visual Basic
|
cc0-1.0
| 1,733
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGen
Friend Partial Class CodeGenerator
Private Sub EmitStatement(statement As BoundStatement)
Select Case statement.Kind
Case BoundKind.Block
EmitBlock(DirectCast(statement, BoundBlock))
Case BoundKind.SequencePoint
EmitSequencePointStatement(DirectCast(statement, BoundSequencePoint))
Case BoundKind.SequencePointWithSpan
EmitSequencePointStatement(DirectCast(statement, BoundSequencePointWithSpan))
Case BoundKind.ExpressionStatement
EmitExpression((DirectCast(statement, BoundExpressionStatement)).Expression, False)
Case BoundKind.NoOpStatement
EmitNoOpStatement(DirectCast(statement, BoundNoOpStatement))
Case BoundKind.StatementList
Dim list = DirectCast(statement, BoundStatementList)
Dim n As Integer = list.Statements.Length
For i = 0 To n - 1
EmitStatement(list.Statements(i))
Next
Case BoundKind.ReturnStatement
EmitReturnStatement(DirectCast(statement, BoundReturnStatement))
Case BoundKind.ThrowStatement
EmitThrowStatement(DirectCast(statement, BoundThrowStatement))
Case BoundKind.GotoStatement
EmitGotoStatement(DirectCast(statement, BoundGotoStatement))
Case BoundKind.LabelStatement
EmitLabelStatement(DirectCast(statement, BoundLabelStatement))
Case BoundKind.ConditionalGoto
EmitConditionalGoto(DirectCast(statement, BoundConditionalGoto))
Case BoundKind.TryStatement
EmitTryStatement(DirectCast(statement, BoundTryStatement))
Case BoundKind.SelectStatement
EmitSelectStatement(DirectCast(statement, BoundSelectStatement))
Case BoundKind.UnstructuredExceptionOnErrorSwitch
EmitUnstructuredExceptionOnErrorSwitch(DirectCast(statement, BoundUnstructuredExceptionOnErrorSwitch))
Case BoundKind.UnstructuredExceptionResumeSwitch
EmitUnstructuredExceptionResumeSwitch(DirectCast(statement, BoundUnstructuredExceptionResumeSwitch))
Case BoundKind.StateMachineScope
EmitStateMachineScope(DirectCast(statement, BoundStateMachineScope))
Case Else
Throw ExceptionUtilities.UnexpectedValue(statement.Kind)
End Select
#If DEBUG Then
If Me._stackLocals Is Nothing OrElse Not Me._stackLocals.Any Then
_builder.AssertStackEmpty()
End If
#End If
End Sub
Private Function EmitStatementAndCountInstructions(statement As BoundStatement) As Integer
Dim n = _builder.InstructionsEmitted
EmitStatement(statement)
Return _builder.InstructionsEmitted - n
End Function
Private Sub EmitNoOpStatement(statement As BoundNoOpStatement)
Select Case statement.Flavor
Case NoOpStatementFlavor.Default
If _ilEmitStyle = ILEmitStyle.Debug Then
_builder.EmitOpCode(ILOpCode.Nop)
End If
Case NoOpStatementFlavor.AwaitYieldPoint
Debug.Assert((_asyncYieldPoints Is Nothing) = (_asyncResumePoints Is Nothing))
If _asyncYieldPoints Is Nothing Then
_asyncYieldPoints = ArrayBuilder(Of Integer).GetInstance
_asyncResumePoints = ArrayBuilder(Of Integer).GetInstance
End If
Debug.Assert(_asyncYieldPoints.Count = _asyncResumePoints.Count)
_asyncYieldPoints.Add(_builder.AllocateILMarker())
Case NoOpStatementFlavor.AwaitResumePoint
Debug.Assert(_asyncYieldPoints IsNot Nothing)
Debug.Assert(_asyncResumePoints IsNot Nothing)
Debug.Assert((_asyncYieldPoints.Count - 1) = _asyncResumePoints.Count)
_asyncResumePoints.Add(_builder.AllocateILMarker())
Case Else
Throw ExceptionUtilities.UnexpectedValue(statement.Flavor)
End Select
End Sub
Private Sub EmitTryStatement(statement As BoundTryStatement, Optional emitCatchesOnly As Boolean = False)
Debug.Assert(Not statement.CatchBlocks.IsDefault)
' Stack must be empty at beginning of try block.
_builder.AssertStackEmpty()
' IL requires catches and finally block to be distinct try
' blocks so if the source contained both a catch and
' a finally, nested scopes are emitted.
Dim emitNestedScopes As Boolean = (Not emitCatchesOnly AndAlso (statement.CatchBlocks.Length > 0) AndAlso (statement.FinallyBlockOpt IsNot Nothing))
_builder.OpenLocalScope(ScopeType.TryCatchFinally)
_builder.OpenLocalScope(ScopeType.Try)
Me._tryNestingLevel += 1
If emitNestedScopes Then
EmitTryStatement(statement, emitCatchesOnly:=True)
Else
EmitBlock(statement.TryBlock)
End If
Debug.Assert(Me._tryNestingLevel > 0)
Me._tryNestingLevel -= 1
' close Try scope
_builder.CloseLocalScope()
If Not emitNestedScopes Then
For Each catchBlock In statement.CatchBlocks
EmitCatchBlock(catchBlock)
Next
End If
If Not emitCatchesOnly AndAlso (statement.FinallyBlockOpt IsNot Nothing) Then
_builder.OpenLocalScope(ScopeType.Finally)
EmitBlock(statement.FinallyBlockOpt)
_builder.CloseLocalScope()
End If
_builder.CloseLocalScope()
If Not emitCatchesOnly AndAlso statement.ExitLabelOpt IsNot Nothing Then
_builder.MarkLabel(statement.ExitLabelOpt)
End If
End Sub
'The interesting part in the following method is the support for exception filters.
'=== Example:
'
'Try
' <SomeCode>
'Catch ex as NullReferenceException When ex.Message isnot Nothing
' <Handler>
'End Try
'
'gets emitted as something like ===>
'
'Try
' <SomeCode>
'Filter
' Condition ' starts with exception on the stack
' Dim temp As NullReferenceException = TryCast(Pop, NullReferenceException)
' if temp is Nothing
' Push 0
' Else
' ex = temp
' Push if ((ex.Message isnot Nothing), 1, 0)
' End If
' End Condition ' leaves 1 or 0 on the stack
' Handler ' gets called after finalization of nested exception frames if condition above produced 1
' <Handler>
' End Handler
'End Try
Private Sub EmitCatchBlock(catchBlock As BoundCatchBlock)
Dim oldCatchBlock = _currentCatchBlock
_currentCatchBlock = catchBlock
Dim typeCheckFailedLabel As Object = Nothing
Dim exceptionSource = catchBlock.ExceptionSourceOpt
Dim exceptionType As Cci.ITypeReference
If exceptionSource IsNot Nothing Then
exceptionType = Me._module.Translate(exceptionSource.Type, exceptionSource.Syntax, _diagnostics)
Else
' if type is not specified it is assumed to be System.Exception
exceptionType = Me._module.Translate(Me._module.Compilation.GetWellKnownType(WellKnownType.System_Exception), catchBlock.Syntax, _diagnostics)
End If
' exception on stack
_builder.AdjustStack(1)
If catchBlock.ExceptionFilterOpt IsNot Nothing AndAlso catchBlock.ExceptionFilterOpt.Kind = BoundKind.UnstructuredExceptionHandlingCatchFilter Then
' This is a special catch created for Unstructured Exception Handling
Debug.Assert(catchBlock.LocalOpt Is Nothing)
Debug.Assert(exceptionSource Is Nothing)
'
' Generate the OnError filter.
'
' The On Error filter catches an exception when a handler is active and the method
' isn't currently in the process of handling an earlier error. We know the method
' is handling an earlier error when we have a valid Resume target.
'
' The filter expression is the equivalent of:
'
' Catch e When (TypeOf e Is Exception) And (ActiveHandler <> 0) And (ResumeTarget = 0)
'
Dim filter = DirectCast(catchBlock.ExceptionFilterOpt, BoundUnstructuredExceptionHandlingCatchFilter)
_builder.OpenLocalScope(ScopeType.Filter)
'Determine if the exception object is or inherits from System.Exception
_builder.EmitOpCode(ILOpCode.Isinst)
_builder.EmitToken(exceptionType, catchBlock.Syntax, _diagnostics)
_builder.EmitOpCode(ILOpCode.Ldnull)
_builder.EmitOpCode(ILOpCode.Cgt_un)
' Calculate ActiveHandler <> 0
EmitLocalLoad(filter.ActiveHandlerLocal, used:=True)
_builder.EmitIntConstant(0)
_builder.EmitOpCode(ILOpCode.Cgt_un)
' AND the values together.
_builder.EmitOpCode(ILOpCode.And)
' Calculate ResumeTarget = 0
EmitLocalLoad(filter.ResumeTargetLocal, used:=True)
_builder.EmitIntConstant(0)
_builder.EmitOpCode(ILOpCode.Ceq)
' AND the values together.
_builder.EmitOpCode(ILOpCode.And)
' Now we are starting the actual handler
_builder.MarkFilterConditionEnd()
_builder.EmitOpCode(ILOpCode.Castclass)
_builder.EmitToken(exceptionType, catchBlock.Syntax, _diagnostics)
If ShouldNoteProjectErrors() Then
EmitSetProjectError(catchBlock.Syntax, catchBlock.ErrorLineNumberOpt)
Else
_builder.EmitOpCode(ILOpCode.Pop)
End If
Else
' open appropriate exception handler scope. (Catch or Filter)
' if it is a Filter, emit prologue that checks if the type on the stack
' converts to what we want.
If catchBlock.ExceptionFilterOpt Is Nothing Then
_builder.OpenLocalScope(ScopeType.Catch, exceptionType)
If catchBlock.IsSynthesizedAsyncCatchAll Then
Debug.Assert(_asyncCatchHandlerOffset < 0)
_asyncCatchHandlerOffset = _builder.AllocateILMarker()
End If
Else
_builder.OpenLocalScope(ScopeType.Filter)
' Filtering starts with simulating regular Catch through an imperative type check
' If this is not our type, then we are done
Dim typeCheckPassedLabel As New Object
typeCheckFailedLabel = New Object
_builder.EmitOpCode(ILOpCode.Isinst)
_builder.EmitToken(exceptionType, catchBlock.Syntax, _diagnostics)
_builder.EmitOpCode(ILOpCode.Dup)
_builder.EmitBranch(ILOpCode.Brtrue, typeCheckPassedLabel)
_builder.EmitOpCode(ILOpCode.Pop)
_builder.EmitIntConstant(0)
_builder.EmitBranch(ILOpCode.Br, typeCheckFailedLabel)
_builder.MarkLabel(typeCheckPassedLabel)
End If
' define local if we have one
Dim localOpt = catchBlock.LocalOpt
If localOpt IsNot Nothing Then
' TODO: this local can be released when we can release named locals.
Dim declNodes = localOpt.DeclaringSyntaxReferences
DefineLocal(localOpt, If(Not declNodes.IsEmpty, DirectCast(declNodes(0).GetSyntax(), VisualBasicSyntaxNode), catchBlock.Syntax))
End If
' assign the exception variable if we have one
If exceptionSource IsNot Nothing Then
If ShouldNoteProjectErrors() Then
_builder.EmitOpCode(ILOpCode.Dup)
EmitSetProjectError(catchBlock.Syntax, catchBlock.ErrorLineNumberOpt)
End If
' here we have our exception on the stack in a form of a reference type (O)
' it means that we have to "unbox" it before storing to the local
' if exception's type is a generic type parameter.
If exceptionSource.Type.IsTypeParameter Then
_builder.EmitOpCode(ILOpCode.Unbox_any)
EmitSymbolToken(exceptionSource.Type, exceptionSource.Syntax)
End If
' TODO: parts of the following code is common with AssignmentExpression
' the only major difference is that assignee is on the stack
' consider factoring out common code.
While exceptionSource.Kind = BoundKind.Sequence
Dim seq = DirectCast(exceptionSource, BoundSequence)
EmitSideEffects(seq.SideEffects)
If seq.ValueOpt Is Nothing Then
Exit While
Else
exceptionSource = seq.ValueOpt
End If
End While
Select Case exceptionSource.Kind
Case BoundKind.Local
Debug.Assert(Not DirectCast(exceptionSource, BoundLocal).LocalSymbol.IsByRef)
_builder.EmitLocalStore(GetLocal(DirectCast(exceptionSource, BoundLocal)))
Case BoundKind.Parameter
Dim left = DirectCast(exceptionSource, BoundParameter)
' When assigning to a byref param
' we need to push param address below the exception
If left.ParameterSymbol.IsByRef Then
Dim temp = AllocateTemp(exceptionSource.Type, exceptionSource.Syntax)
_builder.EmitLocalStore(temp)
_builder.EmitLoadArgumentOpcode(ParameterSlot(left))
_builder.EmitLocalLoad(temp)
FreeTemp(temp)
End If
EmitParameterStore(left)
Case BoundKind.FieldAccess
Dim left = DirectCast(exceptionSource, BoundFieldAccess)
If Not left.FieldSymbol.IsShared Then
Dim stateMachineField = TryCast(left.FieldSymbol, StateMachineFieldSymbol)
If (stateMachineField IsNot Nothing) AndAlso (stateMachineField.SlotIndex >= 0) Then
DefineUserDefinedStateMachineHoistedLocal(stateMachineField)
End If
' When assigning to a field
' we need to push param address below the exception
Dim temp = AllocateTemp(exceptionSource.Type, exceptionSource.Syntax)
_builder.EmitLocalStore(temp)
Dim receiver = left.ReceiverOpt
' EmitFieldReceiver will handle receivers with type parameter type,
' but we do not know of a test case that will get here with receiver
' of type T. The assert is here to catch such a case. If the assert
' fails, remove the assert and add a corresponding test case.
Debug.Assert(receiver.Type.TypeKind <> TypeKind.TypeParameter)
Dim temp1 = EmitReceiverRef(receiver, isAccessConstrained:=False, addressKind:=AddressKind.[ReadOnly])
Debug.Assert(temp1 Is Nothing, "temp is unexpected when assigning to a field")
_builder.EmitLocalLoad(temp)
End If
EmitFieldStore(left)
Case Else
Throw ExceptionUtilities.UnexpectedValue(exceptionSource.Kind)
End Select
Else
If ShouldNoteProjectErrors() Then
EmitSetProjectError(catchBlock.Syntax, catchBlock.ErrorLineNumberOpt)
Else
_builder.EmitOpCode(ILOpCode.Pop)
End If
End If
' emit the actual filter expression, if we have one,
' and normalize results
If catchBlock.ExceptionFilterOpt IsNot Nothing Then
EmitCondExpr(catchBlock.ExceptionFilterOpt, True)
' Normalize the return value because values other than 0 or 1 produce unspecified results.
_builder.EmitIntConstant(0)
_builder.EmitOpCode(ILOpCode.Cgt_un)
_builder.MarkLabel(typeCheckFailedLabel)
' Now we are starting the actual handler
_builder.MarkFilterConditionEnd()
'pop the exception, it should have been already stored to the variable by the filter.
_builder.EmitOpCode(ILOpCode.Pop)
End If
End If
' emit actual handler body
' Note that it is a block so it will introduce its own scope for locals
' it should also have access to the exception local if we have declared one
' as that is scoped to the whole Catch/Filter
EmitBlock(catchBlock.Body)
' if the end of handler is reachable we should clear project errors.
' (if unreachable, this will not be emitted)
If ShouldNoteProjectErrors() AndAlso
(catchBlock.ExceptionFilterOpt Is Nothing OrElse catchBlock.ExceptionFilterOpt.Kind <> BoundKind.UnstructuredExceptionHandlingCatchFilter) Then
EmitClearProjectError(catchBlock.Syntax)
End If
_builder.CloseLocalScope()
_currentCatchBlock = oldCatchBlock
End Sub
''' <summary>
''' Tells if we should emit [Set/Clear]ProjectErrors when entering/leaving handlers
''' </summary>
Private Function ShouldNoteProjectErrors() As Boolean
Return Not Me._module.SourceModule.ContainingSourceAssembly.IsVbRuntime
End Function
Private Sub EmitSetProjectError(syntaxNode As VisualBasicSyntaxNode, errorLineNumberOpt As BoundExpression)
Dim setProjectErrorMethod As MethodSymbol
If errorLineNumberOpt Is Nothing Then
setProjectErrorMethod = DirectCast(Me._module.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError), MethodSymbol)
' consumes exception object from the stack
_builder.EmitOpCode(ILOpCode.Call, -1)
Else
setProjectErrorMethod = DirectCast(Me._module.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError_Int32), MethodSymbol)
EmitExpression(errorLineNumberOpt, used:=True)
' consumes exception object from the stack and the error line number
_builder.EmitOpCode(ILOpCode.Call, -2)
End If
Me.EmitSymbolToken(setProjectErrorMethod, syntaxNode)
End Sub
Private Sub EmitClearProjectError(syntaxNode As VisualBasicSyntaxNode)
Const clearProjectError As WellKnownMember = WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__ClearProjectError
Dim clearProjectErrorMethod = DirectCast(Me._module.Compilation.GetWellKnownTypeMember(clearProjectError), MethodSymbol)
' void static with no arguments
_builder.EmitOpCode(ILOpCode.Call, 0)
Me.EmitSymbolToken(clearProjectErrorMethod, syntaxNode)
End Sub
' specifies whether emitted conditional expression was a constant true/false or not a constant
Private Enum ConstResKind
ConstFalse
ConstTrue
NotAConst
End Enum
Private Sub EmitConditionalGoto(boundConditionalGoto As BoundConditionalGoto)
Dim label As Object = boundConditionalGoto.Label
Debug.Assert(label IsNot Nothing)
EmitCondBranch(boundConditionalGoto.Condition, label, boundConditionalGoto.JumpIfTrue)
End Sub
' 3.17 The brfalse instruction transfers control to target if value (of type int32, int64, object reference, managed
'pointer, unmanaged pointer or native int) is zero (false). If value is non-zero (true), execution continues at
'the next instruction.
Private Function CanPassToBrfalse(ts As TypeSymbol) As Boolean
If ts.IsEnumType Then
' valid enums are all primitives
Return True
End If
Dim tc = ts.PrimitiveTypeCode
Select Case tc
Case Cci.PrimitiveTypeCode.Float32, Cci.PrimitiveTypeCode.Float64
Return False
Case Cci.PrimitiveTypeCode.NotPrimitive
' if this is a generic type param, verifier will want us to box
' EmitCondBranch knows that
Return ts.IsReferenceType
Case Else
Debug.Assert(tc <> Cci.PrimitiveTypeCode.Invalid)
Debug.Assert(tc <> Cci.PrimitiveTypeCode.Void)
Return True
End Select
End Function
Private Function TryReduce(condition As BoundBinaryOperator, ByRef sense As Boolean) As BoundExpression
Dim opKind = condition.OperatorKind And BinaryOperatorKind.OpMask
Debug.Assert(opKind = BinaryOperatorKind.Equals OrElse
opKind = BinaryOperatorKind.NotEquals OrElse
opKind = BinaryOperatorKind.Is OrElse
opKind = BinaryOperatorKind.IsNot)
Dim nonConstOp As BoundExpression
Dim constOp As ConstantValue = condition.Left.ConstantValueOpt
If constOp IsNot Nothing Then
nonConstOp = condition.Right
Else
constOp = condition.Right.ConstantValueOpt
If constOp Is Nothing Then
Return Nothing
End If
nonConstOp = condition.Left
End If
Dim nonConstType = nonConstOp.Type
Debug.Assert(nonConstType IsNot Nothing OrElse (nonConstOp.IsNothingLiteral() AndAlso (opKind = BinaryOperatorKind.Is OrElse opKind = BinaryOperatorKind.IsNot)))
If nonConstType IsNot Nothing AndAlso Not CanPassToBrfalse(nonConstType) Then
Return Nothing
End If
Dim isBool As Boolean = nonConstType IsNot Nothing AndAlso nonConstType.PrimitiveTypeCode = Microsoft.Cci.PrimitiveTypeCode.Boolean
Dim isZero As Boolean = constOp.IsDefaultValue
If Not isBool AndAlso Not isZero Then
Return Nothing
End If
If isZero Then
sense = Not sense
End If
If opKind = BinaryOperatorKind.NotEquals OrElse opKind = BinaryOperatorKind.IsNot Then
sense = Not sense
End If
Return nonConstOp
End Function
Private Const s_IL_OP_CODE_ROW_LENGTH = 4
' // < <= > >=
' ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Signed
' ILOpCode.Bge, ILOpCode.Bgt, ILOpCode.Ble, ILOpCode.Blt, // Signed Invert
' ILOpCode.Blt_un, ILOpCode.Ble_un, ILOpCode.Bgt_un, ILOpCode.Bge_un, // Unsigned
' ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Unsigned Invert
' ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Float
' ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Float Invert
Private Shared ReadOnly s_condJumpOpCodes As ILOpCode() = New ILOpCode() {
ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge,
ILOpCode.Bge, ILOpCode.Bgt, ILOpCode.Ble, ILOpCode.Blt,
ILOpCode.Blt_un, ILOpCode.Ble_un, ILOpCode.Bgt_un, ILOpCode.Bge_un,
ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un,
ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge,
ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un}
Private Function CodeForJump(expression As BoundBinaryOperator, sense As Boolean, <Out()> ByRef revOpCode As ILOpCode) As ILOpCode
Dim opIdx As Integer
Dim opKind = (expression.OperatorKind And BinaryOperatorKind.OpMask)
Dim operandType = expression.Left.Type
Debug.Assert(operandType IsNot Nothing OrElse (expression.Left.IsNothingLiteral() AndAlso (opKind = BinaryOperatorKind.Is OrElse opKind = BinaryOperatorKind.IsNot)))
If operandType IsNot Nothing AndAlso operandType.IsBooleanType() Then
' Since VB True is -1 but is stored as 1 in IL, relational operations on Boolean must
' be reversed to yield the correct results. Note that = and <> do not need reversal.
Select Case opKind
Case BinaryOperatorKind.LessThan
opKind = BinaryOperatorKind.GreaterThan
Case BinaryOperatorKind.LessThanOrEqual
opKind = BinaryOperatorKind.GreaterThanOrEqual
Case BinaryOperatorKind.GreaterThan
opKind = BinaryOperatorKind.LessThan
Case BinaryOperatorKind.GreaterThanOrEqual
opKind = BinaryOperatorKind.LessThanOrEqual
End Select
End If
Select Case opKind
Case BinaryOperatorKind.IsNot
ValidateReferenceEqualityOperands(expression)
Return If(sense, ILOpCode.Bne_un, ILOpCode.Beq)
Case BinaryOperatorKind.Is
ValidateReferenceEqualityOperands(expression)
Return If(sense, ILOpCode.Beq, ILOpCode.Bne_un)
Case BinaryOperatorKind.Equals
Return If(sense, ILOpCode.Beq, ILOpCode.Bne_un)
Case BinaryOperatorKind.NotEquals
Return If(sense, ILOpCode.Bne_un, ILOpCode.Beq)
Case BinaryOperatorKind.LessThan
opIdx = 0
Case BinaryOperatorKind.LessThanOrEqual
opIdx = 1
Case BinaryOperatorKind.GreaterThan
opIdx = 2
Case BinaryOperatorKind.GreaterThanOrEqual
opIdx = 3
Case Else
Throw ExceptionUtilities.UnexpectedValue(opKind)
End Select
If operandType IsNot Nothing Then
If operandType.IsUnsignedIntegralType() Then
opIdx += 2 * s_IL_OP_CODE_ROW_LENGTH 'unsigned
Else
If operandType.IsFloatingType() Then
opIdx += 4 * s_IL_OP_CODE_ROW_LENGTH 'float
End If
End If
End If
Dim revOpIdx = opIdx
If Not sense Then
opIdx += s_IL_OP_CODE_ROW_LENGTH 'invert op
Else
revOpIdx += s_IL_OP_CODE_ROW_LENGTH 'invert orev
End If
revOpCode = s_condJumpOpCodes(revOpIdx)
Return s_condJumpOpCodes(opIdx)
End Function
' generate a jump to dest if (condition == sense) is true
' it is ok if lazyDest is Nothing
' if lazyDest is needed it will be initialized to a new object
Private Sub EmitCondBranch(condition As BoundExpression, ByRef lazyDest As Object, sense As Boolean)
oneMoreTime:
Dim ilcode As ILOpCode
Dim constExprValue = condition.ConstantValueOpt
If constExprValue IsNot Nothing Then
' make sure that only the bool bits are set or it is a Nothing literal
' or it is a string literal in which case it is equal to True
Debug.Assert(constExprValue.Discriminator = ConstantValueTypeDiscriminator.Boolean OrElse
constExprValue.Discriminator = ConstantValueTypeDiscriminator.String OrElse
constExprValue.IsNothing)
Dim taken As Boolean = constExprValue.IsDefaultValue <> sense
If taken Then
lazyDest = If(lazyDest, New Object())
_builder.EmitBranch(ILOpCode.Br, lazyDest)
Else
' otherwise this branch will never be taken, so just fall through...
End If
Return
End If
Select Case condition.Kind
Case BoundKind.BinaryOperator
Dim binOp = DirectCast(condition, BoundBinaryOperator)
Dim testBothArgs As Boolean = sense
Select Case binOp.OperatorKind And BinaryOperatorKind.OpMask
Case BinaryOperatorKind.OrElse
testBothArgs = Not testBothArgs
GoTo BinaryOperatorKindLogicalAnd
Case BinaryOperatorKind.AndAlso
BinaryOperatorKindLogicalAnd:
If testBothArgs Then
' gotoif(a != sense) fallThrough
' gotoif(b == sense) dest
' fallThrough:
Dim lazyFallThrough = New Object
EmitCondBranch(binOp.Left, lazyFallThrough, Not sense)
EmitCondBranch(binOp.Right, lazyDest, sense)
If (lazyFallThrough IsNot Nothing) Then
_builder.MarkLabel(lazyFallThrough)
End If
Else
EmitCondBranch(binOp.Left, lazyDest, sense)
condition = binOp.Right
GoTo oneMoreTime
End If
Return
Case BinaryOperatorKind.IsNot,
BinaryOperatorKind.Is
ValidateReferenceEqualityOperands(binOp)
GoTo BinaryOperatorKindEqualsNotEquals
Case BinaryOperatorKind.Equals,
BinaryOperatorKind.NotEquals
BinaryOperatorKindEqualsNotEquals:
Dim reduced = TryReduce(binOp, sense)
If reduced IsNot Nothing Then
condition = reduced
GoTo oneMoreTime
End If
GoTo BinaryOperatorKindLessThan
Case BinaryOperatorKind.LessThan,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThan,
BinaryOperatorKind.GreaterThanOrEqual
BinaryOperatorKindLessThan:
EmitExpression(binOp.Left, True)
EmitExpression(binOp.Right, True)
Dim revOpCode As ILOpCode
ilcode = CodeForJump(binOp, sense, revOpCode)
lazyDest = If(lazyDest, New Object())
_builder.EmitBranch(ilcode, lazyDest, revOpCode)
Return
End Select
' none of above.
' then it is regular binary expression - Or, And, Xor ...
GoTo OtherExpressions
Case BoundKind.UnaryOperator
Dim unOp = DirectCast(condition, BoundUnaryOperator)
If (unOp.OperatorKind = UnaryOperatorKind.Not) Then
Debug.Assert(unOp.Type.IsBooleanType())
sense = Not sense
condition = unOp.Operand
GoTo oneMoreTime
Else
GoTo OtherExpressions
End If
Case BoundKind.TypeOf
Dim typeOfExpression = DirectCast(condition, BoundTypeOf)
EmitTypeOfExpression(typeOfExpression, used:=True, optimize:=True)
If typeOfExpression.IsTypeOfIsNotExpression Then
sense = Not sense
End If
ilcode = If(sense, ILOpCode.Brtrue, ILOpCode.Brfalse)
lazyDest = If(lazyDest, New Object())
_builder.EmitBranch(ilcode, lazyDest)
Return
#If False Then
Case BoundKind.AsOperator
Dim asOp = DirectCast(condition, BoundIsOperator)
EmitExpression(asOp.Operand, True)
_builder.EmitOpCode(ILOpCode.Isinst)
EmitSymbolToken(asOp.TargetType.Type)
ilcode = If(sense, ILOpCode.Brtrue, ILOpCode.Brfalse)
_builder.EmitBranch(ilcode, dest)
Return
#End If
Case BoundKind.Sequence
Dim sequence = DirectCast(condition, BoundSequence)
EmitSequenceCondBranch(sequence, lazyDest, sense)
Return
Case Else
OtherExpressions:
EmitExpression(condition, True)
Dim conditionType = condition.Type
If conditionType.IsReferenceType AndAlso Not IsVerifierReference(conditionType) Then
EmitBox(conditionType, condition.Syntax)
End If
ilcode = If(sense, ILOpCode.Brtrue, ILOpCode.Brfalse)
lazyDest = If(lazyDest, New Object())
_builder.EmitBranch(ilcode, lazyDest)
Return
End Select
End Sub
<Conditional("DEBUG")>
Private Sub ValidateReferenceEqualityOperands(binOp As BoundBinaryOperator)
Debug.Assert(binOp.Left.IsNothingLiteral() OrElse binOp.Left.Type.SpecialType = SpecialType.System_Object OrElse binOp.WasCompilerGenerated)
Debug.Assert(binOp.Right.IsNothingLiteral() OrElse binOp.Right.Type.SpecialType = SpecialType.System_Object OrElse binOp.WasCompilerGenerated)
End Sub
'TODO: is this to fold value? Same in C#?
Private Sub EmitSequenceCondBranch(sequence As BoundSequence, ByRef lazyDest As Object, sense As Boolean)
Dim hasLocals As Boolean = Not sequence.Locals.IsEmpty
If hasLocals Then
_builder.OpenLocalScope()
For Each local In sequence.Locals
Me.DefineLocal(local, sequence.Syntax)
Next
End If
Me.EmitSideEffects(sequence.SideEffects)
Debug.Assert(sequence.ValueOpt IsNot Nothing)
Me.EmitCondBranch(sequence.ValueOpt, lazyDest, sense)
If hasLocals Then
_builder.CloseLocalScope()
For Each local In sequence.Locals
Me.FreeLocal(local)
Next
End If
End Sub
Private Sub EmitLabelStatement(boundLabelStatement As BoundLabelStatement)
_builder.MarkLabel(boundLabelStatement.Label)
End Sub
Private Sub EmitGotoStatement(boundGotoStatement As BoundGotoStatement)
' if branch leaves current Catch block we need to emit ClearProjectError()
If ShouldNoteProjectErrors() Then
If _currentCatchBlock IsNot Nothing AndAlso
(_currentCatchBlock.ExceptionFilterOpt Is Nothing OrElse _currentCatchBlock.ExceptionFilterOpt.Kind <> BoundKind.UnstructuredExceptionHandlingCatchFilter) AndAlso
Not LabelFinder.NodeContainsLabel(_currentCatchBlock, boundGotoStatement.Label) Then
EmitClearProjectError(boundGotoStatement.Syntax)
End If
End If
_builder.EmitBranch(ILOpCode.Br, boundGotoStatement.Label)
End Sub
''' <summary>
''' tells if given node contains a label statement that defines given label symbol
''' </summary>
Private Class LabelFinder : Inherits BoundTreeWalker
Private ReadOnly _label As LabelSymbol
Private _found As Boolean = False
Private Sub New(label As LabelSymbol)
Me._label = label
End Sub
Public Overrides Function Visit(node As BoundNode) As BoundNode
If Not _found Then
Return MyBase.Visit(node)
End If
Return Nothing
End Function
Public Overrides Function VisitLabelStatement(node As BoundLabelStatement) As BoundNode
If node.Label Is Me._label Then
_found = True
End If
Return MyBase.VisitLabelStatement(node)
End Function
Public Shared Function NodeContainsLabel(node As BoundNode, label As LabelSymbol) As Boolean
Dim finder = New LabelFinder(label)
finder.Visit(node)
Return finder._found
End Function
End Class
Private Sub EmitReturnStatement(boundReturnStatement As BoundReturnStatement)
Me.EmitExpression(boundReturnStatement.ExpressionOpt, True)
_builder.EmitRet(boundReturnStatement.ExpressionOpt Is Nothing)
End Sub
Private Sub EmitThrowStatement(boundThrowStatement As BoundThrowStatement)
Dim operand = boundThrowStatement.ExpressionOpt
If operand IsNot Nothing Then
EmitExpression(operand, used:=True)
Dim operandType = operand.Type
' "Throw Nothing" is not supported by the language
' so operand.Type should always be set.
Debug.Assert(operandType IsNot Nothing)
If (operandType IsNot Nothing) AndAlso (operandType.TypeKind = TypeKind.TypeParameter) Then
EmitBox(operandType, operand.Syntax)
End If
End If
_builder.EmitThrow(operand Is Nothing)
End Sub
Private Sub EmitSelectStatement(boundSelectStatement As BoundSelectStatement)
Debug.Assert(boundSelectStatement.RecommendSwitchTable)
Dim selectExpression = boundSelectStatement.ExpressionStatement.Expression
Dim caseBlocks = boundSelectStatement.CaseBlocks
Dim exitLabel = boundSelectStatement.ExitLabel
Dim fallThroughLabel = exitLabel
Debug.Assert(selectExpression.Type IsNot Nothing)
Debug.Assert(caseBlocks.Any())
' Create labels for case blocks
Dim caseBlockLabels As ImmutableArray(Of GeneratedLabelSymbol) = CreateCaseBlockLabels(caseBlocks)
' Create an array of key value pairs (key: case clause constant value, value: case block label)
' for emitting switch table based header.
' This function also ensures the correct fallThroughLabel is set, i.e. case else block label if one exists, otherwise exit label.
Dim caseLabelsForEmit As KeyValuePair(Of ConstantValue, Object)() = GetCaseLabelsForEmitSwitchHeader(caseBlocks, caseBlockLabels, fallThroughLabel)
' Emit switch table header
EmitSwitchTableHeader(selectExpression, caseLabelsForEmit, fallThroughLabel)
' Emit case blocks
EmitCaseBlocks(caseBlocks, caseBlockLabels, exitLabel)
' Emit exit label
_builder.MarkLabel(exitLabel)
End Sub
' Create a label for each case block
Private Function CreateCaseBlockLabels(caseBlocks As ImmutableArray(Of BoundCaseBlock)) As ImmutableArray(Of GeneratedLabelSymbol)
Debug.Assert(Not caseBlocks.IsEmpty)
Dim caseBlockLabels = ArrayBuilder(Of GeneratedLabelSymbol).GetInstance(caseBlocks.Length)
Dim cur As Integer = 0
For Each caseBlock In caseBlocks
cur = cur + 1
caseBlockLabels.Add(New GeneratedLabelSymbol("Case Block " + cur.ToString()))
Next
Return caseBlockLabels.ToImmutableAndFree()
End Function
' Creates an array of key value pairs (key: case clause constant value, value: case block label)
' for emitting switch table based header.
' This function also ensures the correct fallThroughLabel is set, i.e. case else block label if one exists, otherwise exit label.
Private Function GetCaseLabelsForEmitSwitchHeader(
caseBlocks As ImmutableArray(Of BoundCaseBlock),
caseBlockLabels As ImmutableArray(Of GeneratedLabelSymbol),
ByRef fallThroughLabel As LabelSymbol
) As KeyValuePair(Of ConstantValue, Object)()
Debug.Assert(Not caseBlocks.IsEmpty)
Debug.Assert(Not caseBlockLabels.IsEmpty)
Debug.Assert(caseBlocks.Length = caseBlockLabels.Length)
Dim labelsBuilder = ArrayBuilder(Of KeyValuePair(Of ConstantValue, Object)).GetInstance()
Dim constantsSet = New HashSet(Of ConstantValue)(New SwitchConstantValueHelper.SwitchLabelsComparer())
Dim cur As Integer = 0
For Each caseBlock In caseBlocks
Dim caseBlockLabel = caseBlockLabels(cur)
Dim caseClauses = caseBlock.CaseStatement.CaseClauses
If caseClauses.Any() Then
For Each caseClause In caseClauses
Dim constant As ConstantValue
Select Case caseClause.Kind
Case BoundKind.SimpleCaseClause
Dim simpleCaseClause = DirectCast(caseClause, BoundSimpleCaseClause)
Debug.Assert(simpleCaseClause.ValueOpt IsNot Nothing)
Debug.Assert(simpleCaseClause.ConditionOpt Is Nothing)
constant = simpleCaseClause.ValueOpt.ConstantValueOpt
Case BoundKind.RelationalCaseClause
Dim relationalCaseClause = DirectCast(caseClause, BoundRelationalCaseClause)
Debug.Assert(relationalCaseClause.OperatorKind = BinaryOperatorKind.Equals)
Debug.Assert(relationalCaseClause.OperandOpt IsNot Nothing)
Debug.Assert(relationalCaseClause.ConditionOpt Is Nothing)
constant = relationalCaseClause.OperandOpt.ConstantValueOpt
Case BoundKind.RangeCaseClause
' TODO: For now we use IF lists if we encounter
' TODO: BoundRangeCaseClause, we should not reach here.
Throw ExceptionUtilities.UnexpectedValue(caseClause.Kind)
Case Else
Throw ExceptionUtilities.UnexpectedValue(caseClause.Kind)
End Select
Debug.Assert(constant IsNot Nothing)
Debug.Assert(SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(constant))
' If we have duplicate case value constants, use the lexically first case constant.
If Not constantsSet.Contains(constant) Then
labelsBuilder.Add(New KeyValuePair(Of ConstantValue, Object)(constant, caseBlockLabel))
constantsSet.Add(constant)
End If
Next
Else
Debug.Assert(caseBlock.Syntax.Kind = SyntaxKind.CaseElseBlock)
' We have a case else block, update the fallThroughLabel to the corresponding caseBlockLabel
fallThroughLabel = caseBlockLabel
End If
cur = cur + 1
Next
Return labelsBuilder.ToArrayAndFree()
End Function
Private Sub EmitSwitchTableHeader(selectExpression As BoundExpression, caseLabels As KeyValuePair(Of ConstantValue, Object)(), fallThroughLabel As LabelSymbol)
Debug.Assert(selectExpression.Type IsNot Nothing)
Debug.Assert(caseLabels IsNot Nothing)
If Not caseLabels.Any() Then
' No case labels, emit branch to fallThroughLabel
_builder.EmitBranch(ILOpCode.Br, fallThroughLabel)
Else
Dim exprType = selectExpression.Type
Dim temp As LocalDefinition = Nothing
If exprType.SpecialType <> SpecialType.System_String Then
If selectExpression.Kind = BoundKind.Local AndAlso Not DirectCast(selectExpression, BoundLocal).LocalSymbol.IsByRef Then
_builder.EmitIntegerSwitchJumpTable(caseLabels, fallThroughLabel, GetLocal(DirectCast(selectExpression, BoundLocal)), keyTypeCode:=exprType.GetEnumUnderlyingTypeOrSelf.PrimitiveTypeCode)
ElseIf selectExpression.Kind = BoundKind.Parameter AndAlso Not DirectCast(selectExpression, BoundParameter).ParameterSymbol.IsByRef Then
_builder.EmitIntegerSwitchJumpTable(caseLabels, fallThroughLabel, ParameterSlot(DirectCast(selectExpression, BoundParameter)), keyTypeCode:=exprType.GetEnumUnderlyingTypeOrSelf.PrimitiveTypeCode)
Else
EmitExpression(selectExpression, True)
temp = AllocateTemp(exprType, selectExpression.Syntax)
_builder.EmitLocalStore(temp)
_builder.EmitIntegerSwitchJumpTable(caseLabels, fallThroughLabel, temp, keyTypeCode:=exprType.GetEnumUnderlyingTypeOrSelf.PrimitiveTypeCode)
End If
Else
If selectExpression.Kind = BoundKind.Local AndAlso Not DirectCast(selectExpression, BoundLocal).LocalSymbol.IsByRef Then
EmitStringSwitchJumpTable(caseLabels, fallThroughLabel, GetLocal(DirectCast(selectExpression, BoundLocal)), selectExpression.Syntax)
Else
EmitExpression(selectExpression, True)
temp = AllocateTemp(exprType, selectExpression.Syntax)
_builder.EmitLocalStore(temp)
EmitStringSwitchJumpTable(caseLabels, fallThroughLabel, temp, selectExpression.Syntax)
End If
End If
If temp IsNot Nothing Then
FreeTemp(temp)
End If
End If
End Sub
Private Sub EmitStringSwitchJumpTable(caseLabels As KeyValuePair(Of ConstantValue, Object)(), fallThroughLabel As LabelSymbol, key As LocalDefinition, syntaxNode As VisualBasicSyntaxNode)
Dim genHashTableSwitch As Boolean = SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch(_module, caseLabels.Length)
Dim keyHash As LocalDefinition = Nothing
If genHashTableSwitch Then
Debug.Assert(_module.SupportsPrivateImplClass)
Dim privateImplClass = _module.GetPrivateImplClass(syntaxNode, _diagnostics)
Dim stringHashMethodRef As Microsoft.Cci.IReference = privateImplClass.GetMethod(PrivateImplementationDetails.SynthesizedStringHashFunctionName)
Debug.Assert(stringHashMethodRef IsNot Nothing)
' static uint ComputeStringHash(string s)
' pop 1 (s)
' push 1 (uint return value)
' stackAdjustment = (pushCount - popCount) = 0
_builder.EmitLocalLoad(key)
_builder.EmitOpCode(ILOpCode.[Call], stackAdjustment:=0)
_builder.EmitToken(stringHashMethodRef, syntaxNode, _diagnostics)
Dim UInt32Type = DirectCast(_module.GetSpecialType(SpecialType.System_UInt32, syntaxNode, _diagnostics), TypeSymbol)
keyHash = AllocateTemp(UInt32Type, syntaxNode)
_builder.EmitLocalStore(keyHash)
End If
' Prefer embedded version of the member if present
Dim embeddedOperatorsType As NamedTypeSymbol = Me._module.Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators)
Dim compareStringMember As WellKnownMember =
If(embeddedOperatorsType.IsErrorType AndAlso TypeOf embeddedOperatorsType Is MissingMetadataTypeSymbol,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean)
Dim stringCompareMethod = DirectCast(Me._module.Compilation.GetWellKnownTypeMember(compareStringMember), MethodSymbol)
Dim stringCompareMethodRef As Cci.IReference = Me._module.Translate(stringCompareMethod, needDeclaration:=False, syntaxNodeOpt:=syntaxNode, diagnostics:=_diagnostics)
Dim compareDelegate As SwitchStringJumpTableEmitter.EmitStringCompareAndBranch =
Sub(keyArg, stringConstant, targetLabel)
EmitStringCompareAndBranch(keyArg, syntaxNode, stringConstant, targetLabel, stringCompareMethodRef)
End Sub
_builder.EmitStringSwitchJumpTable(
caseLabels,
fallThroughLabel,
key,
keyHash,
compareDelegate,
AddressOf SynthesizedStringSwitchHashMethod.ComputeStringHash)
If keyHash IsNot Nothing Then
FreeTemp(keyHash)
End If
End Sub
''' <summary>
''' Delegate to emit string compare call and conditional branch based on the compare result.
''' </summary>
''' <param name="key">Key to compare</param>
''' <param name="syntaxNode">Node for diagnostics</param>
''' <param name="stringConstant">Case constant to compare the key against</param>
''' <param name="targetLabel">Target label to branch to if key = stringConstant</param>
''' <param name="stringCompareMethodRef">String equality method</param>
Private Sub EmitStringCompareAndBranch(key As LocalOrParameter, syntaxNode As SyntaxNode, stringConstant As ConstantValue, targetLabel As Object, stringCompareMethodRef As Microsoft.Cci.IReference)
' Emit compare and branch:
' If key = stringConstant Then
' Goto targetLabel
' End If
Debug.Assert(stringCompareMethodRef IsNot Nothing)
#If DEBUG Then
Dim assertDiagnostics = DiagnosticBag.GetInstance()
Debug.Assert(stringCompareMethodRef Is Me._module.Translate(DirectCast(
If(TypeOf Me._module.Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators) Is MissingMetadataTypeSymbol,
Me._module.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean),
Me._module.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean)), MethodSymbol), needDeclaration:=False,
syntaxNodeOpt:=DirectCast(syntaxNode, VisualBasicSyntaxNode), diagnostics:=assertDiagnostics))
assertDiagnostics.Free()
#End If
' Public Shared Function CompareString(Left As String, Right As String, TextCompare As Boolean) As Integer
' pop 3 (Left, Right, TextCompare)
' push 1 (Integer return value)
' stackAdjustment = (pushCount - popCount) = -2
' NOTE: We generate string switch table only for Option Compare Binary, i.e. TextCompare = False
_builder.EmitLoad(key)
_builder.EmitConstantValue(stringConstant)
_builder.EmitConstantValue(ConstantValue.False)
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment:=-2)
_builder.EmitToken(stringCompareMethodRef, syntaxNode, _diagnostics)
' CompareString returns 0 if Left and Right strings are equal.
' Branch to targetLabel if CompareString returned 0.
_builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue)
End Sub
Private Sub EmitCaseBlocks(caseBlocks As ImmutableArray(Of BoundCaseBlock), caseBlockLabels As ImmutableArray(Of GeneratedLabelSymbol), exitLabel As LabelSymbol)
Debug.Assert(Not caseBlocks.IsEmpty)
Debug.Assert(Not caseBlockLabels.IsEmpty)
Debug.Assert(caseBlocks.Length = caseBlockLabels.Length)
Dim cur As Integer = 0
For Each caseBlock In caseBlocks
' Emit case block label
_builder.MarkLabel(caseBlockLabels(cur))
cur = cur + 1
' Emit case statement sequence point
Dim caseStatement = caseBlock.CaseStatement
If Not caseStatement.WasCompilerGenerated Then
Debug.Assert(caseStatement.Syntax IsNot Nothing)
If _emitPdbSequencePoints Then
EmitSequencePoint(caseStatement.Syntax)
End If
If _ilEmitStyle = ILEmitStyle.Debug Then
' Emit nop for the case statement otherwise the above sequence point
' will get associated with the first statement in subsequent case block.
' This matches the native compiler codegen.
_builder.EmitOpCode(ILOpCode.Nop)
End If
End If
' Emit case block body
EmitBlock(caseBlock.Body)
' Emit a branch to exit label
_builder.EmitBranch(ILOpCode.Br, exitLabel)
Next
End Sub
Private Sub EmitBlock(scope As BoundBlock)
Dim hasLocals As Boolean = Not scope.Locals.IsEmpty
If hasLocals Then
_builder.OpenLocalScope()
For Each local In scope.Locals
Dim declNodes = local.DeclaringSyntaxReferences
Me.DefineLocal(local, If(declNodes.IsEmpty, scope.Syntax, declNodes(0).GetVisualBasicSyntax()))
Next
End If
For Each statement In scope.Statements
EmitStatement(statement)
Next
If hasLocals Then
_builder.CloseLocalScope()
'TODO: can we free any locals here? Perhaps nameless temps?
End If
End Sub
Private Function DefineLocal(local As LocalSymbol, syntaxNode As VisualBasicSyntaxNode) As LocalDefinition
Dim specType = local.Type.SpecialType
' We're treating constants of type Decimal and DateTime as local here to not create a new instance for each time
' the value is accessed. This means there will be one local in the scope for this constant.
' This has the side effect that this constant will later on appear in the PDB file as a common local and one is able
' to modify the value in the debugger (which is a regression from Dev10).
' To fix this while keeping the behavior of having just one local for the const, one would need to preserve the
' information that this local is a ConstantButNotMetadataConstant (update ScopeManager.DeclareLocal & LocalDefinition)
' and modify PEWriter.Initialize to DefineLocalConstant instead of DefineLocalVariable if the local is
' ConstantButNotMetadataConstant.
' See bug #11047
If local.HasConstantValue Then
Dim compileTimeValue As MetadataConstant = _module.CreateConstant(local.Type, local.ConstantValue, syntaxNode, _diagnostics)
Dim localConstantDef = New LocalConstantDefinition(local.Name, If(local.Locations.FirstOrDefault(), Location.None), compileTimeValue)
' Reference in the scope for debugging purpose
_builder.AddLocalConstantToScope(localConstantDef)
Return Nothing
End If
If Me.IsStackLocal(local) Then
Return Nothing
End If
Dim translatedType = _module.Translate(local.Type, syntaxNodeOpt:=syntaxNode, diagnostics:=_diagnostics)
' Even though we don't need the token immediately, we will need it later when signature for the local is emitted.
' Also, requesting the token has side-effect of registering types used, which is critical for embedded types (NoPia, VBCore, etc).
_module.GetFakeSymbolTokenForIL(translatedType, syntaxNode, _diagnostics)
Dim constraints = If(local.IsByRef, LocalSlotConstraints.ByRef, LocalSlotConstraints.None) Or
If(local.IsPinned, LocalSlotConstraints.Pinned, LocalSlotConstraints.None)
Dim localId As LocalDebugId = Nothing
Dim name As String = GetLocalDebugName(local, localId)
Dim synthesizedKind = local.SynthesizedKind
Dim localDef = _builder.LocalSlotManager.DeclareLocal(
type:=translatedType,
symbol:=local,
name:=name,
kind:=synthesizedKind,
id:=localId,
pdbAttributes:=synthesizedKind.PdbAttributes(),
constraints:=constraints,
isDynamic:=False,
dynamicTransformFlags:=Nothing,
isSlotReusable:=synthesizedKind.IsSlotReusable(_ilEmitStyle <> ILEmitStyle.Release))
' If named, add it to the local debug scope.
If localDef.Name IsNot Nothing Then
_builder.AddLocalToScope(localDef)
End If
Return localDef
End Function
''' <summary>
''' Gets the name And id of the local that are going to be generated into the debug metadata.
''' </summary>
Private Function GetLocalDebugName(local As LocalSymbol, <Out> ByRef localId As LocalDebugId) As String
localId = LocalDebugId.None
If local.IsImportedFromMetadata Then
Return local.Name
End If
' We include function value locals in async and iterator methods so that appropriate
' errors can be reported when users attempt to refer to them. However, there's no
' reason to actually emit them into the resulting MoveNext method, because they will
' never be accessed. Unfortunately, for implementation-specific reasons, dropping them
' would be non-trivial. Instead, we drop their names so that they do not appear while
' debugging (esp in the Locals window).
If local.DeclarationKind = LocalDeclarationKind.FunctionValue AndAlso
TypeOf _method Is SynthesizedStateMachineMethod Then
Return Nothing
End If
Dim localKind = local.SynthesizedKind
' only user-defined locals should be named during lowering:
Debug.Assert((local.Name Is Nothing) = (localKind <> SynthesizedLocalKind.UserDefined))
If Not localKind.IsLongLived() Then
Return Nothing
End If
If _ilEmitStyle = ILEmitStyle.Debug Then
Dim syntax = local.GetDeclaratorSyntax()
Dim syntaxOffset = _method.CalculateLocalSyntaxOffset(syntax.SpanStart, syntax.SyntaxTree)
Dim ordinal = _synthesizedLocalOrdinals.AssignLocalOrdinal(localKind, syntaxOffset)
' user-defined locals should have 0 ordinal
Debug.Assert(ordinal = 0 OrElse localKind <> SynthesizedLocalKind.UserDefined)
localId = New LocalDebugId(syntaxOffset, ordinal)
End If
If local.Name IsNot Nothing Then
Return local.Name
End If
Return GeneratedNames.MakeSynthesizedLocalName(localKind, _uniqueNameId)
End Function
Private Function IsSlotReusable(local As LocalSymbol) As Boolean
Return local.SynthesizedKind.IsSlotReusable(_ilEmitStyle <> ILEmitStyle.Release)
End Function
Private Sub FreeLocal(local As LocalSymbol)
'TODO: releasing locals with name NYI.
'NOTE: VB considers named local's extent to be whole method
' so releasing them may just not be possible.
If local.Name Is Nothing AndAlso IsSlotReusable(local) AndAlso Not IsStackLocal(local) Then
_builder.LocalSlotManager.FreeLocal(local)
End If
End Sub
''' <summary>
''' Gets already declared and initialized local.
''' </summary>
Private Function GetLocal(localExpression As BoundLocal) As LocalDefinition
Dim symbol = localExpression.LocalSymbol
Return GetLocal(symbol)
End Function
Private Function GetLocal(symbol As LocalSymbol) As LocalDefinition
Return _builder.LocalSlotManager.GetLocal(symbol)
End Function
''' <summary>
''' Allocates a temp without identity.
''' </summary>
Private Function AllocateTemp(type As TypeSymbol, syntaxNode As VisualBasicSyntaxNode) As LocalDefinition
Return _builder.LocalSlotManager.AllocateSlot(
Me._module.Translate(type, syntaxNodeOpt:=syntaxNode, diagnostics:=_diagnostics),
LocalSlotConstraints.None)
End Function
''' <summary>
''' Frees a temp without identity.
''' </summary>
Private Sub FreeTemp(temp As LocalDefinition)
_builder.LocalSlotManager.FreeSlot(temp)
End Sub
''' <summary>
''' Frees an optional temp.
''' </summary>
Private Sub FreeOptTemp(temp As LocalDefinition)
If temp IsNot Nothing Then
FreeTemp(temp)
End If
End Sub
Private Sub EmitUnstructuredExceptionOnErrorSwitch(node As BoundUnstructuredExceptionOnErrorSwitch)
EmitExpression(node.Value, used:=True)
EmitSwitch(node.Jumps)
End Sub
Private Sub EmitSwitch(jumps As ImmutableArray(Of BoundGotoStatement))
Dim labels(jumps.Length - 1) As Object
For i As Integer = 0 To jumps.Length - 1
labels(i) = jumps(i).Label
Next
_builder.EmitSwitch(labels)
End Sub
Private Sub EmitStateMachineScope(scope As BoundStateMachineScope)
_builder.OpenLocalScope()
'VB EE uses name mangling to match up original locals and the fields where they are hoisted
'The scoping information is passed by recording PDB scopes of "fake" locals named the same
'as the fields. These locals are not emitted to IL.
' vb\language\debugger\procedurecontext.cpp
' 813 // Since state machines lift (almost) all locals of a method, the lifted fields should
' 814 // only be shown in the debugger when the original local variable was in scope. So
' 815 // we first check if there's a local by the given name and attempt to remove it from
' 816 // m_localVariableMap. If it was present, we decode the original local's name, otherwise
' 817 // we skip loading this lifted field since it is out of scope.
For Each field In scope.Fields
DefineUserDefinedStateMachineHoistedLocal(DirectCast(field, StateMachineFieldSymbol))
Next
EmitStatement(scope.Statement)
_builder.CloseLocalScope()
End Sub
Private Sub DefineUserDefinedStateMachineHoistedLocal(field As StateMachineFieldSymbol)
Debug.Assert(field.SlotIndex >= 0)
Dim fakePdbOnlyLocal = New LocalDefinition(
symbolOpt:=Nothing,
nameOpt:=field.Name,
type:=Nothing,
slot:=field.SlotIndex,
synthesizedKind:=SynthesizedLocalKind.EmitterTemp,
id:=Nothing,
pdbAttributes:=Cci.PdbWriter.DefaultLocalAttributesValue,
constraints:=LocalSlotConstraints.None,
isDynamic:=False,
dynamicTransformFlags:=Nothing)
_builder.AddLocalToScope(fakePdbOnlyLocal)
End Sub
Private Sub EmitUnstructuredExceptionResumeSwitch(node As BoundUnstructuredExceptionResumeSwitch)
' Resume statements will branch here. Just load the resume local and
' branch to the switch table
EmitLabelStatement(node.ResumeLabel)
EmitExpression(node.ResumeTargetTemporary, used:=True)
Dim switchLabel As New Object()
_builder.EmitBranch(ILOpCode.Br_s, switchLabel)
_builder.AdjustStack(-1)
' Resume Next statements will branch here. Increment the resume local and
' fall through to the switch table
EmitLabelStatement(node.ResumeNextLabel)
EmitExpression(node.ResumeTargetTemporary, used:=True)
_builder.EmitIntConstant(1)
_builder.EmitOpCode(ILOpCode.Add)
' now start generating the resume switch table
_builder.MarkLabel(switchLabel)
' but first clear the resume local
_builder.EmitIntConstant(0)
_builder.EmitLocalStore(GetLocal(node.ResumeTargetTemporary))
EmitSwitch(node.Jumps)
End Sub
End Class
End Namespace
|
dovzhikova/roslyn
|
src/Compilers/VisualBasic/Portable/CodeGen/EmitStatement.vb
|
Visual Basic
|
apache-2.0
| 68,890
|
Imports NOF2.Interface
Public Class Subject
Implements IBounded
Public Overridable Property Id As Integer
Public Property mappedName As String
Private myName As TextString
<DemoProperty(Order:=1)>
Public ReadOnly Property Name As TextString
Get
myName = If(myName, New TextString(mappedName, Sub(v) mappedName = v))
Return myName
End Get
End Property
Public Function Title() As Title
Return New Title(Name)
End Function
End Class
|
NakedObjectsGroup/NakedObjectsFramework
|
Template/NOF2 Server/Template.Model/Subject.vb
|
Visual Basic
|
apache-2.0
| 527
|
Module Test_0_5_Data
Public Function GetDataTable() As DataTable
Dim ret As New DataTable()
ret.Columns.Add("bumonCd", GetType(Decimal))
ret.Columns.Add("bumon", GetType(String))
ret.Columns.Add("uriageDate", GetType(DateTime))
ret.Columns.Add("denpyoNo", GetType(Decimal))
ret.Columns.Add("shohinCd", GetType(String))
ret.Columns.Add("shohin", GetType(String))
ret.Columns.Add("tanka", GetType(Decimal))
ret.Columns.Add("suryo", GetType(Decimal))
For i As Integer = 1 To 100
For j As Integer = 1 To 50
ret.Rows.Add(i, "部門" & i, _
DateTime.ParseExact("2013/02/01", "yyyy/MM/dd", Nothing), _
j, "PC00001", "ノートパソコン", 70000, 10)
ret.Rows.Add(i, "部門" & i, _
DateTime.ParseExact("2013/02/01", "yyyy/MM/dd", Nothing), _
j, "DP00002", "モニター", 25000, 10)
ret.Rows.Add(i, "部門" & i, _
DateTime.ParseExact("2013/02/01", "yyyy/MM/dd", Nothing), _
j, "PR00003", "プリンタ", 20000, 2)
ret.Rows.Add(i, "部門" & i, _
DateTime.ParseExact("2013/02/10", "yyyy/MM/dd", Nothing), _
j, "PR00003", "プリンタ", 20000, 3)
Next
Next
Return ret
End Function
End Module
|
rapidreport/dotnet-pdf2
|
test/Test_0_5_Data.vb
|
Visual Basic
|
bsd-2-clause
| 1,444
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyDescription("")>
<Assembly: CLSCompliant(True)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("6071A28C-DA66-47B5-88BD-BF7260D8947A")>
|
EIDSS/EIDSS-Legacy
|
EIDSS v6/vb/EIDSS/EIDSS_Admin/AssemblyInfo.vb
|
Visual Basic
|
bsd-2-clause
| 547
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Runtime.CompilerServices
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.ExtractMethod
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod
Friend Module Extensions
<Extension()>
Public Function GetUnparenthesizedExpression(node As SyntaxNode) As ExpressionSyntax
Dim parenthesizedExpression = TryCast(node, ParenthesizedExpressionSyntax)
If parenthesizedExpression Is Nothing Then
Return DirectCast(node, ExpressionSyntax)
End If
Return GetUnparenthesizedExpression(parenthesizedExpression.Expression)
End Function
<Extension()>
Public Function GetStatementContainer(node As SyntaxNode) As SyntaxNode
Contract.ThrowIfNull(node)
Dim statement = node.GetStatementUnderContainer()
If statement Is Nothing Then
Return Nothing
End If
Return statement.Parent
End Function
<Extension()>
Public Function GetStatementUnderContainer(node As SyntaxNode) As ExecutableStatementSyntax
Contract.ThrowIfNull(node)
Do While node IsNot Nothing
If node.Parent.IsStatementContainerNode() AndAlso
TypeOf node Is ExecutableStatementSyntax AndAlso
node.Parent.ContainStatement(DirectCast(node, ExecutableStatementSyntax)) Then
Return TryCast(node, ExecutableStatementSyntax)
End If
node = node.Parent
Loop
Return Nothing
End Function
<Extension()>
Public Function ContainStatement(node As SyntaxNode, statement As StatementSyntax) As Boolean
Contract.ThrowIfNull(node)
Contract.ThrowIfNull(statement)
If Not node.IsStatementContainerNode() Then
Return False
End If
Return node.GetStatements().IndexOf(statement) >= 0
End Function
<Extension()>
Public Function GetOutermostNodeWithSameSpan(initialNode As SyntaxNode, predicate As Func(Of SyntaxNode, Boolean)) As SyntaxNode
If initialNode Is Nothing Then
Return Nothing
End If
' now try to find outmost node that has same span
Dim firstContainingSpan = initialNode.Span
Dim node = initialNode
Dim lastNode = Nothing
Do
If predicate(node) Then
lastNode = node
End If
node = node.Parent
Loop While node IsNot Nothing AndAlso node.Span.Equals(firstContainingSpan)
Return CType(If(lastNode, initialNode), SyntaxNode)
End Function
<Extension()>
Public Function PartOfConstantInitializerExpression(node As SyntaxNode) As Boolean
Return node.PartOfConstantInitializerExpression(Of FieldDeclarationSyntax)(Function(n) n.Modifiers) OrElse
node.PartOfConstantInitializerExpression(Of LocalDeclarationStatementSyntax)(Function(n) n.Modifiers)
End Function
<Extension()>
Private Function PartOfConstantInitializerExpression(Of T As SyntaxNode)(node As SyntaxNode, modifiersGetter As Func(Of T, SyntaxTokenList)) As Boolean
Dim decl = node.GetAncestor(Of T)()
If decl Is Nothing Then
Return False
End If
If Not modifiersGetter(decl).Any(Function(m) m.Kind = SyntaxKind.ConstKeyword) Then
Return False
End If
' we are under decl with const modifier, check we are part of initializer expression
Dim equal = node.GetAncestor(Of EqualsValueSyntax)()
If equal Is Nothing Then
Return False
End If
Return equal.Value IsNot Nothing AndAlso equal.Value.Span.Contains(node.Span)
End Function
<Extension()>
Public Function IsArgumentForByRefParameter(node As SyntaxNode, model As SemanticModel, cancellationToken As CancellationToken) As Boolean
Dim argument = node.FirstAncestorOrSelf(Of ArgumentSyntax)()
' make sure we are the argument
If argument Is Nothing OrElse node.Span <> argument.Span Then
Return False
End If
' now find invocation node
Dim invocation = argument.FirstAncestorOrSelf(Of InvocationExpressionSyntax)()
' argument for something we are not interested in
If invocation Is Nothing Then
Return False
End If
' find argument index
Dim argumentIndex = invocation.ArgumentList.Arguments.IndexOf(argument)
If argumentIndex < 0 Then
Return False
End If
' get all method symbols
Dim methodSymbols = model.GetSymbolInfo(invocation, cancellationToken).GetAllSymbols().Where(Function(s) s.Kind = SymbolKind.Method).Cast(Of IMethodSymbol)()
For Each method In methodSymbols
' not a right method
If method.Parameters.Length <= argumentIndex Then
Continue For
End If
' make sure there is no ref type
Dim parameter = method.Parameters(argumentIndex)
If parameter.RefKind <> RefKind.None Then
Return True
End If
Next
Return False
End Function
<Extension()>
Public Function ContainArgumentlessThrowWithoutEnclosingCatch(ByVal tokens As IEnumerable(Of SyntaxToken), ByVal textSpan As TextSpan) As Boolean
For Each token In tokens
If token.Kind <> SyntaxKind.ThrowKeyword Then
Continue For
End If
Dim throwStatement = TryCast(token.Parent, ThrowStatementSyntax)
If throwStatement Is Nothing OrElse throwStatement.Expression IsNot Nothing Then
Continue For
End If
Dim catchBlock = token.GetAncestor(Of CatchBlockSyntax)()
If catchBlock Is Nothing OrElse Not textSpan.Contains(catchBlock.Span) Then
Return True
End If
Next token
Return False
End Function
<Extension()>
Public Function ContainPreprocessorCrossOver(ByVal tokens As IEnumerable(Of SyntaxToken), ByVal textSpan As TextSpan) As Boolean
Dim activeRegions As Integer = 0
Dim activeIfs As Integer = 0
For Each trivia In tokens.GetAllTrivia()
If Not trivia.IsDirective Then
Continue For
End If
Dim directive = DirectCast(trivia.GetStructure(), DirectiveTriviaSyntax)
If Not textSpan.Contains(directive.Span) Then
Continue For
End If
Select Case directive.Kind
Case SyntaxKind.RegionDirectiveTrivia
activeRegions += 1
Case SyntaxKind.EndRegionDirectiveTrivia
If activeRegions <= 0 Then Return True
activeRegions -= 1
Case SyntaxKind.IfDirectiveTrivia
activeIfs += 1
Case SyntaxKind.EndIfDirectiveTrivia
If activeIfs <= 0 Then Return True
activeIfs -= 1
Case SyntaxKind.ElseDirectiveTrivia, SyntaxKind.ElseIfDirectiveTrivia
If activeIfs <= 0 Then Return True
End Select
Next trivia
Return activeIfs <> 0 OrElse activeRegions <> 0
End Function
<Extension()>
Public Function GetAllTrivia(ByVal tokens As IEnumerable(Of SyntaxToken)) As IEnumerable(Of SyntaxTrivia)
Dim list = New List(Of SyntaxTrivia)()
For Each token In tokens
list.AddRange(token.LeadingTrivia)
list.AddRange(token.TrailingTrivia)
Next token
Return list
End Function
<Extension()>
Public Function ContainsFieldInitializer(node As SyntaxNode) As Boolean
node = node.GetOutermostNodeWithSameSpan(Function(n) True)
Return node.DescendantNodesAndSelf().Any(Function(n) TypeOf n Is FieldInitializerSyntax)
End Function
<Extension()>
Public Function ContainsDotMemberAccess(node As SyntaxNode) As Boolean
Dim predicate = Function(n As SyntaxNode)
Dim member = TryCast(n, MemberAccessExpressionSyntax)
If member Is Nothing Then
Return False
End If
Return member.Expression Is Nothing AndAlso member.OperatorToken.Kind = SyntaxKind.DotToken
End Function
Return node.DescendantNodesAndSelf().Any(predicate)
End Function
<Extension()>
Public Function UnderWithBlockContext(token As SyntaxToken) As Boolean
Dim withBlock = token.GetAncestor(Of WithBlockSyntax)()
If withBlock Is Nothing Then
Return False
End If
Dim withBlockSpan = TextSpan.FromBounds(withBlock.WithStatement.Span.End, withBlock.EndWithStatement.SpanStart)
Return withBlockSpan.Contains(token.Span)
End Function
<Extension()>
Public Function UnderObjectMemberInitializerContext(token As SyntaxToken) As Boolean
Dim initializer = token.GetAncestor(Of ObjectMemberInitializerSyntax)()
If initializer Is Nothing Then
Return False
End If
Dim initializerSpan = TextSpan.FromBounds(initializer.WithKeyword.Span.End, initializer.Span.End)
Return initializerSpan.Contains(token.Span)
End Function
<Extension()>
Public Function UnderValidContext(token As SyntaxToken) As Boolean
Dim predicate As Func(Of SyntaxNode, Boolean) =
Function(n)
Dim range = TryCast(n, RangeArgumentSyntax)
If range IsNot Nothing Then
If range.UpperBound.Span.Contains(token.Span) AndAlso
range.GetAncestor(Of FieldDeclarationSyntax)() IsNot Nothing Then
Return True
End If
End If
Dim [property] = TryCast(n, PropertyStatementSyntax)
If [property] IsNot Nothing Then
Dim asNewClause = TryCast([property].AsClause, AsNewClauseSyntax)
If asNewClause IsNot Nothing AndAlso asNewClause.NewExpression IsNot Nothing Then
Dim span = TextSpan.FromBounds(asNewClause.NewExpression.NewKeyword.Span.End, asNewClause.NewExpression.Span.End)
Return span.Contains(token.Span)
End If
End If
If n.CheckTopLevel(token.Span) Then
Return True
End If
Return False
End Function
Return token.GetAncestors(Of SyntaxNode)().Any(predicate)
End Function
<Extension()>
Public Function ContainsInMethodBlockBody(block As MethodBlockBaseSyntax, textSpan As TextSpan) As Boolean
If block Is Nothing Then
Return False
End If
Dim blockSpan = TextSpan.FromBounds(block.BlockStatement.Span.End, block.EndBlockStatement.SpanStart)
Return blockSpan.Contains(textSpan)
End Function
<Extension()> _
Public Function UnderValidContext(ByVal node As SyntaxNode) As Boolean
Contract.ThrowIfNull(node)
Dim predicate As Func(Of SyntaxNode, Boolean) =
Function(n)
If TypeOf n Is MethodBlockBaseSyntax OrElse
TypeOf n Is MultiLineLambdaExpressionSyntax OrElse
TypeOf n Is SingleLineLambdaExpressionSyntax Then
Return True
End If
Return False
End Function
If Not node.GetAncestorsOrThis(Of SyntaxNode)().Any(predicate) Then
Return False
End If
If node.FromScript() OrElse node.GetAncestor(Of TypeBlockSyntax)() IsNot Nothing Then
Return True
End If
Return False
End Function
<Extension()>
Public Function IsReturnableConstruct(node As SyntaxNode) As Boolean
Return TypeOf node Is MethodBlockBaseSyntax OrElse
TypeOf node Is SingleLineLambdaExpressionSyntax OrElse
TypeOf node Is MultiLineLambdaExpressionSyntax
End Function
<Extension()>
Public Function HasSyntaxAnnotation([set] As HashSet(Of SyntaxAnnotation), node As SyntaxNode) As Boolean
Return [set].Any(Function(a) node.GetAnnotatedNodesAndTokens(a).Any())
End Function
<Extension()>
Public Function IsFunctionValue(symbol As ISymbol) As Boolean
Dim local = TryCast(symbol, ILocalSymbol)
Return local IsNot Nothing AndAlso local.IsFunctionValue
End Function
<Extension()>
Public Function ToSeparatedList(Of T As SyntaxNode)(nodes As IEnumerable(Of Tuple(Of T, SyntaxToken))) As SeparatedSyntaxList(Of T)
Dim list = New List(Of SyntaxNodeOrToken)
For Each tuple In nodes
Contract.ThrowIfNull(tuple.Item1)
list.Add(tuple.Item1)
If tuple.Item2.Kind = SyntaxKind.None Then
Exit For
End If
list.Add(tuple.Item2)
Next
Return SyntaxFactory.SeparatedList(Of T)(list)
End Function
<Extension()>
Public Function CreateAssignmentExpressionStatementWithValue(identifier As SyntaxToken, rvalue As ExpressionSyntax) As StatementSyntax
Return SyntaxFactory.SimpleAssignmentStatement(SyntaxFactory.IdentifierName(identifier), SyntaxFactory.Token(SyntaxKind.EqualsToken), rvalue).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker)
End Function
<Extension()>
Public Function ProcessLocalDeclarationStatement(variableToRemoveMap As HashSet(Of SyntaxAnnotation),
declarationStatement As LocalDeclarationStatementSyntax,
expressionStatements As List(Of StatementSyntax),
variableDeclarators As List(Of VariableDeclaratorSyntax),
triviaList As List(Of SyntaxTrivia)) As Boolean
' go through each var decls in decl statement, and create new assignment if
' variable is initialized at decl.
Dim hasChange As Boolean = False
Dim leadingTriviaApplied As Boolean = False
For Each variableDeclarator In declarationStatement.Declarators
Dim identifierList = New List(Of ModifiedIdentifierSyntax)()
Dim nameCount = variableDeclarator.Names.Count
For i = 0 To nameCount - 1 Step 1
Dim variable = variableDeclarator.Names(i)
If variableToRemoveMap.HasSyntaxAnnotation(variable) Then
If variableDeclarator.Initializer IsNot Nothing AndAlso i = nameCount - 1 Then
' move comments with the variable here
Dim identifier As SyntaxToken = variable.Identifier
' The leading trivia from the declaration is applied to the first variable
' There is not much value in appending the trailing trivia of the modifier
If i = 0 AndAlso Not leadingTriviaApplied AndAlso declarationStatement.HasLeadingTrivia Then
identifier = identifier.WithLeadingTrivia(declarationStatement.GetLeadingTrivia.AddRange(identifier.LeadingTrivia))
leadingTriviaApplied = True
End If
expressionStatements.Add(identifier.CreateAssignmentExpressionStatementWithValue(variableDeclarator.Initializer.Value))
Continue For
End If
' we don't remove trivia around tokens we remove
triviaList.AddRange(variable.GetLeadingTrivia())
triviaList.AddRange(variable.GetTrailingTrivia())
Continue For
End If
If triviaList.Count > 0 Then
identifierList.Add(variable.WithPrependedLeadingTrivia(triviaList))
triviaList.Clear()
Continue For
End If
identifierList.Add(variable)
Next
If identifierList.Count = 0 Then
' attach left over trivia to last expression statement
If triviaList.Count > 0 AndAlso expressionStatements.Count > 0 Then
Dim lastStatement = expressionStatements(expressionStatements.Count - 1)
lastStatement = lastStatement.WithPrependedLeadingTrivia(triviaList)
expressionStatements(expressionStatements.Count - 1) = lastStatement
triviaList.Clear()
End If
Continue For
ElseIf identifierList.Count = variableDeclarator.Names.Count Then
variableDeclarators.Add(variableDeclarator)
ElseIf identifierList.Count > 0 Then
variableDeclarators.Add(
variableDeclarator.WithNames(SyntaxFactory.SeparatedList(identifierList)).
WithPrependedLeadingTrivia(triviaList))
hasChange = True
End If
Next variableDeclarator
Return hasChange OrElse declarationStatement.Declarators.Count <> variableDeclarators.Count
End Function
<Extension()>
Public Function IsExpressionInCast(node As SyntaxNode) As Boolean
Return TypeOf node Is ExpressionSyntax AndAlso TypeOf node.Parent Is CastExpressionSyntax
End Function
<Extension()>
Public Function IsErrorType(type As ITypeSymbol) As Boolean
Return type Is Nothing OrElse type.Kind = SymbolKind.ErrorType
End Function
<Extension()>
Public Function IsObjectType(type As ITypeSymbol) As Boolean
Return type Is Nothing OrElse type.SpecialType = SpecialType.System_Object
End Function
End Module
End Namespace
|
DavidKarlas/roslyn
|
src/Features/VisualBasic/ExtractMethod/Extensions.vb
|
Visual Basic
|
apache-2.0
| 19,807
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
' Binding of conversion operators is implemented in this part.
Partial Friend Class Binder
Private Function BindCastExpression(
node As CastExpressionSyntax,
diagnostics As DiagnosticBag
) As BoundExpression
Dim result As BoundExpression
Select Case node.Keyword.Kind
Case SyntaxKind.CTypeKeyword
result = BindCTypeExpression(node, diagnostics)
Case SyntaxKind.DirectCastKeyword
result = BindDirectCastExpression(node, diagnostics)
Case SyntaxKind.TryCastKeyword
result = BindTryCastExpression(node, diagnostics)
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Keyword.Kind)
End Select
Return result
End Function
Private Function BindCTypeExpression(
node As CastExpressionSyntax,
diagnostics As DiagnosticBag
) As BoundExpression
Debug.Assert(node.Keyword.Kind = SyntaxKind.CTypeKeyword)
Dim argument = BindValue(node.Expression, diagnostics)
Dim targetType = BindTypeSyntax(node.Type, diagnostics)
Return ApplyConversion(node, targetType, argument, isExplicit:=True, diagnostics:=diagnostics)
End Function
Private Function BindDirectCastExpression(
node As CastExpressionSyntax,
diagnostics As DiagnosticBag
) As BoundExpression
Debug.Assert(node.Keyword.Kind = SyntaxKind.DirectCastKeyword)
Dim argument = BindValue(node.Expression, diagnostics)
Dim targetType = BindTypeSyntax(node.Type, diagnostics)
Return ApplyDirectCastConversion(node, argument, targetType, diagnostics)
End Function
Private Function ApplyDirectCastConversion(
node As VisualBasicSyntaxNode,
argument As BoundExpression,
targetType As TypeSymbol,
diagnostics As DiagnosticBag
) As BoundExpression
Debug.Assert(argument.IsValue)
' Deal with erroneous arguments
If (argument.HasErrors OrElse targetType.IsErrorType) Then
argument = MakeRValue(argument, diagnostics)
Return New BoundDirectCast(node, argument, ConversionKind:=Nothing, Type:=targetType, HasErrors:=True)
End If
' Classify conversion
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Dim conv As ConversionKind = Conversions.ClassifyDirectCastConversion(argument, targetType, Me, useSiteDiagnostics)
If diagnostics.Add(node, useSiteDiagnostics) Then
' Suppress any additional diagnostics
diagnostics = New DiagnosticBag()
End If
If ReclassifyExpression(argument, SyntaxKind.DirectCastKeyword, node, conv, True, targetType, diagnostics) Then
If argument.Syntax IsNot node Then
' If its an explicit conversion, we must have a bound node that corresponds to that syntax node for GetSemanticInfo.
' Insert an identity conversion if necessary.
Debug.Assert(argument.Kind <> BoundKind.DirectCast, "Associated wrong node with conversion?")
argument = New BoundDirectCast(node, argument, ConversionKind.Identity, targetType)
End If
Return argument
Else
argument = MakeRValue(argument, diagnostics)
End If
If argument.HasErrors Then
Return New BoundDirectCast(node, argument, conv, targetType, HasErrors:=True)
End If
Dim sourceType = argument.Type
If sourceType IsNot Nothing AndAlso sourceType.IsErrorType() Then
Return New BoundDirectCast(node, argument, conv, targetType, HasErrors:=True)
End If
Debug.Assert(argument.IsNothingLiteral() OrElse (sourceType IsNot Nothing AndAlso Not sourceType.IsErrorType()))
' Check for special error conditions
If Conversions.NoConversion(conv) Then
If sourceType.IsValueType AndAlso sourceType.IsRestrictedType() AndAlso
(targetType.IsObjectType() OrElse targetType.SpecialType = SpecialType.System_ValueType) Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_RestrictedConversion1, sourceType)
Return New BoundDirectCast(node, argument, conv, targetType, HasErrors:=True)
End If
End If
WarnOnNarrowingConversionBetweenSealedClassAndAnInterface(conv, argument.Syntax, sourceType, targetType, diagnostics)
If Conversions.NoConversion(conv) Then
ReportNoConversionError(argument.Syntax, sourceType, targetType, diagnostics)
Return New BoundDirectCast(node, argument, conv, targetType, HasErrors:=True)
End If
If Conversions.IsIdentityConversion(conv) Then
If targetType.IsFloatingType() Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_IdentityDirectCastForFloat)
ElseIf targetType.IsValueType Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.WRN_ObsoleteIdentityDirectCastForValueType)
End If
End If
Dim integerOverflow As Boolean = False
Dim constantResult = Conversions.TryFoldConstantConversion(
argument,
targetType,
integerOverflow)
If constantResult IsNot Nothing Then
Debug.Assert(Conversions.IsIdentityConversion(conv) OrElse
conv = ConversionKind.WideningNothingLiteral OrElse
sourceType.GetEnumUnderlyingTypeOrSelf().IsSameTypeIgnoringCustomModifiers(targetType.GetEnumUnderlyingTypeOrSelf()))
Debug.Assert(Not integerOverflow)
Debug.Assert(Not constantResult.IsBad)
Else
constantResult = Conversions.TryFoldNothingReferenceConversion(argument, conv, targetType)
End If
Return New BoundDirectCast(node, argument, conv, constantResult, targetType)
End Function
Private Function BindTryCastExpression(
node As CastExpressionSyntax,
diagnostics As DiagnosticBag
) As BoundExpression
Debug.Assert(node.Keyword.Kind = SyntaxKind.TryCastKeyword)
Dim argument = BindValue(node.Expression, diagnostics)
Dim targetType = BindTypeSyntax(node.Type, diagnostics)
Return ApplyTryCastConversion(node, argument, targetType, diagnostics)
End Function
Private Function ApplyTryCastConversion(
node As VisualBasicSyntaxNode,
argument As BoundExpression,
targetType As TypeSymbol,
diagnostics As DiagnosticBag
) As BoundExpression
Debug.Assert(argument.IsValue)
' Deal with erroneous arguments
If (argument.HasErrors OrElse targetType.IsErrorType) Then
argument = MakeRValue(argument, diagnostics)
Return New BoundTryCast(node, argument, ConversionKind:=Nothing, Type:=targetType, HasErrors:=True)
End If
' Classify conversion
Dim conv As ConversionKind
If targetType.IsReferenceType Then
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
conv = Conversions.ClassifyTryCastConversion(argument, targetType, Me, useSiteDiagnostics)
If diagnostics.Add(node, useSiteDiagnostics) Then
' Suppress any additional diagnostics
diagnostics = New DiagnosticBag()
End If
Else
conv = Nothing
End If
If ReclassifyExpression(argument, SyntaxKind.TryCastKeyword, node, conv, True, targetType, diagnostics) Then
If argument.Syntax IsNot node Then
' If its an explicit conversion, we must have a bound node that corresponds to that syntax node for GetSemanticInfo.
' Insert an identity conversion if necessary.
Debug.Assert(argument.Kind <> BoundKind.TryCast, "Associated wrong node with conversion?")
argument = New BoundTryCast(node, argument, ConversionKind.Identity, targetType)
End If
Return argument
Else
argument = MakeRValue(argument, diagnostics)
End If
If argument.HasErrors Then
Return New BoundTryCast(node, argument, conv, targetType, HasErrors:=True)
End If
Dim sourceType = argument.Type
If sourceType IsNot Nothing AndAlso sourceType.IsErrorType() Then
Return New BoundTryCast(node, argument, conv, targetType, HasErrors:=True)
End If
Debug.Assert(argument.IsNothingLiteral() OrElse (sourceType IsNot Nothing AndAlso Not sourceType.IsErrorType()))
' Check for special error conditions
If Conversions.NoConversion(conv) Then
If targetType.IsValueType() Then
Dim castSyntax = TryCast(node, CastExpressionSyntax)
ReportDiagnostic(diagnostics, If(castSyntax IsNot Nothing, castSyntax.Type, node), ERRID.ERR_TryCastOfValueType1, targetType)
Return New BoundTryCast(node, argument, conv, targetType, HasErrors:=True)
ElseIf targetType.IsTypeParameter() AndAlso Not targetType.IsReferenceType Then
Dim castSyntax = TryCast(node, CastExpressionSyntax)
ReportDiagnostic(diagnostics, If(castSyntax IsNot Nothing, castSyntax.Type, node), ERRID.ERR_TryCastOfUnconstrainedTypeParam1, targetType)
Return New BoundTryCast(node, argument, conv, targetType, HasErrors:=True)
ElseIf sourceType.IsValueType AndAlso sourceType.IsRestrictedType() AndAlso
(targetType.IsObjectType() OrElse targetType.SpecialType = SpecialType.System_ValueType) Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_RestrictedConversion1, sourceType)
Return New BoundTryCast(node, argument, conv, targetType, HasErrors:=True)
End If
End If
WarnOnNarrowingConversionBetweenSealedClassAndAnInterface(conv, argument.Syntax, sourceType, targetType, diagnostics)
If Conversions.NoConversion(conv) Then
ReportNoConversionError(argument.Syntax, sourceType, targetType, diagnostics)
Return New BoundTryCast(node, argument, conv, targetType, HasErrors:=True)
End If
Dim constantResult = Conversions.TryFoldNothingReferenceConversion(argument, conv, targetType)
Return New BoundTryCast(node, argument, conv, constantResult, targetType)
End Function
Private Function BindPredefinedCastExpression(
node As PredefinedCastExpressionSyntax,
diagnostics As DiagnosticBag
) As BoundExpression
Dim targetType As SpecialType
Select Case node.Keyword.Kind
Case SyntaxKind.CBoolKeyword : targetType = SpecialType.System_Boolean
Case SyntaxKind.CByteKeyword : targetType = SpecialType.System_Byte
Case SyntaxKind.CCharKeyword : targetType = SpecialType.System_Char
Case SyntaxKind.CDateKeyword : targetType = SpecialType.System_DateTime
Case SyntaxKind.CDecKeyword : targetType = SpecialType.System_Decimal
Case SyntaxKind.CDblKeyword : targetType = SpecialType.System_Double
Case SyntaxKind.CIntKeyword : targetType = SpecialType.System_Int32
Case SyntaxKind.CLngKeyword : targetType = SpecialType.System_Int64
Case SyntaxKind.CObjKeyword : targetType = SpecialType.System_Object
Case SyntaxKind.CSByteKeyword : targetType = SpecialType.System_SByte
Case SyntaxKind.CShortKeyword : targetType = SpecialType.System_Int16
Case SyntaxKind.CSngKeyword : targetType = SpecialType.System_Single
Case SyntaxKind.CStrKeyword : targetType = SpecialType.System_String
Case SyntaxKind.CUIntKeyword : targetType = SpecialType.System_UInt32
Case SyntaxKind.CULngKeyword : targetType = SpecialType.System_UInt64
Case SyntaxKind.CUShortKeyword : targetType = SpecialType.System_UInt16
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Keyword.Kind)
End Select
Return ApplyConversion(node, GetSpecialType(targetType, node.Keyword, diagnostics),
BindValue(node.Expression, diagnostics),
isExplicit:=True, diagnostics:=diagnostics)
End Function
''' <summary>
''' This function must return a BoundConversion node in case of non-identity conversion.
''' </summary>
Friend Function ApplyImplicitConversion(
node As VisualBasicSyntaxNode,
targetType As TypeSymbol,
expression As BoundExpression,
diagnostics As DiagnosticBag,
Optional isOperandOfConditionalBranch As Boolean = False
) As BoundExpression
Return ApplyConversion(node, targetType, expression, False, diagnostics, isOperandOfConditionalBranch:=isOperandOfConditionalBranch)
End Function
''' <summary>
''' This function must return a BoundConversion node in case of explicit or non-identity conversion.
''' </summary>
Private Function ApplyConversion(
node As VisualBasicSyntaxNode,
targetType As TypeSymbol,
argument As BoundExpression,
isExplicit As Boolean,
diagnostics As DiagnosticBag,
Optional isOperandOfConditionalBranch As Boolean = False,
Optional explicitSemanticForConcatArgument As Boolean = False
) As BoundExpression
Debug.Assert(node IsNot Nothing)
Debug.Assert(Not isOperandOfConditionalBranch OrElse Not isExplicit)
Debug.Assert(argument.IsValue())
' Deal with erroneous arguments
If targetType.IsErrorType Then
argument = MakeRValueAndIgnoreDiagnostics(argument)
If Not isExplicit AndAlso argument.Type.IsSameTypeIgnoringCustomModifiers(targetType) Then
Return argument
End If
Return New BoundConversion(node,
argument,
conversionKind:=Nothing,
checked:=CheckOverflow,
explicitCastInCode:=isExplicit,
type:=targetType,
hasErrors:=True)
End If
If argument.HasErrors Then
' Suppress any additional diagnostics produced by this function
diagnostics = New DiagnosticBag()
End If
' Classify conversion
Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol)
Dim applyNullableIsTrueOperator As Boolean = False
Dim isTrueOperator As OverloadResolution.OverloadResolutionResult = Nothing
Dim result As BoundExpression
Debug.Assert(Not isOperandOfConditionalBranch OrElse targetType.IsBooleanType())
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
If isOperandOfConditionalBranch AndAlso targetType.IsBooleanType() Then
Debug.Assert(Not isExplicit)
conv = Conversions.ClassifyConversionOfOperandOfConditionalBranch(argument, targetType, Me,
applyNullableIsTrueOperator,
isTrueOperator,
useSiteDiagnostics)
If diagnostics.Add(node, useSiteDiagnostics) Then
' Suppress any additional diagnostics
diagnostics = New DiagnosticBag()
End If
If isTrueOperator.BestResult.HasValue Then
' Apply IsTrue operator.
Dim isTrue As BoundUserDefinedUnaryOperator = BindUserDefinedUnaryOperator(node, UnaryOperatorKind.IsTrue, argument, isTrueOperator, diagnostics)
isTrue.SetWasCompilerGenerated()
isTrue.UnderlyingExpression.SetWasCompilerGenerated()
result = isTrue
Else
Dim intermediateTargetType As TypeSymbol
If applyNullableIsTrueOperator Then
' Note, use site error will be reported by ApplyNullableIsTrueOperator later.
Dim nullableOfT As NamedTypeSymbol = Compilation.GetSpecialType(SpecialType.System_Nullable_T)
intermediateTargetType = Compilation.GetSpecialType(SpecialType.System_Nullable_T).
Construct(ImmutableArray.Create(Of TypeSymbol)(targetType))
Else
intermediateTargetType = targetType
End If
result = CreateConversionAndReportDiagnostic(node, argument, conv, isExplicit, intermediateTargetType, diagnostics)
End If
If applyNullableIsTrueOperator Then
result = Binder.ApplyNullableIsTrueOperator(result, targetType)
End If
Else
conv = Conversions.ClassifyConversion(argument, targetType, Me, useSiteDiagnostics)
If diagnostics.Add(node, useSiteDiagnostics) Then
' Suppress any additional diagnostics
diagnostics = New DiagnosticBag()
End If
result = CreateConversionAndReportDiagnostic(node, argument, conv, isExplicit, targetType, diagnostics,
explicitSemanticForConcatArgument:=explicitSemanticForConcatArgument)
End If
Return result
End Function
Private Shared Function ApplyNullableIsTrueOperator(argument As BoundExpression, booleanType As TypeSymbol) As BoundNullableIsTrueOperator
Debug.Assert(argument.Type.IsNullableOfBoolean() AndAlso booleanType.IsBooleanType())
Return New BoundNullableIsTrueOperator(argument.Syntax, argument, booleanType).MakeCompilerGenerated()
End Function
''' <summary>
''' This function must return a BoundConversion node in case of non-identity conversion.
''' </summary>
Private Function CreateConversionAndReportDiagnostic(
tree As VisualBasicSyntaxNode,
argument As BoundExpression,
convKind As KeyValuePair(Of ConversionKind, MethodSymbol),
isExplicit As Boolean,
targetType As TypeSymbol,
diagnostics As DiagnosticBag,
Optional copybackConversionParamName As String = Nothing,
Optional explicitSemanticForConcatArgument As Boolean = False
) As BoundExpression
Debug.Assert(argument.IsValue())
' We need to preserve any conversion that was explicitly written in code
' (so that GetSemanticInfo can find the syntax in the bound tree). Implicit identity conversion
' don't need representation in the bound tree (they would be optimized away in emit, but are so common
' that this is an important way to save both time and memory).
If (Not isExplicit OrElse explicitSemanticForConcatArgument) AndAlso Conversions.IsIdentityConversion(convKind.Key) Then
Debug.Assert(argument.Type.IsSameTypeIgnoringCustomModifiers(targetType))
Debug.Assert(tree Is argument.Syntax)
Return MakeRValue(argument, diagnostics)
End If
If (convKind.Key And ConversionKind.UserDefined) = 0 AndAlso
ReclassifyExpression(argument, SyntaxKind.CTypeKeyword, tree, convKind.Key, isExplicit, targetType, diagnostics) Then
argument = MakeRValue(argument, diagnostics)
If isExplicit AndAlso argument.Syntax IsNot tree Then
' If its an explicit conversion, we must have a bound node that corresponds to that syntax node for GetSemanticInfo.
' Insert an identity conversion if necessary.
Debug.Assert(argument.Kind <> BoundKind.Conversion, "Associated wrong node with conversion?")
argument = New BoundConversion(tree, argument, ConversionKind.Identity, CheckOverflow, isExplicit, targetType)
End If
Return argument
ElseIf Not argument.IsNothingLiteral() AndAlso argument.Kind <> BoundKind.ArrayLiteral Then
argument = MakeRValue(argument, diagnostics)
End If
Debug.Assert(argument.Kind <> BoundKind.Conversion OrElse DirectCast(argument, BoundConversion).ExplicitCastInCode OrElse
Not argument.IsNothingLiteral() OrElse
TypeOf argument.Syntax.Parent Is BinaryExpressionSyntax OrElse
TypeOf argument.Syntax.Parent Is UnaryExpressionSyntax OrElse
(TypeOf argument.Syntax.Parent Is AssignmentStatementSyntax AndAlso argument.Syntax.Parent.Kind <> SyntaxKind.SimpleAssignmentStatement),
"Applying yet another conversion to an implicit conversion from NOTHING, probably MakeRValue was called too early.")
Dim sourceType = argument.Type
' At this point if the expression is an array literal then the conversion must be user defined.
Debug.Assert(argument.Kind <> BoundKind.ArrayLiteral OrElse (convKind.Key And ConversionKind.UserDefined) <> 0)
Dim reportArrayLiteralElementNarrowingConversion = False
If argument.Kind = BoundKind.ArrayLiteral Then
' The array will get the type from the input type of the user defined conversion.
sourceType = convKind.Value.Parameters(0).Type
' If the conversion from the inferred element type to the source type of the user defined conversion is a narrowing conversion then
' skip to the user defined conversion. Conversion errors on the individual elements will be reported when the array literal is reclassified.
If Not isExplicit AndAlso
Conversions.IsNarrowingConversion(convKind.Key) AndAlso
Conversions.IsNarrowingConversion(Conversions.ClassifyArrayLiteralConversion(DirectCast(argument, BoundArrayLiteral), sourceType, Me, Nothing)) Then
reportArrayLiteralElementNarrowingConversion = True
GoTo DoneWithDiagnostics
End If
End If
If argument.HasErrors Then
GoTo DoneWithDiagnostics
End If
If sourceType IsNot Nothing AndAlso sourceType.IsErrorType() Then
GoTo DoneWithDiagnostics
End If
Debug.Assert(argument.IsNothingLiteral() OrElse (sourceType IsNot Nothing AndAlso Not sourceType.IsErrorType()))
' Check for special error conditions
If Conversions.NoConversion(convKind.Key) Then
If sourceType.IsValueType AndAlso sourceType.IsRestrictedType() AndAlso
(targetType.IsObjectType() OrElse targetType.SpecialType = SpecialType.System_ValueType) Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_RestrictedConversion1, sourceType)
Return New BoundConversion(tree, argument, convKind.Key, CheckOverflow, isExplicit, targetType, HasErrors:=True)
End If
End If
WarnOnNarrowingConversionBetweenSealedClassAndAnInterface(convKind.Key, argument.Syntax, sourceType, targetType, diagnostics)
' Deal with implicit narrowing conversions
If Not isExplicit AndAlso Conversions.IsNarrowingConversion(convKind.Key) AndAlso
(convKind.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) = 0 Then
If copybackConversionParamName IsNot Nothing Then
If OptionStrict = VisualBasic.OptionStrict.On Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_StrictArgumentCopyBackNarrowing3,
copybackConversionParamName, sourceType, targetType)
ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.WRN_ImplicitConversionCopyBack,
copybackConversionParamName, sourceType, targetType)
End If
Else
' We have a narrowing conversion. This is how we might display it, depending on context:
' ERR_NarrowingConversionDisallowed2 "Option Strict On disallows implicit conversions from '|1' to '|2'."
' ERR_NarrowingConversionCollection2 "Option Strict On disallows implicit conversions from '|1' to '|2';
' the Visual Basic 6.0 collection type is not compatible with the .NET Framework collection type."
' ERR_AmbiguousCastConversion2 "Option Strict On disallows implicit conversions from '|1' to '|2' because the conversion is ambiguous."
' The Collection error is for when one type is Microsoft.VisualBasic.Collection and
' the other type is named _Collection.
' The Ambiguous error is for when the conversion was classed as "Narrowing" for reasons of ambiguity.
If OptionStrict = VisualBasic.OptionStrict.On Then
If Not MakeVarianceConversionSuggestion(convKind.Key, argument.Syntax, sourceType, targetType, diagnostics, justWarn:=False) Then
Dim err As ERRID = ERRID.ERR_NarrowingConversionDisallowed2
Const _Collection As String = "_Collection"
If (convKind.Key And ConversionKind.VarianceConversionAmbiguity) <> 0 Then
err = ERRID.ERR_AmbiguousCastConversion2
ElseIf (sourceType.IsMicrosoftVisualBasicCollection() AndAlso String.Equals(targetType.Name, _Collection, StringComparison.Ordinal)) OrElse
(String.Equals(sourceType.Name, _Collection, StringComparison.Ordinal) AndAlso targetType.IsMicrosoftVisualBasicCollection()) Then
' Got both, so use the more specific error message
err = ERRID.ERR_NarrowingConversionCollection2
End If
ReportDiagnostic(diagnostics, argument.Syntax, err, sourceType, targetType)
End If
ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then
' Avoid reporting a warning if narrowing caused exclusively by "zero argument" relaxation
' for an Anonymous Delegate. Note, that dropping a return is widening.
If (convKind.Key And ConversionKind.AnonymousDelegate) = 0 OrElse
(convKind.Key And ConversionKind.DelegateRelaxationLevelMask) <> ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs Then
If Not MakeVarianceConversionSuggestion(convKind.Key, argument.Syntax, sourceType, targetType, diagnostics, justWarn:=True) Then
Dim wrnId1 As ERRID = ERRID.WRN_ImplicitConversionSubst1
Dim wrnId2 As ERRID = ERRID.WRN_ImplicitConversion2
If (convKind.Key And ConversionKind.VarianceConversionAmbiguity) <> 0 Then
wrnId2 = ERRID.WRN_AmbiguousCastConversion2
End If
ReportDiagnostic(diagnostics, argument.Syntax, wrnId1, ErrorFactory.ErrorInfo(wrnId2, sourceType, targetType))
End If
End If
End If
End If
End If
If Conversions.NoConversion(convKind.Key) Then
If Conversions.FailedDueToNumericOverflow(convKind.Key) Then
Dim errorTargetType As TypeSymbol
If (convKind.Key And ConversionKind.UserDefined) <> 0 AndAlso convKind.Value IsNot Nothing Then
errorTargetType = convKind.Value.Parameters(0).Type
Else
errorTargetType = targetType
End If
ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_ExpressionOverflow1, errorTargetType)
ElseIf isExplicit OrElse Not MakeVarianceConversionSuggestion(convKind.Key, argument.Syntax, sourceType, targetType, diagnostics, justWarn:=False) Then
ReportNoConversionError(argument.Syntax, sourceType, targetType, diagnostics, copybackConversionParamName)
End If
Return New BoundConversion(tree, argument, convKind.Key, CheckOverflow, isExplicit, targetType, HasErrors:=True)
End If
DoneWithDiagnostics:
If (convKind.Key And ConversionKind.UserDefined) <> 0 Then
Return CreateUserDefinedConversion(tree, argument, convKind, isExplicit, targetType, reportArrayLiteralElementNarrowingConversion, diagnostics)
End If
If argument.HasErrors OrElse (sourceType IsNot Nothing AndAlso sourceType.IsErrorType()) Then
Return New BoundConversion(tree, argument, convKind.Key, CheckOverflow, isExplicit, targetType, HasErrors:=True)
End If
Return CreatePredefinedConversion(tree, argument, convKind.Key, isExplicit, targetType, diagnostics)
End Function
Private Structure VarianceSuggestionTypeParameterInfo
Private _isViable As Boolean
Private _typeParameter As TypeParameterSymbol
Private _derivedArgument As TypeSymbol
Private _baseArgument As TypeSymbol
Public Sub [Set](parameter As TypeParameterSymbol, derived As TypeSymbol, base As TypeSymbol)
_typeParameter = parameter
_derivedArgument = derived
_baseArgument = base
_isViable = True
End Sub
Public ReadOnly Property IsViable As Boolean
Get
Return _isViable
End Get
End Property
Public ReadOnly Property TypeParameter As TypeParameterSymbol
Get
Return _typeParameter
End Get
End Property
Public ReadOnly Property DerivedArgument As TypeSymbol
Get
Return _derivedArgument
End Get
End Property
Public ReadOnly Property BaseArgument As TypeSymbol
Get
Return _baseArgument
End Get
End Property
End Structure
''' <summary>
''' Returns True if error or warning was reported.
'''
''' This function is invoked on the occasion of a Narrowing or NoConversion.
''' It looks at the conversion. If the conversion could have been helped by variance in
''' some way, it reports an error/warning message to that effect and returns true. This
''' message is a substitute for whatever other conversion-failed message might have been displayed.
'''
''' Note: these variance-related messages will NOT show auto-correct suggestion of using CType. That's
''' because, in these cases, it's more likely than not that CType will fail, so it would be a bad suggestion
''' </summary>
Private Function MakeVarianceConversionSuggestion(
convKind As ConversionKind,
location As VisualBasicSyntaxNode,
sourceType As TypeSymbol,
targetType As TypeSymbol,
diagnostics As DiagnosticBag,
justWarn As Boolean
) As Boolean
If (convKind And ConversionKind.UserDefined) <> 0 Then
Return False
End If
' Variance scenario 2: Dim x As List(Of Animal) = New List(Of Tiger)
' "List(Of Tiger) cannot be converted to List(Of Animal). Consider using IEnumerable(Of Animal) instead."
'
' (1) If the user attempts a conversion to DEST which is a generic binding of one of the non-variant
' standard generic collection types List(Of D), Collection(Of D), ReadOnlyCollection(Of D),
' IList(Of D), ICollection(Of D)
' (2) and if the conversion failed (either ConversionNarrowing or ConversionError),
' (3) and if the source type SOURCE implemented/inherited exactly one binding ISOURCE=G(Of S) of that
' generic collection type G
' (4) and if there is a reference conversion from S to D
' (5) Then report "G(Of S) cannot be converted to G(Of D). Consider converting to IEnumerable(Of D) instead."
If targetType.Kind <> SymbolKind.NamedType Then
Return False
End If
Dim targetNamedType = DirectCast(targetType, NamedTypeSymbol)
If Not targetNamedType.IsGenericType Then
Return False
End If
Dim targetGenericDefinition As NamedTypeSymbol = targetNamedType.OriginalDefinition
If targetGenericDefinition.SpecialType = SpecialType.System_Collections_Generic_IList_T OrElse
targetGenericDefinition.SpecialType = SpecialType.System_Collections_Generic_ICollection_T OrElse
targetGenericDefinition.SpecialType = SpecialType.System_Collections_Generic_IReadOnlyList_T OrElse
targetGenericDefinition.SpecialType = SpecialType.System_Collections_Generic_IReadOnlyCollection_T OrElse
targetGenericDefinition Is Compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_List_T) OrElse
targetGenericDefinition Is Compilation.GetWellKnownType(WellKnownType.System_Collections_ObjectModel_Collection_T) OrElse
targetGenericDefinition Is Compilation.GetWellKnownType(WellKnownType.System_Collections_ObjectModel_ReadOnlyCollection_T) Then
Dim sourceTypeArgument As TypeSymbol = Nothing
If targetGenericDefinition.IsInterfaceType() Then
Dim matchingInterfaces As New HashSet(Of NamedTypeSymbol)()
If IsOrInheritsFromOrImplementsInterface(sourceType, targetGenericDefinition, useSiteDiagnostics:=Nothing, matchingInterfaces:=matchingInterfaces) AndAlso
matchingInterfaces.Count = 1 Then
sourceTypeArgument = matchingInterfaces(0).TypeArgumentsNoUseSiteDiagnostics(0)
End If
Else
Dim typeToCheck As TypeSymbol = sourceType
Do
If typeToCheck.OriginalDefinition Is targetGenericDefinition Then
sourceTypeArgument = DirectCast(typeToCheck, NamedTypeSymbol).TypeArgumentsNoUseSiteDiagnostics(0)
Exit Do
End If
typeToCheck = typeToCheck.BaseTypeNoUseSiteDiagnostics
Loop While typeToCheck IsNot Nothing
End If
If sourceTypeArgument IsNot Nothing AndAlso
Conversions.IsWideningConversion(Conversions.Classify_Reference_Array_TypeParameterConversion(sourceTypeArgument,
targetNamedType.TypeArgumentsNoUseSiteDiagnostics(0),
varianceCompatibilityClassificationDepth:=0,
useSiteDiagnostics:=Nothing)) Then
Dim iEnumerable_T As NamedTypeSymbol = Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T)
If Not iEnumerable_T.IsErrorType() Then
Dim suggestion As NamedTypeSymbol = iEnumerable_T.Construct(targetNamedType.TypeArgumentsNoUseSiteDiagnostics(0))
If justWarn Then
ReportDiagnostic(diagnostics, location, ERRID.WRN_ImplicitConversionSubst1,
ErrorFactory.ErrorInfo(ERRID.WRN_VarianceIEnumerableSuggestion3, sourceType, targetType, suggestion))
Else
ReportDiagnostic(diagnostics, location, ERRID.ERR_VarianceIEnumerableSuggestion3, sourceType, targetType, suggestion)
End If
Return True
End If
End If
End If
' Variance scenario 1: | Variance scenario 3:
' Dim x as IEnumerable(Of Tiger) = New List(Of Animal) | Dim x As IFoo(Of Animal) = New MyFoo
' "List(Of Animal) cannot be converted to | "MyFoo cannot be converted to IFoo(Of Animal).
' IEnumerable(Of Tiger) because 'Animal' is not derived | Consider changing the 'T' in the definition
' from 'Tiger', as required for the 'Out' generic | of interface IFoo(Of T) to an Out type
' parameter 'T' in 'IEnumerable(Of Out T)'" | parameter, Out T."
' |
' (1) If the user attempts a conversion to | (1) If the user attempts a conversion to some
' some target type DEST=G(Of D1,D2,...) which is | target type DEST=G(Of D1,D2,...) which is
' a generic instantiation of some variant interface/| a generic instantiation of some interface/delegate
' delegate type G(Of T1,T2,...), | type G(...), which NEED NOT be variant!
' (2) and if the conversion fails (Narrowing/Error), | (2) and if the type G is defined in source-code,
' (3) and if the source type SOURCE implements/ | not imported metadata. And the conversion fails.
' inherits exactly one binding INHSOURCE= | (3) And INHSOURCE=exactly one binding of G
' G(Of S1,S2,...) of that generic type G, | (4) And if ever difference is either Di/Si/Ti
' (4) and if the only differences between (D1,D2,...) | where Ti has In/Out variance, or is
' and (S1,S2,...) occur in positions "Di/Si" | Dj/Sj/Tj such that Tj has no variance and
' such that the corresponding Ti has either In | Dj has a CLR conversion to Sj or vice versa
' or Out variance | (5) Then pick the first difference Dj/Sj
' (5) Then pick on the one such difference Si/Di/Ti | (6) and report "SOURCE cannot be converted to
' (6) and report "SOURCE cannot be converted to DEST | DEST. Consider changing Tj in the definition
' because Si is not derived from Di, as required | of interface/delegate IFoo(Of T) to an
' for the 'In/Out' generic parameter 'T' in | In/Out type parameter, In/Out T".
' 'IEnumerable(Of Out T)'" |
Dim matchingGenericInstantiation As NamedTypeSymbol
' (1) If the user attempts a conversion
Select Case targetGenericDefinition.TypeKind
Case TypeKind.Delegate
If sourceType.OriginalDefinition Is targetGenericDefinition Then
matchingGenericInstantiation = DirectCast(sourceType, NamedTypeSymbol)
Else
Return False
End If
Case TypeKind.Interface
Dim matchingInterfaces As New HashSet(Of NamedTypeSymbol)()
If IsOrInheritsFromOrImplementsInterface(sourceType, targetGenericDefinition, useSiteDiagnostics:=Nothing, matchingInterfaces:=matchingInterfaces) AndAlso
matchingInterfaces.Count = 1 Then
matchingGenericInstantiation = matchingInterfaces(0)
Else
Return False
End If
Case Else
Return False
End Select
' (3) and if the source type implemented exactly one binding of it...
Dim source As NamedTypeSymbol = matchingGenericInstantiation
Dim destination As NamedTypeSymbol = targetNamedType
Dim oneVariantDifference As VarianceSuggestionTypeParameterInfo = Nothing ' for Di/Si/Ti
Dim oneInvariantConvertibleDifference As TypeParameterSymbol = Nothing 'for Dj/Sj/Tj where Sj<Dj
Dim oneInvariantReverseConvertibleDifference As TypeParameterSymbol = Nothing ' Dj/Sj/Tj where Dj<Sj
Do
Dim typeParameters As ImmutableArray(Of TypeParameterSymbol) = source.TypeParameters
Dim sourceArguments As ImmutableArray(Of TypeSymbol) = source.TypeArgumentsNoUseSiteDiagnostics
Dim destinationArguments As ImmutableArray(Of TypeSymbol) = destination.TypeArgumentsNoUseSiteDiagnostics
For i As Integer = 0 To typeParameters.Length - 1
Dim sourceArg As TypeSymbol = sourceArguments(i)
Dim destinationArg As TypeSymbol = destinationArguments(i)
If sourceArg.IsSameTypeIgnoringCustomModifiers(destinationArg) Then
Continue For
End If
If sourceArg.IsErrorType() OrElse destinationArg.IsErrorType() Then
Continue For
End If
Dim conv As ConversionKind = Nothing
Select Case typeParameters(i).Variance
Case VarianceKind.Out
If sourceArg.IsValueType OrElse destinationArg.IsValueType Then
oneVariantDifference.Set(typeParameters(i), sourceArg, destinationArg)
Else
conv = Conversions.Classify_Reference_Array_TypeParameterConversion(sourceArg, destinationArg,
varianceCompatibilityClassificationDepth:=0,
useSiteDiagnostics:=Nothing)
If Not Conversions.IsWideningConversion(conv) Then
If Not Conversions.IsNarrowingConversion(conv) OrElse (conv And ConversionKind.VarianceConversionAmbiguity) = 0 Then
oneVariantDifference.Set(typeParameters(i), sourceArg, destinationArg)
End If
End If
End If
Case VarianceKind.In
If sourceArg.IsValueType OrElse destinationArg.IsValueType Then
oneVariantDifference.Set(typeParameters(i), destinationArg, sourceArg)
Else
conv = Conversions.Classify_Reference_Array_TypeParameterConversion(destinationArg, sourceArg,
varianceCompatibilityClassificationDepth:=0,
useSiteDiagnostics:=Nothing)
If Not Conversions.IsWideningConversion(conv) Then
If (targetNamedType.IsDelegateType AndAlso destinationArg.IsReferenceType AndAlso sourceArg.IsReferenceType) OrElse
Not Conversions.IsNarrowingConversion(conv) OrElse
(conv And ConversionKind.VarianceConversionAmbiguity) = 0 Then
oneVariantDifference.Set(typeParameters(i), destinationArg, sourceArg)
End If
End If
End If
Case Else
conv = Conversions.ClassifyDirectCastConversion(sourceArg, destinationArg, Nothing)
If Conversions.IsWideningConversion(conv) Then
oneInvariantConvertibleDifference = typeParameters(i)
Else
conv = Conversions.ClassifyDirectCastConversion(destinationArg, sourceArg, Nothing)
If Conversions.IsWideningConversion(conv) Then
oneInvariantReverseConvertibleDifference = typeParameters(i)
Else
Return False
End If
End If
End Select
Next
source = source.ContainingType
destination = destination.ContainingType
Loop While source IsNot Nothing
' (5) If a Di/Si/Ti, and no Dj/Sj/Tj nor Dk/Sk/Tk, then report...
If oneVariantDifference.IsViable AndAlso
oneInvariantConvertibleDifference Is Nothing AndAlso
oneInvariantReverseConvertibleDifference Is Nothing Then
Dim containerFormatter As FormattedSymbol
If oneVariantDifference.TypeParameter.ContainingType.IsDelegateType Then
containerFormatter = CustomSymbolDisplayFormatter.DelegateSignature(oneVariantDifference.TypeParameter.ContainingSymbol)
Else
containerFormatter = CustomSymbolDisplayFormatter.ErrorNameWithKind(oneVariantDifference.TypeParameter.ContainingSymbol)
End If
If justWarn Then
ReportDiagnostic(diagnostics, location, ERRID.WRN_ImplicitConversionSubst1,
ErrorFactory.ErrorInfo(If(oneVariantDifference.TypeParameter.Variance = VarianceKind.Out,
ERRID.WRN_VarianceConversionFailedOut6,
ERRID.WRN_VarianceConversionFailedIn6),
oneVariantDifference.DerivedArgument,
oneVariantDifference.BaseArgument,
oneVariantDifference.TypeParameter.Name,
containerFormatter,
sourceType,
targetType))
Else
ReportDiagnostic(diagnostics, location, If(oneVariantDifference.TypeParameter.Variance = VarianceKind.Out,
ERRID.ERR_VarianceConversionFailedOut6,
ERRID.ERR_VarianceConversionFailedIn6),
oneVariantDifference.DerivedArgument,
oneVariantDifference.BaseArgument,
oneVariantDifference.TypeParameter.Name,
containerFormatter,
sourceType,
targetType)
End If
Return True
End If
' (5b) Otherwise, if a Dj/Sj/Tj and no Dk/Sk/Tk, and G came not from metadata, then report...
If (oneInvariantConvertibleDifference IsNot Nothing OrElse oneInvariantReverseConvertibleDifference IsNot Nothing) AndAlso
targetType.ContainingModule Is Compilation.SourceModule Then
Dim oneInvariantDifference As TypeParameterSymbol
If oneInvariantConvertibleDifference IsNot Nothing Then
oneInvariantDifference = oneInvariantConvertibleDifference
Else
oneInvariantDifference = oneInvariantReverseConvertibleDifference
End If
Dim containerFormatter As FormattedSymbol
If oneInvariantDifference.ContainingType.IsDelegateType Then
containerFormatter = CustomSymbolDisplayFormatter.DelegateSignature(oneInvariantDifference.ContainingSymbol)
Else
containerFormatter = CustomSymbolDisplayFormatter.ErrorNameWithKind(oneInvariantDifference.ContainingSymbol)
End If
If justWarn Then
ReportDiagnostic(diagnostics, location, ERRID.WRN_ImplicitConversionSubst1,
ErrorFactory.ErrorInfo(If(oneInvariantConvertibleDifference IsNot Nothing,
ERRID.WRN_VarianceConversionFailedTryOut4,
ERRID.WRN_VarianceConversionFailedTryIn4),
sourceType,
targetType,
oneInvariantDifference.Name,
containerFormatter))
Else
ReportDiagnostic(diagnostics, location, If(oneInvariantConvertibleDifference IsNot Nothing,
ERRID.ERR_VarianceConversionFailedTryOut4,
ERRID.ERR_VarianceConversionFailedTryIn4),
sourceType,
targetType,
oneInvariantDifference.Name,
containerFormatter)
End If
Return True
End If
Return False
End Function
Private Function CreatePredefinedConversion(
tree As VisualBasicSyntaxNode,
argument As BoundExpression,
convKind As ConversionKind,
isExplicit As Boolean,
targetType As TypeSymbol,
diagnostics As DiagnosticBag
) As BoundConversion
Debug.Assert(Conversions.ConversionExists(convKind) AndAlso (convKind And ConversionKind.UserDefined) = 0)
Dim sourceType = argument.Type
' Handle Anonymous Delegate conversion.
If (convKind And ConversionKind.AnonymousDelegate) <> 0 Then
' Don't spend time building a narrowing relaxation stub if we already complained about the narrowing.
If isExplicit OrElse OptionStrict <> VisualBasic.OptionStrict.On OrElse Conversions.IsWideningConversion(convKind) Then
Debug.Assert(Not Conversions.IsIdentityConversion(convKind))
Debug.Assert(sourceType.IsDelegateType() AndAlso DirectCast(sourceType, NamedTypeSymbol).IsAnonymousType AndAlso targetType.IsDelegateType() AndAlso
targetType.SpecialType <> SpecialType.System_MulticastDelegate)
Dim boundLambdaOpt As BoundLambda = Nothing
Dim relaxationReceiverPlaceholderOpt As BoundRValuePlaceholder = Nothing
Dim methodToConvert As MethodSymbol = DirectCast(sourceType, NamedTypeSymbol).DelegateInvokeMethod
If (convKind And ConversionKind.NeedAStub) <> 0 Then
Dim relaxationBinder As Binder
' If conversion is explicit, use Option Strict Off.
If isExplicit AndAlso Me.OptionStrict <> VisualBasic.OptionStrict.Off Then
relaxationBinder = New OptionStrictOffBinder(Me)
Else
relaxationBinder = Me
End If
Debug.Assert(Not isExplicit OrElse relaxationBinder.OptionStrict = VisualBasic.OptionStrict.Off)
boundLambdaOpt = relaxationBinder.BuildDelegateRelaxationLambda(tree, tree, argument, methodToConvert,
Nothing, QualificationKind.QualifiedViaValue,
DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod,
convKind And ConversionKind.DelegateRelaxationLevelMask,
isZeroArgumentKnownToBeUsed:=False,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation:=False,
diagnostics:=diagnostics,
relaxationReceiverPlaceholder:=relaxationReceiverPlaceholderOpt)
End If
' The conversion has the lambda stored internally to not clutter the bound tree with synthesized nodes
' in the first pass. Later the node get's rewritten into a delegate creation with the lambda if needed.
Return New BoundConversion(tree, argument, convKind, False, isExplicit, boundLambdaOpt, relaxationReceiverPlaceholderOpt, targetType)
Else
Debug.Assert(diagnostics.HasAnyErrors())
End If
End If
Dim integerOverflow As Boolean = False
Dim constantResult = Conversions.TryFoldConstantConversion(
argument,
targetType,
integerOverflow)
If constantResult IsNot Nothing Then
' Overflow should have been detected at classification time.
Debug.Assert(Not integerOverflow OrElse Not CheckOverflow)
Debug.Assert(Not constantResult.IsBad)
Else
constantResult = Conversions.TryFoldNothingReferenceConversion(argument, convKind, targetType)
End If
Return New BoundConversion(tree, argument, convKind, CheckOverflow, isExplicit, constantResult, targetType)
End Function
Private Function CreateUserDefinedConversion(
tree As VisualBasicSyntaxNode,
argument As BoundExpression,
convKind As KeyValuePair(Of ConversionKind, MethodSymbol),
isExplicit As Boolean,
targetType As TypeSymbol,
reportArrayLiteralElementNarrowingConversion As Boolean,
diagnostics As DiagnosticBag
) As BoundConversion
Debug.Assert((convKind.Key And ConversionKind.UserDefined) <> 0 AndAlso convKind.Value IsNot Nothing AndAlso
convKind.Value.ParameterCount = 1 AndAlso Not convKind.Value.IsSub AndAlso
Not convKind.Value.Parameters(0).IsByRef AndAlso convKind.Value.IsShared)
' Suppress any Option Strict diagnostics.
Dim conversionBinder = New OptionStrictOffBinder(Me)
Dim argumentSyntax = argument.Syntax
Dim originalArgumentType As TypeSymbol = argument.Type
Dim inType As TypeSymbol = convKind.Value.Parameters(0).Type
Dim outType As TypeSymbol = convKind.Value.ReturnType
Dim intermediateConv As ConversionKind
Dim inOutConversionFlags As Byte = 0
If argument.Kind = BoundKind.ArrayLiteral Then
' For array literals, report Option Strict diagnostics for each element when reportArrayLiteralElementNarrowingConversion is true.
Dim arrayLiteral = DirectCast(argument, BoundArrayLiteral)
Dim arrayLiteralBinder = If(reportArrayLiteralElementNarrowingConversion, Me, conversionBinder)
intermediateConv = Conversions.ClassifyArrayLiteralConversion(arrayLiteral, inType, arrayLiteralBinder, Nothing)
argument = arrayLiteralBinder.ReclassifyArrayLiteralExpression(SyntaxKind.CTypeKeyword, tree,
intermediateConv,
isExplicit,
arrayLiteral,
inType, diagnostics)
originalArgumentType = inType
Else
intermediateConv = Conversions.ClassifyPredefinedConversion(argument, inType, conversionBinder, Nothing)
If Not Conversions.IsIdentityConversion(intermediateConv) Then
#If DEBUG Then
Dim oldArgument = argument
#End If
argument = conversionBinder.CreatePredefinedConversion(tree, argument, intermediateConv, isExplicit, inType, diagnostics).
MakeCompilerGenerated()
#If DEBUG Then
Debug.Assert(oldArgument IsNot argument AndAlso argument.Kind = BoundKind.Conversion)
#End If
inOutConversionFlags = 1
End If
End If
ReportUseSiteError(diagnostics, tree, convKind.Value)
ReportDiagnosticsIfObsolete(diagnostics, convKind.Value, tree)
Debug.Assert(convKind.Value.IsUserDefinedOperator())
If Me.ContainingMember Is convKind.Value Then
ReportDiagnostic(diagnostics, argumentSyntax, ERRID.WRN_RecursiveOperatorCall, convKind.Value)
End If
argument = New BoundCall(tree,
method:=convKind.Value,
methodGroupOpt:=Nothing,
receiverOpt:=Nothing,
arguments:=ImmutableArray.Create(Of BoundExpression)(argument),
constantValueOpt:=Nothing,
suppressObjectClone:=True,
type:=outType).MakeCompilerGenerated()
intermediateConv = Conversions.ClassifyPredefinedConversion(argument, targetType, conversionBinder, Nothing)
If Not Conversions.IsIdentityConversion(intermediateConv) Then
#If DEBUG Then
Dim oldArgument = argument
#End If
argument = conversionBinder.CreatePredefinedConversion(tree, argument, intermediateConv, isExplicit, targetType, diagnostics).
MakeCompilerGenerated()
#If DEBUG Then
Debug.Assert(oldArgument IsNot argument AndAlso argument.Kind = BoundKind.Conversion)
#End If
inOutConversionFlags = inOutConversionFlags Or CByte(2)
End If
argument = New BoundUserDefinedConversion(tree, argument, inOutConversionFlags, originalArgumentType).MakeCompilerGenerated()
Return New BoundConversion(tree, argument, convKind.Key, CheckOverflow, isExplicit, DirectCast(Nothing, ConstantValue), targetType)
End Function
''' <summary>
''' Handle expression reclassification, if any applicable.
'''
''' If function returns True, the "argument" parameter has been replaced
''' with result of reclassification (possibly an error node) and appropriate
''' diagnostic, if any, has been reported.
'''
''' If function returns false, the "argument" parameter must be unchanged and no
''' diagnostic should be reported.
'''
''' conversionSemantics can be one of these:
''' SyntaxKind.CTypeKeyword, SyntaxKind.DirectCastKeyword, SyntaxKind.TryCastKeyword
''' </summary>
Private Function ReclassifyExpression(
ByRef argument As BoundExpression,
conversionSemantics As SyntaxKind,
tree As VisualBasicSyntaxNode,
convKind As ConversionKind,
isExplicit As Boolean,
targetType As TypeSymbol,
diagnostics As DiagnosticBag
) As Boolean
Debug.Assert(argument.Kind <> BoundKind.GroupTypeInferenceLambda)
Select Case argument.Kind
Case BoundKind.Parenthesized
If argument.Type Is Nothing AndAlso Not argument.IsNothingLiteral() Then
Dim parenthesized = DirectCast(argument, BoundParenthesized)
Dim enclosed As BoundExpression = parenthesized.Expression
' Reclassify enclosed expression.
If ReclassifyExpression(enclosed, conversionSemantics, enclosed.Syntax, convKind, isExplicit, targetType, diagnostics) Then
argument = parenthesized.Update(enclosed, enclosed.Type)
If conversionSemantics = SyntaxKind.CTypeKeyword Then
argument = ApplyConversion(tree, targetType, argument, isExplicit, diagnostics)
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
argument = ApplyDirectCastConversion(tree, argument, targetType, diagnostics)
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
argument = ApplyTryCastConversion(tree, argument, targetType, diagnostics)
Else
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End If
Return True
End If
End If
Case BoundKind.UnboundLambda
argument = ReclassifyUnboundLambdaExpression(DirectCast(argument, UnboundLambda), conversionSemantics, tree,
convKind, isExplicit, targetType, diagnostics)
Return True
Case BoundKind.QueryLambda
argument = ReclassifyQueryLambdaExpression(DirectCast(argument, BoundQueryLambda), conversionSemantics, tree,
convKind, isExplicit, targetType, diagnostics)
Return True
Case BoundKind.LateAddressOfOperator
Dim addressOfExpression = DirectCast(argument, BoundLateAddressOfOperator)
If targetType.TypeKind <> TypeKind.Delegate AndAlso targetType.TypeKind <> TypeKind.Error Then
' 'AddressOf' expression cannot be converted to '{0}' because '{0}' is not a delegate type.
ReportDiagnostic(diagnostics, addressOfExpression.Syntax, ERRID.ERR_AddressOfNotDelegate1, targetType)
End If
argument = addressOfExpression.Update(addressOfExpression.Binder, addressOfExpression.MemberAccess, targetType)
Return True
Case BoundKind.AddressOfOperator
Dim delegateResolutionResult As DelegateResolutionResult = Nothing
Dim addressOfExpression = DirectCast(argument, BoundAddressOfOperator)
If addressOfExpression.GetDelegateResolutionResult(targetType, delegateResolutionResult) Then
diagnostics.AddRange(delegateResolutionResult.Diagnostics)
Dim hasErrors = True
If Conversions.ConversionExists(delegateResolutionResult.DelegateConversions) Then
Dim reclassifyBinder As Binder
' If conversion is explicit, use Option Strict Off.
If isExplicit AndAlso Me.OptionStrict <> VisualBasic.OptionStrict.Off Then
reclassifyBinder = New OptionStrictOffBinder(Me)
Else
reclassifyBinder = Me
End If
Debug.Assert(Not isExplicit OrElse reclassifyBinder.OptionStrict = VisualBasic.OptionStrict.Off)
argument = reclassifyBinder.ReclassifyAddressOf(addressOfExpression, delegateResolutionResult, targetType, diagnostics, isForHandles:=False,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation:=Not isExplicit AndAlso tree.Kind <> SyntaxKind.ObjectCreationExpression)
hasErrors = argument.HasErrors
Debug.Assert(convKind = delegateResolutionResult.DelegateConversions)
End If
If argument.Kind <> BoundKind.DelegateCreationExpression Then
If conversionSemantics = SyntaxKind.CTypeKeyword Then
argument = New BoundConversion(tree, argument, convKind, False, isExplicit, targetType, hasErrors:=hasErrors)
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
argument = New BoundDirectCast(tree, argument, convKind, targetType, hasErrors:=hasErrors)
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
argument = New BoundTryCast(tree, argument, convKind, targetType, hasErrors:=hasErrors)
Else
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End If
End If
Return True
End If
Case BoundKind.ArrayLiteral
argument = ReclassifyArrayLiteralExpression(conversionSemantics, tree, convKind, isExplicit, DirectCast(argument, BoundArrayLiteral), targetType, diagnostics)
Return True
Case BoundKind.InterpolatedStringExpression
argument = ReclassifyInterpolatedStringExpression(conversionSemantics, tree, convKind, isExplicit, DirectCast(argument, BoundInterpolatedStringExpression), targetType, diagnostics)
Return argument.Kind = BoundKind.Conversion
End Select
Return False
End Function
Private Function ReclassifyUnboundLambdaExpression(
unboundLambda As UnboundLambda,
conversionSemantics As SyntaxKind,
tree As VisualBasicSyntaxNode,
convKind As ConversionKind,
isExplicit As Boolean,
targetType As TypeSymbol,
diagnostics As DiagnosticBag
) As BoundExpression
Dim targetDelegateType As NamedTypeSymbol ' the target delegate type; if targetType is Expression(Of D), then this is D, otherwise targetType or Nothing.
Dim delegateInvoke As MethodSymbol
If targetType.IsStrictSupertypeOfConcreteDelegate() Then ' covers Object, System.Delegate, System.MulticastDelegate
' Reclassify the lambda as an instance of an Anonymous Delegate.
Dim anonymousDelegate As BoundExpression = ReclassifyUnboundLambdaExpression(unboundLambda, diagnostics)
#If DEBUG Then
Dim anonymousDelegateInfo As KeyValuePair(Of NamedTypeSymbol, ImmutableArray(Of Diagnostic)) = unboundLambda.InferredAnonymousDelegate
Debug.Assert(anonymousDelegate.Type Is anonymousDelegateInfo.Key)
' If we have errors for the inference, we know that there is no conversion.
If Not anonymousDelegateInfo.Value.IsDefault AndAlso anonymousDelegateInfo.Value.HasAnyErrors() Then
Debug.Assert(Conversions.NoConversion(convKind) AndAlso (convKind And ConversionKind.DelegateRelaxationLevelMask) = 0)
Else
Debug.Assert(Conversions.NoConversion(convKind) OrElse
(convKind And ConversionKind.DelegateRelaxationLevelMask) >= ConversionKind.DelegateRelaxationLevelWideningToNonLambda)
End If
#End If
' Now convert it to the target type.
If conversionSemantics = SyntaxKind.CTypeKeyword Then
Return ApplyConversion(tree, targetType, anonymousDelegate, isExplicit, diagnostics)
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
Return ApplyDirectCastConversion(tree, anonymousDelegate, targetType, diagnostics)
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
Return ApplyTryCastConversion(tree, anonymousDelegate, targetType, diagnostics)
Else
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End If
Else
targetDelegateType = targetType.DelegateOrExpressionDelegate(Me)
If targetDelegateType Is Nothing Then
Debug.Assert((convKind And ConversionKind.DelegateRelaxationLevelMask) = 0)
ReportDiagnostic(diagnostics, unboundLambda.Syntax, ERRID.ERR_LambdaNotDelegate1, targetType)
delegateInvoke = Nothing ' No conversion
Else
delegateInvoke = targetDelegateType.DelegateInvokeMethod
If delegateInvoke Is Nothing Then
ReportDiagnostic(diagnostics, unboundLambda.Syntax, ERRID.ERR_LambdaNotDelegate1, targetDelegateType)
delegateInvoke = Nothing ' No conversion
ElseIf ReportDelegateInvokeUseSiteError(diagnostics, unboundLambda.Syntax, targetDelegateType, delegateInvoke) Then
delegateInvoke = Nothing ' No conversion
ElseIf unboundLambda.IsInferredDelegateForThisLambda(delegateInvoke.ContainingType) Then
Dim inferenceDiagnostics As ImmutableArray(Of Diagnostic) = unboundLambda.InferredAnonymousDelegate.Value
If Not inferenceDiagnostics.IsEmpty Then
diagnostics.AddRange(inferenceDiagnostics)
If inferenceDiagnostics.HasAnyErrors() Then
delegateInvoke = Nothing ' No conversion
End If
End If
End If
Debug.Assert(delegateInvoke IsNot Nothing OrElse (convKind And ConversionKind.DelegateRelaxationLevelMask) = 0)
End If
End If
Dim boundLambda As BoundLambda = Nothing
If delegateInvoke IsNot Nothing Then
boundLambda = unboundLambda.GetBoundLambda(New UnboundLambda.TargetSignature(delegateInvoke))
Debug.Assert(boundLambda IsNot Nothing)
If boundLambda Is Nothing Then
' An unlikely case.
Debug.Assert((convKind And ConversionKind.DelegateRelaxationLevelMask) = 0)
ReportDiagnostic(diagnostics,
unboundLambda.Syntax,
If(unboundLambda.IsFunctionLambda, ERRID.ERR_LambdaBindingMismatch1, ERRID.ERR_LambdaBindingMismatch2),
If(targetDelegateType.TypeKind = TypeKind.Delegate AndAlso targetDelegateType.IsFromCompilation(Me.Compilation),
CType(CustomSymbolDisplayFormatter.DelegateSignature(targetDelegateType), Object),
CType(targetDelegateType, Object)))
End If
End If
If boundLambda Is Nothing Then
Debug.Assert(Conversions.NoConversion(convKind))
Dim errorRecovery As BoundLambda = unboundLambda.BindForErrorRecovery()
If conversionSemantics = SyntaxKind.CTypeKeyword Then
Return New BoundConversion(tree, errorRecovery, convKind, False, isExplicit, targetType, hasErrors:=True)
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
Return New BoundDirectCast(tree, errorRecovery, convKind, targetType, hasErrors:=True)
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
Return New BoundTryCast(tree, errorRecovery, convKind, targetType, hasErrors:=True)
Else
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End If
End If
Dim boundLambdaDiagnostics = boundLambda.Diagnostics
Debug.Assert((convKind And ConversionKind.DelegateRelaxationLevelMask) >= boundLambda.DelegateRelaxation)
Debug.Assert(Conversions.ClassifyMethodConversionForLambdaOrAnonymousDelegate(delegateInvoke, boundLambda.LambdaSymbol, Nothing) = MethodConversionKind.Identity OrElse
((convKind And ConversionKind.DelegateRelaxationLevelMask) <> ConversionKind.DelegateRelaxationLevelNone AndAlso
boundLambda.MethodConversionKind <> MethodConversionKind.Identity))
Dim reportedAnError As Boolean = False
If boundLambdaDiagnostics.Any() Then
diagnostics.AddRange(boundLambdaDiagnostics)
reportedAnError = boundLambdaDiagnostics.HasAnyErrors()
End If
Dim relaxationLambdaOpt As BoundLambda = Nothing
If (convKind And ConversionKind.DelegateRelaxationLevelMask) = ConversionKind.DelegateRelaxationLevelInvalid AndAlso
Not reportedAnError AndAlso Not boundLambda.HasErrors Then
' We don't try to infer return type of a lambda that has both Async and Iterator modifiers, let's suppress the
' signature mismatch error in this case.
If unboundLambda.ReturnType IsNot Nothing OrElse unboundLambda.Flags <> (SourceMemberFlags.Async Or SourceMemberFlags.Iterator) Then
Dim err As ERRID
If unboundLambda.IsFunctionLambda Then
err = ERRID.ERR_LambdaBindingMismatch1
Else
err = ERRID.ERR_LambdaBindingMismatch2
End If
ReportDiagnostic(diagnostics,
unboundLambda.Syntax,
err,
If(targetDelegateType.TypeKind = TypeKind.Delegate AndAlso targetDelegateType.IsFromCompilation(Me.Compilation),
CType(CustomSymbolDisplayFormatter.DelegateSignature(targetDelegateType), Object),
CType(targetDelegateType, Object)))
End If
ElseIf Conversions.IsStubRequiredForMethodConversion(boundLambda.MethodConversionKind) Then
Debug.Assert(Conversions.IsDelegateRelaxationSupportedFor(boundLambda.MethodConversionKind))
' Need to produce a stub.
' First, we need to get an Anonymous Delegate of the same shape as the lambdaSymbol.
Dim lambdaSymbol As LambdaSymbol = boundLambda.LambdaSymbol
Dim anonymousDelegateType As NamedTypeSymbol = ConstructAnonymousDelegateSymbol(unboundLambda,
(lambdaSymbol.Parameters.As(Of BoundLambdaParameterSymbol)),
lambdaSymbol.ReturnType,
diagnostics)
' Second, reclassify the bound lambda as an instance of the Anonymous Delegate.
Dim anonymousDelegateInstance = New BoundConversion(tree, boundLambda, ConversionKind.Widening Or ConversionKind.Lambda,
False, False, anonymousDelegateType)
anonymousDelegateInstance.SetWasCompilerGenerated()
' Third, create a method group representing Invoke method of the instance of the Anonymous Delegate.
Dim methodGroup = New BoundMethodGroup(unboundLambda.Syntax,
Nothing,
ImmutableArray.Create(anonymousDelegateType.DelegateInvokeMethod),
LookupResultKind.Good,
anonymousDelegateInstance,
QualificationKind.QualifiedViaValue)
methodGroup.SetWasCompilerGenerated()
' Fourth, create a lambda with the shape of the target delegate that calls the Invoke with appropriate conversions
' and drops parameters and/or return value, if needed, thus performing the relaxation.
Dim relaxationBinder As Binder
' If conversion is explicit, use Option Strict Off.
If isExplicit AndAlso Me.OptionStrict <> VisualBasic.OptionStrict.Off Then
relaxationBinder = New OptionStrictOffBinder(Me)
Else
relaxationBinder = Me
End If
Debug.Assert(Not isExplicit OrElse relaxationBinder.OptionStrict = VisualBasic.OptionStrict.Off)
relaxationLambdaOpt = relaxationBinder.BuildDelegateRelaxationLambda(unboundLambda.Syntax,
delegateInvoke,
methodGroup,
boundLambda.DelegateRelaxation,
isZeroArgumentKnownToBeUsed:=False,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation:=Not isExplicit AndAlso tree.Kind <> SyntaxKind.ObjectCreationExpression,
diagnostics:=diagnostics)
End If
If conversionSemantics = SyntaxKind.CTypeKeyword Then
Return New BoundConversion(tree, boundLambda, convKind, False, isExplicit, relaxationLambdaOpt, targetType)
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
Return New BoundDirectCast(tree, boundLambda, convKind, relaxationLambdaOpt, targetType)
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
Return New BoundTryCast(tree, boundLambda, convKind, relaxationLambdaOpt, targetType)
Else
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End If
End Function
Private Function ReclassifyQueryLambdaExpression(
lambda As BoundQueryLambda,
conversionSemantics As SyntaxKind,
tree As VisualBasicSyntaxNode,
convKind As ConversionKind,
isExplicit As Boolean,
targetType As TypeSymbol,
diagnostics As DiagnosticBag
) As BoundExpression
Debug.Assert(lambda.Type Is Nothing)
' the target delegate type; if targetType is Expression(Of D), then this is D, otherwise targetType or Nothing.
Dim targetDelegateType As NamedTypeSymbol = targetType.DelegateOrExpressionDelegate(Me)
If Conversions.NoConversion(convKind) Then
If targetType.IsStrictSupertypeOfConcreteDelegate() AndAlso Not targetType.IsObjectType() Then
ReportDiagnostic(diagnostics, lambda.Syntax, ERRID.ERR_LambdaNotCreatableDelegate1, targetType)
Else
If targetDelegateType Is Nothing Then
ReportDiagnostic(diagnostics, lambda.Syntax, ERRID.ERR_LambdaNotDelegate1, targetType)
Else
Dim invoke As MethodSymbol = targetDelegateType.DelegateInvokeMethod
If invoke Is Nothing Then
ReportDiagnostic(diagnostics, lambda.Syntax, ERRID.ERR_LambdaNotDelegate1, targetDelegateType)
ElseIf Not ReportDelegateInvokeUseSiteError(diagnostics, lambda.Syntax, targetDelegateType, invoke) Then
' Conversion could fail because we couldn't convert body of the lambda
' to the target delegate type. We want to report that error instead of
' lambda signature mismatch.
If lambda.LambdaSymbol.ReturnType Is LambdaSymbol.ReturnTypePendingDelegate AndAlso
Not invoke.IsSub AndAlso
Conversions.FailedDueToQueryLambdaBodyMismatch(convKind) Then
lambda = lambda.Update(lambda.LambdaSymbol, lambda.RangeVariables,
ApplyImplicitConversion(lambda.Expression.Syntax,
invoke.ReturnType,
lambda.Expression,
diagnostics,
If(invoke.ReturnType.IsBooleanType,
lambda.ExprIsOperandOfConditionalBranch,
False)),
exprIsOperandOfConditionalBranch:=False)
Else
ReportDiagnostic(diagnostics, lambda.Syntax, ERRID.ERR_LambdaBindingMismatch1, targetDelegateType)
End If
End If
End If
End If
If conversionSemantics = SyntaxKind.CTypeKeyword Then
Return New BoundConversion(tree, lambda, convKind, False, isExplicit, targetType, hasErrors:=True).MakeCompilerGenerated()
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
Return New BoundDirectCast(tree, lambda, convKind, targetType, hasErrors:=True).MakeCompilerGenerated()
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
Return New BoundTryCast(tree, lambda, convKind, targetType, hasErrors:=True).MakeCompilerGenerated()
End If
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End If
Dim delegateInvoke As MethodSymbol = targetDelegateType.DelegateInvokeMethod
For Each delegateParam As ParameterSymbol In delegateInvoke.Parameters
If delegateParam.IsByRef OrElse delegateParam.OriginalDefinition.Type.IsTypeParameter() Then
Dim restrictedType As TypeSymbol = Nothing
If delegateParam.Type.IsRestrictedTypeOrArrayType(restrictedType) Then
ReportDiagnostic(diagnostics, lambda.LambdaSymbol.Parameters(delegateParam.Ordinal).Locations(0),
ERRID.ERR_RestrictedType1, restrictedType)
End If
End If
Next
Dim delegateReturnType As TypeSymbol = delegateInvoke.ReturnType
If delegateInvoke.OriginalDefinition.ReturnType.IsTypeParameter() Then
Dim restrictedType As TypeSymbol = Nothing
If delegateReturnType.IsRestrictedTypeOrArrayType(restrictedType) Then
Dim location As VisualBasicSyntaxNode
If lambda.Expression.Kind = BoundKind.RangeVariableAssignment Then
location = DirectCast(lambda.Expression, BoundRangeVariableAssignment).Value.Syntax
Else
location = lambda.Expression.Syntax
End If
ReportDiagnostic(diagnostics, location, ERRID.ERR_RestrictedType1, restrictedType)
End If
End If
If lambda.LambdaSymbol.ReturnType Is LambdaSymbol.ReturnTypePendingDelegate Then
lambda = lambda.Update(lambda.LambdaSymbol, lambda.RangeVariables,
ApplyImplicitConversion(lambda.Expression.Syntax, delegateReturnType, lambda.Expression,
diagnostics,
If(delegateReturnType.IsBooleanType(), lambda.ExprIsOperandOfConditionalBranch, False)),
exprIsOperandOfConditionalBranch:=False)
Else
lambda = lambda.Update(lambda.LambdaSymbol, lambda.RangeVariables,
lambda.Expression, exprIsOperandOfConditionalBranch:=False)
End If
If conversionSemantics = SyntaxKind.CTypeKeyword Then
Return New BoundConversion(tree, lambda, convKind, False, isExplicit, targetType).MakeCompilerGenerated()
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
Return New BoundDirectCast(tree, lambda, convKind, targetType).MakeCompilerGenerated()
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
Return New BoundTryCast(tree, lambda, convKind, targetType).MakeCompilerGenerated()
End If
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End Function
Private Function ReclassifyInterpolatedStringExpression(conversionSemantics As SyntaxKind, tree As VisualBasicSyntaxNode, convKind As ConversionKind, isExplicit As Boolean, node As BoundInterpolatedStringExpression, targetType As TypeSymbol, diagnostics As DiagnosticBag) As BoundExpression
If convKind = ConversionKind.InterpolatedString Then
Debug.Assert(targetType.Equals(Compilation.GetWellKnownType(WellKnownType.System_IFormattable)) OrElse targetType.Equals(Compilation.GetWellKnownType(WellKnownType.System_FormattableString)))
Return New BoundConversion(tree, node, ConversionKind.InterpolatedString, False, isExplicit, targetType)
End If
Return node
End Function
Private Sub WarnOnNarrowingConversionBetweenSealedClassAndAnInterface(
convKind As ConversionKind,
location As VisualBasicSyntaxNode,
sourceType As TypeSymbol,
targetType As TypeSymbol,
diagnostics As DiagnosticBag
)
If Conversions.IsNarrowingConversion(convKind) Then
Dim interfaceType As TypeSymbol = Nothing
Dim classType As NamedTypeSymbol = Nothing
If sourceType.IsInterfaceType() Then
If targetType.IsClassType() Then
interfaceType = sourceType
classType = DirectCast(targetType, NamedTypeSymbol)
End If
ElseIf sourceType.IsClassType() AndAlso targetType.IsInterfaceType() Then
interfaceType = targetType
classType = DirectCast(sourceType, NamedTypeSymbol)
End If
If classType IsNot Nothing AndAlso
interfaceType IsNot Nothing AndAlso
classType.IsNotInheritable AndAlso
Not classType.IsComImport() AndAlso
Not Conversions.IsWideningConversion(Conversions.ClassifyDirectCastConversion(classType, interfaceType, Nothing)) Then
' Report specific warning if converting IEnumerable(Of XElement) to String.
If (targetType.SpecialType = SpecialType.System_String) AndAlso IsIEnumerableOfXElement(sourceType, Nothing) Then
ReportDiagnostic(diagnostics, location, ERRID.WRN_UseValueForXmlExpression3, sourceType, targetType, sourceType)
Else
ReportDiagnostic(diagnostics, location, ERRID.WRN_InterfaceConversion2, sourceType, targetType)
End If
End If
End If
End Sub
Private Function IsIEnumerableOfXElement(type As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As Boolean
Return type.IsOrImplementsIEnumerableOfXElement(Compilation, useSiteDiagnostics)
End Function
Private Sub ReportNoConversionError(
location As VisualBasicSyntaxNode,
sourceType As TypeSymbol,
targetType As TypeSymbol,
diagnostics As DiagnosticBag,
Optional copybackConversionParamName As String = Nothing
)
If sourceType.IsArrayType() AndAlso targetType.IsArrayType() Then
Dim sourceArray = DirectCast(sourceType, ArrayTypeSymbol)
Dim targetArray = DirectCast(targetType, ArrayTypeSymbol)
Dim sourceElement = sourceArray.ElementType
Dim targetElement = targetArray.ElementType
If sourceArray.Rank <> targetArray.Rank Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_ConvertArrayRankMismatch2, sourceType, targetType)
ElseIf sourceArray.IsSZArray <> targetArray.IsSZArray
ReportDiagnostic(diagnostics, location, ERRID.ERR_TypeMismatch2, sourceType, targetType)
ElseIf Not (sourceElement.IsErrorType() OrElse targetElement.IsErrorType()) Then
Dim elemConv = Conversions.ClassifyDirectCastConversion(sourceElement, targetElement, Nothing)
If Not Conversions.IsIdentityConversion(elemConv) AndAlso
(targetElement.IsObjectType() OrElse targetElement.SpecialType = SpecialType.System_ValueType) AndAlso
Not sourceElement.IsReferenceType() Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_ConvertObjectArrayMismatch3, sourceType, targetType, sourceElement)
ElseIf Not Conversions.IsIdentityConversion(elemConv) AndAlso
Not (Conversions.IsWideningConversion(elemConv) AndAlso
(elemConv And (ConversionKind.Reference Or ConversionKind.Value Or ConversionKind.TypeParameter)) <> 0) Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_ConvertArrayMismatch4, sourceType, targetType, sourceElement, targetElement)
Else
ReportDiagnostic(diagnostics, location, ERRID.ERR_TypeMismatch2, sourceType, targetType)
End If
End If
ElseIf sourceType.IsDateTimeType() AndAlso targetType.IsDoubleType() Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_DateToDoubleConversion)
ElseIf targetType.IsDateTimeType() AndAlso sourceType.IsDoubleType() Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_DoubleToDateConversion)
ElseIf targetType.IsCharType() AndAlso sourceType.IsIntegralType() Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_IntegralToCharTypeMismatch1, sourceType)
ElseIf sourceType.IsCharType() AndAlso targetType.IsIntegralType() Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_CharToIntegralTypeMismatch1, targetType)
ElseIf copybackConversionParamName IsNot Nothing Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_CopyBackTypeMismatch3,
copybackConversionParamName, sourceType, targetType)
ElseIf sourceType.IsInterfaceType() AndAlso targetType.IsValueType() AndAlso IsIEnumerableOfXElement(sourceType, Nothing) Then
ReportDiagnostic(diagnostics, location, ERRID.ERR_TypeMismatchForXml3, sourceType, targetType, sourceType)
Else
ReportDiagnostic(diagnostics, location, ERRID.ERR_TypeMismatch2, sourceType, targetType)
End If
End Sub
End Class
End Namespace
|
MatthieuMEZIL/roslyn
|
src/Compilers/VisualBasic/Portable/Binding/Binder_Conversions.vb
|
Visual Basic
|
apache-2.0
| 96,308
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
'-----------------------------------------------------------------------------------------------------------
'Reads the tree from an XML file into a ParseTree object and sub-objects. Reports many kinds of errors
'during the reading process.
'-----------------------------------------------------------------------------------------------------------
Imports System.IO
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports System.Xml
Imports System.Xml.Schema
Imports <xmlns="http://schemas.microsoft.com/VisualStudio/Roslyn/Compiler">
Public Module ReadTree
Private s_currentFile As String
' Read an XML file and return the resulting ParseTree object.
Public Function TryReadTheTree(fileName As String, <Out> ByRef tree As ParseTree) As Boolean
tree = Nothing
Console.WriteLine("Reading input file ""{0}""...", fileName)
Dim validationError As Boolean = False
Dim xDoc = GetXDocument(fileName, validationError)
If validationError Then
Return False
End If
tree = New ParseTree
Dim x = xDoc.<define-parse-tree>
tree.FileName = fileName
tree.NamespaceName = xDoc.<define-parse-tree>.@namespace
tree.VisitorName = xDoc.<define-parse-tree>.@visitor
tree.RewriteVisitorName = xDoc.<define-parse-tree>.@<rewrite-visitor>
tree.FactoryClassName = xDoc.<define-parse-tree>.@<factory-class>
tree.ContextualFactoryClassName = xDoc.<define-parse-tree>.@<contextual-factory-class>
Dim defs = xDoc.<define-parse-tree>.<definitions>
For Each struct In defs.<node-structure>
If tree.NodeStructures.ContainsKey(struct.@name) Then
tree.ReportError(struct, "node-structure with name ""{0}"" already defined", struct.@name)
Else
tree.NodeStructures.Add(struct.@name, New ParseNodeStructure(struct, tree))
End If
Next
For Each al In defs.<node-kind-alias>
If tree.Aliases.ContainsKey(al.@name) Then
tree.ReportError(al, "node-kind-alias with name ""{0}"" already defined", al.@name)
Else
tree.Aliases.Add(al.@name, New ParseNodeKindAlias(al, tree))
End If
Next
For Each en In defs.<enumeration>
If tree.Enumerations.ContainsKey(en.@name) Then
tree.ReportError(en, "enumeration with name ""{0}"" already defined", en.@name)
Else
tree.Enumerations.Add(en.@name, New ParseEnumeration(en, tree))
End If
Next
tree.FinishedReading()
Return True
End Function
' Open the input XML file as an XDocument, using the reading options that we want.
' We use a schema to validate the input.
Private Function GetXDocument(fileName As String, <Out> ByRef validationError As Boolean) As XDocument
s_currentFile = fileName
Dim hadError = False
Dim onValidationError =
Sub(sender As Object, e As ValidationEventArgs)
' A validation error occurred while reading the document. Tell the user.
Console.Error.WriteLine("{0}({1},{2}): Invalid input: {3}", s_currentFile, e.Exception.LineNumber, e.Exception.LinePosition, e.Exception.Message)
hadError = True
End Sub
Dim xDoc As XDocument
Using schemaReader = XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream("VBSyntaxModelSchema.xsd"))
Dim readerSettings As New XmlReaderSettings()
readerSettings.DtdProcessing = DtdProcessing.Prohibit
readerSettings.XmlResolver = Nothing
readerSettings.Schemas.Add(Nothing, schemaReader)
readerSettings.ValidationType = ValidationType.Schema
AddHandler readerSettings.ValidationEventHandler, onValidationError
Dim fileStream As New FileStream(fileName, FileMode.Open, FileAccess.Read)
Using reader = XmlReader.Create(fileStream, readerSettings)
xDoc = XDocument.Load(reader, LoadOptions.SetLineInfo Or LoadOptions.PreserveWhitespace)
End Using
End Using
validationError = hadError
Return xDoc
End Function
End Module
|
droyad/roslyn
|
src/Tools/Source/CompilerGeneratorTools/Source/VisualBasicSyntaxGenerator/XML/ReadTree.vb
|
Visual Basic
|
apache-2.0
| 4,474
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Globalization
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CaseCorrection
Friend Partial Class VisualBasicCaseCorrectionService
Private Class Rewriter
Inherits VisualBasicSyntaxRewriter
Private ReadOnly _createAliasSet As Func(Of ImmutableHashSet(Of String)) =
Function()
Dim model = DirectCast(Me._semanticModel.GetOriginalSemanticModel(), SemanticModel)
' root should be already available
If Not model.SyntaxTree.HasCompilationUnitRoot Then
Return ImmutableHashSet.Create(Of String)()
End If
Dim root = model.SyntaxTree.GetCompilationUnitRoot()
Dim [set] = ImmutableHashSet.CreateBuilder(Of String)(StringComparer.OrdinalIgnoreCase)
For Each importsClause In root.GetAliasImportsClauses()
If Not String.IsNullOrWhiteSpace(importsClause.Alias.Identifier.ValueText) Then
[set].Add(importsClause.Alias.Identifier.ValueText)
End If
Next
For Each import In model.Compilation.AliasImports
[set].Add(import.Name)
Next
Return [set].ToImmutable()
End Function
Private ReadOnly _syntaxFactsService As ISyntaxFactsService
Private ReadOnly _semanticModel As SemanticModel
Private ReadOnly _aliasSet As Lazy(Of ImmutableHashSet(Of String))
Private ReadOnly _cancellationToken As CancellationToken
Public Sub New(syntaxFactsService As ISyntaxFactsService, semanticModel As SemanticModel, cancellationToken As CancellationToken)
MyBase.New(visitIntoStructuredTrivia:=True)
Me._syntaxFactsService = syntaxFactsService
Me._semanticModel = semanticModel
Me._aliasSet = New Lazy(Of ImmutableHashSet(Of String))(_createAliasSet)
Me._cancellationToken = cancellationToken
End Sub
Public Overrides Function VisitToken(token As SyntaxToken) As SyntaxToken
Dim newToken = MyBase.VisitToken(token)
If _syntaxFactsService.IsIdentifier(newToken) Then
Return VisitIdentifier(token, newToken)
ElseIf _syntaxFactsService.IsKeyword(newToken) OrElse _syntaxFactsService.IsContextualKeyword(newToken) Then
Return VisitKeyword(newToken)
ElseIf token.IsNumericLiteral() Then
Return VisitNumericLiteral(newToken)
ElseIf token.IsCharacterLiteral() Then
Return VisitCharacterLiteral(newToken)
End If
Return newToken
End Function
Private Function VisitIdentifier(token As SyntaxToken, newToken As SyntaxToken) As SyntaxToken
If newToken.IsMissing OrElse TypeOf newToken.Parent Is ArgumentSyntax OrElse _semanticModel Is Nothing Then
Return newToken
End If
If token.Parent.IsPartOfStructuredTrivia() Then
Dim identifierSyntax = TryCast(token.Parent, IdentifierNameSyntax)
If identifierSyntax IsNot Nothing Then
Dim preprocessingSymbolInfo = _semanticModel.GetPreprocessingSymbolInfo(identifierSyntax)
If preprocessingSymbolInfo.Symbol IsNot Nothing Then
Dim name = preprocessingSymbolInfo.Symbol.Name
If Not String.IsNullOrEmpty(name) AndAlso name <> token.ValueText Then
' Name should differ only in case
Contract.Requires(name.Equals(token.ValueText, StringComparison.OrdinalIgnoreCase))
Return GetIdentifierWithCorrectedName(name, newToken)
End If
End If
End If
Return newToken
Else
Dim methodDeclaration = TryCast(token.Parent, MethodStatementSyntax)
If methodDeclaration IsNot Nothing Then
' If this is a partial method implementation part, then case correct the method name to match the partial method definition part.
Dim definitionPart As IMethodSymbol = Nothing
Dim otherPartOfPartial = GetOtherPartOfPartialMethod(methodDeclaration, definitionPart)
If otherPartOfPartial IsNot Nothing And otherPartOfPartial Is definitionPart Then
Return CaseCorrectIdentifierIfNamesDiffer(token, newToken, otherPartOfPartial)
End If
Else
Dim parameterSyntax = token.GetAncestor(Of ParameterSyntax)()
If parameterSyntax IsNot Nothing Then
' If this is a parameter declaration for a partial method implementation part,
' then case correct the parameter name to match the corresponding parameter in the partial method definition part.
methodDeclaration = parameterSyntax.GetAncestor(Of MethodStatementSyntax)()
If methodDeclaration IsNot Nothing Then
Dim definitionPart As IMethodSymbol = Nothing
Dim otherPartOfPartial = GetOtherPartOfPartialMethod(methodDeclaration, definitionPart)
If otherPartOfPartial IsNot Nothing And otherPartOfPartial Is definitionPart Then
Dim ordinal As Integer = 0
For Each param As SyntaxNode In methodDeclaration.ParameterList.Parameters
If param Is parameterSyntax Then
Exit For
End If
ordinal = ordinal + 1
Next
Contract.Requires(otherPartOfPartial.Parameters.Length > ordinal)
Dim otherPartParam = otherPartOfPartial.Parameters(ordinal)
' We don't want to rename the parameter if names are not equal ignoring case.
' Compiler will anyways generate an error for this case.
Return CaseCorrectIdentifierIfNamesDiffer(token, newToken, otherPartParam, namesMustBeEqualIgnoringCase:=True)
End If
End If
End If
End If
End If
Dim symbol = GetAliasOrAnySymbol(_semanticModel, token.Parent, _cancellationToken)
If symbol Is Nothing Then
Return newToken
End If
Dim expression = TryCast(token.Parent, ExpressionSyntax)
If expression IsNot Nothing AndAlso SyntaxFacts.IsInNamespaceOrTypeContext(expression) AndAlso Not IsNamespaceOrTypeRelatedSymbol(symbol) Then
Return newToken
End If
If TypeOf symbol Is ITypeSymbol AndAlso DirectCast(symbol, ITypeSymbol).TypeKind = TypeKind.Error Then
Return newToken
End If
' If it's a constructor we bind to, then we want to compare the name on the token to the
' name of the type. The name of the bound symbol will be something useless like '.ctor'.
' However, if it's an explicit New on the right side of a member access or qualified name, we want to use "New".
If symbol.IsConstructor Then
If token.IsNewOnRightSideOfDotOrBang() Then
Return SyntaxFactory.Identifier(newToken.LeadingTrivia, "New", newToken.TrailingTrivia)
End If
symbol = symbol.ContainingType
End If
Return CaseCorrectIdentifierIfNamesDiffer(token, newToken, symbol)
End Function
Private Shared Function IsNamespaceOrTypeRelatedSymbol(symbol As ISymbol) As Boolean
Return TypeOf symbol Is INamespaceOrTypeSymbol OrElse
(TypeOf symbol Is IAliasSymbol AndAlso TypeOf DirectCast(symbol, IAliasSymbol).Target Is INamespaceOrTypeSymbol) OrElse
(symbol.IsKind(SymbolKind.Method) AndAlso DirectCast(symbol, IMethodSymbol).MethodKind = MethodKind.Constructor)
End Function
Private Function GetAliasOrAnySymbol(model As SemanticModel, node As SyntaxNode, cancellationToken As CancellationToken) As ISymbol
Dim identifier = TryCast(node, IdentifierNameSyntax)
If identifier IsNot Nothing AndAlso Me._aliasSet.Value.Contains(identifier.Identifier.ValueText) Then
Dim [alias] = model.GetAliasInfo(identifier, cancellationToken)
If [alias] IsNot Nothing Then
Return [alias]
End If
End If
Return model.GetSymbolInfo(node, cancellationToken).GetAnySymbol()
End Function
Private Shared Function CaseCorrectIdentifierIfNamesDiffer(
token As SyntaxToken,
newToken As SyntaxToken,
symbol As ISymbol,
Optional namesMustBeEqualIgnoringCase As Boolean = False
) As SyntaxToken
If NamesDiffer(symbol, token) Then
If namesMustBeEqualIgnoringCase AndAlso Not String.Equals(symbol.Name, token.ValueText, StringComparison.OrdinalIgnoreCase) Then
Return newToken
End If
Dim correctedName = GetCorrectedName(token, symbol)
Return GetIdentifierWithCorrectedName(correctedName, newToken)
End If
Return newToken
End Function
Private Function GetOtherPartOfPartialMethod(methodDeclaration As MethodStatementSyntax, <Out> ByRef definitionPart As IMethodSymbol) As IMethodSymbol
Contract.ThrowIfNull(methodDeclaration)
Contract.ThrowIfNull(_semanticModel)
Dim methodSymbol = _semanticModel.GetDeclaredSymbol(methodDeclaration, _cancellationToken)
If methodSymbol IsNot Nothing Then
definitionPart = If(methodSymbol.PartialDefinitionPart, methodSymbol)
Return If(methodSymbol.PartialDefinitionPart, methodSymbol.PartialImplementationPart)
End If
Return Nothing
End Function
Private Shared Function GetCorrectedName(token As SyntaxToken, symbol As ISymbol) As String
If symbol.IsAttribute Then
If String.Equals(token.ValueText & s_attributeSuffix, symbol.Name, StringComparison.OrdinalIgnoreCase) Then
Return symbol.Name.Substring(0, symbol.Name.Length - s_attributeSuffix.Length)
End If
End If
Return symbol.Name
End Function
Private Shared Function GetIdentifierWithCorrectedName(correctedName As String, token As SyntaxToken) As SyntaxToken
If token.IsBracketed Then
Return SyntaxFactory.BracketedIdentifier(token.LeadingTrivia, correctedName, token.TrailingTrivia)
Else
Return SyntaxFactory.Identifier(token.LeadingTrivia, correctedName, token.TrailingTrivia)
End If
End Function
Private Shared Function NamesDiffer(symbol As ISymbol,
token As SyntaxToken) As Boolean
If String.IsNullOrEmpty(symbol.Name) Then
Return False
End If
If symbol.Name = token.ValueText Then
Return False
End If
If symbol.IsAttribute() Then
If symbol.Name = token.ValueText & s_attributeSuffix Then
Return False
End If
End If
Return True
End Function
Private Function VisitKeyword(token As SyntaxToken) As SyntaxToken
If Not token.IsMissing Then
Dim actualText = token.ToString()
Dim expectedText = _syntaxFactsService.GetText(token.Kind)
If Not String.IsNullOrWhiteSpace(expectedText) AndAlso actualText <> expectedText Then
Return SyntaxFactory.Token(token.LeadingTrivia, token.Kind, token.TrailingTrivia, expectedText)
End If
End If
Return token
End Function
Private Function VisitNumericLiteral(token As SyntaxToken) As SyntaxToken
If Not token.IsMissing Then
' For any numeric literal, we simply case correct any letters to uppercase.
' The only letters allowed in a numeric literal are:
' * Type characters: S, US, I, UI, L, UL, D, F, R
' * Hex/Octal literals: H, O and A, B, C, D, E, F
' * Exponent: E
' * Time literals: AM, PM
Dim actualText = token.ToString()
Dim expectedText = actualText.ToUpperInvariant()
If actualText <> expectedText Then
Return SyntaxFactory.ParseToken(expectedText).WithLeadingTrivia(token.LeadingTrivia).WithTrailingTrivia(token.TrailingTrivia)
End If
End If
Return token
End Function
Private Function VisitCharacterLiteral(token As SyntaxToken) As SyntaxToken
If Not token.IsMissing Then
' For character literals, we case correct the type character to "c".
Dim actualText = token.ToString()
If actualText.EndsWith("C", StringComparison.Ordinal) Then
Dim expectedText = actualText.Substring(0, actualText.Length - 1) & "c"
Return SyntaxFactory.ParseToken(expectedText).WithLeadingTrivia(token.LeadingTrivia).WithTrailingTrivia(token.TrailingTrivia)
End If
End If
Return token
End Function
Public Overrides Function VisitTrivia(trivia As SyntaxTrivia) As SyntaxTrivia
trivia = MyBase.VisitTrivia(trivia)
If trivia.Kind = SyntaxKind.CommentTrivia AndAlso trivia.Width >= 3 Then
Dim remText = trivia.ToString().Substring(0, 3)
Dim remKeywordText As String = _syntaxFactsService.GetText(SyntaxKind.REMKeyword)
If remText <> remKeywordText AndAlso SyntaxFacts.GetKeywordKind(remText) = SyntaxKind.REMKeyword Then
Dim expectedText = remKeywordText & trivia.ToString().Substring(3)
Return SyntaxFactory.CommentTrivia(expectedText)
End If
End If
Return trivia
End Function
End Class
End Class
End Namespace
|
mmitche/roslyn
|
src/Workspaces/VisualBasic/Portable/CaseCorrection/VisualBasicCaseCorrectionService.Rewriter.vb
|
Visual Basic
|
apache-2.0
| 16,151
|
Imports System.IO
Imports Aspose.Cells
Namespace Worksheets.Value
Public Class AddingPageBreaks
Public Shared Sub Run()
' ExStart:1
' The path to the documents directory.
Dim dataDir As String = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
' Instantiating a Workbook object
Dim workbook As New Workbook()
' Add a page break at cell Y30
workbook.Worksheets(0).HorizontalPageBreaks.Add("Y30")
workbook.Worksheets(0).VerticalPageBreaks.Add("Y30")
' Save the Excel file.
workbook.Save(dataDir & Convert.ToString("AddingPageBreaks_out.xls"))
' ExEnd:1
End Sub
End Class
End Namespace
|
maria-shahid-aspose/Aspose.Cells-for-.NET
|
Examples/VisualBasic/Worksheets/Value/AddingPageBreaks.vb
|
Visual Basic
|
mit
| 782
|
Imports GemBox.Document
Module Program
Sub Main()
' If using Professional version, put your serial key below.
ComponentInfo.SetLicense("FREE-LIMITED-KEY")
Dim document As DocumentModel = DocumentModel.Load("Print.docx")
' Set Word document's page options.
For Each section As Section In document.Sections
Dim pageSetup As PageSetup = section.PageSetup
pageSetup.Orientation = Orientation.Landscape
pageSetup.LineNumberRestartSetting = LineNumberRestartSetting.NewPage
pageSetup.LineNumberDistanceFromText = 50
Dim pageMargins As PageMargins = pageSetup.PageMargins
pageMargins.Top = 20
pageMargins.Left = 100
Next
' Print Word document to default printer.
Dim printer As String = Nothing
document.Print(printer)
End Sub
End Module
|
gemboxsoftware-dev-team/GemBox.Document.Examples
|
VB.NET/Common Uses/Print/PrintInConsole/Program.vb
|
Visual Basic
|
mit
| 904
|
#Region "License"
' The MIT License (MIT)
'
' Copyright (c) 2017 Richard L King (TradeWright Software Systems)
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
#End Region
Imports ChartSkil27
Imports StudyUtils27
Imports TWUtilities40
Module Globals
#Region "Constants"
Public Const ProjectName As String = "TradeBuildUI"
#End Region
#Region "Enums"
#End Region
#Region "Types"
#End Region
#Region "Global object references"
Friend ChartSkil As New ChartSkilClass
Friend StudyUtils As New StudyUtils
Friend TWUtilities As New TWUtilities
'Friend ContractUtils As New ContractUtils
#End Region
#Region "External function declarations"
#End Region
#Region "Variables"
Private mErrorLogger As Logger = TWUtilities.GetLogger("error")
Private mDiagLogger As FormattingLogger = TWUtilities.CreateFormattingLogger("diag.TradeWright.Trading.UI.Trading", ProjectName)
Private mStartOfDay As Date
#End Region
#Region "mStudyPickerForm Event Handlers"
#End Region
#Region "Properties"
Public ReadOnly Property gDiagLogger() As FormattingLogger
Get
Return mDiagLogger
End Get
End Property
Public ReadOnly Property gErrorLogger() As Logger
Get
Return mErrorLogger
End Get
End Property
Public ReadOnly Property COMStartOfDay As Date
Get
Static sComStartOfDay As Date = Date.FromOADate(0.0)
Return sComStartOfDay
End Get
End Property
Public ReadOnly Property StartOfDay As TimeSpan
Get
Static sStartOfDay As TimeSpan = TimeSpan.Zero
Return sStartOfDay
End Get
End Property
#End Region
#Region "Methods"
Friend Sub NotifyUnhandledError(e As Exception, procName As String, moduleName As String)
TWUtilities.UnhandledErrorHandler.Notify(procName,
moduleName,
"TradingUI",
pErrorNumber:=e.HResult,
pErrorDesc:=e.Message,
pErrorSource:=e.StackTrace)
End Sub
#End Region
#Region "Helper Functions"
#End Region
End Module
|
tradewright/tradebuild-platform.net
|
src/TradingUI/Globals.vb
|
Visual Basic
|
mit
| 3,303
|
Namespace Utilities
Public Class Hex
''' <summary>
''' Returns whether or not the given Input is a hex string.
''' </summary>
''' <param name="Input"></param>
''' <returns></returns>
Public Shared Function IsHex(Input As String) As Boolean
Dim output As Boolean = True
For Each item In Input
Dim upper = item.ToString.ToUpper
If Not (IsNumeric(item) OrElse upper = "A" OrElse upper = "B" OrElse upper = "C" OrElse upper = "D" OrElse upper = "E" OrElse upper = "F") Then
output = False
Exit For
End If
Next
Return output
End Function
End Class
End Namespace
|
evandixon/Sky-Editor
|
Message-FARC Patcher/Utilities/Hex.vb
|
Visual Basic
|
mit
| 778
|
Public Class ParamDepreciacionActivo
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Me.Page.IsPostBack = False Then
Me.RadDatePicker2.SelectedDate = Date.Parse(Session("Fecha"))
End If
End Sub
Protected Sub ImageButton1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click
Dim cadena_java As String
cadena_java = "<script type='text/javascript'> " & _
" window.open('ReporteDepreciacionActivo.aspx?fecha=" + Me.RadDatePicker2.SelectedDate.ToString + "' ); " & _
Chr(60) & "/script>"
ScriptManager.RegisterStartupScript(Page, GetType(Page), "Cerrar", cadena_java.ToString, False)
End Sub
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.WebSite/Contabilidad/Formularios/ParamDepreciacionActivo.aspx.vb
|
Visual Basic
|
mit
| 874
|
#Region "License"
' The MIT License (MIT)
'
' Copyright (c) 2018 Richard L King (TradeWright Software Systems)
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
#End Region
Imports System.Threading.Tasks
Friend NotInheritable Class NewsArticleParser
Inherits ParserBase
Implements IParser
Private Const ModuleName As String = NameOf(NewsArticleParser)
Friend Overrides Async Function ParseAsync(pVersion As Integer, timestamp As Date) As Task(Of Boolean)
Dim requestId = Await _Reader.GetIntAsync("Request id")
Dim type = Await _Reader.GetIntAsync("Article Type")
Dim text = Await _Reader.GetStringAsync("Text")
LogSocketInputMessage(ModuleName, "ParseAsync")
Try
_EventConsumers.NewsConsumer?.NotifyNewsArticle(New NewsArticleEventArgs(timestamp, requestId, type, text))
Return True
Catch e As Exception
Throw New ApiApplicationException("NotifyNewsArticle", e)
End Try
End Function
Friend Overrides ReadOnly Property MessageType As ApiSocketInMsgType
Get
Return ApiSocketInMsgType.NewsArticle
End Get
End Property
End Class
|
tradewright/tradewright-twsapi
|
src/IBApi/Parsers/NewsArticleParser.vb
|
Visual Basic
|
mit
| 2,201
|
Imports Microsoft.Reporting.WinForms
Imports MySql.Data.MySqlClient
Namespace Printing
Public Class ReportDetteClient
Public query As String
Public point_vente As String
Public titre As String
Private Sub ReportEtatStock_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer1.Start()
End Sub
Dim counter As Integer = 0
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If counter = 1 Then
Timer1.Stop()
RefreshReport()
End If
counter += 1
End Sub
Sub RefreshReport()
Try
Dim cmd = Database.GetCommand
Dim ds As New DataSetTables
cmd.CommandText = query
Dim adapter As New MySqlDataAdapter
adapter.SelectCommand = cmd
adapter.Fill(ds.DettesClients)
Report.LocalReport.ReportPath = System.Environment.CurrentDirectory & "\reports\ReportDetteClient.rdlc"
With Report
.ZoomMode = ZoomMode.PageWidth
.ProcessingMode = Microsoft.Reporting.WinForms.ProcessingMode.Local
.LocalReport.DataSources.Clear()
.LocalReport.DataSources.Add(New ReportDataSource("DataSetTables", CType(ds.DettesClients, DataTable)))
.RefreshReport()
End With
'Me.report.RefreshReport()
cmd.Connection.Close()
Catch ex As Exception
If My.Settings.app_debug_mode Then
Util.ShowMessage(ex.ToString, 2)
Else
Util.ShowMessage("Echec de connexion a la base de donnees", 2)
End If
Finally
Database.CloseConnection()
GC.Collect()
End Try
End Sub
End Class
End Namespace
|
lepresk/HG
|
HG/Printing/ReportDetteClient.vb
|
Visual Basic
|
mit
| 1,994
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.34209
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.Bwl.Graphics3D.CatRender.Test.TestForm
End Sub
End Class
End Namespace
|
Lifemotion/Bwl.Graphics3D.CatRender
|
Bwl.Graphics3D.CatRender.Test/My Project/Application.Designer.vb
|
Visual Basic
|
apache-2.0
| 1,536
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.SignatureHelp
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators
Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp
Friend MustInherit Class AbstractIntrinsicOperatorSignatureHelpProvider(Of TSyntaxNode As SyntaxNode)
Inherits AbstractVisualBasicSignatureHelpProvider
Protected MustOverride Function IsTriggerToken(token As SyntaxToken) As Boolean
Protected MustOverride Function IsArgumentListToken(node As TSyntaxNode, token As SyntaxToken) As Boolean
Protected MustOverride Function GetIntrinsicOperatorDocumentationAsync(node As TSyntaxNode, document As Document, cancellationToken As CancellationToken) As ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))
Private Function TryGetSyntaxNode(root As SyntaxNode, position As Integer, syntaxFacts As ISyntaxFactsService, triggerReason As SignatureHelpTriggerReason, cancellationToken As CancellationToken, ByRef node As TSyntaxNode) As Boolean
Return CommonSignatureHelpUtilities.TryGetSyntax(
root,
position,
syntaxFacts,
triggerReason,
AddressOf IsTriggerToken,
AddressOf IsArgumentListToken,
cancellationToken,
node)
End Function
Protected Overrides Async Function GetItemsWorkerAsync(document As Document, position As Integer, triggerInfo As SignatureHelpTriggerInfo, cancellationToken As CancellationToken) As Task(Of SignatureHelpItems)
Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
Dim node As TSyntaxNode = Nothing
If Not TryGetSyntaxNode(root, position, document.GetLanguageService(Of ISyntaxFactsService), triggerInfo.TriggerReason, cancellationToken, node) Then
Return Nothing
End If
Dim items As New List(Of SignatureHelpItem)
Dim semanticModel = Await document.GetSemanticModelForNodeAsync(node, cancellationToken).ConfigureAwait(False)
For Each documentation In Await GetIntrinsicOperatorDocumentationAsync(node, document, cancellationToken).ConfigureAwait(False)
Dim signatureHelpItem = GetSignatureHelpItemForIntrinsicOperator(document, semanticModel, node.SpanStart, documentation, cancellationToken)
items.Add(signatureHelpItem)
Next
Dim textSpan = CommonSignatureHelpUtilities.GetSignatureHelpSpan(node, node.SpanStart, Function(n) n.ChildTokens.FirstOrDefault(Function(c) c.Kind = SyntaxKind.CloseParenToken))
Dim syntaxFacts = document.GetLanguageService(Of ISyntaxFactsService)
Return CreateSignatureHelpItems(
items, textSpan,
GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem:=Nothing)
End Function
Friend Function GetSignatureHelpItemForIntrinsicOperator(document As Document, semanticModel As SemanticModel, position As Integer, documentation As AbstractIntrinsicOperatorDocumentation, cancellationToken As CancellationToken) As SignatureHelpItem
Dim parameters As New List(Of SignatureHelpSymbolParameter)
For i = 0 To documentation.ParameterCount - 1
Dim capturedIndex = i
parameters.Add(
New SignatureHelpSymbolParameter(
name:=documentation.GetParameterName(i),
isOptional:=False,
documentationFactory:=Function(c As CancellationToken) documentation.GetParameterDocumentation(capturedIndex).ToSymbolDisplayParts().ToTaggedText(),
displayParts:=documentation.GetParameterDisplayParts(i)))
Next
Dim suffixParts = documentation.GetSuffix(semanticModel, position, Nothing, cancellationToken)
Dim anonymousTypeDisplayService = document.GetLanguageService(Of IAnonymousTypeDisplayService)()
Return CreateItem(
Nothing, semanticModel, position,
anonymousTypeDisplayService,
isVariadic:=False,
documentationFactory:=Function(c) SpecializedCollections.SingletonEnumerable(New TaggedText(TextTags.Text, documentation.DocumentationText)),
prefixParts:=documentation.PrefixParts,
separatorParts:=GetSeparatorParts(),
suffixParts:=suffixParts,
parameters:=parameters)
End Function
Protected Overridable Function GetCurrentArgumentStateWorker(node As SyntaxNode, position As Integer) As SignatureHelpState
Dim commaTokens As New List(Of SyntaxToken)
commaTokens.AddRange(node.ChildTokens().Where(Function(token) token.Kind = SyntaxKind.CommaToken))
' Also get any leading skipped tokens on the next token after this node
Dim nextToken = node.GetLastToken().GetNextToken()
For Each leadingTrivia In nextToken.LeadingTrivia
If leadingTrivia.Kind = SyntaxKind.SkippedTokensTrivia Then
commaTokens.AddRange(leadingTrivia.GetStructure().ChildTokens().Where(Function(token) token.Kind = SyntaxKind.CommaToken))
End If
Next
' Count how many commas are before us
Return New SignatureHelpState(
argumentIndex:=commaTokens.Where(Function(token) token.SpanStart < position).Count(),
argumentCount:=commaTokens.Count() + 1,
argumentName:=Nothing, argumentNames:=Nothing)
End Function
Public Overrides Function GetCurrentArgumentState(root As SyntaxNode, position As Integer, syntaxFacts As ISyntaxFactsService, currentSpan As TextSpan, cancellationToken As CancellationToken) As SignatureHelpState
Dim node As TSyntaxNode = Nothing
If TryGetSyntaxNode(root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, node) AndAlso
currentSpan.Start = node.SpanStart Then
Return GetCurrentArgumentStateWorker(node, position)
End If
Return Nothing
End Function
End Class
End Namespace
|
reaction1989/roslyn
|
src/Features/VisualBasic/Portable/SignatureHelp/AbstractIntrinsicOperatorSignatureHelpProvider.vb
|
Visual Basic
|
apache-2.0
| 6,671
|
Class MainWindow
End Class
|
soeleman/Program
|
diKoding/XamlMvvmBasic/XamlMvvmBasicVb/MainWindow.xaml.vb
|
Visual Basic
|
apache-2.0
| 31
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:2.0.50727.1433
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings),MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.PHP.Core.CodeDom.Test.My.MySettings
Get
Return Global.PHP.Core.CodeDom.Test.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
DEVSENSE/Phalanger
|
Testing/CodeDOM/CodeDOMTest/My Project/Settings.Designer.vb
|
Visual Basic
|
apache-2.0
| 3,001
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Operations
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Allows asking semantic questions about a tree of syntax nodes in a Compilation. Typically,
''' an instance is obtained by a call to Compilation.GetBinding.
''' </summary>
''' <remarks>
''' <para>An instance of SemanticModel caches local symbols and semantic information. Thus, it
''' is much more efficient to use a single instance of SemanticModel when asking multiple
''' questions about a syntax tree, because information from the first question may be reused.
''' This also means that holding onto an instance of SemanticModel for a long time may keep a
''' significant amount of memory from being garbage collected.
''' </para>
''' <para>
''' When an answer is a named symbol that is reachable by traversing from the root of the symbol
''' table, (that is, from an AssemblySymbol of the Compilation), that symbol will be returned
''' (i.e. the returned value will be reference-equal to one reachable from the root of the
''' symbol table). Symbols representing entities without names (e.g. array-of-int) may or may
''' not exhibit reference equality. However, some named symbols (such as local variables) are
''' not reachable from the root. These symbols are visible as answers to semantic questions.
''' When the same SemanticModel object is used, the answers exhibit reference-equality.
''' </para>
''' </remarks>
Friend MustInherit Class VBSemanticModel
Inherits SemanticModel
''' <summary>
''' The compilation associated with this binding.
''' </summary>
Public MustOverride Shadows ReadOnly Property Compilation As VisualBasicCompilation
''' <summary>
''' The root node of the syntax tree that this binding is based on.
''' </summary>
Friend MustOverride Shadows ReadOnly Property Root As SyntaxNode
''' <summary>
''' Gets symbol information about an expression syntax node. This is the worker
''' function that is overridden in various derived kinds of Semantic Models. It can assume that
''' CheckSyntaxNode has already been called.
''' </summary>
Friend MustOverride Function GetExpressionSymbolInfo(node As ExpressionSyntax, options As SymbolInfoOptions, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
''' <summary>
''' Gets symbol information about the 'Add' method corresponding to an expression syntax <paramref name="node"/> within collection initializer.
''' This is the worker function that is overridden in various derived kinds of Semantic Models. It can assume that
''' CheckSyntaxNode has already been called and the <paramref name="node"/> is in the right place in the syntax tree.
''' </summary>
Friend MustOverride Function GetCollectionInitializerAddSymbolInfo(collectionInitializer As ObjectCreationExpressionSyntax, node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
''' <summary>
''' Gets symbol information about an attribute syntax node. This is the worker
''' function that is overridden in various derived kinds of Semantic Models. It can assume that
''' CheckSyntaxNode has already been called.
''' </summary>
Friend MustOverride Function GetAttributeSymbolInfo(attribute As AttributeSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
''' <summary>
''' Gets type information about an expression syntax node. This is the worker
''' function that is overridden in various derived kinds of Semantic Models. It can assume that
''' CheckSyntaxNode has already been called.
''' </summary>
Friend MustOverride Function GetExpressionTypeInfo(node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As VisualBasicTypeInfo
''' <summary>
''' Gets type information about an attribute syntax node. This is the worker
''' function that is overridden in various derived kinds of Semantic Models. It can assume that
''' CheckSyntaxNode has already been called.
''' </summary>
Friend MustOverride Function GetAttributeTypeInfo(attribute As AttributeSyntax, Optional cancellationToken As CancellationToken = Nothing) As VisualBasicTypeInfo
''' <summary>
''' Gets constant value information about an expression syntax node. This is the worker
''' function that is overridden in various derived kinds of Semantic Models. It can assume that
''' CheckSyntaxNode has already been called.
''' </summary>
Friend MustOverride Function GetExpressionConstantValue(node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As ConstantValue
''' <summary>
''' Gets member group information about an expression syntax node. This is the worker
''' function that is overridden in various derived kinds of Semantic Models. It can assume that
''' CheckSyntaxNode has already been called.
''' </summary>
Friend MustOverride Function GetExpressionMemberGroup(node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Symbol)
''' <summary>
''' Gets member group information about an attribute syntax node. This is the worker
''' function that is overridden in various derived kinds of Semantic Models. It can assume that
''' CheckSyntaxNode has already been called.
''' </summary>
Friend MustOverride Function GetAttributeMemberGroup(attribute As AttributeSyntax, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Symbol)
''' <summary>
''' Gets symbol information about a cref reference syntax node. This is the worker
''' function that is overridden in various derived kinds of Semantic Models.
''' </summary>
Friend MustOverride Function GetCrefReferenceSymbolInfo(crefReference As CrefReferenceSyntax, options As SymbolInfoOptions, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
' Is this node one that could be successfully interrogated by GetSymbolInfo/GetTypeInfo/GetMemberGroup/GetConstantValue?
Friend Function CanGetSemanticInfo(node As VisualBasicSyntaxNode, Optional allowNamedArgumentName As Boolean = False) As Boolean
Debug.Assert(node IsNot Nothing)
' These aren't really expressions - it's just a manifestation of the SyntaxNode type hierarchy.
If node.Kind = SyntaxKind.XmlName Then
Return False
End If
Dim trivia As StructuredTriviaSyntax = node.EnclosingStructuredTrivia
If trivia IsNot Nothing Then
' Allow getting semantic info on names from Cref and Name attributes
' inside documentation trivia
Return IsInCrefOrNameAttributeInterior(node)
End If
Return Not node.IsMissing AndAlso
(TypeOf (node) Is ExpressionSyntax AndAlso (allowNamedArgumentName OrElse Not SyntaxFacts.IsNamedArgumentName(node)) OrElse
TypeOf (node) Is AttributeSyntax OrElse
TypeOf (node) Is QueryClauseSyntax OrElse
TypeOf (node) Is ExpressionRangeVariableSyntax OrElse
TypeOf (node) Is OrderingSyntax)
End Function
Protected Overrides Function GetOperationCore(node As SyntaxNode, cancellationToken As CancellationToken) As IOperation
Dim vbnode = DirectCast(node, VisualBasicSyntaxNode)
CheckSyntaxNode(vbnode)
Return GetOperationWorker(vbnode, cancellationToken)
End Function
Friend Overridable Function GetOperationWorker(node As VisualBasicSyntaxNode, cancellationToken As CancellationToken) As IOperation
Return Nothing
End Function
''' <summary>
''' Returns what symbol(s), if any, the given expression syntax bound to in the program.
'''
''' An AliasSymbol will never be returned by this method. What the alias refers to will be
''' returned instead. To get information about aliases, call GetAliasInfo.
'''
''' If binding the type name C in the expression "new C(...)" the actual constructor bound to
''' will be returned (or all constructor if overload resolution failed). This occurs as long as C
''' unambiguously binds to a single type that has a constructor. If C ambiguously binds to multiple
''' types, or C binds to a static class, then type(s) are returned.
''' </summary>
Public Shadows Function GetSymbolInfo(expression As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
CheckSyntaxNode(expression)
If CanGetSemanticInfo(expression, allowNamedArgumentName:=True) Then
If SyntaxFacts.IsNamedArgumentName(expression) Then
' Named arguments are handled in a special way.
Return GetNamedArgumentSymbolInfo(DirectCast(expression, IdentifierNameSyntax), cancellationToken)
Else
Return GetExpressionSymbolInfo(expression, SymbolInfoOptions.DefaultOptions, cancellationToken)
End If
Else
Return SymbolInfo.None
End If
End Function
''' <summary>
''' Returns what 'Add' method symbol(s), if any, corresponds to the given expression syntax
''' within <see cref="ObjectCollectionInitializerSyntax.Initializer"/>.
''' </summary>
Public Shadows Function GetCollectionInitializerSymbolInfo(expression As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
CheckSyntaxNode(expression)
If expression.Parent IsNot Nothing AndAlso expression.Parent.Kind = SyntaxKind.CollectionInitializer AndAlso
expression.Parent.Parent IsNot Nothing AndAlso expression.Parent.Parent.Kind = SyntaxKind.ObjectCollectionInitializer AndAlso
DirectCast(expression.Parent.Parent, ObjectCollectionInitializerSyntax).Initializer Is expression.Parent AndAlso
expression.Parent.Parent.Parent IsNot Nothing AndAlso expression.Parent.Parent.Parent.Kind = SyntaxKind.ObjectCreationExpression AndAlso
CanGetSemanticInfo(expression.Parent.Parent.Parent, allowNamedArgumentName:=False) Then
Dim collectionInitializer = DirectCast(expression.Parent.Parent.Parent, ObjectCreationExpressionSyntax)
If collectionInitializer.Initializer Is expression.Parent.Parent Then
Return GetCollectionInitializerAddSymbolInfo(collectionInitializer, expression, cancellationToken)
End If
End If
Return SymbolInfo.None
End Function
''' <summary>
''' Returns what symbol(s), if any, the given cref reference syntax bound to in the documentation comment.
'''
''' An AliasSymbol will never be returned by this method. What the alias refers to will be
''' returned instead.
''' </summary>
Public Shadows Function GetSymbolInfo(crefReference As CrefReferenceSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
CheckSyntaxNode(crefReference)
Return GetCrefReferenceSymbolInfo(crefReference, SymbolInfoOptions.DefaultOptions, cancellationToken)
End Function
''' <summary>
''' Binds the expression in the context of the specified location and get semantic
''' information such as type, symbols and diagnostics. This method is used to get semantic
''' information about an expression that did not actually appear in the source code.
''' </summary>
''' <param name="position">A character position used to identify a declaration scope and
''' accessibility. This character position must be within the FullSpan of the Root syntax
''' node in this SemanticModel.
''' </param>
''' <param name="expression">A syntax node that represents a parsed expression. This syntax
''' node need not and typically does not appear in the source code referred to SemanticModel
''' instance.</param>
''' <param name="bindingOption">Indicates whether to binding the expression as a full expressions,
''' or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then
''' expression should derive from TypeSyntax.</param>
''' <returns>The semantic information for the topmost node of the expression.</returns>
''' <remarks>The passed in expression is interpreted as a stand-alone expression, as if it
''' appeared by itself somewhere within the scope that encloses "position".</remarks>
Public Shadows Function GetSpeculativeSymbolInfo(position As Integer, expression As ExpressionSyntax, bindingOption As SpeculativeBindingOption) As SymbolInfo
Dim binder As Binder = Nothing ' Passed ByRef to GetSpeculativelyBoundNodeSummary.
Dim bnodeSummary = GetSpeculativelyBoundNodeSummary(position, expression, bindingOption, binder)
If bnodeSummary.LowestBoundNode IsNot Nothing Then
Return Me.GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, bnodeSummary, binder)
Else
Return SymbolInfo.None
End If
End Function
''' <summary>
''' Bind the attribute in the context of the specified location and get semantic information
''' such as type, symbols and diagnostics. This method is used to get semantic information about an attribute
''' that did not actually appear in the source code.
''' </summary>
''' <param name="position">A character position used to identify a declaration scope and accessibility. This
''' character position must be within the FullSpan of the Root syntax node in this SemanticModel. In order to obtain
''' the correct scoping rules for the attribute, position should be the Start position of the Span of the symbol that
''' the attribute is being applied to.
''' </param>
''' <param name="attribute">A syntax node that represents a parsed attribute. This syntax node
''' need not and typically does not appear in the source code referred to SemanticModel instance.</param>
''' <returns>The semantic information for the topmost node of the attribute.</returns>
Public Shadows Function GetSpeculativeSymbolInfo(position As Integer, attribute As AttributeSyntax) As SymbolInfo
Dim binder As Binder = Nothing ' Passed ByRef to GetSpeculativelyBoundNodeSummary.
Dim bnodeSummary = GetSpeculativelyBoundAttributeSummary(position, attribute, binder)
If bnodeSummary.LowestBoundNode IsNot Nothing Then
Return Me.GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, bnodeSummary, binder)
Else
Return SymbolInfo.None
End If
End Function
Public Shadows Function GetSymbolInfo(attribute As AttributeSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
CheckSyntaxNode(attribute)
If CanGetSemanticInfo(attribute) Then
Return GetAttributeSymbolInfo(attribute, cancellationToken)
Else
Return SymbolInfo.None
End If
End Function
' Gets the symbol info from a specific bound node
Friend Function GetSymbolInfoForNode(options As SymbolInfoOptions, boundNodes As BoundNodeSummary, binderOpt As Binder) As SymbolInfo
' Determine the symbols, resultKind, and member group.
Dim resultKind As LookupResultKind = LookupResultKind.Empty
Dim memberGroup As ImmutableArray(Of Symbol) = Nothing
Dim symbols As ImmutableArray(Of Symbol) = GetSemanticSymbols(boundNodes, binderOpt, options, resultKind, memberGroup)
Return SymbolInfoFactory.Create(symbols, resultKind)
End Function
''' <summary>
''' Gets type information about an expression.
''' </summary>
''' <param name="expression">The syntax node to get type information for.</param>
Public Shadows Function GetTypeInfo(expression As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As TypeInfo
Return GetTypeInfoWorker(expression, cancellationToken)
End Function
Friend Overloads Function GetTypeInfoWorker(expression As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As VisualBasicTypeInfo
CheckSyntaxNode(expression)
If CanGetSemanticInfo(expression) Then
If SyntaxFacts.IsNamedArgumentName(expression) Then
Return VisualBasicTypeInfo.None
Else
Return GetExpressionTypeInfo(expression, cancellationToken)
End If
Else
Return VisualBasicTypeInfo.None
End If
End Function
''' <summary>
''' Binds the expression in the context of the specified location and gets type information.
''' This method is used to get type information about an expression that did not actually
''' appear in the source code.
''' </summary>
''' <param name="position">A character position used to identify a declaration scope and
''' accessibility. This character position must be within the FullSpan of the Root syntax
''' node in this SemanticModel.
''' </param>
''' <param name="expression">A syntax node that represents a parsed expression. This syntax
''' node need not and typically does not appear in the source code referred to by the
''' SemanticModel instance.</param>
''' <param name="bindingOption">Indicates whether to binding the expression as a full expressions,
''' or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then
''' expression should derive from TypeSyntax.</param>
''' <returns>The type information for the topmost node of the expression.</returns>
''' <remarks>The passed in expression is interpreted as a stand-alone expression, as if it
''' appeared by itself somewhere within the scope that encloses "position".</remarks>
Public Shadows Function GetSpeculativeTypeInfo(position As Integer, expression As ExpressionSyntax, bindingOption As SpeculativeBindingOption) As TypeInfo
Return GetSpeculativeTypeInfoWorker(position, expression, bindingOption)
End Function
Friend Function GetSpeculativeTypeInfoWorker(position As Integer, expression As ExpressionSyntax, bindingOption As SpeculativeBindingOption) As VisualBasicTypeInfo
Dim binder As Binder = Nothing ' passed ByRef to GetSpeculativelyBoundNodeSummary
Dim bnodeSummary = GetSpeculativelyBoundNodeSummary(position, expression, bindingOption, binder)
If bnodeSummary.LowestBoundNode IsNot Nothing Then
Return Me.GetTypeInfoForNode(bnodeSummary)
Else
Return VisualBasicTypeInfo.None
End If
End Function
Public Shadows Function GetTypeInfo(attribute As AttributeSyntax, Optional cancellationToken As CancellationToken = Nothing) As TypeInfo
Return GetTypeInfoWorker(attribute, cancellationToken)
End Function
Private Overloads Function GetTypeInfoWorker(attribute As AttributeSyntax, Optional cancellationToken As CancellationToken = Nothing) As VisualBasicTypeInfo
CheckSyntaxNode(attribute)
If CanGetSemanticInfo(attribute) Then
Return GetAttributeTypeInfo(attribute, cancellationToken)
Else
Return VisualBasicTypeInfo.None
End If
End Function
' Gets the type info from a specific bound node
Friend Function GetTypeInfoForNode(boundNodes As BoundNodeSummary) As VisualBasicTypeInfo
' Determine the type, converted type, and expression
Dim type As TypeSymbol = Nothing
Dim convertedType As TypeSymbol = Nothing
Dim conversion As Conversion = Nothing
type = GetSemanticType(boundNodes, convertedType, conversion)
Return New VisualBasicTypeInfo(type, convertedType, conversion)
End Function
''' <summary>
''' Gets the conversion that occurred between the expression's type and type implied by the expression's context.
''' </summary>
Public Function GetConversion(node As SyntaxNode, Optional cancellationToken As CancellationToken = Nothing) As Conversion
Dim expression = TryCast(node, ExpressionSyntax)
If expression IsNot Nothing Then
Return GetTypeInfoWorker(expression, cancellationToken).ImplicitConversion
End If
Dim attribute = TryCast(node, AttributeSyntax)
If attribute IsNot Nothing Then
Return GetTypeInfoWorker(attribute, cancellationToken).ImplicitConversion
End If
Return VisualBasicTypeInfo.None.ImplicitConversion
End Function
''' <summary>
''' Gets the conversion that occurred between the expression's type and type implied by the expression's context.
''' </summary>
Public Function GetSpeculativeConversion(position As Integer, expression As ExpressionSyntax, bindingOption As SpeculativeBindingOption) As Conversion
Return GetSpeculativeTypeInfoWorker(position, expression, bindingOption).ImplicitConversion
End Function
Public Shadows Function GetConstantValue(expression As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As [Optional](Of Object)
CheckSyntaxNode(expression)
If CanGetSemanticInfo(expression) Then
Dim val As ConstantValue = GetExpressionConstantValue(expression, cancellationToken)
If val IsNot Nothing AndAlso Not val.IsBad Then
Return New [Optional](Of Object)(val.Value)
End If
End If
Return Nothing
End Function
''' <summary>
''' Binds the expression in the context of the specified location and gets constant value information.
''' This method is used to get information about an expression that did not actually appear in the source code.
''' </summary>
''' <param name="position">A character position used to identify a declaration scope and
''' accessibility. This character position must be within the FullSpan of the Root syntax
''' node in this SemanticModel.
''' </param>
''' <param name="expression">A syntax node that represents a parsed expression. This syntax
''' node need not and typically does not appear in the source code referred to by SemanticModel
''' instance.</param>
''' <remarks>The passed in expression is interpreted as a stand-alone expression, as if it
''' appeared by itself somewhere within the scope that encloses "position".</remarks>
Public Shadows Function GetSpeculativeConstantValue(position As Integer, expression As ExpressionSyntax) As [Optional](Of Object)
Dim binder As Binder = Nothing ' passed ByRef to GetSpeculativelyBoundNodeSummary
Dim bnodeSummary = GetSpeculativelyBoundNodeSummary(position, expression, SpeculativeBindingOption.BindAsExpression, binder)
If bnodeSummary.LowestBoundNode IsNot Nothing Then
Dim val As ConstantValue = Me.GetConstantValueForNode(bnodeSummary)
If val IsNot Nothing AndAlso Not val.IsBad Then
Return New [Optional](Of Object)(val.Value)
End If
End If
Return Nothing
End Function
Friend Function GetConstantValueForNode(boundNodes As BoundNodeSummary) As ConstantValue
Dim constValue As ConstantValue = Nothing
Dim lowerExpr = TryCast(boundNodes.LowestBoundNode, BoundExpression)
If lowerExpr IsNot Nothing Then
constValue = lowerExpr.ConstantValueOpt
End If
Return constValue
End Function
Public Shadows Function GetMemberGroup(expression As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of ISymbol)
CheckSyntaxNode(expression)
If CanGetSemanticInfo(expression) Then
Dim result = GetExpressionMemberGroup(expression, cancellationToken)
#If DEBUG Then
For Each item In result
Debug.Assert(item.Kind <> SymbolKind.Namespace)
Next
#End If
Return StaticCast(Of ISymbol).From(result)
Else
Return ImmutableArray(Of ISymbol).Empty
End If
End Function
Public Shadows Function GetSpeculativeMemberGroup(position As Integer, expression As ExpressionSyntax) As ImmutableArray(Of ISymbol)
Dim binder As Binder = Nothing ' passed ByRef to GetSpeculativelyBoundNodeSummary
Dim bnodeSummary = GetSpeculativelyBoundNodeSummary(position, expression, SpeculativeBindingOption.BindAsExpression, binder)
If bnodeSummary.LowestBoundNode IsNot Nothing Then
Dim result = Me.GetMemberGroupForNode(bnodeSummary, binderOpt:=Nothing)
#If DEBUG Then
For Each item In result
Debug.Assert(item.Kind <> SymbolKind.Namespace)
Next
#End If
Return StaticCast(Of ISymbol).From(result)
Else
Return ImmutableArray(Of ISymbol).Empty
End If
End Function
Public Shadows Function GetMemberGroup(attribute As AttributeSyntax, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of ISymbol)
CheckSyntaxNode(attribute)
If CanGetSemanticInfo(attribute) Then
Dim result = GetAttributeMemberGroup(attribute, cancellationToken)
#If DEBUG Then
For Each item In result
Debug.Assert(item.Kind <> SymbolKind.Namespace)
Next
#End If
Return StaticCast(Of ISymbol).From(result)
Else
Return ImmutableArray(Of ISymbol).Empty
End If
End Function
Friend Function GetMemberGroupForNode(boundNodes As BoundNodeSummary, binderOpt As Binder) As ImmutableArray(Of Symbol)
' Determine the symbols, resultKind, and member group.
Dim resultKind As LookupResultKind = LookupResultKind.Empty
Dim memberGroup As ImmutableArray(Of Symbol) = Nothing
Dim symbols As ImmutableArray(Of Symbol) = GetSemanticSymbols(boundNodes, binderOpt, SymbolInfoOptions.DefaultOptions, resultKind, memberGroup)
Return memberGroup
End Function
''' <summary>
''' If "nameSyntax" resolves to an alias name, return the AliasSymbol corresponding
''' to A. Otherwise return null.
''' </summary>
Public Shadows Function GetAliasInfo(nameSyntax As IdentifierNameSyntax, Optional cancellationToken As CancellationToken = Nothing) As IAliasSymbol
CheckSyntaxNode(nameSyntax)
If CanGetSemanticInfo(nameSyntax) Then
Dim info = GetExpressionSymbolInfo(nameSyntax, SymbolInfoOptions.PreferTypeToConstructors Or SymbolInfoOptions.PreserveAliases, cancellationToken)
Return TryCast(info.Symbol, IAliasSymbol)
Else
Return Nothing
End If
End Function
''' <summary>
''' Binds the name in the context of the specified location and sees if it resolves to an
''' alias name. If it does, return the AliasSymbol corresponding to it. Otherwise, return null.
''' </summary>
''' <param name="position">A character position used to identify a declaration scope and
''' accessibility. This character position must be within the FullSpan of the Root syntax
''' node in this SemanticModel.
''' </param>
''' <param name="nameSyntax">A syntax node that represents a name. This syntax
''' node need not and typically does not appear in the source code referred to by the
''' SemanticModel instance.</param>
''' <param name="bindingOption">Indicates whether to binding the name as a full expression,
''' or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then
''' expression should derive from TypeSyntax.</param>
''' <remarks>The passed in name is interpreted as a stand-alone name, as if it
''' appeared by itself somewhere within the scope that encloses "position".</remarks>
Public Shadows Function GetSpeculativeAliasInfo(position As Integer, nameSyntax As IdentifierNameSyntax, bindingOption As SpeculativeBindingOption) As IAliasSymbol
Dim binder As Binder = Nothing
Dim bnodeSummary = GetSpeculativelyBoundNodeSummary(position, nameSyntax, bindingOption, binder)
If bnodeSummary.LowestBoundNode IsNot Nothing Then
Dim info As SymbolInfo = Me.GetSymbolInfoForNode(SymbolInfoOptions.PreferTypeToConstructors Or SymbolInfoOptions.PreserveAliases, bnodeSummary, binderOpt:=binder)
Return TryCast(info.Symbol, IAliasSymbol)
Else
Return Nothing
End If
End Function
''' <summary>
''' Gets the binder that encloses the position. See comment on LookupSymbols for how
''' positions are interpreted.
''' </summary>
Friend MustOverride Function GetEnclosingBinder(position As Integer) As Binder
Friend Function IsInTree(node As SyntaxNode) As Boolean
Return IsUnderNode(node, Me.Root)
End Function
Private Shared Function IsUnderNode(node As SyntaxNode, root As SyntaxNode) As Boolean
While node IsNot Nothing
If node Is root Then
Return True
End If
If node.IsStructuredTrivia Then
node = DirectCast(node, StructuredTriviaSyntax).ParentTrivia.Token.Parent
Else
node = node.Parent
End If
End While
Return False
End Function
' Checks that a position is within the span of the root of this binding.
Protected Sub CheckPosition(position As Integer)
Dim fullStart As Integer = Root.Position
Dim fullEnd As Integer = Root.EndPosition
' Is position at the actual end of file (not just end of Root.FullSpan)?
Dim atEOF As Boolean = (position = fullEnd AndAlso position = SyntaxTree.GetRoot().FullSpan.End)
If (fullStart <= position AndAlso position < fullEnd) OrElse
atEOF OrElse
(fullStart = fullEnd AndAlso position = fullEnd) Then
Return
End If
Throw New ArgumentException(VBResources.PositionIsNotWithinSyntax)
End Sub
Friend Sub CheckSyntaxNode(node As VisualBasicSyntaxNode)
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
If Not IsInTree(node) Then
Throw New ArgumentException(VBResources.NodeIsNotWithinSyntaxTree)
End If
End Sub
Private Sub CheckModelAndSyntaxNodeToSpeculate(node As VisualBasicSyntaxNode)
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
If Me.IsSpeculativeSemanticModel Then
Throw New InvalidOperationException(VBResources.ChainingSpeculativeModelIsNotSupported)
End If
If Me.Compilation.ContainsSyntaxTree(node.SyntaxTree) Then
Throw New ArgumentException(VBResources.SpeculatedSyntaxNodeCannotBelongToCurrentCompilation)
End If
End Sub
' Find the initial syntax node to start traversing up the syntax when getting binders from
' a position. Just using FindToken doesn't give quite the right results, especially in situations where
' end constructs haven't been typed yet. If we are in the trivia between two tokens, we move backward to the previous
' token. There are also some special cases around beginning and end of the whole tree.
Friend Function FindInitialNodeFromPosition(position As Integer) As SyntaxNode
Dim fullStart As Integer = Root.Position
Dim fullEnd As Integer = Root.EndPosition
' Is position at the actual end of file (not just end of Root.FullSpan)?
Dim atEOF As Boolean = (position = fullEnd AndAlso position = SyntaxTree.GetRoot().FullSpan.End)
If (fullStart <= position AndAlso position < fullEnd) OrElse atEOF Then
Dim token As SyntaxToken
If atEOF Then
token = SyntaxTree.GetRoot().FindToken(position, True)
Else
token = Root.FindToken(position, True)
End If
Dim trivia As StructuredTriviaSyntax = DirectCast(token.Parent, VisualBasicSyntaxNode).EnclosingStructuredTrivia
If trivia Is Nothing OrElse Not IsInCrefOrNameAttributeInterior(DirectCast(token.Parent, VisualBasicSyntaxNode)) Then
If atEOF Then
token = SyntaxTree.GetRoot().FindToken(position)
Else
token = Root.FindToken(position)
End If
End If
If (position < token.SpanStart) Then
' Before the start of this token, go to previous token.
token = token.GetPreviousToken(includeSkipped:=False, includeDirectives:=False, includeDocumentationComments:=False)
End If
' If the first token in the root is missing, it's possible to step backwards
' past the start of the root. All sorts of bad things will happen in that case,
' so just use the root.
If token.SpanStart < fullStart Then
Return Root
ElseIf token.Parent IsNot Nothing Then
Debug.Assert(IsInTree(token.Parent))
Return DirectCast(token.Parent, VisualBasicSyntaxNode)
Else
Return Root
End If
ElseIf fullStart = fullEnd AndAlso position = fullEnd Then
' The root is an empty span and isn't the full compilation unit. No other choice here.
Return Root
End If
' Should have been caught by CheckPosition
Throw ExceptionUtilities.Unreachable
End Function
' Is this node in a place where it bind to an implemented member.
Friend Shared Function IsInCrefOrNameAttributeInterior(node As VisualBasicSyntaxNode) As Boolean
Debug.Assert(node IsNot Nothing)
Select Case node.Kind
Case SyntaxKind.IdentifierName,
SyntaxKind.GenericName,
SyntaxKind.PredefinedType,
SyntaxKind.QualifiedName,
SyntaxKind.GlobalName,
SyntaxKind.QualifiedCrefOperatorReference,
SyntaxKind.CrefOperatorReference,
SyntaxKind.CrefReference,
SyntaxKind.XmlString
' fall through
Case Else
Return False
End Select
Dim parent As VisualBasicSyntaxNode = node.Parent
Dim inXmlAttribute As Boolean = False
While parent IsNot Nothing
Select Case parent.Kind
Case SyntaxKind.XmlCrefAttribute,
SyntaxKind.XmlNameAttribute
Return True
Case SyntaxKind.XmlAttribute
inXmlAttribute = True
parent = parent.Parent
Case SyntaxKind.DocumentationCommentTrivia
If inXmlAttribute Then
Return True
End If
parent = parent.Parent
Case Else
parent = parent.Parent
End Select
End While
Return False
End Function
Friend Function GetSpeculativeBinderForExpression(position As Integer, expression As ExpressionSyntax, bindingOption As SpeculativeBindingOption) As SpeculativeBinder
Debug.Assert(expression IsNot Nothing)
CheckPosition(position)
If bindingOption = SpeculativeBindingOption.BindAsTypeOrNamespace Then
If TryCast(expression, TypeSyntax) Is Nothing Then
Return Nothing
End If
End If
Dim binder = Me.GetEnclosingBinder(position)
' Add speculative binder to bind speculatively.
Return If(binder IsNot Nothing, SpeculativeBinder.Create(binder), Nothing)
End Function
Private Function GetSpeculativelyBoundNode(
binder As Binder,
expression As ExpressionSyntax,
bindingOption As SpeculativeBindingOption,
diagnostics As DiagnosticBag
) As BoundNode
Debug.Assert(binder IsNot Nothing)
Debug.Assert(binder.IsSemanticModelBinder)
Debug.Assert(expression IsNot Nothing)
Debug.Assert(bindingOption <> SpeculativeBindingOption.BindAsTypeOrNamespace OrElse
TryCast(expression, TypeSyntax) IsNot Nothing)
Dim bnode As BoundNode
If bindingOption = SpeculativeBindingOption.BindAsTypeOrNamespace Then
bnode = binder.BindNamespaceOrTypeExpression(DirectCast(expression, TypeSyntax), diagnostics)
Else
Debug.Assert(bindingOption = SpeculativeBindingOption.BindAsExpression)
bnode = Me.Bind(binder, expression, diagnostics)
bnode = MakeValueIfPossible(binder, bnode)
End If
Return bnode
End Function
Friend Function GetSpeculativelyBoundNode(position As Integer,
expression As ExpressionSyntax,
bindingOption As SpeculativeBindingOption,
<Out> ByRef binder As Binder) As BoundNode
Debug.Assert(expression IsNot Nothing)
binder = Me.GetSpeculativeBinderForExpression(position, expression, bindingOption)
If binder IsNot Nothing Then
Dim diagnostics = DiagnosticBag.GetInstance()
Dim bnode = Me.GetSpeculativelyBoundNode(binder, expression, bindingOption, diagnostics)
diagnostics.Free()
Return bnode
Else
Return Nothing
End If
End Function
Private Function GetSpeculativelyBoundNodeSummary(position As Integer,
expression As ExpressionSyntax,
bindingOption As SpeculativeBindingOption,
<Out> ByRef binder As Binder) As BoundNodeSummary
If expression Is Nothing Then
Throw New ArgumentNullException(NameOf(expression))
End If
Dim standalone = SyntaxFactory.GetStandaloneExpression(expression)
Dim bnode = Me.GetSpeculativelyBoundNode(position, standalone, bindingOption, binder)
If bnode IsNot Nothing Then
Debug.Assert(binder IsNot Nothing)
Return New BoundNodeSummary(bnode, bnode, Nothing)
Else
Return Nothing
End If
End Function
''' <summary>
''' When doing speculative binding, we don't have any context information about expressions or the
''' context that is expected. We try to interpret as a value, but
''' only if it doesn't cause additional errors (indicating that it wasn't value to interpret it
''' that way). This should get us the most "liberal" interpretation
''' for semantic information.
''' </summary>
Private Function MakeValueIfPossible(binder As Binder, node As BoundNode) As BoundNode
' Convert a stand-alone speculatively bound expression to an rvalue.
' This will get the value of properties, convert lambdas to anonymous
' delegate type, etc.
Dim boundExpression = TryCast(node, BoundExpression)
If boundExpression IsNot Nothing Then
' Try calling ReclassifyAsValue
Dim diagnostics = DiagnosticBag.GetInstance()
Dim resultNode = binder.ReclassifyAsValue(boundExpression, diagnostics)
' Reclassify ArrayLiterals and other expressions missing types to expressions with types.
If Not resultNode.HasErrors AndAlso resultNode.Type Is Nothing Then
resultNode = binder.ReclassifyExpression(resultNode, diagnostics)
End If
Dim noErrors As Boolean = Not diagnostics.HasAnyErrors()
diagnostics.Free()
If noErrors Then
Return resultNode
End If
End If
Return node
End Function
Private Function GetSpeculativeAttributeBinder(position As Integer, attribute As AttributeSyntax) As AttributeBinder
Debug.Assert(attribute IsNot Nothing)
CheckPosition(position)
Dim binder = Me.GetEnclosingBinder(position)
' Add speculative attribute binder to bind speculatively.
Return If(binder IsNot Nothing,
BinderBuilder.CreateBinderForAttribute(binder.SyntaxTree, binder, attribute),
Nothing)
End Function
''' <summary>
''' Bind the given attribute speculatively at the given position, and return back
''' the resulting bound node. May return null in some error cases.
''' </summary>
Friend Function GetSpeculativelyBoundAttribute(position As Integer, attribute As AttributeSyntax, <Out> ByRef binder As Binder) As BoundAttribute
binder = Me.GetSpeculativeAttributeBinder(position, attribute)
If binder IsNot Nothing Then
Dim diagnostics = DiagnosticBag.GetInstance()
Dim bnode As BoundAttribute = binder.BindAttribute(attribute, diagnostics)
diagnostics.Free()
Return bnode
Else
Return Nothing
End If
End Function
''' <summary>
''' Bind the given attribute speculatively at the given position, and return back
''' the resulting bound node summary. May return null in some error cases.
''' </summary>
Private Function GetSpeculativelyBoundAttributeSummary(position As Integer, attribute As AttributeSyntax, <Out> ByRef binder As Binder) As BoundNodeSummary
If attribute Is Nothing Then
Throw New ArgumentNullException(NameOf(attribute))
End If
Dim bnode = GetSpeculativelyBoundAttribute(position, attribute, binder)
If bnode IsNot Nothing Then
Debug.Assert(binder IsNot Nothing)
Return New BoundNodeSummary(bnode, bnode, Nothing)
Else
Return Nothing
End If
End Function
' Given a diagnosticInfo, add any symbols from the diagnosticInfo to the symbol builder.
Private Sub AddSymbolsFromDiagnosticInfo(symbolsBuilder As ArrayBuilder(Of Symbol), diagnosticInfo As DiagnosticInfo)
Dim diagInfoWithSymbols = TryCast(diagnosticInfo, IDiagnosticInfoWithSymbols)
If diagInfoWithSymbols IsNot Nothing Then
diagInfoWithSymbols.GetAssociatedSymbols(symbolsBuilder)
End If
End Sub
' Given a symbolsBuilder with a bunch of symbols in it, return an ImmutableArray containing
' just the symbols that are not ErrorTypeSymbols, and without any duplicates.
Friend Function RemoveErrorTypesAndDuplicates(symbolsBuilder As ArrayBuilder(Of Symbol), options As SymbolInfoOptions) As ImmutableArray(Of Symbol)
' Common case is 0 or 1 symbol, so we optimize those cases to not allocate a HashSet, since
' duplicates aren't possible for those cases.
If symbolsBuilder.Count = 0 Then
Return ImmutableArray(Of Symbol).Empty
ElseIf symbolsBuilder.Count = 1 Then
Dim s = symbolsBuilder(0)
If (options And SymbolInfoOptions.ResolveAliases) <> 0 Then
s = UnwrapAlias(s)
End If
If TypeOf s Is ErrorTypeSymbol Then
symbolsBuilder.Clear()
AddSymbolsFromDiagnosticInfo(symbolsBuilder, DirectCast(s, ErrorTypeSymbol).ErrorInfo)
Return symbolsBuilder.ToImmutable()
Else
Return ImmutableArray.Create(s)
End If
Else
' 2 or more symbols. Use a hash set to remove duplicates.
Dim symbolSet = PooledHashSet(Of Symbol).GetInstance()
For Each s In symbolsBuilder
If (options And SymbolInfoOptions.ResolveAliases) <> 0 Then
s = UnwrapAlias(s)
End If
If TypeOf s Is ErrorTypeSymbol Then
Dim tempBuilder As ArrayBuilder(Of Symbol) = ArrayBuilder(Of Symbol).GetInstance()
AddSymbolsFromDiagnosticInfo(tempBuilder, DirectCast(s, ErrorTypeSymbol).ErrorInfo)
For Each sym In tempBuilder
symbolSet.Add(sym)
Next
tempBuilder.Free()
Else
symbolSet.Add(s)
End If
Next
Dim result = ImmutableArray.CreateRange(symbolSet)
symbolSet.Free()
Return result
End If
End Function
' Given the lower and upper bound expressions, get the type, converted type, and conversion.
Private Function GetSemanticType(boundNodes As BoundNodeSummary,
ByRef convertedType As TypeSymbol,
ByRef conversion As Conversion) As TypeSymbol
convertedType = Nothing
conversion = New Conversion(Conversions.Identity)
Dim lowestExpr = TryCast(boundNodes.LowestBoundNode, BoundExpression)
Dim highestExpr = TryCast(boundNodes.HighestBoundNode, BoundExpression)
If lowestExpr Is Nothing Then
' Only BoundExpressions have a type.
Return Nothing
End If
' Do not return any type information for a ObjectCreationExpressionSyntax.Type node.
If boundNodes.LowestBoundNodeOfSyntacticParent IsNot Nothing AndAlso
boundNodes.LowestBoundNodeOfSyntacticParent.Syntax.Kind = SyntaxKind.ObjectCreationExpression AndAlso
DirectCast(boundNodes.LowestBoundNodeOfSyntacticParent.Syntax, ObjectCreationExpressionSyntax).Type Is lowestExpr.Syntax Then
Return Nothing
End If
Dim type As TypeSymbol
' Similar to a lambda expression, array literal doesn't have a type.
' However, during binding we create BoundArrayCreation node that has type the literal got converted to.
' Let's account for that.
If lowestExpr.Kind = BoundKind.ArrayCreation AndAlso DirectCast(lowestExpr, BoundArrayCreation).ArrayLiteralOpt IsNot Nothing Then
type = Nothing
conversion = New Conversion(New KeyValuePair(Of ConversionKind, MethodSymbol)(DirectCast(lowestExpr, BoundArrayCreation).ArrayLiteralConversion, Nothing))
ElseIf lowestExpr.Kind = BoundKind.ConvertedTupleLiteral Then
type = DirectCast(lowestExpr, BoundConvertedTupleLiteral).NaturalTypeOpt
Else
type = lowestExpr.Type
End If
Dim useOfLocalBeforeDeclaration As Boolean = False
' Use of local before declaration requires some additional fixup.
' Due complications around implicit locals and type inference, we do not
' try to obtain a type of a local when it is used before declaration, we use
' a special error type symbol. However, semantic model should return the same
' type information for usage of a local before and after its declaration.
' We will detect the use before declaration cases and replace the error type
' symbol with the one obtained from the local. It is safe to get the type
' from the local at this point because we have already bound the whole method
' body if implicit locals were allowed.
If type Is LocalSymbol.UseBeforeDeclarationResultType AndAlso
lowestExpr.Kind = BoundKind.Local Then
useOfLocalBeforeDeclaration = True
type = DirectCast(lowestExpr, BoundLocal).LocalSymbol.Type
End If
' See if the node is being implicitly converted to another type. If so, there would
' be a higher conversion node associated to the same syntax node.
If highestExpr IsNot Nothing Then
If highestExpr.Type IsNot Nothing AndAlso highestExpr.Type.TypeKind <> TypeKind.Error Then
convertedType = highestExpr.Type
If (type Is Nothing OrElse Not type.IsSameTypeIgnoringAll(convertedType)) Then
' If the upper expression is of a different type, we want to return
' a conversion. Hopefully we have a conversion node.
' TODO: Understand cases where we don't have a conversion node better.
If highestExpr.Kind = BoundKind.Conversion Then
Dim conversionNode = DirectCast(highestExpr, BoundConversion)
If useOfLocalBeforeDeclaration AndAlso Not type.IsErrorType() Then
conversion = New Conversion(Conversions.ClassifyConversion(type, convertedType, Nothing))
Else
conversion = New Conversion(KeyValuePairUtil.Create(conversionNode.ConversionKind,
TryCast(conversionNode.ExpressionSymbol, MethodSymbol)))
End If
End If
End If
End If
End If
If type Is Nothing AndAlso TypeOf boundNodes.LowestBoundNodeOfSyntacticParent Is BoundBadExpression Then
' Special case: overload failure on X in New X(...), where overload resolution failed.
' Binds to method group which can't have a type.
Dim parentSyntax As SyntaxNode = boundNodes.LowestBoundNodeOfSyntacticParent.Syntax
If parentSyntax IsNot Nothing AndAlso
parentSyntax Is boundNodes.LowestBoundNode.Syntax.Parent AndAlso
((parentSyntax.Kind = SyntaxKind.ObjectCreationExpression AndAlso (DirectCast(parentSyntax, ObjectCreationExpressionSyntax).Type Is boundNodes.LowestBoundNode.Syntax))) Then
type = DirectCast(boundNodes.LowestBoundNodeOfSyntacticParent, BoundBadExpression).Type
End If
End If
' If we didn't have a converted type, then use the type.
If convertedType Is Nothing Then
convertedType = type
End If
Return type
End Function
' Given the lower and upper bound expressions, get the symbols, resultkind, and member group.
Private Function GetSemanticSymbols(boundNodes As BoundNodeSummary,
binderOpt As Binder,
options As SymbolInfoOptions,
ByRef resultKind As LookupResultKind,
ByRef memberGroup As ImmutableArray(Of Symbol)) As ImmutableArray(Of Symbol)
' TODO: Understand the case patched by TODO in GetSemanticInfoForNode and create a better fix.
Dim symbolsBuilder = ArrayBuilder(Of Symbol).GetInstance()
Dim memberGroupBuilder = ArrayBuilder(Of Symbol).GetInstance()
resultKind = LookupResultKind.Good ' assume good unless we find out otherwise.
If boundNodes.LowestBoundNode IsNot Nothing Then
Select Case boundNodes.LowestBoundNode.Kind
Case BoundKind.MethodGroup
' Complex enough to split out into its own function.
GetSemanticSymbolsForMethodGroup(boundNodes, symbolsBuilder, memberGroupBuilder, resultKind)
Case BoundKind.PropertyGroup
' Complex enough to split out into its own function.
GetSemanticSymbolsForPropertyGroup(boundNodes, symbolsBuilder, memberGroupBuilder, resultKind)
Case BoundKind.TypeExpression
' Watch out for not creatable types within object creation syntax
If boundNodes.LowestBoundNodeOfSyntacticParent IsNot Nothing AndAlso
boundNodes.LowestBoundNodeOfSyntacticParent.Syntax.Kind = SyntaxKind.ObjectCreationExpression AndAlso
DirectCast(boundNodes.LowestBoundNodeOfSyntacticParent.Syntax, ObjectCreationExpressionSyntax).Type Is boundNodes.LowestBoundNode.Syntax AndAlso
boundNodes.LowestBoundNodeOfSyntacticParent.Kind = BoundKind.BadExpression AndAlso
DirectCast(boundNodes.LowestBoundNodeOfSyntacticParent, BoundBadExpression).ResultKind = LookupResultKind.NotCreatable Then
resultKind = LookupResultKind.NotCreatable
End If
' We want to return the alias symbol if one exists, otherwise the type symbol.
' If its an error type look at underlying symbols and kind.
' The alias symbol is latter mapped to its target depending on options in RemoveErrorTypesAndDuplicates.
Dim boundType = DirectCast(boundNodes.LowestBoundNode, BoundTypeExpression)
If boundType.AliasOpt IsNot Nothing Then
symbolsBuilder.Add(boundType.AliasOpt)
Else
Dim typeSymbol As TypeSymbol = boundType.Type
Dim originalErrorType = TryCast(typeSymbol.OriginalDefinition, ErrorTypeSymbol)
If originalErrorType IsNot Nothing Then
resultKind = originalErrorType.ResultKind
symbolsBuilder.AddRange(originalErrorType.CandidateSymbols)
Else
symbolsBuilder.Add(typeSymbol)
End If
End If
Case BoundKind.Attribute
Debug.Assert(boundNodes.LowestBoundNodeOfSyntacticParent Is Nothing)
Dim attribute = DirectCast(boundNodes.LowestBoundNode, BoundAttribute)
resultKind = attribute.ResultKind
' If attribute name bound to a single named type or an error type
' with a single named type candidate symbol, we will return constructors
' of the named type in the semantic info.
' Otherwise, we will return the error type candidate symbols.
Dim namedType = DirectCast(attribute.Type, NamedTypeSymbol)
If namedType.IsErrorType() Then
Debug.Assert(resultKind <> LookupResultKind.Good)
Dim errorType = DirectCast(namedType, ErrorTypeSymbol)
Dim candidateSymbols = errorType.CandidateSymbols
' If error type has a single named type candidate symbol, we want to
' use that type for symbol info.
If candidateSymbols.Length = 1 AndAlso candidateSymbols(0).Kind = SymbolKind.NamedType Then
namedType = DirectCast(errorType.CandidateSymbols(0), NamedTypeSymbol)
Else
symbolsBuilder.AddRange(candidateSymbols)
Exit Select
End If
End If
Dim symbols = ImmutableArray(Of Symbol).Empty
AdjustSymbolsForObjectCreation(attribute, namedType, attribute.Constructor, binderOpt, symbols, memberGroupBuilder, resultKind)
symbolsBuilder.AddRange(symbols)
Case BoundKind.ObjectCreationExpression
Dim creation = DirectCast(boundNodes.LowestBoundNode, BoundObjectCreationExpression)
If creation.MethodGroupOpt IsNot Nothing Then
creation.MethodGroupOpt.GetExpressionSymbols(memberGroupBuilder)
resultKind = creation.MethodGroupOpt.ResultKind
End If
If creation.ConstructorOpt IsNot Nothing Then
symbolsBuilder.Add(creation.ConstructorOpt)
Else
symbolsBuilder.AddRange(memberGroupBuilder)
End If
Case BoundKind.LateMemberAccess
GetSemanticSymbolsForLateBoundMemberAccess(boundNodes, symbolsBuilder, memberGroupBuilder, resultKind)
Case BoundKind.LateInvocation
Dim lateInvocation = DirectCast(boundNodes.LowestBoundNode, BoundLateInvocation)
GetSemanticSymbolsForLateBoundInvocation(lateInvocation, symbolsBuilder, memberGroupBuilder, resultKind)
Case BoundKind.MyBaseReference,
BoundKind.MeReference,
BoundKind.MyClassReference
Dim meReference = DirectCast(boundNodes.LowestBoundNode, BoundExpression)
Dim binder As Binder = If(binderOpt, GetEnclosingBinder(boundNodes.LowestBoundNode.Syntax.SpanStart))
Dim containingType As NamedTypeSymbol = binder.ContainingType
Dim containingMember = binder.ContainingMember
Dim meParam As ParameterSymbol = GetMeParameter(meReference.Type, containingType, containingMember, resultKind)
symbolsBuilder.Add(meParam)
Case BoundKind.TypeOrValueExpression
' If we're seeing a node of this kind, then we failed to resolve the member access
' as either a type or a property/field/event/local/parameter. In such cases,
' the second interpretation applies so just visit the node for that.
Dim boundTypeOrValue = DirectCast(boundNodes.LowestBoundNode, BoundTypeOrValueExpression)
Dim valueBoundNodes = New BoundNodeSummary(boundTypeOrValue.Data.ValueExpression, boundNodes.HighestBoundNode, boundNodes.LowestBoundNodeOfSyntacticParent)
Return GetSemanticSymbols(valueBoundNodes, binderOpt, options, resultKind, memberGroup)
Case Else
_Default:
' Currently, only nodes deriving from BoundExpression have symbols or
' resultkind. If this turns out to be too restrictive, we can move them up
' the hierarchy.
Dim lowestExpr = TryCast(boundNodes.LowestBoundNode, BoundExpression)
If lowestExpr IsNot Nothing Then
lowestExpr.GetExpressionSymbols(symbolsBuilder)
resultKind = lowestExpr.ResultKind
If lowestExpr.Kind = BoundKind.BadExpression AndAlso lowestExpr.Syntax.Kind = SyntaxKind.ObjectCreationExpression Then
' Look for a method group under this bad node
Dim typeSyntax = DirectCast(lowestExpr.Syntax, ObjectCreationExpressionSyntax).Type
For Each child In DirectCast(lowestExpr, BoundBadExpression).ChildBoundNodes
If child.Kind = BoundKind.MethodGroup AndAlso child.Syntax Is typeSyntax Then
Dim group = DirectCast(child, BoundMethodGroup)
group.GetExpressionSymbols(memberGroupBuilder)
If resultKind = LookupResultKind.NotCreatable Then
resultKind = group.ResultKind
Else
resultKind = LookupResult.WorseResultKind(resultKind, group.ResultKind)
End If
Exit For
End If
Next
End If
End If
End Select
End If
Dim bindingSymbols As ImmutableArray(Of Symbol) = RemoveErrorTypesAndDuplicates(symbolsBuilder, options)
symbolsBuilder.Free()
If boundNodes.LowestBoundNodeOfSyntacticParent IsNot Nothing AndAlso (options And SymbolInfoOptions.PreferConstructorsToType) <> 0 Then
' Adjust symbols to get the constructors if we're T in a "New T(...)".
AdjustSymbolsForObjectCreation(boundNodes, binderOpt, bindingSymbols, memberGroupBuilder, resultKind)
End If
memberGroup = memberGroupBuilder.ToImmutableAndFree()
' We have a different highest bound node than lowest bound node. If it has a result kind less good than the
' one we already determined, use that. This is typically the case where a BoundBadExpression or BoundBadValue
' is created around another expression.
' CONSIDER: Can it arise that the highest node has associated symbols but the lowest node doesn't? In that case,
' we may wish to use the symbols from the highest.
Dim highestBoundNodeExpr = TryCast(boundNodes.HighestBoundNode, BoundExpression)
If highestBoundNodeExpr IsNot Nothing AndAlso boundNodes.HighestBoundNode IsNot boundNodes.LowestBoundNode Then
If highestBoundNodeExpr.ResultKind <> LookupResultKind.Empty AndAlso highestBoundNodeExpr.ResultKind < resultKind Then
resultKind = highestBoundNodeExpr.ResultKind
End If
If highestBoundNodeExpr.Kind = BoundKind.BadExpression AndAlso bindingSymbols.Length = 0 Then
' If we didn't have symbols from the lowest, maybe the bad expression has symbols.
bindingSymbols = DirectCast(highestBoundNodeExpr, BoundBadExpression).Symbols
End If
End If
Return bindingSymbols
End Function
Private Shared Function GetMeParameter(referenceType As TypeSymbol,
containingType As TypeSymbol,
containingMember As Symbol,
ByRef resultKind As LookupResultKind) As ParameterSymbol
If containingMember Is Nothing OrElse containingType Is Nothing Then
' not in a member of a type (can happen when speculating)
resultKind = LookupResultKind.NotReferencable
Return New MeParameterSymbol(containingMember, referenceType)
End If
Dim meParam As ParameterSymbol
Select Case containingMember.Kind
Case SymbolKind.Method, SymbolKind.Field, SymbolKind.Property
If containingMember.IsShared Then
' in a static member
resultKind = LookupResultKind.MustNotBeInstance
meParam = New MeParameterSymbol(containingMember, containingType)
Else
If TypeSymbol.Equals(referenceType, ErrorTypeSymbol.UnknownResultType, TypeCompareKind.ConsiderEverything) Then
' in an instance member, but binder considered Me/MyBase/MyClass unreferenceable
meParam = New MeParameterSymbol(containingMember, containingType)
resultKind = LookupResultKind.NotReferencable
Else
' should be good
resultKind = LookupResultKind.Good
meParam = containingMember.GetMeParameter()
End If
End If
Case Else
meParam = New MeParameterSymbol(containingMember, referenceType)
resultKind = LookupResultKind.NotReferencable
End Select
Return meParam
End Function
Private Sub GetSemanticSymbolsForLateBoundInvocation(lateInvocation As BoundLateInvocation,
symbolsBuilder As ArrayBuilder(Of Symbol),
memberGroupBuilder As ArrayBuilder(Of Symbol),
ByRef resultKind As LookupResultKind)
resultKind = LookupResultKind.LateBound
Dim group = lateInvocation.MethodOrPropertyGroupOpt
If group IsNot Nothing Then
group.GetExpressionSymbols(memberGroupBuilder)
group.GetExpressionSymbols(symbolsBuilder)
End If
End Sub
Private Sub GetSemanticSymbolsForLateBoundMemberAccess(boundNodes As BoundNodeSummary,
symbolsBuilder As ArrayBuilder(Of Symbol),
memberGroupBuilder As ArrayBuilder(Of Symbol),
ByRef resultKind As LookupResultKind)
If boundNodes.LowestBoundNodeOfSyntacticParent IsNot Nothing AndAlso
boundNodes.LowestBoundNodeOfSyntacticParent.Kind = BoundKind.LateInvocation Then
GetSemanticSymbolsForLateBoundInvocation(DirectCast(boundNodes.LowestBoundNodeOfSyntacticParent, BoundLateInvocation),
symbolsBuilder,
memberGroupBuilder,
resultKind)
Return
End If
resultKind = LookupResultKind.LateBound
End Sub
' Get the semantic symbols for a BoundMethodGroup. These are somewhat complex, as we want to get the result
' of overload resolution even though that result is associated with the parent node.
Private Sub GetSemanticSymbolsForMethodGroup(boundNodes As BoundNodeSummary,
symbolsBuilder As ArrayBuilder(Of Symbol),
memberGroupBuilder As ArrayBuilder(Of Symbol),
ByRef resultKind As LookupResultKind)
' Get the method group.
Dim methodGroup = DirectCast(boundNodes.LowestBoundNode, BoundMethodGroup)
resultKind = methodGroup.ResultKind
methodGroup.GetExpressionSymbols(memberGroupBuilder)
' Try to figure out what method this resolved to from the parent node.
Dim foundResolution As Boolean = False
'TODO: Will the below work correctly even in the case where M is a parameterless method that returns
'something with a default parameter (e.g. Item) on it?
If boundNodes.LowestBoundNodeOfSyntacticParent IsNot Nothing Then
Select Case boundNodes.LowestBoundNodeOfSyntacticParent.Kind
Case BoundKind.Call
' If we are looking for info on M in M(args), we want the symbol that overload resolution chose for M.
Dim parentCall = DirectCast(boundNodes.LowestBoundNodeOfSyntacticParent, BoundCall)
symbolsBuilder.Add(parentCall.Method)
If parentCall.ResultKind < resultKind Then
resultKind = parentCall.ResultKind
End If
foundResolution = True
Case BoundKind.DelegateCreationExpression
' If we are looking for info on M in AddressOf M, we want the symbol that overload resolution chose for M. This
' should be a BoundDelegateCreation.
Dim parentDelegateCreation = DirectCast(boundNodes.LowestBoundNodeOfSyntacticParent, BoundDelegateCreationExpression)
symbolsBuilder.Add(parentDelegateCreation.Method)
If parentDelegateCreation.ResultKind < resultKind Then
resultKind = parentDelegateCreation.ResultKind
End If
foundResolution = True
Case BoundKind.BadExpression
Dim badExpression = DirectCast(boundNodes.LowestBoundNodeOfSyntacticParent, BoundBadExpression)
' If the bad expressions has symbols(s) from the method group, it better
' indicates the problem.
symbolsBuilder.AddRange(badExpression.Symbols.Where(Function(sym) memberGroupBuilder.Contains(sym)))
If symbolsBuilder.Count > 0 Then
resultKind = badExpression.ResultKind
foundResolution = True
End If
Case BoundKind.NameOfOperator
symbolsBuilder.AddRange(memberGroupBuilder)
resultKind = LookupResultKind.MemberGroup
foundResolution = True
End Select
End If
If Not foundResolution Then
' If we didn't find a resolution, then use what we had as the member group.
symbolsBuilder.AddRange(memberGroupBuilder)
resultKind = LookupResultKind.OverloadResolutionFailure
End If
If methodGroup.ResultKind < resultKind Then
resultKind = methodGroup.ResultKind
End If
End Sub
' Get the semantic symbols for a BoundPropertyGroup. These are somewhat complex, as we want to get the result
' of overload resolution even though that result is associated with the parent node.
Private Sub GetSemanticSymbolsForPropertyGroup(boundNodes As BoundNodeSummary,
symbolsBuilder As ArrayBuilder(Of Symbol),
memberGroupBuilder As ArrayBuilder(Of Symbol),
ByRef resultKind As LookupResultKind)
' Get the property group.
Dim propertyGroup = DirectCast(boundNodes.LowestBoundNode, BoundPropertyGroup)
resultKind = propertyGroup.ResultKind
memberGroupBuilder.AddRange(propertyGroup.Properties)
' Try to figure out what property this resolved to from the parent node.
Dim foundResolution As Boolean = False
If boundNodes.LowestBoundNodeOfSyntacticParent IsNot Nothing Then
Select Case boundNodes.LowestBoundNodeOfSyntacticParent.Kind
Case BoundKind.PropertyAccess
' If we are looking for info on M in M(args), we want the symbol that overload resolution chose for M.
Dim parentPropAccess = TryCast(boundNodes.LowestBoundNodeOfSyntacticParent, BoundPropertyAccess)
If parentPropAccess IsNot Nothing Then
symbolsBuilder.Add(parentPropAccess.PropertySymbol)
If parentPropAccess.ResultKind < resultKind Then
resultKind = parentPropAccess.ResultKind
End If
foundResolution = True
End If
Case BoundKind.BadExpression
Dim badExpression = DirectCast(boundNodes.LowestBoundNodeOfSyntacticParent, BoundBadExpression)
' If the bad expressions has symbols(s) from the property group, it better
' indicates the problem.
symbolsBuilder.AddRange(badExpression.Symbols.Where(Function(sym) memberGroupBuilder.Contains(sym)))
If symbolsBuilder.Count > 0 Then
resultKind = badExpression.ResultKind
foundResolution = True
End If
Case BoundKind.NameOfOperator
symbolsBuilder.AddRange(memberGroupBuilder)
resultKind = LookupResultKind.MemberGroup
foundResolution = True
End Select
End If
If Not foundResolution Then
' If we didn't find a resolution, then use what we had as the member group.
symbolsBuilder.AddRange(memberGroupBuilder)
resultKind = LookupResultKind.OverloadResolutionFailure
End If
If propertyGroup.ResultKind < resultKind Then
resultKind = propertyGroup.ResultKind
End If
End Sub
Private Shared Function UnwrapAliases(symbols As ImmutableArray(Of Symbol)) As ImmutableArray(Of Symbol)
Dim anyAliases As Boolean = symbols.Any(Function(sym) sym.Kind = SymbolKind.Alias)
If Not anyAliases Then
Return symbols
End If
Dim builder As ArrayBuilder(Of Symbol) = ArrayBuilder(Of Symbol).GetInstance()
For Each sym In symbols
builder.Add(UnwrapAlias(sym))
Next
Return builder.ToImmutableAndFree()
End Function
''' <summary>
''' In cases where we are binding C in "[C(...)]", the bound nodes return the symbol for the type. However, we've
''' decided that we want this case to return the constructor of the type instead (based on the SemanticInfoOptions. This
''' affects only attributes. This method checks for this situation and adjusts the syntax and method group.
''' </summary>
Private Sub AdjustSymbolsForObjectCreation(boundNodes As BoundNodeSummary,
binderOpt As Binder,
ByRef bindingSymbols As ImmutableArray(Of Symbol),
memberGroupBuilder As ArrayBuilder(Of Symbol),
ByRef resultKind As LookupResultKind)
Dim constructor As MethodSymbol = Nothing
Dim lowestBoundNode = boundNodes.LowestBoundNode
Dim boundNodeOfSyntacticParent = boundNodes.LowestBoundNodeOfSyntacticParent
Debug.Assert(boundNodeOfSyntacticParent IsNot Nothing)
' Check if boundNode.Syntax is the type-name child of an ObjectCreationExpression or Attribute.
Dim parentSyntax As SyntaxNode = boundNodeOfSyntacticParent.Syntax
If parentSyntax IsNot Nothing AndAlso
lowestBoundNode IsNot Nothing AndAlso
parentSyntax Is lowestBoundNode.Syntax.Parent AndAlso
parentSyntax.Kind = SyntaxKind.Attribute AndAlso
(DirectCast(parentSyntax, AttributeSyntax).Name Is lowestBoundNode.Syntax) Then
Dim unwrappedSymbols = UnwrapAliases(bindingSymbols)
' We must have bound to a single named type
If unwrappedSymbols.Length = 1 AndAlso TypeOf unwrappedSymbols(0) Is TypeSymbol Then
Dim typeSymbol As TypeSymbol = DirectCast(unwrappedSymbols(0), TypeSymbol)
Dim namedTypeSymbol As NamedTypeSymbol = TryCast(typeSymbol, NamedTypeSymbol)
' Figure out which constructor was selected.
Select Case boundNodeOfSyntacticParent.Kind
Case BoundKind.Attribute
Dim boundAttribute As BoundAttribute = DirectCast(boundNodeOfSyntacticParent, BoundAttribute)
Debug.Assert(resultKind <> LookupResultKind.Good OrElse TypeSymbol.Equals(namedTypeSymbol, boundAttribute.Type, TypeCompareKind.ConsiderEverything))
constructor = boundAttribute.Constructor
resultKind = LookupResult.WorseResultKind(resultKind, boundAttribute.ResultKind)
Case BoundKind.BadExpression
' Note that namedTypeSymbol might be null here; e.g., a type parameter.
Dim boundBadExpression As BoundBadExpression = DirectCast(boundNodeOfSyntacticParent, BoundBadExpression)
resultKind = LookupResult.WorseResultKind(resultKind, boundBadExpression.ResultKind)
Case Else
Throw ExceptionUtilities.UnexpectedValue(boundNodeOfSyntacticParent.Kind)
End Select
AdjustSymbolsForObjectCreation(lowestBoundNode, namedTypeSymbol, constructor, binderOpt, bindingSymbols, memberGroupBuilder, resultKind)
End If
End If
End Sub
Private Sub AdjustSymbolsForObjectCreation(
lowestBoundNode As BoundNode,
namedTypeSymbol As NamedTypeSymbol,
constructor As MethodSymbol,
binderOpt As Binder,
ByRef bindingSymbols As ImmutableArray(Of Symbol),
memberGroupBuilder As ArrayBuilder(Of Symbol),
ByRef resultKind As LookupResultKind)
Debug.Assert(memberGroupBuilder IsNot Nothing)
Debug.Assert(lowestBoundNode IsNot Nothing)
Debug.Assert(binderOpt IsNot Nothing OrElse IsInTree(lowestBoundNode.Syntax))
If namedTypeSymbol IsNot Nothing Then
Debug.Assert(lowestBoundNode.Syntax IsNot Nothing)
' Filter namedTypeSymbol's instance constructors by accessibility.
' If all the instance constructors are inaccessible, we retain
' all the instance constructors.
Dim binder As Binder = If(binderOpt, GetEnclosingBinder(lowestBoundNode.Syntax.SpanStart))
Dim candidateConstructors As ImmutableArray(Of MethodSymbol)
If binder IsNot Nothing Then
Dim interfaceCoClass As NamedTypeSymbol = If(namedTypeSymbol.IsInterface,
TryCast(namedTypeSymbol.CoClassType, NamedTypeSymbol), Nothing)
candidateConstructors = binder.GetAccessibleConstructors(If(interfaceCoClass, namedTypeSymbol), useSiteDiagnostics:=Nothing)
Dim instanceConstructors = namedTypeSymbol.InstanceConstructors
If Not candidateConstructors.Any() AndAlso instanceConstructors.Any() Then
Debug.Assert(resultKind <> LookupResultKind.Good)
candidateConstructors = instanceConstructors
End If
Else
candidateConstructors = ImmutableArray(Of MethodSymbol).Empty
End If
If constructor IsNot Nothing Then
Debug.Assert(candidateConstructors.Contains(constructor))
bindingSymbols = ImmutableArray.Create(Of Symbol)(constructor)
ElseIf candidateConstructors.Length <> 0 Then
bindingSymbols = StaticCast(Of Symbol).From(candidateConstructors)
resultKind = LookupResult.WorseResultKind(resultKind, LookupResultKind.OverloadResolutionFailure)
End If
memberGroupBuilder.AddRange(candidateConstructors)
End If
End Sub
' Gets SymbolInfo for a type or namespace or alias reference or implemented method.
Friend Function GetSymbolInfoForSymbol(
symbol As Symbol,
options As SymbolInfoOptions
) As SymbolInfo
' 1. Determine type, dig through alias if needed.
Dim type = TryCast(UnwrapAlias(symbol), TypeSymbol)
' 2. Determine symbols.
' We never return error symbols in the SemanticInfo.
' Error types carry along other symbols and result kinds in error cases.
' Getting the set of symbols is a bit involved. We use the union of the symbol with
' any symbols from the diagnostics, but error symbols are not included.\
Dim resultKind As LookupResultKind
Dim symbolsBuilder = ArrayBuilder(Of Symbol).GetInstance()
Dim originalErrorSymbol = If(type IsNot Nothing, TryCast(type.OriginalDefinition, ErrorTypeSymbol), Nothing)
If originalErrorSymbol IsNot Nothing Then
' Error case.
resultKind = originalErrorSymbol.ResultKind
If resultKind <> LookupResultKind.Empty Then
symbolsBuilder.AddRange(originalErrorSymbol.CandidateSymbols)
End If
ElseIf symbol.Kind = SymbolKind.Namespace AndAlso DirectCast(symbol, NamespaceSymbol).NamespaceKind = NamespaceKindNamespaceGroup Then
symbolsBuilder.AddRange(DirectCast(symbol, NamespaceSymbol).ConstituentNamespaces)
resultKind = LookupResultKind.Ambiguous
Else
symbolsBuilder.Add(symbol)
resultKind = LookupResultKind.Good
End If
Dim symbols As ImmutableArray(Of Symbol) = RemoveErrorTypesAndDuplicates(symbolsBuilder, options)
symbolsBuilder.Free()
Return SymbolInfoFactory.Create(symbols, resultKind)
End Function
' Gets TypeInfo for a type or namespace or alias reference or implemented method.
Friend Function GetTypeInfoForSymbol(
symbol As Symbol
) As VisualBasicTypeInfo
' 1. Determine type, dig through alias if needed.
Dim type = TryCast(UnwrapAlias(symbol), TypeSymbol)
Return New VisualBasicTypeInfo(type, type, New Conversion(Conversions.Identity))
End Function
' This is used by other binding API's to invoke the right binder API
Friend Overridable Function Bind(binder As Binder, node As SyntaxNode, diagnostics As DiagnosticBag) As BoundNode
Dim expr = TryCast(node, ExpressionSyntax)
If expr IsNot Nothing Then
Return binder.BindNamespaceOrTypeOrExpressionSyntaxForSemanticModel(expr, diagnostics)
Else
Dim statement = TryCast(node, StatementSyntax)
If statement IsNot Nothing Then
Return binder.BindStatement(statement, diagnostics)
End If
End If
Return Nothing
End Function
''' <summary>
''' Gets the available named symbols in the context of the specified location And optional container. Only
''' symbols that are accessible And visible from the given location are returned.
''' </summary>
''' <param name="position">The character position for determining the enclosing declaration scope And
''' accessibility.</param>
''' <param name="container">The container to search for symbols within. If null then the enclosing declaration
''' scope around position Is used.</param>
''' <param name="name">The name of the symbol to find. If null Is specified then symbols
''' with any names are returned.</param>
''' <param name="includeReducedExtensionMethods">Consider (reduced) extension methods.</param>
''' <returns>A list of symbols that were found. If no symbols were found, an empty list Is returned.</returns>
''' <remarks>
''' The "position" Is used to determine what variables are visible And accessible. Even if "container" Is
''' specified, the "position" location Is significant for determining which members of "containing" are
''' accessible.
'''
''' Labels are Not considered (see <see cref="LookupLabels"/>).
'''
''' Non-reduced extension methods are considered regardless of the value of <paramref name="includeReducedExtensionMethods"/>.
''' </remarks>
Public Shadows Function LookupSymbols(
position As Integer,
Optional container As INamespaceOrTypeSymbol = Nothing,
Optional name As String = Nothing,
Optional includeReducedExtensionMethods As Boolean = False
) As ImmutableArray(Of ISymbol)
Dim options = If(includeReducedExtensionMethods, LookupOptions.Default, LookupOptions.IgnoreExtensionMethods)
Dim result = LookupSymbolsInternal(position, ToLanguageSpecific(container), name, options, useBaseReferenceAccessibility:=False)
#If DEBUG Then
For Each item In result
Debug.Assert(item.Kind <> SymbolKind.Namespace OrElse DirectCast(item, NamespaceSymbol).NamespaceKind <> NamespaceKindNamespaceGroup)
Next
#End If
Return StaticCast(Of ISymbol).From(result)
End Function
''' <summary>
''' Gets the available base type members in the context of the specified location. Akin to
''' calling <see cref="LookupSymbols"/> with the container set to the immediate base type of
''' the type in which <paramref name="position"/> occurs. However, the accessibility rules
''' are different: protected members of the base type will be visible.
'''
''' Consider the following example:
'''
''' Public Class Base
''' Protected Sub M()
''' End Sub
''' End Class
'''
''' Public Class Derived : Inherits Base
''' Sub Test(b as Base)
''' b.M() ' Error - cannot access protected member.
''' MyBase.M()
''' End Sub
''' End Class
'''
''' Protected members of an instance of another type are only accessible if the instance is known
''' to be "this" instance (as indicated by the "MyBase" keyword).
''' </summary>
''' <param name="position">The character position for determining the enclosing declaration scope and
''' accessibility.</param>
''' <param name="name">The name of the symbol to find. If null is specified then symbols
''' with any names are returned.</param>
''' <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns>
''' <remarks>
''' The "position" is used to determine what variables are visible and accessible.
'''
''' Non-reduced extension methods are considered, but reduced extension methods are not.
''' </remarks>
Public Shadows Function LookupBaseMembers(
position As Integer,
Optional name As String = Nothing
) As ImmutableArray(Of ISymbol)
Dim result = LookupSymbolsInternal(position, Nothing, name, LookupOptions.Default, useBaseReferenceAccessibility:=True)
#If DEBUG Then
For Each item In result
Debug.Assert(item.Kind <> SymbolKind.Namespace)
Next
#End If
Return StaticCast(Of ISymbol).From(result)
End Function
''' <summary>
''' Gets the available named static member symbols in the context of the specified location And optional container.
''' Only members that are accessible And visible from the given location are returned.
'''
''' Non-reduced extension methods are considered, since they are static methods.
''' </summary>
''' <param name="position">The character position for determining the enclosing declaration scope And
''' accessibility.</param>
''' <param name="container">The container to search for symbols within. If null then the enclosing declaration
''' scope around position Is used.</param>
''' <param name="name">The name of the symbol to find. If null Is specified then symbols
''' with any names are returned.</param>
''' <returns>A list of symbols that were found. If no symbols were found, an empty list Is returned.</returns>
''' <remarks>
''' The "position" Is used to determine what variables are visible And accessible. Even if "container" Is
''' specified, the "position" location Is significant for determining which members of "containing" are
''' accessible.
''' </remarks>
Public Shadows Function LookupStaticMembers(
position As Integer,
Optional container As INamespaceOrTypeSymbol = Nothing,
Optional name As String = Nothing
) As ImmutableArray(Of ISymbol)
Dim result = LookupSymbolsInternal(position, ToLanguageSpecific(container), name, LookupOptions.MustNotBeInstance Or LookupOptions.IgnoreExtensionMethods, useBaseReferenceAccessibility:=False)
#If DEBUG Then
For Each item In result
Debug.Assert(item.Kind <> SymbolKind.Namespace OrElse DirectCast(item, NamespaceSymbol).NamespaceKind <> NamespaceKindNamespaceGroup)
Next
#End If
Return StaticCast(Of ISymbol).From(result)
End Function
''' <summary>
''' Gets the available named namespace And type symbols in the context of the specified location And optional container.
''' Only members that are accessible And visible from the given location are returned.
''' </summary>
''' <param name="position">The character position for determining the enclosing declaration scope And
''' accessibility.</param>
''' <param name="container">The container to search for symbols within. If null then the enclosing declaration
''' scope around position Is used.</param>
''' <param name="name">The name of the symbol to find. If null Is specified then symbols
''' with any names are returned.</param>
''' <returns>A list of symbols that were found. If no symbols were found, an empty list Is returned.</returns>
''' <remarks>
''' The "position" Is used to determine what variables are visible And accessible. Even if "container" Is
''' specified, the "position" location Is significant for determining which members of "containing" are
''' accessible.
'''
''' Does Not return INamespaceOrTypeSymbol, because there could be aliases.
''' </remarks>
Public Shadows Function LookupNamespacesAndTypes(
position As Integer,
Optional container As INamespaceOrTypeSymbol = Nothing,
Optional name As String = Nothing
) As ImmutableArray(Of ISymbol)
Dim result = LookupSymbolsInternal(position, ToLanguageSpecific(container), name, LookupOptions.NamespacesOrTypesOnly, useBaseReferenceAccessibility:=False)
#If DEBUG Then
For Each item In result
Debug.Assert(item.Kind <> SymbolKind.Namespace OrElse DirectCast(item, NamespaceSymbol).NamespaceKind <> NamespaceKindNamespaceGroup)
Next
#End If
Return StaticCast(Of ISymbol).From(result)
End Function
''' <summary>
''' Gets the available named label symbols in the context of the specified location And optional container.
''' Only members that are accessible And visible from the given location are returned.
''' </summary>
''' <param name="position">The character position for determining the enclosing declaration scope And
''' accessibility.</param>
''' <param name="name">The name of the symbol to find. If null Is specified then symbols
''' with any names are returned.</param>
''' <returns>A list of symbols that were found. If no symbols were found, an empty list Is returned.</returns>
''' <remarks>
''' The "position" Is used to determine what variables are visible And accessible. Even if "container" Is
''' specified, the "position" location Is significant for determining which members of "containing" are
''' accessible.
''' </remarks>
Public Shadows Function LookupLabels(
position As Integer,
Optional name As String = Nothing
) As ImmutableArray(Of ISymbol)
Dim result = LookupSymbolsInternal(position, container:=Nothing, name:=name, options:=LookupOptions.LabelsOnly, useBaseReferenceAccessibility:=False)
#If DEBUG Then
For Each item In result
Debug.Assert(item.Kind <> SymbolKind.Namespace)
Next
#End If
Return StaticCast(Of ISymbol).From(result)
End Function
''' <summary>
''' Gets the available named symbols in the context of the specified location and optional
''' container. Only symbols that are accessible and visible from the given location are
''' returned.
''' </summary>
''' <param name="position">The character position for determining the enclosing declaration
''' scope and accessibility.</param>
''' <param name="container">The container to search for symbols within. If null then the
''' enclosing declaration scope around position is used.</param>
''' <param name="name">The name of the symbol to find. If null is specified then symbols
''' with any names are returned.</param>
''' <param name="options">Additional options that affect the lookup process.</param>
''' <param name="useBaseReferenceAccessibility">Ignore 'throughType' in accessibility checking.
''' Used in checking accessibility of symbols accessed via 'MyBase' or 'base'.</param>
''' <returns>A list of symbols that were found. If no symbols were found, an empty list is
''' returned.</returns>
''' <remarks>
''' The "position" is used to determine what variables are visible and accessible. Even if
''' "container" is specified, the "position" location is significant for determining which
''' members of "containing" are accessible.
'''
''' Locations are character locations, just as used as the Syntax APIs such as FindToken, or
''' returned from the Span property on tokens and syntax node.
'''
''' The text of the program is divided into scopes, which nest but don't otherwise
''' intersect. When doing an operation such as LookupSymbols, the code first determines the
''' smallest scope containing the position, and from there all containing scopes.
'''
''' Scopes that span an entire block statement start at the beginning of the first token of
''' the block header, and end immediately before the statement terminator token following
''' the end statement of the block. If the end statement of the block is missing, it ends
''' immediately before the next token. Examples of these include members and type parameters
''' of a type, type parameters of a method, and variables declared in a For statement.
'''
''' Scopes that span the interior of a block statement start at the statement terminator of
''' the block header statement, and end immediately before the first token of the end
''' statement of the block. If the end statement of the block is missing, it ends
''' immediately before the next statement. Examples of these include local variables, method
''' parameters, and members of a namespace.
'''
''' Scopes of variables declared in a single-line If statement start at the beginning of the
''' "Then" token, and end immediately before the Else token or statement terminator.
'''
''' Scopes of variables declared in the Else part of a single-line If start at the beginning
''' of the "Else" token, and end immediately before the statement terminator.
'''
''' Some specialized binding rules are in place for a single statement, like Imports or
''' Inherits. These specialized binding rules begin at the start of the first token of the
''' statement, and end immediately before the statement terminator of that statement.
'''
''' In all of the above, the "start" means the start of a token without considering leading
''' trivia. In other words, Span.Start, not FullSpan.Start. With the exception of
''' documentation comments, all scopes begin at the start of a token, and end immediately
''' before the start of a token.
'''
''' The scope of the default namespace, and all symbols introduced via Imports statements,
''' is the entire file.
'''
''' Positions within a documentation comment that is correctly attached to a symbol take on
''' the binding scope of that symbol.
''' </remarks>
''' <exception cref="ArgumentException">Throws an argument exception if the passed lookup options are invalid.</exception>
Private Function LookupSymbolsInternal(position As Integer,
container As NamespaceOrTypeSymbol,
name As String,
options As LookupOptions,
useBaseReferenceAccessibility As Boolean) As ImmutableArray(Of Symbol)
Debug.Assert((options And LookupOptions.UseBaseReferenceAccessibility) = 0, "Use the useBaseReferenceAccessibility parameter.")
If useBaseReferenceAccessibility Then
options = options Or LookupOptions.UseBaseReferenceAccessibility
End If
Debug.Assert(options.IsValid())
CheckPosition(position)
Dim binder = Me.GetEnclosingBinder(position)
If binder Is Nothing Then
Return ImmutableArray(Of Symbol).Empty
End If
If useBaseReferenceAccessibility Then
Debug.Assert(container Is Nothing)
Dim containingType = binder.ContainingType
Dim baseType = If(containingType Is Nothing, Nothing, containingType.BaseTypeNoUseSiteDiagnostics)
If baseType Is Nothing Then
Throw New ArgumentException(NameOf(position),
"Not a valid position for a call to LookupBaseMembers (must be in a type with a base type)")
End If
container = baseType
End If
If name Is Nothing Then
' If they didn't provide a name, then look up all names and associated arities
' and find all the corresponding symbols.
Dim info = LookupSymbolsInfo.GetInstance()
Me.AddLookupSymbolsInfo(position, info, container, options)
Dim results = ArrayBuilder(Of Symbol).GetInstance(info.Count)
For Each foundName In info.Names
AppendSymbolsWithName(results, foundName, binder, container, options, info)
Next
info.Free()
Dim sealedResults = results.ToImmutableAndFree()
Dim builder As ArrayBuilder(Of Symbol) = Nothing
Dim pos = 0
For Each result In sealedResults
' Special case: we want to see constructors, even though they can't be referenced by name.
If result.CanBeReferencedByName OrElse
(result.Kind = SymbolKind.Method AndAlso DirectCast(result, MethodSymbol).MethodKind = MethodKind.Constructor) Then
If builder IsNot Nothing Then
builder.Add(result)
End If
ElseIf builder Is Nothing Then
builder = ArrayBuilder(Of Symbol).GetInstance()
builder.AddRange(sealedResults, pos)
End If
pos = pos + 1
Next
Return If(builder Is Nothing, sealedResults, builder.ToImmutableAndFree())
Else
' They provided a name. Find all the arities for that name, and then look all of those up.
Dim info = LookupSymbolsInfo.GetInstance()
info.FilterName = name
Me.AddLookupSymbolsInfo(position, info, container, options)
Dim results = ArrayBuilder(Of Symbol).GetInstance(info.Count)
AppendSymbolsWithName(results, name, binder, container, options, info)
info.Free()
' If the name was specified, we don't have to do additional filtering - this is what they asked for.
Return results.ToImmutableAndFree()
End If
End Function
Private Sub AppendSymbolsWithName(results As ArrayBuilder(Of Symbol), name As String, binder As Binder, container As NamespaceOrTypeSymbol, options As LookupOptions, info As LookupSymbolsInfo)
Dim arities As LookupSymbolsInfo.IArityEnumerable = Nothing
Dim uniqueSymbol As Symbol = Nothing
If info.TryGetAritiesAndUniqueSymbol(name, arities, uniqueSymbol) Then
If uniqueSymbol IsNot Nothing Then
' This name mapped to something unique. We don't need to proceed
' with a costly lookup. Just add it straight to the results.
results.Add(uniqueSymbol)
Else
' The name maps to multiple symbols. Actually do a real lookup so
' that we will properly figure out hiding and whatnot.
If arities IsNot Nothing Then
Me.LookupSymbols(binder, container, name, arities, options, results)
Else
' If there's no unique symbol, then there won't have been a non-zero arity
Me.LookupSymbols(binder, container, name, 0, options, results)
End If
End If
End If
End Sub
' Lookup symbol using a given binding. Options has already had the ByLocation and AllNames
' flags taken off appropriately.
Private Shadows Sub LookupSymbols(binder As Binder,
container As NamespaceOrTypeSymbol,
name As String,
arities As LookupSymbolsInfo.IArityEnumerable,
options As LookupOptions,
results As ArrayBuilder(Of Symbol))
Debug.Assert(results IsNot Nothing)
Dim uniqueSymbols = PooledHashSet(Of Symbol).GetInstance()
Dim tempResults = ArrayBuilder(Of Symbol).GetInstance(arities.Count)
For Each knownArity In arities
' TODO: What happens here if options has LookupOptions.AllMethodsOfAnyArity bit set?
' It looks like we will be dealing with a lot of duplicate methods. Should we optimize this
' by clearing the bit?
Me.LookupSymbols(binder, container, name, knownArity, options, tempResults)
uniqueSymbols.UnionWith(tempResults)
tempResults.Clear()
Next
tempResults.Free()
results.AddRange(uniqueSymbols)
uniqueSymbols.Free()
End Sub
Private Shadows Sub LookupSymbols(binder As Binder,
container As NamespaceOrTypeSymbol,
name As String,
arity As Integer,
options As LookupOptions,
results As ArrayBuilder(Of Symbol))
If name = WellKnownMemberNames.InstanceConstructorName Then ' intentionally case sensitive; constructors always exactly ".ctor".
' Constructors have very different lookup rules.
LookupInstanceConstructors(binder, container, options, results)
Return
End If
Dim result = LookupResult.GetInstance()
Dim realArity = arity
options = CType(options Or LookupOptions.EagerlyLookupExtensionMethods, LookupOptions)
If options.IsAttributeTypeLookup Then
binder.LookupAttributeType(result, container, name, options, useSiteDiagnostics:=Nothing)
ElseIf container Is Nothing Then
binder.Lookup(result, name, realArity, options, useSiteDiagnostics:=Nothing)
Else
binder.LookupMember(result, container, name, realArity, options, useSiteDiagnostics:=Nothing)
End If
If result.IsGoodOrAmbiguous Then
If result.HasDiagnostic Then
' In the ambiguous symbol case, we have a good symbol with a diagnostics that
' mentions the other symbols. Union everything together with a set to prevent dups.
Dim symbolSet = PooledHashSet(Of Symbol).GetInstance()
Dim symBuilder = ArrayBuilder(Of Symbol).GetInstance()
AddSymbolsFromDiagnosticInfo(symBuilder, result.Diagnostic)
symbolSet.UnionWith(symBuilder)
symbolSet.UnionWith(result.Symbols)
symBuilder.Free()
results.AddRange(symbolSet)
symbolSet.Free()
ElseIf result.HasSingleSymbol AndAlso result.SingleSymbol.Kind = SymbolKind.Namespace AndAlso
DirectCast(result.SingleSymbol, NamespaceSymbol).NamespaceKind = NamespaceKindNamespaceGroup Then
results.AddRange(DirectCast(result.SingleSymbol, NamespaceSymbol).ConstituentNamespaces)
Else
results.AddRange(result.Symbols)
End If
End If
result.Free()
End Sub
' Do a lookup of instance constructors, taking LookupOptions into account.
Private Sub LookupInstanceConstructors(
binder As Binder,
container As NamespaceOrTypeSymbol,
options As LookupOptions,
results As ArrayBuilder(Of Symbol)
)
Debug.Assert(results IsNot Nothing)
Dim constructors As ImmutableArray(Of MethodSymbol) = ImmutableArray(Of MethodSymbol).Empty
Dim type As NamedTypeSymbol = TryCast(container, NamedTypeSymbol)
If type IsNot Nothing AndAlso
(options And (LookupOptions.LabelsOnly Or LookupOptions.NamespacesOrTypesOnly Or LookupOptions.MustNotBeInstance)) = 0 Then
If (options And LookupOptions.IgnoreAccessibility) <> 0 Then
constructors = type.InstanceConstructors
Else
constructors = binder.GetAccessibleConstructors(type, useSiteDiagnostics:=Nothing)
End If
End If
results.AddRange(constructors)
End Sub
''' <summary>
''' Gets the names of the available named symbols in the context of the specified location
''' and optional container. Only symbols that are accessible and visible from the given
''' location are returned.
''' </summary>
''' <param name="position">A character position used to identify a declaration scope and
''' accessibility. This character position must be within the FullSpan of the Root syntax
''' node in this SemanticModel.
''' </param>
''' <param name="container">The container to search for symbols within. If null then the
''' enclosing declaration scope around position is used.</param>
''' <param name="options">Additional options that affect the lookup process.</param>
''' <remarks>
''' The "position" is used to determine what variables are visible and accessible. Even if
''' "container" is specified, the "position" location is significant for determining which
''' members of "containing" are accessible.
''' </remarks>
Private Sub AddLookupSymbolsInfo(position As Integer,
info As LookupSymbolsInfo,
Optional container As NamespaceOrTypeSymbol = Nothing,
Optional options As LookupOptions = LookupOptions.Default)
CheckPosition(position)
Dim binder = Me.GetEnclosingBinder(position)
If binder IsNot Nothing Then
If container Is Nothing Then
binder.AddLookupSymbolsInfo(info, options)
Else
binder.AddMemberLookupSymbolsInfo(info, container, options)
End If
End If
End Sub
''' <summary>
''' Determines if the symbol is accessible from the specified location.
''' </summary>
''' <param name="position">A character position used to identify a declaration scope and
''' accessibility. This character position must be within the FullSpan of the Root syntax
''' node in this SemanticModel.
''' </param>
''' <param name="symbol">The symbol that we are checking to see if it accessible.</param>
''' <returns>
''' True if "symbol is accessible, false otherwise.</returns>
''' <remarks>
''' This method only checks accessibility from the point of view of the accessibility
''' modifiers on symbol and its containing types. Even if true is returned, the given symbol
''' may not be able to be referenced for other reasons, such as name hiding.
''' </remarks>
Public Shadows Function IsAccessible(position As Integer, symbol As ISymbol) As Boolean
CheckPosition(position)
If symbol Is Nothing Then
Throw New ArgumentNullException(NameOf(symbol))
End If
Dim vbsymbol = symbol.EnsureVbSymbolOrNothing(Of Symbol)(NameOf(symbol))
Dim binder = Me.GetEnclosingBinder(position)
If binder IsNot Nothing Then
Return binder.IsAccessible(vbsymbol, Nothing)
End If
Return False
End Function
''' <summary>
''' Analyze control-flow within a part of a method body.
''' </summary>
''' <param name="firstStatement">The first statement to be included in the analysis.</param>
''' <param name="lastStatement">The last statement to be included in the analysis.</param>
''' <returns>An object that can be used to obtain the result of the control flow analysis.</returns>
''' <exception cref="ArgumentException">The two statements are not contained within the same statement list.</exception>
Public Overridable Shadows Function AnalyzeControlFlow(firstStatement As StatementSyntax, lastStatement As StatementSyntax) As ControlFlowAnalysis
Throw New NotSupportedException()
End Function
''' <summary>
''' Analyze control-flow within a part of a method body.
''' </summary>
''' <param name="statement">The statement to be included in the analysis.</param>
''' <returns>An object that can be used to obtain the result of the control flow analysis.</returns>
Public Overridable Shadows Function AnalyzeControlFlow(statement As StatementSyntax) As ControlFlowAnalysis
Return AnalyzeControlFlow(statement, statement)
End Function
''' <summary>
''' Analyze data-flow within an expression.
''' </summary>
''' <param name="expression">The expression within the associated SyntaxTree to analyze.</param>
''' <returns>An object that can be used to obtain the result of the data flow analysis.</returns>
Public Overridable Shadows Function AnalyzeDataFlow(expression As ExpressionSyntax) As DataFlowAnalysis
Throw New NotSupportedException()
End Function
''' <summary>
''' Analyze data-flow within a set of contiguous statements.
''' </summary>
''' <param name="firstStatement">The first statement to be included in the analysis.</param>
''' <param name="lastStatement">The last statement to be included in the analysis.</param>
''' <returns>An object that can be used to obtain the result of the data flow analysis.</returns>
''' <exception cref="ArgumentException">The two statements are not contained within the same statement list.</exception>
Public Overridable Shadows Function AnalyzeDataFlow(firstStatement As StatementSyntax, lastStatement As StatementSyntax) As DataFlowAnalysis
Throw New NotSupportedException()
End Function
''' <summary>
''' Analyze data-flow within a statement.
''' </summary>
''' <param name="statement">The statement to be included in the analysis.</param>
''' <returns>An object that can be used to obtain the result of the data flow analysis.</returns>
Public Overridable Shadows Function AnalyzeDataFlow(statement As StatementSyntax) As DataFlowAnalysis
Return AnalyzeDataFlow(statement, statement)
End Function
''' <summary>
''' Get a SemanticModel object that is associated with a method body that did not appear in this source code.
''' Given <paramref name="position"/> must lie within an existing method body of the Root syntax node for this SemanticModel.
''' Locals and labels declared within this existing method body are not considered to be in scope of the speculated method body.
''' </summary>
''' <param name="position">A character position used to identify a declaration scope and accessibility. This
''' character position must be within the FullSpan of the Root syntax node in this SemanticModel and must be
''' within the FullSpan of a Method body within the Root syntax node.</param>
''' <param name="method">A syntax node that represents a parsed method declaration. This method should not be
''' present in the syntax tree associated with this object, but must have identical signature to the method containing
''' the given <paramref name="position"/> in this SemanticModel.</param>
''' <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic
''' information associated with syntax nodes within <paramref name="method"/>.</param>
''' <returns>Flag indicating whether a speculative semantic model was created.</returns>
''' <exception cref="ArgumentException">Throws this exception if the <paramref name="method"/> node is contained any SyntaxTree in the current Compilation.</exception>
''' <exception cref="ArgumentNullException">Throws this exception if <paramref name="method"/> is null.</exception>
''' <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="IsSpeculativeSemanticModel"/> is True.
''' Chaining of speculative semantic model is not supported.</exception>
Public Function TryGetSpeculativeSemanticModelForMethodBody(position As Integer, method As MethodBlockBaseSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
CheckPosition(position)
CheckModelAndSyntaxNodeToSpeculate(method)
Return TryGetSpeculativeSemanticModelForMethodBodyCore(DirectCast(Me, SyntaxTreeSemanticModel), position, method, speculativeModel)
End Function
Friend MustOverride Function TryGetSpeculativeSemanticModelForMethodBodyCore(parentModel As SyntaxTreeSemanticModel, position As Integer, method As MethodBlockBaseSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
''' <summary>
''' Get a SemanticModel object that is associated with a range argument syntax that did not appear in
''' this source code. This can be used to get detailed semantic information about sub-parts
''' of this node that did not appear in source code.
''' </summary>
''' <param name="position">A character position used to identify a declaration scope and accessibility. This
''' character position must be within the FullSpan of the Root syntax node in this SemanticModel.
''' </param>
''' <param name="rangeArgument">A syntax node that represents a parsed RangeArgumentSyntax node. This node should not be
''' present in the syntax tree associated with this object.</param>
''' <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic
''' information associated with syntax nodes within <paramref name="rangeArgument"/>.</param>
''' <returns>Flag indicating whether a speculative semantic model was created.</returns>
''' <exception cref="ArgumentException">Throws this exception if the <paramref name="rangeArgument"/> node is contained any SyntaxTree in the current Compilation.</exception>
''' <exception cref="ArgumentNullException">Throws this exception if <paramref name="rangeArgument"/> is null.</exception>
''' <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="IsSpeculativeSemanticModel"/> is True.
''' Chaining of speculative semantic model is not supported.</exception>
Public Function TryGetSpeculativeSemanticModel(position As Integer, rangeArgument As RangeArgumentSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
CheckPosition(position)
CheckModelAndSyntaxNodeToSpeculate(rangeArgument)
Return TryGetSpeculativeSemanticModelCore(DirectCast(Me, SyntaxTreeSemanticModel), position, rangeArgument, speculativeModel)
End Function
Friend MustOverride Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, rangeArgument As RangeArgumentSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
''' <summary>
''' Get a SemanticModel object that is associated with an executable statement that did not appear in
''' this source code. This can be used to get detailed semantic information about sub-parts
''' of a statement that did not appear in source code.
''' </summary>
''' <param name="position">A character position used to identify a declaration scope and accessibility. This
''' character position must be within the FullSpan of the Root syntax node in this SemanticModel.</param>
''' <param name="statement">A syntax node that represents a parsed statement. This statement should not be
''' present in the syntax tree associated with this object.</param>
''' <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic
''' information associated with syntax nodes within <paramref name="statement"/>.</param>
''' <returns>Flag indicating whether a speculative semantic model was created.</returns>
''' <exception cref="ArgumentException">Throws this exception if the <paramref name="statement"/> node is contained any SyntaxTree in the current Compilation.</exception>
''' <exception cref="ArgumentNullException">Throws this exception if <paramref name="statement"/> is null.</exception>
''' <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="IsSpeculativeSemanticModel"/> is True.
''' Chaining of speculative semantic model is not supported.</exception>
Public Function TryGetSpeculativeSemanticModel(position As Integer, statement As ExecutableStatementSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
CheckPosition(position)
CheckModelAndSyntaxNodeToSpeculate(statement)
Return TryGetSpeculativeSemanticModelCore(DirectCast(Me, SyntaxTreeSemanticModel), position, statement, speculativeModel)
End Function
Friend MustOverride Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, statement As ExecutableStatementSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
''' <summary>
''' Get a SemanticModel object that is associated with an initializer that did not appear in
''' this source code. This can be used to get detailed semantic information about sub-parts
''' of a field initializer, property initializer or default parameter value that did not appear in source code.
''' </summary>
''' <param name="position">A character position used to identify a declaration scope and accessibility. This
''' character position must be within the FullSpan of the Root syntax node in this SemanticModel.
''' </param>
''' <param name="initializer">A syntax node that represents a parsed initializer. This initializer should not be
''' present in the syntax tree associated with this object.</param>
''' <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic
''' information associated with syntax nodes within <paramref name="initializer"/>.</param>
''' <returns>Flag indicating whether a speculative semantic model was created.</returns>
''' <exception cref="ArgumentException">Throws this exception if the <paramref name="initializer"/> node is contained any SyntaxTree in the current Compilation.</exception>
''' <exception cref="ArgumentNullException">Throws this exception if <paramref name="initializer"/> is null.</exception>
''' <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="IsSpeculativeSemanticModel"/> is True.
''' Chaining of speculative semantic model is not supported.</exception>
Public Function TryGetSpeculativeSemanticModel(position As Integer, initializer As EqualsValueSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
CheckPosition(position)
CheckModelAndSyntaxNodeToSpeculate(initializer)
Return TryGetSpeculativeSemanticModelCore(DirectCast(Me, SyntaxTreeSemanticModel), position, initializer, speculativeModel)
End Function
Friend MustOverride Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, initializer As EqualsValueSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
''' <summary>
''' Get a SemanticModel object that is associated with an attribute that did not appear in
''' this source code. This can be used to get detailed semantic information about sub-parts
''' of an attribute that did not appear in source code.
''' </summary>
''' <param name="position">A character position used to identify a declaration scope and accessibility. This
''' character position must be within the FullSpan of the Root syntax node in this SemanticModel.</param>
''' <param name="attribute">A syntax node that represents a parsed attribute. This attribute should not be
''' present in the syntax tree associated with this object.</param>
''' <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic
''' information associated with syntax nodes within <paramref name="attribute"/>.</param>
''' <returns>Flag indicating whether a speculative semantic model was created.</returns>
''' <exception cref="ArgumentException">Throws this exception if the <paramref name="attribute"/> node is contained any SyntaxTree in the current Compilation.</exception>
''' <exception cref="ArgumentNullException">Throws this exception if <paramref name="attribute"/> is null.</exception>
''' <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="IsSpeculativeSemanticModel"/> is True.
''' Chaining of speculative semantic model is not supported.</exception>
Public Function TryGetSpeculativeSemanticModel(position As Integer, attribute As AttributeSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
CheckPosition(position)
CheckModelAndSyntaxNodeToSpeculate(attribute)
Dim binder As Binder = Me.GetSpeculativeAttributeBinder(position, attribute)
If binder Is Nothing Then
speculativeModel = Nothing
Return False
End If
speculativeModel = AttributeSemanticModel.CreateSpeculative(DirectCast(Me, SyntaxTreeSemanticModel), attribute, binder, position)
Return True
End Function
''' <summary>
''' Get a SemanticModel object that is associated with a type syntax that did not appear in
''' this source code. This can be used to get detailed semantic information about sub-parts
''' of a type syntax that did not appear in source code.
''' </summary>
''' <param name="position">A character position used to identify a declaration scope and accessibility. This
''' character position must be within the FullSpan of the Root syntax node in this SemanticModel.
''' </param>
''' <param name="type">A syntax node that represents a parsed type syntax. This expression should not be
''' present in the syntax tree associated with this object.</param>
''' <param name="bindingOption">Indicates whether to bind the expression as a full expression,
''' or as a type or namespace.</param>
''' <param name="speculativeModel">A SemanticModel object that can be used to inquire about the semantic
''' information associated with syntax nodes within <paramref name="type"/>.</param>
''' <returns>Flag indicating whether a speculative semantic model was created.</returns>
''' <exception cref="ArgumentException">Throws this exception if the <paramref name="type"/> node is contained any SyntaxTree in the current Compilation.</exception>
''' <exception cref="InvalidOperationException">Throws this exception if this model is a speculative semantic model, i.e. <see cref="IsSpeculativeSemanticModel"/> is True.
''' Chaining of speculative semantic model is not supported.</exception>
Public Function TryGetSpeculativeSemanticModel(position As Integer, type As TypeSyntax, <Out> ByRef speculativeModel As SemanticModel, Optional bindingOption As SpeculativeBindingOption = SpeculativeBindingOption.BindAsExpression) As Boolean
CheckPosition(position)
CheckModelAndSyntaxNodeToSpeculate(type)
Return TryGetSpeculativeSemanticModelCore(DirectCast(Me, SyntaxTreeSemanticModel), position, type, bindingOption, speculativeModel)
End Function
Friend MustOverride Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, type As TypeSyntax, bindingOption As SpeculativeBindingOption, <Out> ByRef speculativeModel As SemanticModel) As Boolean
''' <summary>
''' If this is a speculative semantic model, then returns its parent semantic model.
''' Otherwise, returns null.
''' </summary>
Public MustOverride Shadows ReadOnly Property ParentModel As SemanticModel
''' <summary>
''' Determines what type of conversion, if any, would be used if a given expression was
''' converted to a given type.
''' </summary>
''' <param name="expression">An expression which must occur within the syntax tree
''' associated with this object.</param>
''' <param name="destination">The type to attempt conversion to.</param>
''' <returns>Returns a Conversion object that summarizes whether the conversion was
''' possible, and if so, what kind of conversion it was. If no conversion was possible, a
''' Conversion object with a false "Exists " property is returned.</returns>
''' <remarks>To determine the conversion between two types (instead of an expression and a
''' type), use Compilation.ClassifyConversion.</remarks>
Public MustOverride Shadows Function ClassifyConversion(expression As ExpressionSyntax, destination As ITypeSymbol) As Conversion
''' <summary>
''' Determines what type of conversion, if any, would be used if a given expression was
''' converted to a given type.
''' </summary>
''' <param name="position">The character position for determining the enclosing declaration scope and accessibility.</param>
''' <param name="expression">An expression to classify. This expression does not need to be
''' present in the syntax tree associated with this object.</param>
''' <param name="destination">The type to attempt conversion to.</param>
''' <returns>Returns a Conversion object that summarizes whether the conversion was
''' possible, and if so, what kind of conversion it was. If no conversion was possible, a
''' Conversion object with a false "Exists " property is returned.</returns>
''' <remarks>To determine the conversion between two types (instead of an expression and a
''' type), use Compilation.ClassifyConversion.</remarks>
Public Shadows Function ClassifyConversion(position As Integer, expression As ExpressionSyntax, destination As ITypeSymbol) As Conversion
If destination Is Nothing Then
Throw New ArgumentNullException(NameOf(destination))
End If
Dim vbdestination = destination.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(destination))
CheckPosition(position)
Dim binder = Me.GetEnclosingBinder(position)
If binder IsNot Nothing Then
' Add speculative binder to bind speculatively.
binder = SpeculativeBinder.Create(binder)
Dim diagnostics = DiagnosticBag.GetInstance()
Dim bnode = binder.BindValue(expression, diagnostics)
diagnostics.Free()
If bnode IsNot Nothing AndAlso Not vbdestination.IsErrorType() Then
Return New Conversion(Conversions.ClassifyConversion(bnode, vbdestination, binder, Nothing))
End If
End If
Return New Conversion(Nothing) ' NoConversion
End Function
''' <summary>
''' Given a modified identifier that is part of a variable declaration, get the
''' corresponding symbol.
''' </summary>
''' <param name="identifierSyntax">The modified identifier that declares a variable.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overridable Overloads Function GetDeclaredSymbol(identifierSyntax As ModifiedIdentifierSyntax, Optional cancellationToken As CancellationToken = Nothing) As ISymbol
If identifierSyntax Is Nothing Then
Throw New ArgumentNullException(NameOf(identifierSyntax))
End If
If Not IsInTree(identifierSyntax) Then
Throw New ArgumentException(VBResources.IdentifierSyntaxNotWithinSyntaxTree)
End If
Dim binder As Binder = Me.GetEnclosingBinder(identifierSyntax.SpanStart)
Dim blockBinder = TryCast(StripSemanticModelBinder(binder), BlockBaseBinder)
If blockBinder IsNot Nothing Then
' Most of the time, we should be able to find the identifier by name.
Dim lookupResult As LookupResult = LookupResult.GetInstance()
Try
' NB: "binder", not "blockBinder", so that we don't incorrectly mark imports as used.
binder.Lookup(lookupResult, identifierSyntax.Identifier.ValueText, 0, Nothing, useSiteDiagnostics:=Nothing)
If lookupResult.IsGood Then
Dim sym As LocalSymbol = TryCast(lookupResult.Symbols(0), LocalSymbol)
If sym IsNot Nothing AndAlso sym.IdentifierToken = identifierSyntax.Identifier Then
Return sym
End If
End If
Finally
lookupResult.Free()
End Try
' In some error cases, like multiple symbols of the same name in the same scope, we
' need to do a linear search instead.
For Each local In blockBinder.Locals
If local.IdentifierToken = identifierSyntax.Identifier Then
Return local
End If
Next
End If
Return Nothing
End Function
''' <summary>
''' Gets the corresponding symbol for a specified tuple element.
''' </summary>
''' <param name="elementSyntax">A TupleElementSyntax object.</param>
''' <param name="cancellationToken">A cancellation token.</param>
''' <returns>A symbol, for the specified element; otherwise Nothing. </returns>
Public Overloads Function GetDeclaredSymbol(elementSyntax As TupleElementSyntax, Optional cancellationToken As CancellationToken = Nothing) As ISymbol
CheckSyntaxNode(elementSyntax)
Dim tupleTypeSyntax = TryCast(elementSyntax.Parent, TupleTypeSyntax)
If tupleTypeSyntax IsNot Nothing Then
Return TryCast(GetSymbolInfo(tupleTypeSyntax).Symbol, TupleTypeSymbol)?.TupleElements.ElementAtOrDefault(tupleTypeSyntax.Elements.IndexOf(elementSyntax))
End If
Return Nothing
End Function
''' <summary>
''' Given a FieldInitializerSyntax, get the corresponding symbol of anonymous type property.
''' </summary>
''' <param name="fieldInitializerSyntax">The anonymous object creation field initializer syntax.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists or
''' if the field initializer was not part of an anonymous type creation.</returns>
Public Overridable Overloads Function GetDeclaredSymbol(fieldInitializerSyntax As FieldInitializerSyntax, Optional cancellationToken As CancellationToken = Nothing) As IPropertySymbol
If fieldInitializerSyntax Is Nothing Then
Throw New ArgumentNullException(NameOf(fieldInitializerSyntax))
End If
If Not IsInTree(fieldInitializerSyntax) Then
Throw New ArgumentException(VBResources.FieldInitializerSyntaxNotWithinSyntaxTree)
End If
Return Nothing
End Function
''' <summary>
''' Given an AnonymousObjectCreationExpressionSyntax, get the corresponding symbol of anonymous type.
''' </summary>
''' <param name="anonymousObjectCreationExpressionSyntax">The anonymous object creation syntax.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overridable Overloads Function GetDeclaredSymbol(anonymousObjectCreationExpressionSyntax As AnonymousObjectCreationExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As INamedTypeSymbol
If anonymousObjectCreationExpressionSyntax Is Nothing Then
Throw New ArgumentNullException(NameOf(anonymousObjectCreationExpressionSyntax))
End If
If Not IsInTree(anonymousObjectCreationExpressionSyntax) Then
Throw New ArgumentException(VBResources.AnonymousObjectCreationExpressionSyntaxNotWithinTree)
End If
Return Nothing
End Function
''' <summary>
''' Given an ExpressionRangeVariableSyntax, get the corresponding symbol.
''' </summary>
''' <param name="rangeVariableSyntax">The range variable syntax that declares a variable.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overridable Overloads Function GetDeclaredSymbol(rangeVariableSyntax As ExpressionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As IRangeVariableSymbol
If rangeVariableSyntax Is Nothing Then
Throw New ArgumentNullException(NameOf(rangeVariableSyntax))
End If
If Not IsInTree(rangeVariableSyntax) Then
Throw New ArgumentException(VBResources.RangeVariableSyntaxNotWithinSyntaxTree)
End If
Return Nothing
End Function
''' <summary>
''' Given a CollectionRangeVariableSyntax, get the corresponding symbol.
''' </summary>
''' <param name="rangeVariableSyntax">The range variable syntax that declares a variable.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overridable Overloads Function GetDeclaredSymbol(rangeVariableSyntax As CollectionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As IRangeVariableSymbol
If rangeVariableSyntax Is Nothing Then
Throw New ArgumentNullException(NameOf(rangeVariableSyntax))
End If
If Not IsInTree(rangeVariableSyntax) Then
Throw New ArgumentException(VBResources.RangeVariableSyntaxNotWithinSyntaxTree)
End If
Return Nothing
End Function
''' <summary>
''' Given an AggregationRangeVariableSyntax, get the corresponding symbol.
''' </summary>
''' <param name="rangeVariableSyntax">The range variable syntax that declares a variable.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overridable Overloads Function GetDeclaredSymbol(rangeVariableSyntax As AggregationRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As IRangeVariableSymbol
If rangeVariableSyntax Is Nothing Then
Throw New ArgumentNullException(NameOf(rangeVariableSyntax))
End If
If Not IsInTree(rangeVariableSyntax) Then
Throw New ArgumentException(VBResources.RangeVariableSyntaxNotWithinSyntaxTree)
End If
Return Nothing
End Function
''' <summary>
''' Given a label statement, get the corresponding label symbol.
''' </summary>
''' <param name="declarationSyntax">The label statement.</param>
''' <returns>The label symbol, or Nothing if no such symbol exists.</returns>
Public Overridable Overloads Function GetDeclaredSymbol(declarationSyntax As LabelStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As ILabelSymbol
If declarationSyntax Is Nothing Then
Throw New ArgumentNullException(NameOf(declarationSyntax))
End If
If Not IsInTree(declarationSyntax) Then
Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinSyntaxTree)
End If
Dim binder = TryCast(StripSemanticModelBinder(Me.GetEnclosingBinder(declarationSyntax.SpanStart)), BlockBaseBinder)
If binder IsNot Nothing Then
Dim label As LabelSymbol = binder.LookupLabelByNameToken(declarationSyntax.LabelToken)
If label IsNot Nothing Then
Return label
End If
End If
Return Nothing
End Function
''' <summary>
''' Given a declarationSyntax that is part of a enum constant declaration, get the
''' corresponding symbol.
''' </summary>
''' <param name="declarationSyntax">The declarationSyntax that declares a variable.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public MustOverride Overloads Function GetDeclaredSymbol(declarationSyntax As EnumMemberDeclarationSyntax, Optional cancellationToken As CancellationToken = Nothing) As IFieldSymbol
''' <summary>
''' Given a type declaration, get the corresponding type symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a type.</param>
''' <returns>The type symbol that was declared.</returns>
Public MustOverride Overloads Function GetDeclaredSymbol(declarationSyntax As TypeStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As INamedTypeSymbol
''' <summary>
''' Given a type block, get the corresponding type symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a type block.</param>
''' <returns>The type symbol that was declared.</returns>
Public Overloads Function GetDeclaredSymbol(declarationSyntax As TypeBlockSyntax, Optional cancellationToken As CancellationToken = Nothing) As INamedTypeSymbol
Return GetDeclaredSymbol(declarationSyntax.BlockStatement, cancellationToken)
End Function
''' <summary>
''' Given a enum declaration, get the corresponding type symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares an enum.</param>
''' <returns>The type symbol that was declared.</returns>
Public MustOverride Overloads Function GetDeclaredSymbol(declarationSyntax As EnumStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As INamedTypeSymbol
''' <summary>
''' Given a enum block, get the corresponding type symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares an enum block.</param>
''' <returns>The type symbol that was declared.</returns>
Public Overloads Function GetDeclaredSymbol(declarationSyntax As EnumBlockSyntax, Optional cancellationToken As CancellationToken = Nothing) As INamedTypeSymbol
Return GetDeclaredSymbol(declarationSyntax.EnumStatement, cancellationToken)
End Function
''' <summary>
''' Given a namespace declaration, get the corresponding type symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a namespace.</param>
''' <returns>The namespace symbol that was declared.</returns>
Public MustOverride Overloads Function GetDeclaredSymbol(declarationSyntax As NamespaceStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As INamespaceSymbol
''' <summary>
''' Given a namespace block, get the corresponding type symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a namespace block.</param>
''' <returns>The namespace symbol that was declared.</returns>
Public Overloads Function GetDeclaredSymbol(declarationSyntax As NamespaceBlockSyntax, Optional cancellationToken As CancellationToken = Nothing) As INamespaceSymbol
Return GetDeclaredSymbol(declarationSyntax.NamespaceStatement, cancellationToken)
End Function
''' <summary>
''' Given a method, property, or event declaration, get the corresponding symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a method, property, or event.</param>
''' <returns>The method, property, or event symbol that was declared.</returns>
Friend MustOverride Overloads Function GetDeclaredSymbol(declarationSyntax As MethodBaseSyntax, Optional cancellationToken As CancellationToken = Nothing) As ISymbol
''' <summary>
''' Given a parameter declaration, get the corresponding parameter symbol.
''' </summary>
''' <param name="parameter">The syntax node that declares a parameter.</param>
''' <returns>The parameter symbol that was declared.</returns>
Public MustOverride Overloads Function GetDeclaredSymbol(parameter As ParameterSyntax, Optional cancellationToken As CancellationToken = Nothing) As IParameterSymbol
''' <summary>
''' Given a type parameter declaration, get the corresponding type parameter symbol.
''' </summary>
''' <param name="typeParameter">The syntax node that declares a type parameter.</param>
''' <returns>The type parameter symbol that was declared.</returns>
Public MustOverride Overloads Function GetDeclaredSymbol(typeParameter As TypeParameterSyntax, Optional cancellationToken As CancellationToken = Nothing) As ITypeParameterSymbol
''' <summary>
''' Given a delegate statement syntax get the corresponding named type symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a delegate.</param>
''' <returns>The named type that was declared.</returns>
Public Overloads Function GetDeclaredSymbol(declarationSyntax As DelegateStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As NamedTypeSymbol
Return DirectCast(GetDeclaredSymbol(DirectCast(declarationSyntax, MethodBaseSyntax), cancellationToken), NamedTypeSymbol)
End Function
''' <summary>
''' Given a constructor statement syntax get the corresponding method symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a constructor.</param>
''' <returns>The method symbol that was declared.</returns>
Public Overloads Function GetDeclaredSymbol(declarationSyntax As SubNewStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As IMethodSymbol
Return DirectCast(GetDeclaredSymbol(DirectCast(declarationSyntax, MethodBaseSyntax), cancellationToken), MethodSymbol)
End Function
''' <summary>
''' Given a method statement syntax get the corresponding method symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a method.</param>
''' <returns>The method symbol that was declared.</returns>
Public Overloads Function GetDeclaredSymbol(declarationSyntax As MethodStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As IMethodSymbol
Return DirectCast(GetDeclaredSymbol(DirectCast(declarationSyntax, MethodBaseSyntax), cancellationToken), MethodSymbol)
End Function
''' <summary>
''' Given a method statement syntax get the corresponding method symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a method.</param>
''' <returns>The method symbol that was declared.</returns>
Public Overloads Function GetDeclaredSymbol(declarationSyntax As DeclareStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As IMethodSymbol
Return DirectCast(GetDeclaredSymbol(DirectCast(declarationSyntax, MethodBaseSyntax), cancellationToken), MethodSymbol)
End Function
''' <summary>
''' Given a operator statement syntax get the corresponding method symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares an operator.</param>
''' <returns>The method symbol that was declared.</returns>
Public Overloads Function GetDeclaredSymbol(declarationSyntax As OperatorStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As IMethodSymbol
Return DirectCast(GetDeclaredSymbol(DirectCast(declarationSyntax, MethodBaseSyntax), cancellationToken), MethodSymbol)
End Function
''' <summary>
''' Given a method block syntax get the corresponding method, property or event symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares method, property or event.</param>
''' <returns>The method, property or event symbol that was declared.</returns>
Public Overloads Function GetDeclaredSymbol(declarationSyntax As MethodBlockBaseSyntax, Optional cancellationToken As CancellationToken = Nothing) As IMethodSymbol
Return DirectCast(GetDeclaredSymbol(declarationSyntax.BlockStatement, cancellationToken), MethodSymbol)
End Function
''' <summary>
''' Given a property statement syntax get the corresponding property symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a property.</param>
''' <returns>The property symbol that was declared.</returns>
Public Overloads Function GetDeclaredSymbol(declarationSyntax As PropertyStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As IPropertySymbol
Return DirectCast(GetDeclaredSymbol(DirectCast(declarationSyntax, MethodBaseSyntax), cancellationToken), PropertySymbol)
End Function
''' <summary>
''' Given an event statement syntax get the corresponding event symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares an event.</param>
''' <returns>The event symbol that was declared.</returns>
Public Overloads Function GetDeclaredSymbol(declarationSyntax As EventStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As IEventSymbol
Return DirectCast(GetDeclaredSymbol(DirectCast(declarationSyntax, MethodBaseSyntax), cancellationToken), EventSymbol)
End Function
''' <summary>
''' Given a property block syntax get the corresponding property symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares property.</param>
''' <returns>The property symbol that was declared.</returns>
Public Overloads Function GetDeclaredSymbol(declarationSyntax As PropertyBlockSyntax, Optional cancellationToken As CancellationToken = Nothing) As IPropertySymbol
Return GetDeclaredSymbol(declarationSyntax.PropertyStatement, cancellationToken)
End Function
''' <summary>
''' Given a custom event block syntax get the corresponding event symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares the custom event.</param>
''' <returns>The event symbol that was declared.</returns>
Public Overloads Function GetDeclaredSymbol(declarationSyntax As EventBlockSyntax, Optional cancellationToken As CancellationToken = Nothing) As IEventSymbol
Return GetDeclaredSymbol(declarationSyntax.EventStatement, cancellationToken)
End Function
''' <summary>
''' Given a catch statement syntax get the corresponding local symbol.
''' </summary>
''' <param name="declarationSyntax">The catch statement syntax node.</param>
''' <returns>The local symbol that was declared by the Catch statement or Nothing if statement does not declare a local variable.</returns>
Public Overloads Function GetDeclaredSymbol(declarationSyntax As CatchStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As ILocalSymbol
Dim enclosingBinder = StripSemanticModelBinder(Me.GetEnclosingBinder(declarationSyntax.SpanStart))
Dim catchBinder = TryCast(enclosingBinder, CatchBlockBinder)
If catchBinder IsNot Nothing Then
Return catchBinder.Locals.FirstOrDefault
End If
Return Nothing
End Function
''' <summary>
''' Given a property block syntax get the corresponding property symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares property.</param>
''' <returns>The property symbol that was declared.</returns>
Public Overloads Function GetDeclaredSymbol(declarationSyntax As AccessorStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As IMethodSymbol
Return DirectCast(GetDeclaredSymbol(DirectCast(declarationSyntax, MethodBaseSyntax), cancellationToken), MethodSymbol)
End Function
''' <summary>
''' Given an import clause get the corresponding symbol for the import alias that was introduced.
''' </summary>
''' <param name="declarationSyntax">The import statement syntax node.</param>
''' <returns>The alias symbol that was declared or Nothing if no alias symbol was declared.</returns>
Public MustOverride Overloads Function GetDeclaredSymbol(declarationSyntax As SimpleImportsClauseSyntax, Optional cancellationToken As CancellationToken = Nothing) As IAliasSymbol
''' <summary>
''' Given a field declaration syntax, get the corresponding symbols.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares one or more fields.</param>
''' <returns>The field symbols that were declared.</returns>
Friend MustOverride Function GetDeclaredSymbols(declarationSyntax As FieldDeclarationSyntax, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of ISymbol)
''' <summary>
''' Gets bound node summary of the underlying invocation in a case of RaiseEvent
''' </summary>
Friend MustOverride Function GetInvokeSummaryForRaiseEvent(node As RaiseEventStatementSyntax) As BoundNodeSummary
' Get the symbol info of a named argument in an invocation-like expression.
Private Function GetNamedArgumentSymbolInfo(identifierNameSyntax As IdentifierNameSyntax, cancellationToken As CancellationToken) As SymbolInfo
Debug.Assert(SyntaxFacts.IsNamedArgumentName(identifierNameSyntax))
' Argument names do not have bound nodes associated with them, so we cannot use the usual
' GetSemanticInfo mechanism. Instead, we just do the following:
' 1. Find the containing invocation.
' 2. Call GetSemanticInfo on that.
' 3. For each method or indexer in the return semantic info, find the argument
' with the given name (if any).
' 4. Use the ResultKind in that semantic info and any symbols to create the semantic info
' for the named argument.
' 5. Type is always null, as is constant value.
Dim argumentName As String = identifierNameSyntax.Identifier.ValueText
If argumentName.Length = 0 Then
Return SymbolInfo.None
End If
' RaiseEvent Invocation(SimpleArgument(((Identifier):=)(Expression))
' check for RaiseEvent here, it is not an expression.
If identifierNameSyntax.Parent.Parent.Parent.Parent.Kind = SyntaxKind.RaiseEventStatement Then
Dim asRaiseEvent = DirectCast(identifierNameSyntax.Parent.Parent.Parent.Parent, RaiseEventStatementSyntax)
Return GetNamedArgumentSymbolInfoInRaiseEvent(argumentName, asRaiseEvent)
End If
' Invocation(SimpleArgument(((Identifier):=)(Expression))
Dim containingInvocation = DirectCast(identifierNameSyntax.Parent.Parent.Parent.Parent, ExpressionSyntax)
Dim containingInvocationInfo As SymbolInfo = GetExpressionSymbolInfo(containingInvocation, SymbolInfoOptions.PreferConstructorsToType Or SymbolInfoOptions.ResolveAliases, cancellationToken)
Return FindNameParameterInfo(containingInvocationInfo.GetAllSymbols().Cast(Of Symbol).ToImmutableArray(),
argumentName,
containingInvocationInfo.CandidateReason)
End Function
''' <summary>
''' RaiseEvent situation is very special:
''' 1) Unlike other syntaxes that take named arguments, RaiseEvent is a statement.
''' 2) RaiseEvent is essentially a wrapper around underlying call to the event rising method.
''' Note that while event itself may have named parameters in its syntax, their names could be irrelevant
''' For the purpose of fetching named parameters, it is the target of the call that we are interested in.
'''
''' === Example:
'''
''' Interface I1
''' Event E(qwer As Integer)
''' End Interface
'''
''' Class cls1 : Implements I1
''' Event E3(bar As Integer) Implements I1.E ' "bar" means nothing here. Only type matters.
'''
''' Sub moo()
''' RaiseEvent E3(qwer:=123) ' qwer binds to parameter on I1.EEventhandler.invoke(goo)
''' End Sub
'''End Class
'''
'''
''' </summary>
Private Function GetNamedArgumentSymbolInfoInRaiseEvent(argumentName As String,
containingRaiseEvent As RaiseEventStatementSyntax) As SymbolInfo
Dim summary = GetInvokeSummaryForRaiseEvent(containingRaiseEvent)
' Determine the symbols, resultKind, and member group.
Dim resultKind As LookupResultKind = LookupResultKind.Empty
Dim memberGroup As ImmutableArray(Of Symbol) = Nothing
Dim containingInvocationInfosymbols As ImmutableArray(Of Symbol) = GetSemanticSymbols(summary,
Nothing,
SymbolInfoOptions.PreferConstructorsToType Or SymbolInfoOptions.ResolveAliases,
resultKind,
memberGroup)
Return FindNameParameterInfo(containingInvocationInfosymbols,
argumentName,
If(resultKind = LookupResultKind.Good, CandidateReason.None, resultKind.ToCandidateReason()))
End Function
Private Function FindNameParameterInfo(invocationInfosymbols As ImmutableArray(Of Symbol),
arGumentName As String,
reason As CandidateReason) As SymbolInfo
Dim symbols As ArrayBuilder(Of Symbol) = ArrayBuilder(Of Symbol).GetInstance()
For Each invocationSym In invocationInfosymbols
Dim param As ParameterSymbol = FindNamedParameter(invocationSym, arGumentName)
If param IsNot Nothing Then
symbols.Add(param)
End If
Next
If symbols.Count = 0 Then
symbols.Free()
Return SymbolInfo.None
Else
Return SymbolInfoFactory.Create(StaticCast(Of ISymbol).From(symbols.ToImmutableAndFree()), reason)
End If
End Function
' Find the first parameter, if any, on method or property symbol named "argumentName"
Private Function FindNamedParameter(symbol As Symbol, argumentName As String) As ParameterSymbol
Dim params As ImmutableArray(Of ParameterSymbol)
If symbol.Kind = SymbolKind.Method Then
params = DirectCast(symbol, MethodSymbol).Parameters
ElseIf symbol.Kind = SymbolKind.Property Then
params = DirectCast(symbol, PropertySymbol).Parameters
Else
Return Nothing
End If
For Each param In params
If CaseInsensitiveComparison.Equals(param.Name, argumentName) Then
Return param
End If
Next
Return Nothing
End Function
''' <summary>
''' The SyntaxTree that is bound
''' </summary>
Public MustOverride Shadows ReadOnly Property SyntaxTree As SyntaxTree
''' <summary>
''' Gets the semantic information of a for each statement.
''' </summary>
''' <param name="node">The for each syntax node.</param>
Public Shadows Function GetForEachStatementInfo(node As ForEachStatementSyntax) As ForEachStatementInfo
If node.Parent IsNot Nothing AndAlso node.Parent.Kind = SyntaxKind.ForEachBlock Then
Return GetForEachStatementInfoWorker(DirectCast(node.Parent, ForEachBlockSyntax))
End If
Return Nothing
End Function
''' <summary>
''' Gets the semantic information of a for each statement.
''' </summary>
''' <param name="node">The for block syntax node.</param>
Public Shadows Function GetForEachStatementInfo(node As ForEachBlockSyntax) As ForEachStatementInfo
If node.Kind = SyntaxKind.ForEachBlock Then
Return GetForEachStatementInfoWorker(node)
End If
Return Nothing
End Function
''' <summary>
''' Gets the semantic information of a for each statement.
''' </summary>
''' <param name="node">The for each syntax node.</param>
Friend MustOverride Function GetForEachStatementInfoWorker(node As ForEachBlockSyntax) As ForEachStatementInfo
''' <summary>
''' Gets the semantic information of an Await expression.
''' </summary>
Public Function GetAwaitExpressionInfo(awaitExpression As AwaitExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As AwaitExpressionInfo
CheckSyntaxNode(awaitExpression)
If CanGetSemanticInfo(awaitExpression) Then
Return GetAwaitExpressionInfoWorker(awaitExpression, cancellationToken)
Else
Return Nothing
End If
End Function
Friend MustOverride Function GetAwaitExpressionInfoWorker(awaitExpression As AwaitExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As AwaitExpressionInfo
''' <summary>
''' If the given node is within a preprocessing directive, gets the preprocessing symbol info for it.
''' </summary>
''' <param name="node">Preprocessing symbol identifier node.</param>
Public Shadows Function GetPreprocessingSymbolInfo(node As IdentifierNameSyntax) As VisualBasicPreprocessingSymbolInfo
CheckSyntaxNode(node)
If SyntaxFacts.IsWithinPreprocessorConditionalExpression(node) Then
Dim symbolInfo As VisualBasicPreprocessingSymbolInfo = node.SyntaxTree.GetPreprocessingSymbolInfo(node)
If symbolInfo.Symbol IsNot Nothing Then
Debug.Assert(CaseInsensitiveComparison.Equals(symbolInfo.Symbol.Name, node.Identifier.ValueText))
Return symbolInfo
End If
Return New VisualBasicPreprocessingSymbolInfo(New PreprocessingSymbol(node.Identifier.ValueText), constantValueOpt:=Nothing, isDefined:=False)
End If
Return VisualBasicPreprocessingSymbolInfo.None
End Function
''' <summary>
''' Options to control the internal working of GetSemanticInfoWorker. Not currently exposed
''' to public clients, but could be if desired.
''' </summary>
Friend Enum SymbolInfoOptions
''' <summary>
''' When binding "C" new C(...), return the type C and do not return information about
''' which constructor was bound to. Bind "new C(...)" to get information about which constructor
''' was chosen.
''' </summary>
PreferTypeToConstructors = &H1
''' <summary>
''' When binding "C" new C(...), return the constructor of C that was bound to, if C unambiguously
''' binds to a single type with at least one constructor.
''' </summary>
PreferConstructorsToType = &H2
''' <summary>
''' When binding a name X that was declared with a "using X=OtherTypeOrNamespace", return OtherTypeOrNamespace.
''' </summary>
ResolveAliases = &H4
''' <summary>
''' When binding a name X that was declared with a "using X=OtherTypeOrNamespace", return the alias symbol X.
''' </summary>
PreserveAliases = &H8
' Default options
DefaultOptions = PreferConstructorsToType Or ResolveAliases
End Enum
Friend Sub ValidateSymbolInfoOptions(options As SymbolInfoOptions)
Debug.Assert(((options And SymbolInfoOptions.PreferConstructorsToType) <> 0) <> ((options And SymbolInfoOptions.PreferTypeToConstructors) <> 0), "Options are mutually exclusive")
Debug.Assert(((options And SymbolInfoOptions.ResolveAliases) <> 0) <> ((options And SymbolInfoOptions.PreserveAliases) <> 0), "Options are mutually exclusive")
End Sub
''' <summary>
''' Given a position in the SyntaxTree for this SemanticModel returns the innermost Symbol
''' that the position is considered inside of.
''' </summary>
Public Shadows Function GetEnclosingSymbol(position As Integer, Optional cancellationToken As CancellationToken = Nothing) As ISymbol
CheckPosition(position)
Dim binder = Me.GetEnclosingBinder(position)
Return If(binder Is Nothing, Nothing, binder.ContainingMember)
End Function
''' <summary>
''' Get the state of Option Strict for the code covered by this semantic model.
''' This takes into effect both file-level "Option Strict" statements and the project-level
''' defaults.
''' </summary>
Public ReadOnly Property OptionStrict As VisualBasic.OptionStrict
Get
' Since options never change within a file, we can just use the start location.
Dim binder = Me.GetEnclosingBinder(Root.SpanStart) ' should never return null.
Return binder.OptionStrict
End Get
End Property
''' <summary>
''' Get the state of Option Infer for the code covered by this semantic model.
''' This takes into effect both file-level "Option Infer" statements and the project-level
''' defaults.
''' </summary>
''' <value>True if Option Infer On, False if Option Infer Off.</value>
Public ReadOnly Property OptionInfer As Boolean
Get
' Since options never change within a file, we can just use the start location.
Dim binder = Me.GetEnclosingBinder(Root.SpanStart) ' should never return null.
Return binder.OptionInfer
End Get
End Property
''' <summary>
''' Get the state of Option Explicit for the code covered by this semantic model.
''' This takes into effect both file-level "Option Explicit" statements and the project-level
''' defaults.
''' </summary>
''' <value>True if Option Explicit On, False if Option Explicit Off.</value>
Public ReadOnly Property OptionExplicit As Boolean
Get
' Since options never change within a file, we can just use the start location.
Dim binder = Me.GetEnclosingBinder(Root.SpanStart) ' should never return null.
Return binder.OptionExplicit
End Get
End Property
''' <summary>
''' Get the state of Option Compare for the code covered by this semantic model.
''' This takes into effect both file-level "Option Compare" statements and the project-level
''' defaults.
''' </summary>
''' <value>True if Option Compare Text, False if Option Compare Binary.</value>
Public ReadOnly Property OptionCompareText As Boolean
Get
' Since options never change within a file, we can just use the start location.
Dim binder = Me.GetEnclosingBinder(Root.SpanStart) ' should never return null.
Return binder.OptionCompareText
End Get
End Property
Friend Shared Function StripSemanticModelBinder(binder As Binder) As Binder
If binder Is Nothing OrElse Not binder.IsSemanticModelBinder Then
Return binder
End If
Return If(TypeOf binder Is SemanticModelBinder, binder.ContainingBinder, binder)
End Function
#Region "SemanticModel"
Public NotOverridable Overrides ReadOnly Property Language As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
Protected NotOverridable Overrides ReadOnly Property ParentModelCore As SemanticModel
Get
Return Me.ParentModel
End Get
End Property
Protected NotOverridable Overrides ReadOnly Property SyntaxTreeCore As SyntaxTree
Get
Return Me.SyntaxTree
End Get
End Property
Protected NotOverridable Overrides ReadOnly Property CompilationCore As Compilation
Get
Return Me.Compilation
End Get
End Property
Protected NotOverridable Overrides ReadOnly Property RootCore As SyntaxNode
Get
Return Me.Root
End Get
End Property
Private Function GetSymbolInfoForNode(node As SyntaxNode, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
Dim expressionSyntax = TryCast(node, ExpressionSyntax)
If expressionSyntax IsNot Nothing Then
Return Me.GetSymbolInfo(expressionSyntax, cancellationToken)
End If
Dim attributeSyntax = TryCast(node, AttributeSyntax)
If attributeSyntax IsNot Nothing Then
Return Me.GetSymbolInfo(attributeSyntax, cancellationToken)
End If
Dim clauseSyntax = TryCast(node, QueryClauseSyntax)
If clauseSyntax IsNot Nothing Then
Return Me.GetSymbolInfo(clauseSyntax, cancellationToken)
End If
Dim letVariable = TryCast(node, ExpressionRangeVariableSyntax)
If letVariable IsNot Nothing Then
Return Me.GetSymbolInfo(letVariable, cancellationToken)
End If
Dim ordering = TryCast(node, OrderingSyntax)
If ordering IsNot Nothing Then
Return Me.GetSymbolInfo(ordering, cancellationToken)
End If
Dim [function] = TryCast(node, FunctionAggregationSyntax)
If [function] IsNot Nothing Then
Return Me.GetSymbolInfo([function], cancellationToken)
End If
Dim cref = TryCast(node, CrefReferenceSyntax)
If cref IsNot Nothing Then
Return Me.GetSymbolInfo(cref, cancellationToken)
End If
Return SymbolInfo.None
End Function
Private Function GetTypeInfoForNode(node As SyntaxNode, Optional cancellationToken As CancellationToken = Nothing) As VisualBasicTypeInfo
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
Dim expressionSyntax = TryCast(node, ExpressionSyntax)
If expressionSyntax IsNot Nothing Then
Return Me.GetTypeInfoWorker(expressionSyntax, cancellationToken)
End If
Dim attributeSyntax = TryCast(node, AttributeSyntax)
If attributeSyntax IsNot Nothing Then
Return Me.GetTypeInfoWorker(attributeSyntax, cancellationToken)
End If
Return VisualBasicTypeInfo.None
End Function
Private Function GetMemberGroupForNode(node As SyntaxNode, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of ISymbol)
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
Dim expressionSyntax = TryCast(node, ExpressionSyntax)
If expressionSyntax IsNot Nothing Then
Return Me.GetMemberGroup(expressionSyntax, cancellationToken)
End If
Dim attributeSyntax = TryCast(node, AttributeSyntax)
If attributeSyntax IsNot Nothing Then
Return Me.GetMemberGroup(attributeSyntax, cancellationToken)
End If
Return ImmutableArray(Of ISymbol).Empty
End Function
Protected NotOverridable Overrides Function GetSpeculativeTypeInfoCore(position As Integer, expression As SyntaxNode, bindingOption As SpeculativeBindingOption) As TypeInfo
Return If(TypeOf expression Is ExpressionSyntax,
Me.GetSpeculativeTypeInfo(position, DirectCast(expression, ExpressionSyntax), bindingOption),
Nothing)
End Function
Protected NotOverridable Overrides Function GetSpeculativeSymbolInfoCore(position As Integer, expression As SyntaxNode, bindingOption As SpeculativeBindingOption) As SymbolInfo
Return If(TypeOf expression Is ExpressionSyntax,
GetSpeculativeSymbolInfo(position, DirectCast(expression, ExpressionSyntax), bindingOption),
Nothing)
End Function
Protected NotOverridable Overrides Function GetSpeculativeAliasInfoCore(position As Integer, nameSyntax As SyntaxNode, bindingOption As SpeculativeBindingOption) As IAliasSymbol
Return If(TypeOf nameSyntax Is IdentifierNameSyntax,
GetSpeculativeAliasInfo(position, DirectCast(nameSyntax, IdentifierNameSyntax), bindingOption),
Nothing)
End Function
Protected NotOverridable Overrides Function GetSymbolInfoCore(node As SyntaxNode, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
Return GetSymbolInfoForNode(node, cancellationToken)
End Function
Protected NotOverridable Overrides Function GetTypeInfoCore(node As SyntaxNode, Optional cancellationToken As CancellationToken = Nothing) As TypeInfo
Return GetTypeInfoForNode(node, cancellationToken)
End Function
Protected NotOverridable Overrides Function GetAliasInfoCore(node As SyntaxNode, Optional cancellationToken As CancellationToken = Nothing) As IAliasSymbol
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
Dim nameSyntax = TryCast(node, IdentifierNameSyntax)
If nameSyntax IsNot Nothing Then
Return GetAliasInfo(nameSyntax, cancellationToken)
End If
Return Nothing
End Function
Protected NotOverridable Overrides Function GetPreprocessingSymbolInfoCore(node As SyntaxNode) As PreprocessingSymbolInfo
Dim nameSyntax = TryCast(node, IdentifierNameSyntax)
If nameSyntax IsNot Nothing Then
Return GetPreprocessingSymbolInfo(nameSyntax)
End If
Return Nothing
End Function
Protected NotOverridable Overrides Function GetMemberGroupCore(node As SyntaxNode, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of ISymbol)
Return GetMemberGroupForNode(node, cancellationToken)
End Function
Protected NotOverridable Overrides Function LookupSymbolsCore(position As Integer, container As INamespaceOrTypeSymbol, name As String, includeReducedExtensionMethods As Boolean) As ImmutableArray(Of ISymbol)
Return LookupSymbols(position, ToLanguageSpecific(container), name, includeReducedExtensionMethods)
End Function
Protected NotOverridable Overrides Function LookupBaseMembersCore(position As Integer, name As String) As ImmutableArray(Of ISymbol)
Return LookupBaseMembers(position, name)
End Function
Protected NotOverridable Overrides Function LookupStaticMembersCore(position As Integer, container As INamespaceOrTypeSymbol, name As String) As ImmutableArray(Of ISymbol)
Return LookupStaticMembers(position, ToLanguageSpecific(container), name)
End Function
Protected NotOverridable Overrides Function LookupNamespacesAndTypesCore(position As Integer, container As INamespaceOrTypeSymbol, name As String) As ImmutableArray(Of ISymbol)
Return LookupNamespacesAndTypes(position, ToLanguageSpecific(container), name)
End Function
Protected NotOverridable Overrides Function LookupLabelsCore(position As Integer, name As String) As ImmutableArray(Of ISymbol)
Return LookupLabels(position, name)
End Function
Private Shared Function ToLanguageSpecific(container As INamespaceOrTypeSymbol) As NamespaceOrTypeSymbol
If container Is Nothing Then
Return Nothing
End If
Dim result = TryCast(container, NamespaceOrTypeSymbol)
If result Is Nothing Then
Throw New ArgumentException(VBResources.NotAVbSymbol, NameOf(container))
End If
Return result
End Function
Protected NotOverridable Overrides Function GetDeclaredSymbolCore(declaration As SyntaxNode, Optional cancellationToken As CancellationToken = Nothing) As ISymbol
cancellationToken.ThrowIfCancellationRequested()
Dim node = DirectCast(declaration, VisualBasicSyntaxNode)
Select Case node.Kind
Case SyntaxKind.SimpleImportsClause
Return Me.GetDeclaredSymbol(DirectCast(node, SimpleImportsClauseSyntax), cancellationToken)
Case SyntaxKind.TypedTupleElement,
SyntaxKind.NamedTupleElement
Return Me.GetDeclaredSymbol(DirectCast(node, TupleElementSyntax), cancellationToken)
Case SyntaxKind.ModifiedIdentifier
Return Me.GetDeclaredSymbol(DirectCast(node, ModifiedIdentifierSyntax), cancellationToken)
Case SyntaxKind.EnumMemberDeclaration
Return Me.GetDeclaredSymbol(DirectCast(node, EnumMemberDeclarationSyntax), cancellationToken)
Case SyntaxKind.Parameter
Return Me.GetDeclaredSymbol(DirectCast(node, ParameterSyntax), cancellationToken)
Case SyntaxKind.TypeParameter
Return Me.GetDeclaredSymbol(DirectCast(node, TypeParameterSyntax), cancellationToken)
Case SyntaxKind.LabelStatement
Return Me.GetDeclaredSymbol(DirectCast(node, LabelStatementSyntax), cancellationToken)
Case SyntaxKind.NamespaceStatement
Return Me.GetDeclaredSymbol(DirectCast(node, NamespaceStatementSyntax), cancellationToken)
Case SyntaxKind.ClassStatement, SyntaxKind.StructureStatement, SyntaxKind.InterfaceStatement, SyntaxKind.ModuleStatement
Return Me.GetDeclaredSymbol(DirectCast(node, TypeStatementSyntax), cancellationToken)
Case SyntaxKind.EnumStatement
Return Me.GetDeclaredSymbol(DirectCast(node, EnumStatementSyntax), cancellationToken)
Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement
Return Me.GetDeclaredSymbol(DirectCast(node, DelegateStatementSyntax), cancellationToken)
Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement
Return Me.GetDeclaredSymbol(DirectCast(node, MethodStatementSyntax), cancellationToken)
Case SyntaxKind.PropertyStatement
Return Me.GetDeclaredSymbol(DirectCast(node, PropertyStatementSyntax), cancellationToken)
Case SyntaxKind.EventStatement
Return Me.GetDeclaredSymbol(DirectCast(node, EventStatementSyntax), cancellationToken)
Case SyntaxKind.SubNewStatement
Return Me.GetDeclaredSymbol(DirectCast(node, SubNewStatementSyntax), cancellationToken)
Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement
Return Me.GetDeclaredSymbol(DirectCast(node, AccessorStatementSyntax), cancellationToken)
Case SyntaxKind.OperatorStatement,
SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement
Return Me.GetDeclaredSymbol(DirectCast(node, MethodBaseSyntax), cancellationToken)
Case SyntaxKind.NamespaceBlock
Return Me.GetDeclaredSymbol(DirectCast(node, NamespaceBlockSyntax), cancellationToken)
Case SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock
Return Me.GetDeclaredSymbol(DirectCast(node, TypeBlockSyntax), cancellationToken)
Case SyntaxKind.EnumBlock
Return Me.GetDeclaredSymbol(DirectCast(node, EnumBlockSyntax), cancellationToken)
Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock,
SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock
Return Me.GetDeclaredSymbol(DirectCast(node, MethodBlockBaseSyntax), cancellationToken)
Case SyntaxKind.PropertyBlock
Return Me.GetDeclaredSymbol(DirectCast(node, PropertyBlockSyntax), cancellationToken)
Case SyntaxKind.EventBlock
Return Me.GetDeclaredSymbol(DirectCast(node, EventBlockSyntax), cancellationToken)
Case SyntaxKind.CollectionRangeVariable
Return Me.GetDeclaredSymbol(DirectCast(node, CollectionRangeVariableSyntax), cancellationToken)
Case SyntaxKind.ExpressionRangeVariable
Return Me.GetDeclaredSymbol(DirectCast(node, ExpressionRangeVariableSyntax), cancellationToken)
Case SyntaxKind.AggregationRangeVariable
Return Me.GetDeclaredSymbol(DirectCast(node, AggregationRangeVariableSyntax), cancellationToken)
Case SyntaxKind.CatchStatement
Return Me.GetDeclaredSymbol(DirectCast(node, CatchStatementSyntax), cancellationToken)
Case SyntaxKind.InferredFieldInitializer, SyntaxKind.NamedFieldInitializer
Return Me.GetDeclaredSymbol(DirectCast(node, FieldInitializerSyntax), cancellationToken)
Case SyntaxKind.AnonymousObjectCreationExpression
Return Me.GetDeclaredSymbol(DirectCast(node, AnonymousObjectCreationExpressionSyntax), cancellationToken)
End Select
Dim td = TryCast(node, TypeStatementSyntax)
If td IsNot Nothing Then
Return Me.GetDeclaredSymbol(td, cancellationToken)
End If
Dim md = TryCast(node, MethodBaseSyntax)
If md IsNot Nothing Then
Return Me.GetDeclaredSymbol(md, cancellationToken)
End If
Return Nothing
End Function
Protected NotOverridable Overrides Function GetDeclaredSymbolsCore(declaration As SyntaxNode, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of ISymbol)
cancellationToken.ThrowIfCancellationRequested()
Dim field = TryCast(declaration, FieldDeclarationSyntax)
If field IsNot Nothing Then
Return Me.GetDeclaredSymbols(field, cancellationToken)
End If
Dim symbol = GetDeclaredSymbolCore(declaration, cancellationToken)
If symbol IsNot Nothing Then
Return ImmutableArray.Create(symbol)
End If
Return ImmutableArray.Create(Of ISymbol)()
End Function
Protected NotOverridable Overrides Function AnalyzeDataFlowCore(firstStatement As SyntaxNode, lastStatement As SyntaxNode) As DataFlowAnalysis
Return Me.AnalyzeDataFlow(SafeCastArgument(Of StatementSyntax)(firstStatement, NameOf(firstStatement)),
SafeCastArgument(Of StatementSyntax)(lastStatement, NameOf(lastStatement)))
End Function
Protected NotOverridable Overrides Function AnalyzeDataFlowCore(statementOrExpression As SyntaxNode) As DataFlowAnalysis
If statementOrExpression Is Nothing Then
Throw New ArgumentNullException(NameOf(statementOrExpression))
End If
If TypeOf statementOrExpression Is ExecutableStatementSyntax Then
Return Me.AnalyzeDataFlow(DirectCast(statementOrExpression, StatementSyntax))
ElseIf TypeOf statementOrExpression Is ExpressionSyntax Then
Return Me.AnalyzeDataFlow(DirectCast(statementOrExpression, ExpressionSyntax))
Else
Throw New ArgumentException(VBResources.StatementOrExpressionIsNotAValidType)
End If
End Function
Protected NotOverridable Overrides Function AnalyzeControlFlowCore(firstStatement As SyntaxNode, lastStatement As SyntaxNode) As ControlFlowAnalysis
Return Me.AnalyzeControlFlow(SafeCastArgument(Of StatementSyntax)(firstStatement, NameOf(firstStatement)),
SafeCastArgument(Of StatementSyntax)(lastStatement, NameOf(lastStatement)))
End Function
Protected NotOverridable Overrides Function AnalyzeControlFlowCore(statement As SyntaxNode) As ControlFlowAnalysis
Return Me.AnalyzeControlFlow(SafeCastArgument(Of StatementSyntax)(statement, NameOf(statement)))
End Function
Private Shared Function SafeCastArgument(Of T As Class)(node As SyntaxNode, argName As String) As T
If node Is Nothing Then
Throw New ArgumentNullException(argName)
End If
Dim casted = TryCast(node, T)
If casted Is Nothing Then
Throw New ArgumentException(argName & " is not an " & GetType(T).Name)
End If
Return casted
End Function
Protected NotOverridable Overrides Function GetConstantValueCore(node As SyntaxNode, Optional cancellationToken As CancellationToken = Nothing) As [Optional](Of Object)
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
If TypeOf node Is ExpressionSyntax Then
Return GetConstantValue(DirectCast(node, ExpressionSyntax), cancellationToken)
End If
Return Nothing
End Function
Protected NotOverridable Overrides Function GetEnclosingSymbolCore(position As Integer, Optional cancellationToken As System.Threading.CancellationToken = Nothing) As ISymbol
Return GetEnclosingSymbol(position, cancellationToken)
End Function
Protected NotOverridable Overrides Function IsAccessibleCore(position As Integer, symbol As ISymbol) As Boolean
Return Me.IsAccessible(position, symbol.EnsureVbSymbolOrNothing(Of Symbol)(NameOf(symbol)))
End Function
Protected NotOverridable Overrides Function IsEventUsableAsFieldCore(position As Integer, symbol As IEventSymbol) As Boolean
Return False
End Function
Friend Overrides Sub ComputeDeclarationsInSpan(span As TextSpan, getSymbol As Boolean, builder As ArrayBuilder(Of DeclarationInfo), cancellationToken As CancellationToken)
VisualBasicDeclarationComputer.ComputeDeclarationsInSpan(Me, span, getSymbol, builder, cancellationToken)
End Sub
Friend Overrides Sub ComputeDeclarationsInNode(node As SyntaxNode, associatedSymbol As ISymbol, getSymbol As Boolean, builder As ArrayBuilder(Of DeclarationInfo), cancellationToken As CancellationToken, Optional levelsToCompute As Integer? = Nothing)
VisualBasicDeclarationComputer.ComputeDeclarationsInNode(Me, node, getSymbol, builder, cancellationToken)
End Sub
Protected Overrides Function GetTopmostNodeForDiagnosticAnalysis(symbol As ISymbol, declaringSyntax As SyntaxNode) As SyntaxNode
Select Case symbol.Kind
Case SymbolKind.Namespace
If TypeOf declaringSyntax Is NamespaceStatementSyntax Then
If declaringSyntax.Parent IsNot Nothing AndAlso TypeOf declaringSyntax.Parent Is NamespaceBlockSyntax Then
Return declaringSyntax.Parent
End If
End If
Case SymbolKind.NamedType
If TypeOf declaringSyntax Is TypeStatementSyntax Then
If declaringSyntax.Parent IsNot Nothing AndAlso TypeOf declaringSyntax.Parent Is TypeBlockSyntax Then
Return declaringSyntax.Parent
End If
End If
Case SymbolKind.Method
If TypeOf declaringSyntax Is MethodBaseSyntax Then
If declaringSyntax.Parent IsNot Nothing AndAlso TypeOf declaringSyntax.Parent Is MethodBlockBaseSyntax Then
Return declaringSyntax.Parent
End If
End If
Case SymbolKind.Event
If TypeOf declaringSyntax Is EventStatementSyntax Then
If declaringSyntax.Parent IsNot Nothing AndAlso TypeOf declaringSyntax.Parent Is EventBlockSyntax Then
Return declaringSyntax.Parent
End If
End If
Case SymbolKind.Property
If TypeOf declaringSyntax Is PropertyStatementSyntax Then
If declaringSyntax.Parent IsNot Nothing AndAlso TypeOf declaringSyntax.Parent Is PropertyBlockSyntax Then
Return declaringSyntax.Parent
End If
End If
Case SymbolKind.Field
Dim fieldDecl = declaringSyntax.FirstAncestorOrSelf(Of FieldDeclarationSyntax)()
If fieldDecl IsNot Nothing Then
Return fieldDecl
End If
End Select
Return declaringSyntax
End Function
Public NotOverridable Overrides Function GetNullableContext(position As Integer) As NullableContext
Return NullableContext.Disabled Or NullableContext.ContextInherited
End Function
#End Region
#Region "Logging Helpers"
' Following helpers are used when logging ETW events. These helpers are invoked only if we are running
' under an ETW listener that has requested 'verbose' logging. In other words, these helpers will never
' be invoked in the 'normal' case (i.e. when the code is running on user's machine and no ETW listener
' is involved).
' Note: Most of the below helpers are unused at the moment - but we would like to keep them around in
' case we decide we need more verbose logging in certain cases for debugging.
Friend Function GetMessage(position As Integer) As String
Return String.Format("{0}: at {1}", Me.SyntaxTree.FilePath, position)
End Function
Friend Function GetMessage(node As VisualBasicSyntaxNode) As String
If node Is Nothing Then Return Me.SyntaxTree.FilePath
Return String.Format("{0}: {1} ({2})", Me.SyntaxTree.FilePath, node.Kind.ToString(), node.Position)
End Function
Friend Function GetMessage(node As VisualBasicSyntaxNode, position As Integer) As String
If node Is Nothing Then Return Me.SyntaxTree.FilePath
Return String.Format("{0}: {1} ({2}) at {3}", Me.SyntaxTree.FilePath, node.Kind.ToString(), node.Position, position)
End Function
Friend Function GetMessage(firstStatement As StatementSyntax, lastStatement As StatementSyntax) As String
If firstStatement Is Nothing OrElse lastStatement Is Nothing Then Return Me.SyntaxTree.FilePath
Return String.Format("{0}: {1} to {2}", Me.SyntaxTree.FilePath, firstStatement.Position, lastStatement.EndPosition)
End Function
Friend Function GetMessage(expression As ExpressionSyntax, type As TypeSymbol) As String
If expression Is Nothing OrElse type Is Nothing Then Return Me.SyntaxTree.FilePath
Return String.Format("{0}: {1} ({2}) -> {3} {4}", Me.SyntaxTree.FilePath, expression.Kind.ToString(), expression.Position, type.TypeKind.ToString(), type.Name)
End Function
Friend Function GetMessage(expression As ExpressionSyntax, type As TypeSymbol, position As Integer) As String
If expression Is Nothing OrElse type Is Nothing Then Return Me.SyntaxTree.FilePath
Return String.Format("{0}: {1} ({2}) -> {3} {4} at {5}", Me.SyntaxTree.FilePath, expression.Kind.ToString(), expression.Position, type.TypeKind.ToString(), type.Name, position)
End Function
Friend Function GetMessage(expression As ExpressionSyntax, [option] As SpeculativeBindingOption, position As Integer) As String
If expression Is Nothing Then Return Me.SyntaxTree.FilePath
Return String.Format("{0}: {1} ({2}) at {3} ({4})", Me.SyntaxTree.FilePath, expression.Kind.ToString(), expression.Position, position, [option].ToString())
End Function
Friend Function GetMessage(name As String, [option] As LookupOptions, position As Integer) As String
Return String.Format("{0}: {1} at {2} ({3})", Me.SyntaxTree.FilePath, name, position, [option].ToString())
End Function
Friend Function GetMessage(symbol As Symbol, position As Integer) As String
If symbol Is Nothing Then Return Me.SyntaxTree.FilePath
Return String.Format("{0}: {1} {2} at {3}", Me.SyntaxTree.FilePath, symbol.Kind.ToString(), symbol.Name, position)
End Function
Friend Function GetMessage(stage As CompilationStage) As String
Return String.Format("{0} ({1})", Me.SyntaxTree.FilePath, stage.ToString())
End Function
#End Region
End Class
End Namespace
|
panopticoncentral/roslyn
|
src/Compilers/VisualBasic/Portable/Compilation/SemanticModel.vb
|
Visual Basic
|
mit
| 199,255
|
' Copyright 2013, Google Inc. All Rights Reserved.
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
' Author: api.anash@gmail.com (Anash P. Oommen)
Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201306
Imports System
Imports System.Collections.Generic
Imports System.IO
Namespace Google.Api.Ads.AdWords.Examples.VB.v201306
''' <summary>
''' This code example deletes an ad group by setting the status to 'DELETED'.
''' To get ad groups, run GetAdGroups.vb.
'''
''' Tags: AdGroupService.mutate
''' </summary>
Public Class DeleteAdGroup
Inherits ExampleBase
''' <summary>
''' Main method, to run this code example as a standalone application.
''' </summary>
''' <param name="args">The command line arguments.</param>
Public Shared Sub Main(ByVal args As String())
Dim codeExample As New DeleteAdGroup
Console.WriteLine(codeExample.Description)
Try
Dim adGroupId As Long = Long.Parse("INSERT_ADGROUP_ID_HERE")
codeExample.Run(New AdWordsUser, adGroupId)
Catch ex As Exception
Console.WriteLine("An exception occurred while running this code example. {0}", _
ExampleUtilities.FormatException(ex))
End Try
End Sub
''' <summary>
''' Returns a description about the code example.
''' </summary>
Public Overrides ReadOnly Property Description() As String
Get
Return "This code example deletes an ad group by setting the status to 'DELETED'. " & _
"To get ad groups, run GetAdGroups.vb."
End Get
End Property
''' <summary>
''' Runs the code example.
''' </summary>
''' <param name="user">The AdWords user.</param>
''' <param name="adGroupId">Id of the ad group to be deleted.</param>
Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId As Long)
' Get the AdGroupService.
Dim adGroupService As AdGroupService = user.GetService(AdWordsService.v201306.AdGroupService)
' Create ad group with DELETED status.
Dim adGroup As New AdGroup
adGroup.id = adGroupId
' When deleting an ad group, rename it to avoid name collisions with new
' ad groups.
adGroup.name = "Deleted AdGroup - " + ExampleUtilities.GetRandomString
adGroup.status = AdGroupStatus.DELETED
' Create the operation.
Dim operation As New AdGroupOperation
operation.operand = adGroup
operation.operator = [Operator].SET
Try
' Delete the ad group.
Dim retVal As AdGroupReturnValue = adGroupService.mutate( _
New AdGroupOperation() {operation})
' Display the results.
If ((Not retVal Is Nothing) AndAlso (Not retVal.value Is Nothing) AndAlso _
(retVal.value.Length > 0)) Then
Dim deletedAdGroup As AdGroup = retVal.value(0)
Console.WriteLine("Ad group with id = ""{0}"" was renamed to ""{1}"" and deleted.", _
deletedAdGroup.id, deletedAdGroup.name)
Else
Console.WriteLine("No ad groups were deleted.")
End If
Catch ex As Exception
Throw New System.ApplicationException("Failed to delete ad groups.", ex)
End Try
End Sub
End Class
End Namespace
|
akilb/googleads-adwords-dotnet-lib
|
examples/adxbuyer/VB/v201306/BasicOperations/DeleteAdGroup.vb
|
Visual Basic
|
apache-2.0
| 3,734
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
Friend Class CompletionListTagCompletionProvider
Inherits EnumCompletionProvider
Protected Overrides Function GetPreselectedSymbolsWorker(context As SyntaxContext, position As Integer, options As OptionSet, cancellationToken As CancellationToken) As Task(Of IEnumerable(Of ISymbol))
If context.SyntaxTree.IsObjectCreationTypeContext(position, cancellationToken) OrElse
context.SyntaxTree.IsInNonUserCode(position, cancellationToken) Then
Return SpecializedTasks.EmptyEnumerable(Of ISymbol)()
End If
Dim typeInferenceService = context.GetLanguageService(Of ITypeInferenceService)()
Dim inferredType = typeInferenceService.InferType(context.SemanticModel, position, objectAsDefault:=True, cancellationToken:=cancellationToken)
If inferredType Is Nothing Then
Return SpecializedTasks.EmptyEnumerable(Of ISymbol)()
End If
Dim within = context.SemanticModel.GetEnclosingNamedType(position, cancellationToken)
Dim completionListType = GetCompletionListType(inferredType, within, context.SemanticModel.Compilation)
If completionListType Is Nothing Then
Return SpecializedTasks.EmptyEnumerable(Of ISymbol)()
End If
Dim hideAdvancedMembers = options.GetOption(CodeAnalysis.Recommendations.RecommendationOptions.HideAdvancedMembers, context.SemanticModel.Language)
Return Task.FromResult(completionListType.GetAccessibleMembersInThisAndBaseTypes(Of ISymbol)(within) _
.Where(Function(m) m.MatchesKind(SymbolKind.Field, SymbolKind.Property) AndAlso
m.IsStatic AndAlso
m.IsAccessibleWithin(within) AndAlso
m.IsEditorBrowsable(hideAdvancedMembers, context.SemanticModel.Compilation)))
End Function
Protected Overrides Function GetSymbolsWorker(context As SyntaxContext, position As Integer, options As OptionSet, cancellationToken As CancellationToken) As Task(Of IEnumerable(Of ISymbol))
Return SpecializedTasks.EmptyEnumerable(Of ISymbol)()
End Function
Private Function GetCompletionListType(inferredType As ITypeSymbol, within As INamedTypeSymbol, compilation As Compilation) As ITypeSymbol
Dim documentation = inferredType.GetDocumentationComment()
If documentation.CompletionListCref IsNot Nothing Then
Dim crefType = DocumentationCommentId.GetSymbolsForDeclarationId(documentation.CompletionListCref, compilation) _
.OfType(Of INamedTypeSymbol) _
.FirstOrDefault()
If crefType IsNot Nothing AndAlso crefType.IsAccessibleWithin(within) Then
Return crefType
End If
End If
Return Nothing
End Function
Protected Overrides Function GetDisplayAndInsertionText(symbol As ISymbol, context As SyntaxContext) As ValueTuple(Of String, String)
Dim displayFormat = SymbolDisplayFormat.MinimallyQualifiedFormat.WithMemberOptions(SymbolDisplayMemberOptions.IncludeContainingType).WithKindOptions(SymbolDisplayKindOptions.None)
Dim text = symbol.ToMinimalDisplayString(context.SemanticModel, context.Position, displayFormat)
Return ValueTuple.Create(text, text)
End Function
Protected Overrides Function CreateItem(displayText As String, insertionText As String, symbols As List(Of ISymbol), context As SyntaxContext, preselect As Boolean, supportedPlatformData As SupportedPlatformData) As CompletionItem
Return SymbolCompletionItem.Create(
displayText:=displayText,
insertionText:=insertionText,
filterText:=GetFilterText(symbols(0), displayText, context),
symbols:=symbols,
contextPosition:=context.Position,
sortText:=displayText,
glyph:=Glyph.EnumMember,
matchPriority:=MatchPriority.Preselect,
supportedPlatforms:=supportedPlatformData)
End Function
End Class
End Namespace
|
MatthieuMEZIL/roslyn
|
src/Features/VisualBasic/Portable/Completion/CompletionProviders/CompletionListTagCompletionProvider.vb
|
Visual Basic
|
apache-2.0
| 4,980
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.PreprocessorDirectives
Public Class ConstDirectiveKeywordRecommenderTests
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub HashConstInFileTest()
VerifyRecommendationsContain(<File>|</File>, "#Const")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub HashConstInMethodBodyTest()
VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "#Const")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInEnumBlockMemberDeclarationTest()
VerifyRecommendationsMissing(<File>
Enum goo
|
End enum
</File>, "#Const")
End Sub
<WorkItem(544629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544629")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub HashConstAfterSingleNonMatchingCharacterTest()
VerifyRecommendationsContain(<File>a|</File>, "#Const")
End Sub
<WorkItem(544629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544629")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub HashConstAfterPartialConstWithoutHashTest()
VerifyRecommendationsContain(<File>Con|</File>, "#Const")
End Sub
<WorkItem(722, "https://github.com/dotnet/roslyn/issues/722")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotAfterHashConstTest()
VerifyRecommendationsMissing(<File>#Const |</File>, "#Const")
End Sub
<WorkItem(6389, "https://github.com/dotnet/roslyn/issues/6389")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotAfterHashRegionTest()
VerifyRecommendationsMissing(<File>
Class C
#Region |
End Class
</File>, "#Const")
End Sub
End Class
End Namespace
|
physhi/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/PreprocessorDirectives/ConstDirectiveKeywordRecommenderTests.vb
|
Visual Basic
|
apache-2.0
| 2,617
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Editor.Implementation.Interactive
Imports Microsoft.CodeAnalysis.Editor.UnitTests
Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.ChangeSignature
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature
Partial Public Class ChangeSignatureTests
Inherits AbstractChangeSignatureTests
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestRemoveParameters1() As Task
Dim markup = <Text><![CDATA[
Module Program
''' <summary>
''' See <see cref="M(String, Integer, String, Boolean, Integer, String)"/>
''' </summary>
''' <param name="o">o!</param>
''' <param name="a">a!</param>
''' <param name="b">b!</param>
''' <param name="c">c!</param>
''' <param name="x">x!</param>
''' <param name="y">y!</param>
<System.Runtime.CompilerServices.Extension>
Sub $$M(ByVal o As String, a As Integer, b As String, c As Boolean, Optional x As Integer = 0, Optional y As String = "Zero")
Dim t = "Test"
M(t, 1, "Two", True, 3, "Four")
t.M(1, "Two", True, 3, "Four")
M(t, 1, "Two", True, 3)
M(t, 1, "Two", True)
M(t, 1, "Two", True, 3, y:="Four")
M(t, 1, "Two", c:=True)
M(t, 1, "Two", True, y:="Four")
M(t, 1, "Two", True, x:=3)
M(t, 1, "Two", True, y:="Four", x:=3)
M(t, 1, y:="Four", x:=3, b:="Two", c:=True)
M(t, y:="Four", x:=3, c:=True, b:="Two", a:=1)
M(y:="Four", x:=3, c:=True, b:="Two", a:=1, o:=t)
End Sub
End Module
]]></Text>.NormalizedValue()
Dim permutation = {0, 3, 1, 5}
Dim updatedCode = <Text><![CDATA[
Module Program
''' <summary>
''' See <see cref="M(String, Boolean, Integer, String)"/>
''' </summary>
''' <param name="o">o!</param>
''' <param name="c">c!</param>
''' <param name="a">a!</param>
''' <param name="y">y!</param>
'''
'''
<System.Runtime.CompilerServices.Extension>
Sub M(ByVal o As String, c As Boolean, a As Integer, Optional y As String = "Zero")
Dim t = "Test"
M(t, True, 1, "Four")
t.M(True, 1, "Four")
M(t, True, 1)
M(t, True, 1)
M(t, True, 1, y:="Four")
M(t, c:=True, a:=1)
M(t, True, 1, y:="Four")
M(t, True, 1)
M(t, True, 1, y:="Four")
M(t, a:=1, y:="Four", c:=True)
M(t, y:="Four", c:=True, a:=1)
M(y:="Four", c:=True, a:=1, o:=t)
End Sub
End Module
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode)
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.ChangeSignature)>
<Trait(Traits.Feature, Traits.Features.Interactive)>
Public Async Function TestChangeSignatureCommandDisabledInSubmission() As Task
Dim exportProvider = MinimalTestExportProvider.CreateExportProvider(
TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithParts(GetType(InteractiveDocumentSupportsFeatureService)))
Using workspace = Await TestWorkspace.CreateAsync(
<Workspace>
<Submission Language="Visual Basic" CommonReferences="true">
Class C
Sub M$$(x As Integer)
End Sub
End Class
</Submission>
</Workspace>,
workspaceKind:=WorkspaceKind.Interactive,
exportProvider:=exportProvider)
' Force initialization.
workspace.GetOpenDocumentIds().Select(Function(id) workspace.GetTestDocument(id).GetTextView()).ToList()
Dim textView = workspace.Documents.Single().GetTextView()
Dim handler = New ChangeSignatureCommandHandler()
Dim delegatedToNext = False
Dim nextHandler =
Function()
delegatedToNext = True
Return CommandState.Unavailable
End Function
Dim state = handler.GetCommandState(New Commands.ReorderParametersCommandArgs(textView, textView.TextBuffer), nextHandler)
Assert.True(delegatedToNext)
Assert.False(state.IsAvailable)
delegatedToNext = False
state = handler.GetCommandState(New Commands.RemoveParametersCommandArgs(textView, textView.TextBuffer), nextHandler)
Assert.True(delegatedToNext)
Assert.False(state.IsAvailable)
End Using
End Function
End Class
End Namespace
|
ericfe-ms/roslyn
|
src/EditorFeatures/VisualBasicTest/ChangeSignature/RemoveParametersTests.vb
|
Visual Basic
|
apache-2.0
| 5,222
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports System.Text
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests
Friend Module Utils
Friend Function ParseCode(code As String) As SyntaxTree
Dim text = SourceText.From(code)
Return SyntaxFactory.ParseSyntaxTree(text)
End Function
Friend Function StringFromLines(ParamArray lines As String()) As String
Return String.Join(Environment.NewLine, lines)
End Function
Friend Function ParseLines(ParamArray lines As String()) As SyntaxTree
Dim code = StringFromLines(lines)
Return ParseCode(code)
End Function
Friend Function ParseExpression(expr As String) As SyntaxTree
Dim format =
"Class C1 " & vbCrLf &
" Sub S1()" & vbCrLf &
" Dim x = {0}" & vbCrLf &
" End Sub" & vbCrLf &
"End Class"
Dim code = String.Format(format, expr)
Return ParseCode(code)
End Function
Friend Function ParseStatement(statement As String) As SyntaxTree
Dim format = StringFromLines(
"Class C1",
" Sub S1()",
" {0}",
" End Sub",
"End Class")
Dim code = String.Format(format, statement)
Return ParseCode(code)
End Function
''' <summary>
''' DFS search to find the first node of a given type.
''' </summary>
<Extension()>
Friend Function FindFirstNodeOfType(Of T As SyntaxNode)(node As SyntaxNode) As T
If TypeOf (node) Is T Then
Return CType(node, T)
End If
For Each child In node.ChildNodesAndTokens()
If child.IsNode Then
Dim foundNode = child.AsNode().FindFirstNodeOfType(Of T)()
If foundNode IsNot Nothing Then
Return foundNode
End If
End If
Next
Return Nothing
End Function
<Extension()>
Friend Function DigToNthNodeOfType(Of T As SyntaxNode)(node As SyntaxNode, index As Integer) As T
Return node.ChildNodesAndTokens().Where(Function(n) n.IsNode).
Select(Function(n) n.AsNode()).
OfType(Of T).ElementAt(index)
End Function
<Extension()>
Friend Function DigToFirstNodeOfType(Of T As SyntaxNode)(node As SyntaxNode) As T
Return node.ChildNodesAndTokens().Where(Function(n) n.IsNode).
Select(Function(n) n.AsNode()).
OfType(Of T).First()
End Function
<Extension()>
Friend Function DigToFirstNodeOfType(Of T As SyntaxNode)(syntaxTree As SyntaxTree) As T
Return syntaxTree.GetRoot().DigToFirstNodeOfType(Of T)()
End Function
<Extension()>
Friend Function DigToLastNodeOfType(Of T As SyntaxNode)(node As SyntaxNode) As T
Return node.ChildNodesAndTokens().Where(Function(n) n.IsNode).
Select(Function(n) n.AsNode()).
OfType(Of T).Last()
End Function
<Extension()>
Friend Function DigToFirstTypeBlock(syntaxTree As SyntaxTree) As TypeBlockSyntax
Return syntaxTree.GetRoot().ChildNodesAndTokens().Where(Function(n) n.IsNode).
Select(Function(n) n.AsNode()).
OfType(Of TypeBlockSyntax).First()
End Function
<Extension()>
Friend Function DigToFirstNamespace(syntaxTree As SyntaxTree) As NamespaceBlockSyntax
Return syntaxTree.GetRoot().ChildNodesAndTokens().Where(Function(n) n.IsNode).
Select(Function(n) n.AsNode()).
OfType(Of NamespaceBlockSyntax).First()
End Function
Friend Class TreeNodePair(Of T As SyntaxNode)
Private ReadOnly _tree As SyntaxTree
Private ReadOnly _node As T
Public Sub New(syntaxTree As SyntaxTree, node As T)
#If Not CODE_STYLE Then
Contract.ThrowIfNull(syntaxTree)
Contract.ThrowIfNull(node)
#End If
_tree = syntaxTree
_node = node
End Sub
Public ReadOnly Property Tree As SyntaxTree
Get
Return _tree
End Get
End Property
Public ReadOnly Property Node As T
Get
Return _node
End Get
End Property
End Class
Friend Class TreeNodePair
Friend Shared Function Create(Of T As SyntaxNode)(syntaxTree As SyntaxTree, node As T) As TreeNodePair(Of T)
Return New TreeNodePair(Of T)(syntaxTree, node)
End Function
End Class
Private Function SplitIntoLines(
text As String,
separator As String,
Optional removeLeadingLineBreaks As Boolean = True,
Optional removeTrailingLineBreaks As Boolean = True) As IEnumerable(Of String)
Dim lines = text.Split({separator}, StringSplitOptions.None).ToList()
If removeLeadingLineBreaks Then
While lines.Count > 0
If lines(0).Length = 0 Then
lines.RemoveAt(0)
Else
Exit While
End If
End While
End If
If removeTrailingLineBreaks Then
For i = lines.Count - 1 To 0 Step -1
If lines(i).Length = 0 Then
lines.RemoveAt(i)
Else
Exit For
End If
Next
End If
Return lines
End Function
Private Function SurroundAndJoinLines(
lines As IEnumerable(Of String),
Optional leading As String = Nothing,
Optional trailing As String = Nothing) As String
Dim builder As New StringBuilder
For Each line In lines
If Not String.IsNullOrWhiteSpace(line) Then
builder.Append(leading)
End If
builder.Append(line)
builder.Append(trailing)
Next
Return builder.ToString()
End Function
<Extension()>
Friend Function ConvertTestSourceTag(testSource As XElement) As String
' Line breaks in XML values are represented as line feeds.
Dim lines = SplitIntoLines(testSource.NormalizedValue, vbCrLf)
Dim importStatements = "Imports System" & vbCrLf &
"Imports System.Collections.Generic" & vbCrLf &
"Imports System.Linq"
Select Case testSource.Name
Case "ClassDeclaration"
Return importStatements & vbCrLf &
"Class C1" & vbCrLf &
SurroundAndJoinLines(lines, " ", vbCrLf) &
"End Class"
Case "StructureDeclaration"
Return importStatements & vbCrLf &
"Structure S" & vbCrLf &
SurroundAndJoinLines(lines, " ", vbCrLf) &
"End Structure"
Case "NamespaceDeclaration"
Return importStatements & vbCrLf &
"Namespace Roslyn" & vbCrLf &
SurroundAndJoinLines(lines, " ", vbCrLf) &
"End Namespace"
Case "InterfaceDeclaration"
Return importStatements & vbCrLf &
"Interface IInterface" & vbCrLf &
SurroundAndJoinLines(lines, " ", vbCrLf) &
"End Interface"
Case "EnumDeclaration"
Return importStatements & vbCrLf &
"Enum Goo" & vbCrLf &
SurroundAndJoinLines(lines, " ", vbCrLf) &
"End Enum"
Case "ModuleDeclaration"
Return importStatements & vbCrLf &
"Module M1" & vbCrLf &
SurroundAndJoinLines(lines, " ", vbCrLf) &
"End Module"
Case "MethodBody"
Return importStatements & vbCrLf &
"Class C1" & vbCrLf &
" Sub Method()" & vbCrLf &
SurroundAndJoinLines(lines, " ", vbCrLf) &
" End Sub" & vbCrLf &
"End Class"
Case "SharedMethodBody"
Return importStatements & vbCrLf &
"Class C1" & vbCrLf &
" Shared Sub Method()" & vbCrLf &
SurroundAndJoinLines(lines, " ", vbCrLf) &
" End Sub" & vbCrLf &
"End Class"
Case "PropertyGetter"
Return importStatements & vbCrLf &
"Class C1" & vbCrLf &
" ReadOnly Property P As Integer" & vbCrLf &
" Get" & vbCrLf &
SurroundAndJoinLines(lines, " ", vbCrLf) &
" End Get" & vbCrLf &
" End Property" & vbCrLf &
"End Class"
Case "PropertyDeclaration"
Return importStatements & vbCrLf &
"Class C1" & vbCrLf &
" Public Property P As String " & vbCrLf &
SurroundAndJoinLines(lines, " ", vbCrLf) &
" End Property" & vbCrLf &
"End Class"
Case "SharedPropertyGetter"
Return importStatements & vbCrLf &
"Class C1" & vbCrLf &
" Shared ReadOnly Property P As Integer" & vbCrLf &
" Get" & vbCrLf &
SurroundAndJoinLines(lines, " ", vbCrLf) &
" End Get" & vbCrLf &
" End Property" & vbCrLf &
"End Class"
Case "CustomEventDeclaration"
Return importStatements & vbCrLf &
"Class C1" & vbCrLf &
" Custom Event TestEvent As EventHandler" & vbCrLf &
SurroundAndJoinLines(lines, " ", vbCrLf) &
" End Event" & vbCrLf &
"End Class"
Case "EventAddHandler"
Return importStatements & vbCrLf &
"Class C1" & vbCrLf &
" Custom Event TestEvent As EventHandler" & vbCrLf &
" AddHandler(value As EventHandler)" & vbCrLf &
SurroundAndJoinLines(lines, " ", vbCrLf) &
" End AddHandler" & vbCrLf &
" RemoveHandler(value As EventHandler)" & vbCrLf &
" End RemoveHandler" & vbCrLf &
" RaiseEvent(sender As Object, e As EventArgs)" & vbCrLf &
" End RaiseEvent" & vbCrLf &
" End Event" & vbCrLf &
"End Class"
Case "SharedEventAddHandler"
Return importStatements & vbCrLf &
"Class C1" & vbCrLf &
" Shared Custom Event TestEvent As EventHandler" & vbCrLf &
" AddHandler(value As EventHandler)" & vbCrLf &
SurroundAndJoinLines(lines, " ", vbCrLf) &
" End AddHandler" & vbCrLf &
" RemoveHandler(value As EventHandler)" & vbCrLf &
" End RemoveHandler" & vbCrLf &
" RaiseEvent(sender As Object, e As EventArgs)" & vbCrLf &
" End RaiseEvent" & vbCrLf &
" End Event" & vbCrLf &
"End Class"
Case "ModuleMethodBody"
Return importStatements & vbCrLf &
"Module M1" & vbCrLf &
" Sub Method()" & vbCrLf &
SurroundAndJoinLines(lines, " ", vbCrLf) &
" End Sub" & vbCrLf &
"End Module"
Case "StructureMethodBody"
Return importStatements & vbCrLf &
"Structure S" & vbCrLf &
" Sub Method()" & vbCrLf &
SurroundAndJoinLines(lines, " ", vbCrLf) &
" End Sub" & vbCrLf &
"End Structure"
Case "File"
Return testSource.NormalizedValue
Case Else
Throw New ArgumentException("Unexpected testSource XML tag.", NameOf(testSource))
End Select
End Function
End Module
End Namespace
|
AmadeusW/roslyn
|
src/EditorFeatures/VisualBasicTest/Utils.vb
|
Visual Basic
|
apache-2.0
| 14,169
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class SymbolExtensionTests
Inherits BasicTestBase
<Fact>
Public Sub HasNameQualifier()
Dim compilation = CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb">
Class C
End Class
Namespace N
Class C
End Class
Namespace NA
Class C
End Class
Namespace NB
Class C
End Class
End Namespace
End Namespace
Namespace NB
Class C
End Class
End Namespace
End Namespace
Namespace NA
Class C
End Class
Namespace NA
Class C
End Class
End Namespace
Namespace NB
Class C
End Class
End Namespace
End Namespace
Namespace NB
Class C
End Class
End Namespace
</file>
</compilation>)
compilation.AssertNoErrors()
Dim namespaceNames =
{
"",
".",
"N",
"NA",
"NB",
"n",
"AN",
"NAB",
"N.",
".NA",
".NB",
"N.N",
"N.NA",
"N.NB",
"N..NB",
"N.NA.NA",
"N.NA.NB",
"NA.N",
"NA.NA",
"NA.NB",
"NA.NA.NB",
"NA.NB.NB"
}
HasNameQualifierCore(namespaceNames, compilation.GetMember(Of NamedTypeSymbol)("C"), "")
HasNameQualifierCore(namespaceNames, compilation.GetMember(Of NamedTypeSymbol)("N.C"), "N")
HasNameQualifierCore(namespaceNames, compilation.GetMember(Of NamedTypeSymbol)("N.NA.C"), "N.NA")
HasNameQualifierCore(namespaceNames, compilation.GetMember(Of NamedTypeSymbol)("N.NA.NB.C"), "N.NA.NB")
HasNameQualifierCore(namespaceNames, compilation.GetMember(Of NamedTypeSymbol)("NA.C"), "NA")
HasNameQualifierCore(namespaceNames, compilation.GetMember(Of NamedTypeSymbol)("NA.NA.C"), "NA.NA")
HasNameQualifierCore(namespaceNames, compilation.GetMember(Of NamedTypeSymbol)("NA.NB.C"), "NA.NB")
HasNameQualifierCore(namespaceNames, compilation.GetMember(Of NamedTypeSymbol)("NB.C"), "NB")
End Sub
Private Shared Sub HasNameQualifierCore(namespaceNames As String(), type As NamedTypeSymbol, expectedName As String)
Assert.True(Array.IndexOf(namespaceNames, expectedName) >= 0)
Assert.Null(type.GetEmittedNamespaceName())
For Each namespaceName In namespaceNames
Assert.Equal(namespaceName = expectedName, type.HasNameQualifier(namespaceName, StringComparison.Ordinal))
Next
End Sub
End Class
End Namespace
|
jhendrixMSFT/roslyn
|
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/SymbolExtensionTests.vb
|
Visual Basic
|
apache-2.0
| 3,153
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class frmListOfDiscounts
Inherits ComponentFactory.Krypton.Toolkit.KryptonForm
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmListOfDiscounts))
Me.StatusStrip1 = New System.Windows.Forms.StatusStrip
Me.ToolStripStatusLabel1 = New System.Windows.Forms.ToolStripStatusLabel
Me.ToolStrip1 = New System.Windows.Forms.ToolStrip
Me.cmdAddNew = New System.Windows.Forms.ToolStripButton
Me.cmdModify = New System.Windows.Forms.ToolStripButton
Me.cmdDelete = New System.Windows.Forms.ToolStripButton
Me.ToolStripSeparator1 = New System.Windows.Forms.ToolStripSeparator
Me.cmdPrint = New System.Windows.Forms.ToolStripButton
Me.ToolStripSeparator2 = New System.Windows.Forms.ToolStripSeparator
Me.cmdClose = New System.Windows.Forms.ToolStripButton
Me.ToolStrip2 = New System.Windows.Forms.ToolStrip
Me.ToolStripLabel1 = New System.Windows.Forms.ToolStripLabel
Me.txtSearch = New System.Windows.Forms.ToolStripTextBox
Me.cmdSearch = New System.Windows.Forms.ToolStripButton
Me.ToolStripSeparator3 = New System.Windows.Forms.ToolStripSeparator
Me.cmdRefresh = New System.Windows.Forms.ToolStripButton
Me.dvgList = New System.Windows.Forms.DataGridView
Me.StatusStrip1.SuspendLayout()
Me.ToolStrip1.SuspendLayout()
Me.ToolStrip2.SuspendLayout()
CType(Me.dvgList, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'StatusStrip1
'
Me.StatusStrip1.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!)
Me.StatusStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ToolStripStatusLabel1})
Me.StatusStrip1.Location = New System.Drawing.Point(1, 448)
Me.StatusStrip1.Margin = New System.Windows.Forms.Padding(1)
Me.StatusStrip1.Name = "StatusStrip1"
Me.StatusStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.ManagerRenderMode
Me.StatusStrip1.Size = New System.Drawing.Size(800, 22)
Me.StatusStrip1.TabIndex = 3
Me.StatusStrip1.Text = "StatusStrip1"
'
'ToolStripStatusLabel1
'
Me.ToolStripStatusLabel1.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.ToolStripStatusLabel1.Name = "ToolStripStatusLabel1"
Me.ToolStripStatusLabel1.Size = New System.Drawing.Size(144, 17)
Me.ToolStripStatusLabel1.Text = " ToolStripStatusLabel1"
'
'ToolStrip1
'
Me.ToolStrip1.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!)
Me.ToolStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.cmdAddNew, Me.cmdModify, Me.cmdDelete, Me.ToolStripSeparator1, Me.cmdPrint, Me.ToolStripSeparator2, Me.cmdClose})
Me.ToolStrip1.Location = New System.Drawing.Point(1, 1)
Me.ToolStrip1.Name = "ToolStrip1"
Me.ToolStrip1.Size = New System.Drawing.Size(800, 25)
Me.ToolStrip1.TabIndex = 4
Me.ToolStrip1.Text = "ToolStrip1"
'
'cmdAddNew
'
Me.cmdAddNew.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.cmdAddNew.Image = CType(resources.GetObject("cmdAddNew.Image"), System.Drawing.Image)
Me.cmdAddNew.ImageTransparentColor = System.Drawing.Color.Magenta
Me.cmdAddNew.Name = "cmdAddNew"
Me.cmdAddNew.Size = New System.Drawing.Size(79, 22)
Me.cmdAddNew.Text = "Add [F2]"
Me.cmdAddNew.ToolTipText = "Add new department."
'
'cmdModify
'
Me.cmdModify.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.cmdModify.Image = CType(resources.GetObject("cmdModify.Image"), System.Drawing.Image)
Me.cmdModify.ImageTransparentColor = System.Drawing.Color.Magenta
Me.cmdModify.Name = "cmdModify"
Me.cmdModify.Size = New System.Drawing.Size(94, 22)
Me.cmdModify.Text = "Modify [F3]"
Me.cmdModify.ToolTipText = "Modify department."
'
'cmdDelete
'
Me.cmdDelete.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.cmdDelete.Image = CType(resources.GetObject("cmdDelete.Image"), System.Drawing.Image)
Me.cmdDelete.ImageTransparentColor = System.Drawing.Color.Magenta
Me.cmdDelete.Name = "cmdDelete"
Me.cmdDelete.Size = New System.Drawing.Size(94, 22)
Me.cmdDelete.Text = "Delete [F5]"
Me.cmdDelete.ToolTipText = "Delete record."
'
'ToolStripSeparator1
'
Me.ToolStripSeparator1.Name = "ToolStripSeparator1"
Me.ToolStripSeparator1.Size = New System.Drawing.Size(6, 25)
'
'cmdPrint
'
Me.cmdPrint.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.cmdPrint.Image = CType(resources.GetObject("cmdPrint.Image"), System.Drawing.Image)
Me.cmdPrint.ImageTransparentColor = System.Drawing.Color.Magenta
Me.cmdPrint.Name = "cmdPrint"
Me.cmdPrint.Size = New System.Drawing.Size(80, 22)
Me.cmdPrint.Text = "Print [F6]"
Me.cmdPrint.ToolTipText = "Print list."
'
'ToolStripSeparator2
'
Me.ToolStripSeparator2.Name = "ToolStripSeparator2"
Me.ToolStripSeparator2.Size = New System.Drawing.Size(6, 25)
'
'cmdClose
'
Me.cmdClose.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.cmdClose.Image = CType(resources.GetObject("cmdClose.Image"), System.Drawing.Image)
Me.cmdClose.ImageTransparentColor = System.Drawing.Color.Magenta
Me.cmdClose.Name = "cmdClose"
Me.cmdClose.Size = New System.Drawing.Size(101, 22)
Me.cmdClose.Text = "Close [ESC]"
Me.cmdClose.ToolTipText = "Close window"
'
'ToolStrip2
'
Me.ToolStrip2.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!)
Me.ToolStrip2.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ToolStripLabel1, Me.txtSearch, Me.cmdSearch, Me.ToolStripSeparator3, Me.cmdRefresh})
Me.ToolStrip2.Location = New System.Drawing.Point(1, 26)
Me.ToolStrip2.Margin = New System.Windows.Forms.Padding(1)
Me.ToolStrip2.Name = "ToolStrip2"
Me.ToolStrip2.Padding = New System.Windows.Forms.Padding(1)
Me.ToolStrip2.Size = New System.Drawing.Size(800, 25)
Me.ToolStrip2.TabIndex = 5
Me.ToolStrip2.Text = "ToolStrip2"
'
'ToolStripLabel1
'
Me.ToolStripLabel1.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.ToolStripLabel1.Name = "ToolStripLabel1"
Me.ToolStripLabel1.Size = New System.Drawing.Size(54, 20)
Me.ToolStripLabel1.Text = "Search:"
'
'txtSearch
'
Me.txtSearch.Font = New System.Drawing.Font("Tahoma", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.txtSearch.Name = "txtSearch"
Me.txtSearch.Size = New System.Drawing.Size(300, 23)
'
'cmdSearch
'
Me.cmdSearch.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.cmdSearch.Image = CType(resources.GetObject("cmdSearch.Image"), System.Drawing.Image)
Me.cmdSearch.ImageTransparentColor = System.Drawing.Color.Magenta
Me.cmdSearch.Name = "cmdSearch"
Me.cmdSearch.Size = New System.Drawing.Size(71, 20)
Me.cmdSearch.Text = "Search"
Me.cmdSearch.ToolTipText = "Search list."
'
'ToolStripSeparator3
'
Me.ToolStripSeparator3.Name = "ToolStripSeparator3"
Me.ToolStripSeparator3.Size = New System.Drawing.Size(6, 23)
'
'cmdRefresh
'
Me.cmdRefresh.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.cmdRefresh.Image = CType(resources.GetObject("cmdRefresh.Image"), System.Drawing.Image)
Me.cmdRefresh.ImageTransparentColor = System.Drawing.Color.Magenta
Me.cmdRefresh.Name = "cmdRefresh"
Me.cmdRefresh.Size = New System.Drawing.Size(101, 20)
Me.cmdRefresh.Text = "Refresh [F8]"
Me.cmdRefresh.ToolTipText = "Reload list."
'
'dvgList
'
Me.dvgList.AllowUserToAddRows = False
Me.dvgList.AllowUserToDeleteRows = False
Me.dvgList.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.dvgList.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
Me.dvgList.Location = New System.Drawing.Point(2, 53)
Me.dvgList.Margin = New System.Windows.Forms.Padding(1)
Me.dvgList.Name = "dvgList"
Me.dvgList.ReadOnly = True
Me.dvgList.Size = New System.Drawing.Size(798, 393)
Me.dvgList.TabIndex = 6
'
'frmListOfDiscounts
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 16.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.BackColor = System.Drawing.SystemColors.InactiveCaptionText
Me.ClientSize = New System.Drawing.Size(802, 471)
Me.Controls.Add(Me.dvgList)
Me.Controls.Add(Me.ToolStrip2)
Me.Controls.Add(Me.ToolStrip1)
Me.Controls.Add(Me.StatusStrip1)
Me.Font = New System.Drawing.Font("Tahoma", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.Margin = New System.Windows.Forms.Padding(3, 4, 3, 4)
Me.Name = "frmListOfDiscounts"
Me.Padding = New System.Windows.Forms.Padding(1)
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "List of Discounts"
Me.WindowState = System.Windows.Forms.FormWindowState.Maximized
Me.StatusStrip1.ResumeLayout(False)
Me.StatusStrip1.PerformLayout()
Me.ToolStrip1.ResumeLayout(False)
Me.ToolStrip1.PerformLayout()
Me.ToolStrip2.ResumeLayout(False)
Me.ToolStrip2.PerformLayout()
CType(Me.dvgList, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents StatusStrip1 As System.Windows.Forms.StatusStrip
Friend WithEvents ToolStripStatusLabel1 As System.Windows.Forms.ToolStripStatusLabel
Friend WithEvents ToolStrip1 As System.Windows.Forms.ToolStrip
Friend WithEvents cmdAddNew As System.Windows.Forms.ToolStripButton
Friend WithEvents cmdModify As System.Windows.Forms.ToolStripButton
Friend WithEvents cmdDelete As System.Windows.Forms.ToolStripButton
Friend WithEvents ToolStripSeparator1 As System.Windows.Forms.ToolStripSeparator
Friend WithEvents cmdPrint As System.Windows.Forms.ToolStripButton
Friend WithEvents cmdClose As System.Windows.Forms.ToolStripButton
Friend WithEvents ToolStripSeparator2 As System.Windows.Forms.ToolStripSeparator
Friend WithEvents ToolStrip2 As System.Windows.Forms.ToolStrip
Friend WithEvents ToolStripLabel1 As System.Windows.Forms.ToolStripLabel
Friend WithEvents txtSearch As System.Windows.Forms.ToolStripTextBox
Friend WithEvents cmdSearch As System.Windows.Forms.ToolStripButton
Friend WithEvents ToolStripSeparator3 As System.Windows.Forms.ToolStripSeparator
Friend WithEvents cmdRefresh As System.Windows.Forms.ToolStripButton
Friend WithEvents dvgList As System.Windows.Forms.DataGridView
End Class
|
JeffreyAReyes/eSMS
|
Forms/FormsListings/frmListOfDiscounts.Designer.vb
|
Visual Basic
|
mit
| 13,504
|
Imports SistFoncreagro.BussinessEntities
Public Interface IEstadoCotizacionBL
Function GetAllFromEstadoCotizacionByIdCotizacion(ByVal IdCotizacion As Int32) As List(Of EstadoCotizacion)
End Interface
|
crackper/SistFoncreagro
|
SistFoncreagro.BussinesLogic/IEstadoCotizacionBL.vb
|
Visual Basic
|
mit
| 207
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.