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
|
|---|---|---|---|---|---|
' 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 Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.IntroduceVariable
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.IntroduceVariable
Public Class IntroduceVariableTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New IntroduceVariableCodeRefactoringProvider()
End Function
Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction)
Return GetNestedActions(actions)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function Test1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Console.WriteLine([|1 + 1|])
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Const {|Rename:Value|} As Integer = 1 + 1
Console.WriteLine(Value)
End Sub
End Module",
index:=2)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function Test2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Console.WriteLine([|1 + 1|])
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Const {|Rename:Value|} As Integer = 1 + 1
Console.WriteLine(Value)
End Sub
End Module",
index:=3)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestInSingleLineIfExpression1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
If goo([|1 + 1|]) Then bar(1 + 1)
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Const {|Rename:V|} As Integer = 1 + 1
If goo(V) Then bar(1 + 1)
End Sub
End Module",
index:=2)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestInSingleLineIfExpression2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
If goo([|1 + 1|]) Then bar(1 + 1)
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Const {|Rename:V|} As Integer = 1 + 1
If goo(V) Then bar(V)
End Sub
End Module",
index:=3)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestInSingleLineIfStatement1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
If goo(1 + 1) Then bar([|1 + 1|])
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
If goo(1 + 1) Then
Const {|Rename:V|} As Integer = 1 + 1
bar(V)
End If
End Sub
End Module",
index:=2)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestInSingleLineIfStatement2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
If goo(1 + 1) Then bar([|1 + 1|])
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Const {|Rename:V|} As Integer = 1 + 1
If goo(V) Then bar(V)
End Sub
End Module",
index:=3)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestNoIntroduceFieldOnMethodTypeParameter() As Task
Dim source = "Module Program
Sub Main(Of T)()
Goo([|CType(2.ToString(), T)|])
End Sub
End Module"
Await TestExactActionSetOfferedAsync(
source,
expectedActionSet:={
String.Format(FeaturesResources.Introduce_local_for_0, "CType(2.ToString(), T)"),
String.Format(FeaturesResources.Introduce_local_for_all_occurrences_of_0, "CType(2.ToString(), T)")})
' Verifies "Introduce field ..." is missing
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestNoIntroduceFieldOnMethodParameter() As Task
Dim source = "Module Program
Sub Main(x As Integer)
Goo([|x.ToString()|])
End Sub
End Module"
Await TestExactActionSetOfferedAsync(
source,
expectedActionSet:={
String.Format(FeaturesResources.Introduce_local_for_0, "x.ToString()"),
String.Format(FeaturesResources.Introduce_local_for_all_occurrences_of_0, "x.ToString()")})
' Verifies "Introduce field ..." is missing
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestNoRefactoringOnExpressionInAssignmentStatement() As Task
Dim source = "Module Program
Sub Main(x As Integer)
Dim r = [|x.ToString()|]
End Sub
End Module"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestLocalGeneratedInInnerBlock1() As Task
Dim source = "Module Program
Sub Main(x As Integer)
If True Then
Goo([|x.ToString()|])
End If
End Sub
End Module"
Dim expected = "Module Program
Sub Main(x As Integer)
If True Then
Dim {|Rename:v|} As String = x.ToString()
Goo(v)
End If
End Sub
End Module"
Await TestInRegularAndScriptAsync(source, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestLocalGeneratedInInnerBlock2() As Task
Dim source = "Module Program
Sub Main(x As Integer)
If True Then
Goo([|x.ToString()|])
End If
End Sub
End Module"
Dim expected = "Module Program
Sub Main(x As Integer)
If True Then
Dim {|Rename:v|} As String = x.ToString()
Goo(v)
End If
End Sub
End Module"
Await TestInRegularAndScriptAsync(source, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestLocalFromSingleExpressionInAnonType() As Task
Dim source = "Module Program
Sub Main(x As Integer)
Dim f1 = New With {.SomeString = [|x.ToString()|]}
End Sub
End Module"
Dim expected = "Module Program
Sub Main(x As Integer)
Dim {|Rename:v|} As String = x.ToString()
Dim f1 = New With {.SomeString = v}
End Sub
End Module"
Await TestInRegularAndScriptAsync(source, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestLocalFromMultipleExpressionsInAnonType() As Task
Dim source = "Module Program
Sub Main(x As Integer)
Dim f1 = New With {.SomeString = [|x.ToString()|], .SomeOtherString = x.ToString()}
Dim f2 = New With {.SomeString = x.ToString(), .SomeOtherString = x.ToString()}
Dim str As String = x.ToString()
End Sub
End Module"
Dim expected = "Module Program
Sub Main(x As Integer)
Dim {|Rename:v|} As String = x.ToString()
Dim f1 = New With {.SomeString = v, .SomeOtherString = v}
Dim f2 = New With {.SomeString = v, .SomeOtherString = v}
Dim str As String = v
End Sub
End Module"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestLocalFromInferredFieldInitializer() As Task
Dim source = "Imports System
Class C
Sub M()
Dim a As New With {[|Environment.TickCount|]}
End Sub
End Class"
Dim expected = "Imports System
Class C
Sub M()
Dim {|Rename:tickCount|} As Integer = Environment.TickCount
Dim a As New With {tickCount}
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestLocalFromYieldStatement() As Task
Dim source = "Imports System
Class C
Iterator Function F() As IEnumerable(Of Integer)
Yield [|Environment.TickCount * 2|]
End Function
End Class"
Dim expected = "Imports System
Class C
Iterator Function F() As IEnumerable(Of Integer)
Dim {|Rename:v|} As Integer = Environment.TickCount * 2
Yield v
End Function
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestLocalFromWhileStatement() As Task
Dim source = "Class C
Sub M()
Dim x = 1
While [|x = 1|]
End While
End Sub
End Class"
Dim expected = "Class C
Sub M()
Dim x = 1
Dim {|Rename:v|} As Boolean = x = 1
While v
End While
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestLocalFromSingleExpressionInObjectInitializer() As Task
Dim source = "Module Program
Structure GooStruct
Dim GooMember1 As String
End Structure
Sub Main(x As Integer)
Dim f1 = New GooStruct With {.GooMember1 = [|""t"" + ""test""|]}
End Sub
End Module"
Dim expected = "Module Program
Structure GooStruct
Dim GooMember1 As String
End Structure
Sub Main(x As Integer)
Const {|Rename:V|} As String = ""t"" + ""test""
Dim f1 = New GooStruct With {.GooMember1 = V}
End Sub
End Module"
Await TestInRegularAndScriptAsync(source, expected, index:=2)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestLocalFromMultipleExpressionsInObjectInitializer() As Task
Dim code =
"
Module Program
Structure GooStruct
Dim GooMember1 As String
Dim GooMember2 As String
End Structure
Sub Main(x As Integer)
Dim f1 = New GooStruct With {.GooMember1 = [|""t"" + ""test""|], .GooMember2 = ""t"" + ""test""}
Dim f2 = New GooStruct With {.GooMember1 = ""t"" + ""test"", .GooMember2 = ""t"" + ""test""}
Dim str As String = ""t"" + ""test""
End Sub
End Module
"
Dim expected =
"
Module Program
Structure GooStruct
Dim GooMember1 As String
Dim GooMember2 As String
End Structure
Sub Main(x As Integer)
Const {|Rename:V|} As String = ""t"" + ""test""
Dim f1 = New GooStruct With {.GooMember1 = V, .GooMember2 = V}
Dim f2 = New GooStruct With {.GooMember1 = V, .GooMember2 = V}
Dim str As String = V
End Sub
End Module
"
Await TestInRegularAndScriptAsync(code, expected, index:=3)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestFieldFromMultipleExpressionsInAnonType() As Task
Dim source = "Class Program
Dim q = New With {.str = [|""t"" + ""test""|]}
Dim r = New With {.str = ""t"" + ""test""}
Sub Goo()
Dim x = ""t"" + ""test""
End Sub
End Class"
Dim expected = "Class Program
Private Const {|Rename:V|} As String = ""t"" + ""test""
Dim q = New With {.str = V}
Dim r = New With {.str = V}
Sub Goo()
Dim x = V
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestPrivateFieldFromExpressionInField() As Task
Dim source = "Class Program
Dim x = Goo([|2 + 2|])
End Class"
Dim expected = "Class Program
Private Const {|Rename:V|} As Integer = 2 + 2
Dim x = Goo(V)
End Class"
Await TestInRegularAndScriptAsync(source, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestNoLocalFromExpressionInField() As Task
Dim source = "Class Program
Dim x = Goo([|2 + 2|])
End Class"
Await TestExactActionSetOfferedAsync(source, {String.Format(FeaturesResources.Introduce_constant_for_0, "2 + 2"), String.Format(FeaturesResources.Introduce_constant_for_all_occurrences_of_0, "2 + 2")})
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestSharedModifierAbsentInGeneratedModuleFields() As Task
Dim source = "Module Program
Private ReadOnly y As Integer = 1
Dim x = Goo([|2 + y|])
End Module"
Dim expected = "Module Program
Private ReadOnly y As Integer = 1
Private ReadOnly {|Rename:v|} As Integer = 2 + y
Dim x = Goo(v)
End Module"
Await TestInRegularAndScriptAsync(source, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestSingleLocalInsertLocation() As Task
Dim source = "Class Program
Sub Method1()
Dim v1 As String = ""TEST""
Dim v2 As Integer = 2 + 2
Goo([|2 + 2|])
End Sub
End Class"
Dim expected = "Class Program
Sub Method1()
Dim v1 As String = ""TEST""
Dim v2 As Integer = 2 + 2
Const {|Rename:V|} As Integer = 2 + 2
Goo(V)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=2)
End Function
#Region "Parameter context"
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestConstantFieldGenerationForParameterSingleOccurrence() As Task
' This is incorrect: the field type should be Integer, not Object
Dim source = "Module Module1
Sub Goo(Optional x As Integer = [|42|])
End Sub
End Module"
Dim expected = "Module Module1
Private Const {|Rename:V|} As Integer = 42
Sub Goo(Optional x As Integer = V)
End Sub
End Module"
Await TestInRegularAndScriptAsync(source, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestConstantFieldGenerationForParameterAllOccurrences() As Task
' This is incorrect: the field type should be Integer, not Object
Dim source = "Module Module1
Sub Bar(Optional x As Integer = 42)
End Sub
Sub Goo(Optional x As Integer = [|42|])
End Sub
End Module"
Dim expected = "Module Module1
Private Const {|Rename:V|} As Integer = 42
Sub Bar(Optional x As Integer = V)
End Sub
Sub Goo(Optional x As Integer = V)
End Sub
End Module"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
#End Region
<WorkItem(540269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540269")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestReplaceDottedExpression() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Console.WriteLine([|Goo.someVariable|])
Console.WriteLine(Goo.someVariable)
End Sub
End Module
Friend Class Goo
Shared Public someVariable As Integer
End Class",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim {|Rename:someVariable|} As Integer = Goo.someVariable
Console.WriteLine(someVariable)
Console.WriteLine(someVariable)
End Sub
End Module
Friend Class Goo
Shared Public someVariable As Integer
End Class",
index:=1)
End Function
<WorkItem(540457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540457")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestReplaceSingleLineIfWithMultiLine1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
If True Then Goo([|2 + 2|])
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
If True Then
Const {|Rename:V|} As Integer = 2 + 2
Goo(V)
End If
End Sub
End Module",
index:=2)
End Function
<WorkItem(540457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540457")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestReplaceSingleLineIfWithMultiLine2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
If True Then Goo([|1 + 1|]) Else Bar(1 + 1)
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
If True Then
Const {|Rename:V|} As Integer = 1 + 1
Goo(V)
Else
Bar(1 + 1)
End If
End Sub
End Module",
index:=2)
End Function
<WorkItem(540457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540457")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestReplaceSingleLineIfWithMultiLine3() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
If True Then Goo([|1 + 1|]) Else Bar(1 + 1)
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Const {|Rename:V|} As Integer = 1 + 1
If True Then Goo(V) Else Bar(V)
End Sub
End Module",
index:=3)
End Function
<WorkItem(540457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540457")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestReplaceSingleLineIfWithMultiLine4() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
If True Then Goo(1 + 1) Else Bar([|1 + 1|])
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
If True Then
Goo(1 + 1)
Else
Const {|Rename:V|} As Integer = 1 + 1
Bar(V)
End If
End Sub
End Module",
index:=2)
End Function
<WorkItem(540468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540468")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestCantExtractMethodTypeParameterToFieldCount() As Task
Await TestActionCountAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(Of T)(x As Integer)
Goo([|CType(2.ToString(), T)|])
End Sub
End Module",
count:=2)
End Function
<WorkItem(540468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540468")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestCantExtractMethodTypeParameterToField() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(Of T)(x As Integer)
Goo([|CType(2.ToString(), T)|])
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(Of T)(x As Integer)
Dim {|Rename:t|} As T = CType(2.ToString(), T)
Goo(t)
End Sub
End Module")
End Function
<WorkItem(540489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540489")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestOnlyFieldsInsideConstructorInitializer() As Task
Await TestActionCountAsync(
"Class Goo
Sub New()
Me.New([|2 + 2|])
End Sub
Sub New(v As Integer)
End Sub
End Class",
count:=2)
Await TestInRegularAndScriptAsync(
"Class Goo
Sub New()
Me.New([|2 + 2|])
End Sub
Sub New(v As Integer)
End Sub
End Class",
"Class Goo
Private Const {|Rename:V|} As Integer = 2 + 2
Sub New()
Me.New(V)
End Sub
Sub New(v As Integer)
End Sub
End Class")
End Function
<WorkItem(540485, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540485")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestIntroduceLocalForConstantExpression() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim s As String() = New String([|10|]) {}
End Sub
End Module",
"Module Program
Sub Main(args As String())
Const {|Rename:V|} As Integer = 10
Dim s As String() = New String(V) {}
End Sub
End Module",
index:=3)
End Function
<WorkItem(1065689, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1065689")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestIntroduceLocalForConstantExpressionWithTrailingTrivia() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Private Function GetX() As Object
Return [|""c d
"" + ' comment 1
""a
b"" ' comment 2|]
End Function
End Class
",
"
Class C
Private Function GetX() As Object
Const {|Rename:V|} As String = ""c d
"" + ' comment 1
""a
b""
Return V ' comment 2
End Function
End Class
",
index:=3)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestIntroduceFieldWithTrailingTrivia() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Private Sub S()
Dim x = 1 + [|2|] ' comment
End Sub
End Class
",
"
Class C
Private Const {|Rename:V|} As Integer = 2
Private Sub S()
Dim x = 1 + V ' comment
End Sub
End Class
",
index:=1)
End Function
<WorkItem(540487, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540487")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestFormattingForPartialExpression() As Task
Dim code =
"
Module Program
Sub Main()
Dim i = [|1 + 2|] + 3
End Sub
End Module
"
Dim expected =
"
Module Program
Sub Main()
Const {|Rename:V|} As Integer = 1 + 2
Dim i = V + 3
End Sub
End Module
"
Await TestInRegularAndScriptAsync(code, expected, index:=2)
End Function
<WorkItem(540491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540491")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestInAttribute1() As Task
Await TestInRegularAndScriptAsync(
"<Attr([|2 + 2|])>
Class Goo
End Class
Friend Class AttrAttribute
Inherits Attribute
End Class",
"<Attr(Goo.V)>
Class Goo
Friend Const {|Rename:V|} As Integer = 2 + 2
End Class
Friend Class AttrAttribute
Inherits Attribute
End Class")
End Function
<WorkItem(540490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540490")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestInMyClassNew() As Task
Await TestInRegularAndScriptAsync(
"Class Goo
Sub New()
MyClass.New([|42|])
End Sub
Sub New(x As Integer)
End Sub
End Class",
"Class Goo
Private Const {|Rename:X|} As Integer = 42
Sub New()
MyClass.New(X)
End Sub
Sub New(x As Integer)
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestSingleToMultiLineIf1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
If True Then Goo([|2 + 2|]) Else Bar(2 + 2)
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
If True Then
Const {|Rename:V|} As Integer = 2 + 2
Goo(V)
Else
Bar(2 + 2)
End If
End Sub
End Module",
index:=2)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestSingleToMultiLineIf2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
If True Then Goo([|2 + 2|]) Else Bar(2 + 2)
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Const {|Rename:V|} As Integer = 2 + 2
If True Then Goo(V) Else Bar(V)
End Sub
End Module",
index:=3)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestSingleToMultiLineIf3() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
If True Then Goo(2 + 2) Else Bar([|2 + 2|])
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
If True Then
Goo(2 + 2)
Else
Const {|Rename:V|} As Integer = 2 + 2
Bar(V)
End If
End Sub
End Module",
index:=2)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestSingleToMultiLineIf4() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
If True Then Goo(2 + 2) Else Bar([|2 + 2|])
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Const {|Rename:V|} As Integer = 2 + 2
If True Then Goo(V) Else Bar(V)
End Sub
End Module",
index:=3)
End Function
<WorkItem(541604, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541604")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestAttribute() As Task
Await TestInRegularAndScriptAsync(
"<Attr([|2 + 2|])>
Class Goo
End Class
Friend Class AttrAttribute
Inherits System.Attribute
End Class",
"<Attr(Goo.V)>
Class Goo
Friend Const {|Rename:V|} As Integer = 2 + 2
End Class
Friend Class AttrAttribute
Inherits System.Attribute
End Class")
End Function
<WorkItem(542092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542092")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestRangeArgumentLowerBound1() As Task
Await TestMissingInRegularAndScriptAsync("Module M
Sub Main()
Dim x() As Integer
ReDim x([|0|] To 5)
End Sub
End Module")
End Function
<WorkItem(542092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542092")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestRangeArgumentLowerBound2() As Task
Dim code =
"
Module M
Sub Main()
Dim x() As Integer
ReDim x(0 To 5)
Dim a = [|0|] + 1
End Sub
End Module
"
Dim expected =
"
Module M
Sub Main()
Dim x() As Integer
ReDim x(0 To 5)
Const {|Rename:V|} As Integer = 0
Dim a = V + 1
End Sub
End Module
"
Await TestInRegularAndScriptAsync(code, expected, index:=3)
End Function
<WorkItem(543029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543029"), WorkItem(542963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542963"), WorkItem(542295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542295")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestUntypedExpression() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim q As Object
If True Then q = [|Sub()
End Sub|]
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim q As Object
If True Then
Dim {|Rename:p|} As Object = Sub()
End Sub
q = p
End If
End Sub
End Module")
End Function
<WorkItem(542374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542374")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestFieldConstantInAttribute1() As Task
Await TestInRegularAndScriptAsync(
"<Goo(2 + 3 + 4)>
Module Program
Dim x = [|2 + 3|] + 4
End Module
Friend Class GooAttribute
Inherits Attribute
Sub New(x As Integer)
End Sub
End Class",
"<Goo(2 + 3 + 4)>
Module Program
Private Const {|Rename:V|} As Integer = 2 + 3
Dim x = V + 4
End Module
Friend Class GooAttribute
Inherits Attribute
Sub New(x As Integer)
End Sub
End Class")
End Function
<WorkItem(542374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542374")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestFieldConstantInAttribute2() As Task
Await TestAsync(
"<Goo(2 + 3 + 4)>
Module Program
Dim x = [|2 + 3|] + 4
End Module
Friend Class GooAttribute
Inherits Attribute
Sub New(x As Integer)
End Sub
End Class",
"<Goo(V + 4)>
Module Program
Friend Const {|Rename:V|} As Integer = 2 + 3
Dim x = V + 4
End Module
Friend Class GooAttribute
Inherits Attribute
Sub New(x As Integer)
End Sub
End Class",
index:=1,
parseOptions:=Nothing)
End Function
<WorkItem(542783, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542783")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestMissingOnAttributeName() As Task
Await TestMissingInRegularAndScriptAsync(
"<[|Obsolete|]>
Class C
End Class")
End Function
<WorkItem(542811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542811")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestMissingOnFilterClause() As Task
Await TestMissingInRegularAndScriptAsync(
"Module Program
Sub Main()
Try
Catch ex As Exception When [|+|]
End Try
End Sub
End Module")
End Function
<WorkItem(542906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542906")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestNoIntroduceLocalInAttribute() As Task
Dim input =
"Module Program \n <Obsolete([|""""|])> \n Sub Main(args As String()) \n End Sub \n End Module"
Await TestActionCountAsync(
NewLines(input),
count:=2)
Await TestInRegularAndScriptAsync(
NewLines(input),
"Module Program
Private Const {|Rename:V|} As String = """"
<Obsolete(V)>
Sub Main(args As String())
End Sub
End Module")
End Function
<WorkItem(542947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542947")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestNotOnMyBase() As Task
Await TestMissingInRegularAndScriptAsync(
"Class c1
Public res As String
Sub Goo()
res = ""1""
End Sub
End Class
Class c2
Inherits c1
Sub scen1()
[|MyBase|].Goo()
End Sub
End Class")
End Function
<WorkItem(541966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541966")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestNestedMultiLineIf1() As Task
Dim code =
"
Imports System
Module Program
Sub Main()
If True Then If True Then Console.WriteLine([|1|]) Else Console.WriteLine(2) Else Console.WriteLine(3)
End Sub
End Module
"
Dim expected =
"
Imports System
Module Program
Sub Main()
If True Then
If True Then
Const {|Rename:Value|} As Integer = 1
Console.WriteLine(Value)
Else
Console.WriteLine(2)
End If
Else
Console.WriteLine(3)
End If
End Sub
End Module
"
Await TestInRegularAndScriptAsync(code, expected, index:=3)
End Function
<WorkItem(541966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541966")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestNestedMultiLineIf2() As Task
Dim code =
"
Imports System
Module Program
Sub Main()
If True Then If True Then Console.WriteLine(1) Else Console.WriteLine([|2|]) Else Console.WriteLine(3)
End Sub
End Module
"
Dim expected =
"
Imports System
Module Program
Sub Main()
If True Then
If True Then
Console.WriteLine(1)
Else
Const {|Rename:Value|} As Integer = 2
Console.WriteLine(Value)
End If
Else
Console.WriteLine(3)
End If
End Sub
End Module
"
Await TestInRegularAndScriptAsync(code, expected, index:=3)
End Function
<WorkItem(541966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541966")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestNestedMultiLineIf3() As Task
Dim code =
"
Imports System
Module Program
Sub Main()
If True Then If True Then Console.WriteLine(1) Else Console.WriteLine(2) Else Console.WriteLine([|3|])
End Sub
End Module
"
Dim expected =
"
Imports System
Module Program
Sub Main()
If True Then
If True Then Console.WriteLine(1) Else Console.WriteLine(2)
Else
Const {|Rename:Value|} As Integer = 3
Console.WriteLine(Value)
End If
End Sub
End Module
"
Await TestInRegularAndScriptAsync(code, expected, index:=3)
End Function
<WorkItem(543273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543273")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestSingleLineLambda1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module Program
Sub Main
Dim a = Sub(x As Integer) Console.WriteLine([|x + 1|]) ' Introduce local
End Sub
End Module",
"Imports System
Module Program
Sub Main
Dim a = Sub(x As Integer) Dim {|Rename:value|} As Integer = x + 1
Console.WriteLine(value)
End Sub ' Introduce local
End Sub
End Module")
End Function
<WorkItem(543273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543273")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestSingleLineLambda2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module Program
Sub Main
Dim a = Sub(x As Integer) If True Then Console.WriteLine([|x + 1|]) Else Console.WriteLine()
End Sub
End Module",
"Imports System
Module Program
Sub Main
Dim a = Sub(x As Integer)
If True Then
Dim {|Rename:value|} As Integer = x + 1
Console.WriteLine(value)
Else
Console.WriteLine()
End If
End Sub
End Sub
End Module")
End Function
<WorkItem(543273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543273")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestSingleLineLambda3() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module Program
Sub Main
Dim a = Sub(x As Integer) If True Then Console.WriteLine() Else Console.WriteLine([|x + 1|])
End Sub
End Module",
"Imports System
Module Program
Sub Main
Dim a = Sub(x As Integer)
If True Then
Console.WriteLine()
Else
Dim {|Rename:value|} As Integer = x + 1
Console.WriteLine(value)
End If
End Sub
End Sub
End Module")
End Function
<WorkItem(543273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543273")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestSingleLineLambda4() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module Program
Sub Main
Dim a = Sub(x As Integer) If True Then Console.WriteLine([|x + 1|]) Else Console.WriteLine(x + 1)
End Sub
End Module",
"Imports System
Module Program
Sub Main
Dim a = Sub(x As Integer)
Dim {|Rename:value|} As Integer = x + 1
If True Then Console.WriteLine(value) Else Console.WriteLine(value)
End Sub
End Sub
End Module",
index:=1)
End Function
<WorkItem(543299, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543299")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestSingleLineLambda5() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim query = Sub(a) a = New With {Key .Key = Function(ByVal arg As Integer) As Integer
Return arg
End Function}.Key.Invoke([|a Or a|])
End Sub
End Module",
"Module Program
Sub Main(args As String())
Dim query = Sub(a) Dim {|Rename:arg1|} As Object = a Or a
a = New With {Key .Key = Function(ByVal arg As Integer) As Integer
Return arg
End Function}.Key.Invoke(arg1)
End Sub
End Sub
End Module")
End Function
<WorkItem(542762, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542762")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestNotInIntoClause() As Task
Await TestMissingInRegularAndScriptAsync(
"Imports System.Linq
Module
Sub Main()
Dim x = Aggregate y In New Integer() {1}
Into [|Count()|]
End Sub
End Module")
End Function
<WorkItem(543289, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543289")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestNotOnAttribute1() As Task
Await TestMissingInRegularAndScriptAsync(
"Option Explicit Off
Module Program
<Runtime.CompilerServices.[|Extension|]()> _
Function Extension(ByVal x As Integer) As Integer
Return x
End Function
End Module")
End Function
<WorkItem(543289, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543289")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestNotOnAttribute2() As Task
Await TestMissingInRegularAndScriptAsync(
"Option Explicit Off
Module Program
<Runtime.CompilerServices.[|Extension()|]> _
Function Extension(ByVal x As Integer) As Integer
Return x
End Function
End Module")
End Function
<WorkItem(543461, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543461")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestCollectionInitializer() As Task
Await TestMissingInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim i1 = New Integer() [|{4, 5}|]
End Sub
End Module")
End Function
<WorkItem(543573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543573")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestCaseInsensitiveNameConflict() As Task
Await TestInRegularAndScriptAsync(
"Class M
Public Function Goo()
Return [|Me.Goo|] * 0
End Function
End Class",
"Class M
Public Function Goo()
Dim {|Rename:goo1|} As Object = Me.Goo
Return goo1 * 0
End Function
End Class")
End Function
<WorkItem(543590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543590")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestQuery1() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Linq
Public Class Base
Public Function Sample(ByVal arg As Integer) As Integer
Dim results = From s In New Integer() {1}
Select [|Sample(s)|]
Return 0
End Function
End Class",
"Imports System.Linq
Public Class Base
Public Function Sample(ByVal arg As Integer) As Integer
Dim results = From s In New Integer() {1}
Let {|Rename:v|} = Sample(s)
Select v
Return 0
End Function
End Class")
End Function
<WorkItem(543590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543590")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestQueryCount1() As Task
Await TestActionCountAsync(
"Imports System.Linq
Public Class Base
Public Function Sample(ByVal arg As Integer) As Integer
Dim results = From s In New Integer() {1}
Select [|Sample(s)|]
Return 0
End Function
End Class",
count:=2)
End Function
<WorkItem(543590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543590")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestQuery2() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Linq
Public Class Base
Public Function Sample(ByVal arg As Integer) As Integer
Dim results = From s In New Integer() {1}
Where [|Sample(s)|] > 21
Select Sample(s)
Return 0
End Function
End Class",
"Imports System.Linq
Public Class Base
Public Function Sample(ByVal arg As Integer) As Integer
Dim results = From s In New Integer() {1}
Let {|Rename:v|} = Sample(s) Where v > 21
Select Sample(s)
Return 0
End Function
End Class")
End Function
<WorkItem(543590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543590")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestQuery3() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Linq
Public Class Base
Public Function Sample(ByVal arg As Integer) As Integer
Dim results = From s In New Integer() {1}
Where [|Sample(s)|] > 21
Select Sample(s)
Return 0
End Function
End Class",
"Imports System.Linq
Public Class Base
Public Function Sample(ByVal arg As Integer) As Integer
Dim results = From s In New Integer() {1}
Let {|Rename:v|} = Sample(s) Where v > 21
Select v
Return 0
End Function
End Class",
index:=1)
End Function
<WorkItem(543590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543590")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestQuery4() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Linq
Public Class Base
Public Function Sample(ByVal arg As Integer) As Integer
Dim results = From s In New Integer() {1}
Where Sample(s) > 21
Select [|Sample(s)|]
Return 0
End Function
End Class",
"Imports System.Linq
Public Class Base
Public Function Sample(ByVal arg As Integer) As Integer
Dim results = From s In New Integer() {1}
Where Sample(s) > 21
Let {|Rename:v|} = Sample(s)
Select v
Return 0
End Function
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestQuery5() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Linq
Public Class Base
Public Function Sample(ByVal arg As Integer) As Integer
Dim results = From s In New Integer() {1}
Where Sample(s) > 21
Select [|Sample(s)|]
Return 0
End Function
End Class",
"Imports System.Linq
Public Class Base
Public Function Sample(ByVal arg As Integer) As Integer
Dim results = From s In New Integer() {1}
Let {|Rename:v|} = Sample(s)
Where v > 21
Select v
Return 0
End Function
End Class",
index:=1)
End Function
<WorkItem(543529, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543529")>
<WorkItem(909152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/909152")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestInStatementlessConstructorParameter() As Task
Await TestMissingInRegularAndScriptAsync("Class C1
Sub New(Optional ByRef x As String = [|Nothing|])
End Sub
End Class")
End Function
<WorkItem(543650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543650")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestReferenceToAnonymousTypeProperty() As Task
Await TestMissingInRegularAndScriptAsync(
"Class AM
Sub M(args As String())
Dim var1 As New AM
Dim at1 As New With {var1, .friend = [|.var1|]}
End Sub
End Class")
End Function
<WorkItem(543698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543698")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestIntegerArrayExpression() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main()
Return [|New Integer() {}|]
End Sub
End Module",
"Module Program
Sub Main()
Dim {|Rename:v|} As Integer() = New Integer() {}
Return v
End Sub
End Module")
End Function
<WorkItem(544273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544273")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestAttributeNamedParameter() As Task
Await TestMissingInRegularAndScriptAsync(
"Class TestAttribute
Inherits Attribute
Public Sub New(Optional a As Integer = 42)
End Sub
End Class
<Test([|a|]:=5)>
Class Goo
End Class")
End Function
<WorkItem(544265, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544265")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestMissingOnWrittenToExpression() As Task
Await TestMissingInRegularAndScriptAsync(
"Module Program
Sub Main()
Dim x = New Integer() {1, 2}
[|x(1)|] = 2
End Sub
End Module")
End Function
<WorkItem(543824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543824")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestImplicitMemberAccess1() As Task
Await TestMissingInRegularAndScriptAsync(
"Imports System
Public Class C1
Public FieldInt As Long
Public FieldStr As String
Public Property PropInt As Integer
End Class
Public Class C2
Public Shared Sub Main()
Dim x = 1 + New C1() With {.FieldStr = [|.FieldInt|].ToString()}
End Sub
End Class")
End Function
<WorkItem(543824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543824")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestImplicitMemberAccess2() As Task
Await TestMissingInRegularAndScriptAsync(
"Imports System
Public Class C1
Public FieldInt As Long
Public FieldStr As String
Public Property PropInt As Integer
End Class
Public Class C2
Public Shared Sub Main()
Dim x = 1 + New C1() With {.FieldStr = [|.FieldInt.ToString|]()}
End Sub
End Class")
End Function
<WorkItem(543824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543824")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestImplicitMemberAccess3() As Task
Await TestMissingInRegularAndScriptAsync(
"Imports System
Public Class C1
Public FieldInt As Long
Public FieldStr As String
Public Property PropInt As Integer
End Class
Public Class C2
Public Shared Sub Main()
Dim x = 1 + New C1() With {.FieldStr = [|.FieldInt.ToString()|]}
End Sub
End Class")
End Function
<WorkItem(543824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543824")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestImplicitMemberAccess4() As Task
Dim code =
"
Imports System
Public Class C1
Public FieldInt As Long
Public FieldStr As String
Public Property PropInt As Integer
End Class
Public Class C2
Public Shared Sub Main()
Dim x = 1 + [|New C1() With {.FieldStr = .FieldInt.ToString()}|]
End Sub
End Class
"
Dim expected =
"
Imports System
Public Class C1
Public FieldInt As Long
Public FieldStr As String
Public Property PropInt As Integer
End Class
Public Class C2
Public Shared Sub Main()
Dim {|Rename:c1|} As C1 = New C1() With {.FieldStr = .FieldInt.ToString()}
Dim x = 1 + c1
End Sub
End Class
"
Await TestInRegularAndScriptAsync(code, expected)
End Function
<WorkItem(529510, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529510")>
<WpfFact(Skip:="529510"), Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestNoRefactoringOnAddressOfExpression() As Task
Dim source = "Imports System
Module Module1
Public Sub Goo(ByVal a1 As Exception)
End Sub
Public Sub goo(ByVal a1 As Action(Of ArgumentException))
End Sub
Sub Main()
Goo(New Action(Of Exception)([|AddressOf Goo|]))
End Sub
End Module"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<WorkItem(529510, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529510")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)>
Public Async Function TestMissingOnAddressOfInDelegate() As Task
Await TestMissingInRegularAndScriptAsync(
"Module Module1
Public Sub Goo(ByVal a1 As Exception)
End Sub
Public Sub goo(ByVal a1 As Action(Of ArgumentException))
End Sub
Sub Main()
goo(New Action(Of Exception)([|AddressOf Goo|]))
End Sub
End Module")
End Function
<WorkItem(545168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545168")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)>
Public Async Function TestMissingOnXmlName() As Task
Await TestMissingInRegularAndScriptAsync(
"Module M
Sub Main()
Dim x = <[|x|]/>
End Sub
End Module")
End Function
<WorkItem(545262, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545262")>
<WorkItem(909152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/909152")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestInTernaryConditional() As Task
Await TestMissingInRegularAndScriptAsync("Module Program
Sub Main(args As String())
Dim p As Object = Nothing
Dim Obj1 = If(New With {.a = True}.a, p, [|Nothing|])
End Sub
End Module")
End Function
<WorkItem(545316, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545316")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestInPropertyInitializer() As Task
Await TestInRegularAndScriptAsync(
"Module Module1
Property Prop As New List(Of String) From {[|""One""|], ""two""}
End Module",
"Module Module1
Private Const {|Rename:V|} As String = ""One""
Property Prop As New List(Of String) From {V, ""two""}
End Module")
End Function
<WorkItem(545308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545308")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestDoNotMergeAmpersand() As Task
Dim code =
"
Module Module1
Public Sub goo(Optional ByVal arg = ([|""a""|]) & ""b"")
End Sub
End Module
"
Dim expected =
"
Module Module1
Private Const {|Rename:V|} As String = ""a""
Public Sub goo(Optional ByVal arg = V & ""b"")
End Sub
End Module
"
Await TestInRegularAndScriptAsync(code, expected)
End Function
<WorkItem(545258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545258")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestVenusGeneration1() As Task
Dim code =
"
Class C
Sub Goo()
#ExternalSource (""Goo"", 1)
Console.WriteLine([|5|])
#End ExternalSource
End Sub
End Class
"
Dim expected =
"
Class C
Sub Goo()
#ExternalSource (""Goo"", 1)
Const {|Rename:V|} As Integer = 5
Console.WriteLine(V)
#End ExternalSource
End Sub
End Class
"
Await TestExactActionSetOfferedAsync(code,
{String.Format(FeaturesResources.Introduce_local_constant_for_0, "5"),
String.Format(FeaturesResources.Introduce_local_constant_for_all_occurrences_of_0, "5")})
Await TestInRegularAndScriptAsync(code, expected)
End Function
<WorkItem(545258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545258")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestVenusGeneration2() As Task
Dim code =
"
Class C
#ExternalSource (""Goo"", 1)
Sub Goo()
If False Then
Console.WriteLine([|5|])
End If
End Sub
#End ExternalSource
End Class
"
Await TestExactActionSetOfferedAsync(code,
{String.Format(FeaturesResources.Introduce_local_constant_for_0, "5"),
String.Format(FeaturesResources.Introduce_local_constant_for_all_occurrences_of_0, "5")})
End Function
<WorkItem(545258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545258")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestVenusGeneration3() As Task
Dim code =
"
Class C
Sub Goo()
#ExternalSource (""Goo"", 1)
If False Then
Console.WriteLine([|5|])
End If
#End ExternalSource
End Sub
End Class
"
Dim expected =
"
Class C
Sub Goo()
#ExternalSource (""Goo"", 1)
If False Then
Const {|Rename:V|} As Integer = 5
Console.WriteLine(V)
End If
#End ExternalSource
End Sub
End Class
"
Await TestExactActionSetOfferedAsync(code,
{String.Format(FeaturesResources.Introduce_local_constant_for_0, "5"),
String.Format(FeaturesResources.Introduce_local_constant_for_all_occurrences_of_0, "5")})
Await TestInRegularAndScriptAsync(code, expected)
End Function
<WorkItem(545525, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545525")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestInvocation() As Task
Await TestInRegularAndScriptAsync(
"Option Strict On
Class C
Shared Sub Main()
Dim x = [|New C().Goo()|](0)
End Sub
Function Goo() As Integer()
End Function
End Class",
"Option Strict On
Class C
Shared Sub Main()
Dim {|Rename:v|} As Integer() = New C().Goo()
Dim x = v(0)
End Sub
Function Goo() As Integer()
End Function
End Class")
End Function
<WorkItem(545829, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545829")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestOnImplicitMemberAccess() As Task
Await TestAsync(
"Module Program
Sub Main()
With """"
Dim x = [|.GetHashCode|] Xor &H7F3E ' Introduce Local
End With
End Sub
End Module",
"Module Program
Sub Main()
With """"
Dim {|Rename:getHashCode|} As Integer = .GetHashCode
Dim x = getHashCode Xor &H7F3E ' Introduce Local
End With
End Sub
End Module",
parseOptions:=Nothing)
Await TestAsync(
"Module Program
Sub Main()
With """"
Dim x = [|.GetHashCode|] Xor &H7F3E ' Introduce Local
End With
End Sub
End Module",
"Module Program
Sub Main()
With """"
Dim {|Rename:getHashCode|} As Integer = .GetHashCode
Dim x = getHashCode Xor &H7F3E ' Introduce Local
End With
End Sub
End Module",
parseOptions:=GetScriptOptions())
End Function
<WorkItem(545702, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545702")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestMissingInRefLocation() As Task
Dim markup =
"
Module A
Sub Main()
Goo([|1|])
End Sub
Sub Goo(ByRef x As Long)
End Sub
Sub Goo(x As String)
End Sub
End Module
"
Await TestMissingInRegularAndScriptAsync(markup)
End Function
<WorkItem(546139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546139")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestAcrossPartialTypes() As Task
Await TestInRegularAndScriptAsync(
"Partial Class C
Sub goo1(Optional x As String = [|""HELLO""|])
End Sub
End Class
Partial Class C
Sub goo3(Optional x As String = ""HELLO"")
End Sub
End Class",
"Partial Class C
Private Const {|Rename:V|} As String = ""HELLO""
Sub goo1(Optional x As String = V)
End Sub
End Class
Partial Class C
Sub goo3(Optional x As String = V)
End Sub
End Class",
index:=1)
End Function
<WorkItem(544669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544669")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestFunctionBody1() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim a1 = Function(ByVal x) [|x!goo|]
End Sub
End Module",
"Module Program
Sub Main(args As String())
Dim a1 = Function(ByVal x)
Dim {|Rename:goo|} As Object = x!goo
Return goo
End Function
End Sub
End Module")
End Function
<WorkItem(1065689, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1065689")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestTrailingTrivia() As Task
Dim code =
"
Module M
Sub Main()
Dim a = 1 +
[|2|] ' comment
End Sub
End Module
"
Dim expected =
"
Module M
Private Const {|Rename:V|} As Integer = 2
Sub Main()
Dim a = 1 +
V ' comment
End Sub
End Module
"
Await TestInRegularAndScriptAsync(code, expected)
End Function
<WorkItem(546815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546815")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestInIfStatement() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
If [|True|] Then
End If
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Private Const {|Rename:V|} As Boolean = True
Sub Main(args As String())
If V Then
End If
End Sub
End Module")
End Function
<WorkItem(830928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/830928")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestIntroduceLocalRemovesUnnecessaryCast() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Collections.Generic
Class C
Private Shared Sub Main(args As String())
Dim hSet = New HashSet(Of String)()
hSet.Add([|hSet.ToString()|])
End Sub
End Class",
"Imports System.Collections.Generic
Class C
Private Shared Sub Main(args As String())
Dim hSet = New HashSet(Of String)()
Dim {|Rename:item|} As String = hSet.ToString()
hSet.Add(item)
End Sub
End Class")
End Function
<WorkItem(546691, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546691")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestIntroLocalInSingleLineLambda() As Task
Dim code =
"
Module Program
Sub Main()
Dim x = Function() [|Sub()
End Sub|]
End Sub
End Module
"
Dim expected =
"
Module Program
Sub Main()
Dim {|Rename:p|} = Sub()
End Sub
Dim x = Function() p
End Sub
End Module
"
Await TestInRegularAndScriptAsync(code, expected)
End Function
<WorkItem(530720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530720")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestSingleToMultilineLambdaLineBreaks() As Task
Dim code =
"
Module Program
Sub Main()
Dim a = Function(c) [|c!goo|]
End Sub
End Module
"
Dim expected =
"
Module Program
Sub Main()
Dim a = Function(c)
Dim {|Rename:goo|} As Object = c!goo
Return goo
End Function
End Sub
End Module
"
Await TestInRegularAndScriptAsync(code, expected)
End Function
<WorkItem(531478, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531478")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestEscapeKeywordsIfNeeded1() As Task
Dim code =
"
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main()
Take([|From x In """"|])
End Sub
Sub Take(x)
End Sub
End Module
"
Dim expected =
"
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main()
Dim {|Rename:x1|} As IEnumerable(Of Char) = From x In """"
[Take](x1)
End Sub
Sub Take(x)
End Sub
End Module
"
Await TestInRegularAndScriptAsync(code, expected)
End Function
<WorkItem(632327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632327")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestInsertAfterPreprocessor1() As Task
Dim code =
"
Public Class Index_vbhtml
Public Sub Execute()
#ExternalSource (""Home\Index.vbhtml"", 1)
Dim i = [|1 + 2|] + 3
If True Then
Dim j = 1 + 2 + 3
End If
#End ExternalSource
End Sub
End Class
"
Dim expected =
"
Public Class Index_vbhtml
Public Sub Execute()
#ExternalSource (""Home\Index.vbhtml"", 1)
Const {|Rename:V|} As Integer = 1 + 2
Dim i = V + 3
If True Then
Dim j = 1 + 2 + 3
End If
#End ExternalSource
End Sub
End Class
"
Await TestInRegularAndScriptAsync(code, expected)
End Function
<WorkItem(632327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632327")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestInsertAfterPreprocessor2() As Task
Dim code =
"
Public Class Index_vbhtml
Public Sub Execute()
#ExternalSource (""Home\Index.vbhtml"", 1)
Dim i = 1 + 2 + 3
If True Then
Dim j = [|1 + 2|] + 3
End If
#End ExternalSource
End Sub
End Class
"
Dim expected =
"
Public Class Index_vbhtml
Public Sub Execute()
#ExternalSource (""Home\Index.vbhtml"", 1)
Dim i = 1 + 2 + 3
If True Then
Const {|Rename:V|} As Integer = 1 + 2
Dim j = V + 3
End If
#End ExternalSource
End Sub
End Class
"
Await TestInRegularAndScriptAsync(code, expected)
End Function
<WorkItem(682683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682683")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestDontRemoveParenthesesIfOperatorPrecedenceWouldBeBroken() As Task
Dim code =
"
Imports System
Module Program
Sub Main()
Console.WriteLine(5 - ([|1|] + 2))
End Sub
End Module
"
Dim expected =
"
Imports System
Module Program
Sub Main()
Const {|Rename:V|} As Integer = 1
Console.WriteLine(5 - (V + 2))
End Sub
End Module
"
Await TestInRegularAndScriptAsync(code, expected, index:=2)
End Function
<WorkItem(1022458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1022458")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestDontSimplifyParentUnlessEntireInnerNodeIsSelected() As Task
Dim code =
"
Imports System
Module Program
Sub Main()
Dim s = ""Text""
Dim x = 42
If ([|s.Length|].CompareTo(x) > 0 AndAlso
s.Length.CompareTo(x) > 0) Then
End If
End Sub
End Module
"
Dim expected =
"
Imports System
Module Program
Sub Main()
Dim s = ""Text""
Dim x = 42
Dim {|Rename:length|} As Integer = s.Length
If (length.CompareTo(x) > 0 AndAlso
length.CompareTo(x) > 0) Then
End If
End Sub
End Module
"
Await TestInRegularAndScriptAsync(code, expected, index:=1)
End Function
<WorkItem(939259, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939259")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestIntroduceLocalWithTriviaInMultiLineStatements() As Task
Dim code =
"
Imports System
Module Program
Sub Main()
Dim x = If(True,
[|1|], ' TODO: Comment
2)
End Sub
End Module
"
Dim expected =
"
Imports System
Module Program
Sub Main()
Const {|Rename:V|} As Integer = 1
Dim x = If(True,
V, ' TODO: Comment
2)
End Sub
End Module
"
Await TestInRegularAndScriptAsync(code, expected, index:=3)
End Function
<WorkItem(909152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/909152")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestMissingOnNothingLiteral() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Module Program
Sub Main(args As String())
Main([|Nothing|])
M(Nothing)
End Sub
Sub M(i As Integer)
End Sub
End Module
")
End Function
<WorkItem(1130990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130990")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestInParentConditionalAccessExpressions() As Task
Dim code =
"
Imports System
Class C
Function F(Of T)(x As T) As T
Dim y = [|F(New C)|]?.F(New C)?.F(New C)
Return x
End Function
End Class
"
Dim expected =
"
Imports System
Class C
Function F(Of T)(x As T) As T
Dim {|Rename:c|} As C = F(New C)
Dim y = c?.F(New C)?.F(New C)
Return x
End Function
End Class
"
Await TestInRegularAndScriptAsync(code, expected)
End Function
<WorkItem(1130990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130990")>
<WorkItem(3110, "https://github.com/dotnet/roslyn/issues/3110")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestMissingAcrossMultipleParentConditionalAccessExpressions() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Function F(Of T)(x As T) As T
Dim y = [|F(New C)?.F(New C)|]?.F(New C)
Return x
End Function
End Class
")
End Function
<WorkItem(1130990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130990")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestMissingOnInvocationExpressionInParentConditionalAccessExpressions() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Function F(Of T)(x As T) As T
Dim y = F(New C)?.[|F(New C)|]?.F(New C)
Return x
End Function
End Class
")
End Function
<WorkItem(1130990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130990")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestMissingOnMemberBindingExpressionInParentConditionalAccessExpressions() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub F()
Dim s as String = ""Text""
Dim l = s?.[|Length|]
End Sub
End Class
")
End Function
<WorkItem(2026, "https://github.com/dotnet/roslyn/issues/2026")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestReplaceAllFromInsideIfBlock() As Task
Dim code =
"
Imports System
Module DataTipInfoGetterModule
Friend Function GetInfoAsync() As DebugDataTipInfo
Dim expression As ExpressionSyntax = Nothing
Dim curr = DirectCast(expression.Parent, ExpressionSyntax)
If curr Is expression.Parent Then
Return New DebugDataTipInfo([|expression.Parent|].Span)
End If
Return Nothing
End Function
End Module
Friend Class TextSpan
End Class
Friend Class ExpressionSyntax
Public Property Parent As ExpressionSyntax
Public Property Span As TextSpan
End Class
Friend Class DebugDataTipInfo
Public Sub New(span As Object)
End Sub
End Class
"
Dim expected =
"
Imports System
Module DataTipInfoGetterModule
Friend Function GetInfoAsync() As DebugDataTipInfo
Dim expression As ExpressionSyntax = Nothing
Dim {|Rename:parent|} As ExpressionSyntax = expression.Parent
Dim curr = DirectCast(parent, ExpressionSyntax)
If curr Is parent Then
Return New DebugDataTipInfo(parent.Span)
End If
Return Nothing
End Function
End Module
Friend Class TextSpan
End Class
Friend Class ExpressionSyntax
Public Property Parent As ExpressionSyntax
Public Property Span As TextSpan
End Class
Friend Class DebugDataTipInfo
Public Sub New(span As Object)
End Sub
End Class
"
Await TestInRegularAndScriptAsync(code, expected, index:=1)
End Function
<WorkItem(1065661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1065661")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestIntroduceVariableTextDoesntSpanLines1() As Task
Dim code = "
Class C
Sub M()
Dim s = """" + [|""a
b
c""|]
End Sub
End Class"
Await TestSmartTagTextAsync(code, String.Format(FeaturesResources.Introduce_local_constant_for_0, """a b c"""), New TestParameters(index:=2))
End Function
<WorkItem(1065661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1065661")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestIntroduceVariableTextDoesntSpanLines2() As Task
Dim code = "
Class C
Sub M()
Dim s = """" + [|$""a
b
c""|]
End Sub
End Class"
Await TestSmartTagTextAsync(code, String.Format(FeaturesResources.Introduce_local_for_0, "$""a b c"""))
End Function
<WorkItem(976, "https://github.com/dotnet/roslyn/issues/976")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestNoConstantForInterpolatedStrings1() As Task
Dim code =
"
Module Program
Sub Main()
Dim args As String() = Nothing
Console.WriteLine([|$""{DateTime.Now.ToString()}Text{args(0)}""|])
End Sub
End Module
"
Dim expected =
"
Module Program
Sub Main()
Dim args As String() = Nothing
Dim {|Rename:v|} As String = $""{DateTime.Now.ToString()}Text{args(0)}""
Console.WriteLine(v)
End Sub
End Module
"
Await TestInRegularAndScriptAsync(code, expected)
End Function
<WorkItem(976, "https://github.com/dotnet/roslyn/issues/976")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestNoConstantForInterpolatedStrings2() As Task
Dim code =
"
Module Program
Sub Main()
Console.WriteLine([|$""Text{{s}}""|])
Console.WriteLine($""Text{{s}}"")
End Sub
End Module
"
Dim expected =
"
Module Program
Sub Main()
Dim {|Rename:v|} As String = $""Text{{s}}""
Console.WriteLine(v)
Console.WriteLine(v)
End Sub
End Module
"
Await TestInRegularAndScriptAsync(code, expected, index:=1)
End Function
<WorkItem(3147, "https://github.com/dotnet/roslyn/issues/3147")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestHandleFormattableStringTargetTyping1() As Task
Const code = "
Imports System
" & FormattableStringType & "
Namespace N
Class C
Public Sub M()
Dim f = FormattableString.Invariant([|$""""|])
End Sub
End Class
End Namespace"
Const expected = "
Imports System
" & FormattableStringType & "
Namespace N
Class C
Public Sub M()
Dim {|Rename:formattable|} As FormattableString = $""""
Dim f = FormattableString.Invariant(formattable)
End Sub
End Class
End Namespace"
Await TestInRegularAndScriptAsync(code, expected)
End Function
<WorkItem(936, "https://github.com/dotnet/roslyn/issues/936")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestInAutoPropertyInitializerEqualsClause() As Task
Dim code =
"
Imports System
Class C
Property Name As String = [|""Roslyn""|]
End Class
"
Dim expected =
"
Imports System
Class C
Private Const {|Rename:V|} As String = ""Roslyn""
Property Name As String = V
End Class
"
Await TestInRegularAndScriptAsync(code, expected)
End Function
<WorkItem(936, "https://github.com/dotnet/roslyn/issues/936")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestInAutoPropertyWithCollectionInitializerAfterEqualsClause() As Task
Dim code =
"
Imports System
Class C
Property Grades As Integer() = [|{90, 73}|]
End Class
"
Dim expected =
"
Imports System
Class C
Private Shared ReadOnly {|Rename:p|} As Integer() = {90, 73}
Property Grades As Integer() = p
End Class
"
Await TestInRegularAndScriptAsync(code, expected)
End Function
<WorkItem(936, "https://github.com/dotnet/roslyn/issues/936")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestInAutoPropertyInitializerAsClause() As Task
Dim code =
"
Imports System
Class C
Public Property Items As New List(Of String) From {[|""M""|], ""T"", ""W""}
End Class
"
Dim expected =
"
Imports System
Class C
Private Const {|Rename:V|} As String = ""M""
Public Property Items As New List(Of String) From {V, ""T"", ""W""}
End Class
"
Await TestInRegularAndScriptAsync(code, expected)
End Function
<WorkItem(936, "https://github.com/dotnet/roslyn/issues/936")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestInAutoPropertyObjectCreationExpressionWithinAsClause() As Task
Dim code =
"
Imports System
Class C
Property Orders As New List(Of Object)([|500|])
End Class
"
Dim expected =
"
Imports System
Class C
Private Const {|Rename:V|} As Integer = 500
Property Orders As New List(Of Object)(V)
End Class
"
Await TestInRegularAndScriptAsync(code, expected)
End Function
<WorkItem(11777, "https://github.com/dotnet/roslyn/issues/11777")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestGenerateLocalConflictingName1() As Task
Await TestInRegularAndScriptAsync(
"class Program
class MySpan
public Start as integer
end class
sub Method(span as MySpan)
dim pos as integer = span.Start
while pos < [|span.Start|]
dim start as integer = pos
end while
end sub
end class",
"class Program
class MySpan
public Start as integer
end class
sub Method(span as MySpan)
dim pos as integer = span.Start
Dim {|Rename:start1|} As Integer = span.Start
while pos < start1
dim start as integer = pos
end while
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TupleWithInferredName_LeaveExplicitName() As Task
Dim code = "
Class C
Shared Dim y As Integer = 2
Sub M()
Dim a As Integer = 1
Dim t = (a, x:=[|C.y|])
End Sub
End Class
"
Dim expected = "
Class C
Shared Dim y As Integer = 2
Sub M()
Dim a As Integer = 1
Dim {|Rename:y1|} As Integer = C.y
Dim t = (a, x:=y1)
End Sub
End Class
"
Await TestAsync(code, expected, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TupleWithInferredName_InferredNameBecomesExplicit() As Task
Dim code = "
Class C
Shared Dim y As Integer = 2
Sub M()
Dim a As Integer = 1
Dim t = (a, [|C.y|])
End Sub
End Class
"
Dim expected = "
Class C
Shared Dim y As Integer = 2
Sub M()
Dim a As Integer = 1
Dim {|Rename:y1|} As Integer = C.y
Dim t = (a, y:=y1)
End Sub
End Class
"
Await TestAsync(code, expected, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TupleWithInferredName_AllOccurrences() As Task
Dim code = "
Class C
Shared Dim y As Integer = 2
Sub M()
Dim a As Integer = 1
Dim t = (a, [|C.y|])
Dim t2 = (C.y, a)
End Sub
End Class
"
Dim expected = "
Class C
Shared Dim y As Integer = 2
Sub M()
Dim a As Integer = 1
Dim {|Rename:y1|} As Integer = C.y
Dim t = (a, y:=y1)
Dim t2 = (y:=y1, a)
End Sub
End Class
"
Await TestAsync(code, expected, index:=1,
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TupleWithInferredName_NoDuplicateNames() As Task
Dim code = "
Class C
Shared Dim y As Integer = 2
Sub M()
Dim t = (C.y, [|C.y|])
End Sub
End Class
"
Dim expected = "
Class C
Shared Dim y As Integer = 2
Sub M()
Dim {|Rename:y1|} As Integer = C.y
Dim t = (y1, y1)
End Sub
End Class
"
Await TestInRegularAndScriptAsync(code, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TupleWithInferredName_NoReservedNames() As Task
Dim code = "
Class C
Shared Dim rest As Integer = 2
Sub M()
Dim a As Integer = 1
Dim t = (a, [|C.rest|])
End Sub
End Class
"
Dim expected = "
Class C
Shared Dim rest As Integer = 2
Sub M()
Dim a As Integer = 1
Dim {|Rename:rest1|} As Integer = C.rest
Dim t = (a, rest1)
End Sub
End Class
"
Await TestAsync(code, expected, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function AnonymousTypeWithInferredName_LeaveExplicitName() As Task
Dim code = "
Class C
Shared Dim y As Integer = 2
Sub M()
Dim a As Integer = 1
Dim t = New With {a, [|C.y|]}
End Sub
End Class
"
Dim expected = "
Class C
Shared Dim y As Integer = 2
Sub M()
Dim a As Integer = 1
Dim {|Rename:y1|} As Integer = C.y
Dim t = New With {a, .y = y1}
End Sub
End Class
"
Await TestInRegularAndScriptAsync(code, expected)
End Function
<WorkItem(2423, "https://github.com/dotnet/roslyn/issues/2423")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestPickNameBasedOnArgument1() As Task
Await TestInRegularAndScriptAsync(
"class C
public sub new(a as string, b as string)
dim c = new TextSpan([|integer.Parse(a)|], integer.Parse(b))
end sub
end class
structure TextSpan
public sub new(start as integer, length as integer)
end sub
end structure",
"class C
public sub new(a as string, b as string)
Dim {|Rename:start|} As Integer = integer.Parse(a)
dim c = new TextSpan(start, integer.Parse(b))
end sub
end class
structure TextSpan
public sub new(start as integer, length as integer)
end sub
end structure")
End Function
<WorkItem(2423, "https://github.com/dotnet/roslyn/issues/2423")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestPickNameBasedOnArgument2() As Task
Await TestInRegularAndScriptAsync(
"class C
public sub new(a as string, b as string)
dim c = new TextSpan(integer.Parse(a), [|integer.Parse(b)|])
end sub
end class
structure TextSpan
public sub new(start as integer, length as integer)
end sub
end structure",
"class C
public sub new(a as string, b as string)
Dim {|Rename:length|} As Integer = integer.Parse(b)
dim c = new TextSpan(integer.Parse(a), length)
end sub
end class
structure TextSpan
public sub new(start as integer, length as integer)
end sub
end structure")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
<WorkItem(10123, "https://github.com/dotnet/roslyn/issues/10123")>
Public Async Function TestSimpleParameterName() As Task
Dim source = "Module Program
Sub Main(x As Integer)
Goo([|x|])
End Sub
End Module"
Dim expected = "Module Program
Sub Main(x As Integer)
Dim {|Rename:x1|} As Integer = x
Goo(x1)
End Sub
End Module"
Await TestInRegularAndScriptAsync(source, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
<WorkItem(10123, "https://github.com/dotnet/roslyn/issues/10123")>
Public Async Function TestSimpleParameterName_EmptySelection() As Task
Dim source = "Module Program
Sub Main(x As Integer)
Goo([||]x)
End Sub
End Module"
Await TestMissingAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
<WorkItem(10123, "https://github.com/dotnet/roslyn/issues/10123")>
Public Async Function TestFieldName_QualifiedWithMe() As Task
Dim source = "Module Program
Dim x As Integer
Sub Main()
Goo([|x|])
End Sub
End Module"
Dim expected = "Module Program
Dim x As Integer
Sub Main()
Dim {|Rename:x1|} As Integer = x
Goo(x1)
End Sub
End Module"
Await TestInRegularAndScriptAsync(source, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
<WorkItem(10123, "https://github.com/dotnet/roslyn/issues/10123")>
Public Async Function TestFieldName_QualifiedWithType() As Task
Dim source = "Module Program
Shared Dim x As Integer
Sub Main()
Goo([|Program.x|])
End Sub
End Module"
Dim expected = "Module Program
Shared Dim x As Integer
Sub Main()
Dim {|Rename:x1|} As Integer = Program.x
Goo(x1)
End Sub
End Module"
Await TestInRegularAndScriptAsync(source, expected)
End Function
<WorkItem(21373, "https://github.com/dotnet/roslyn/issues/21373")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestInAttribute() As Task
Dim code = "
Class C
Public Property Foo()
<Example([|3 + 3|])>
Public Property Bar()
End Class
"
Dim expected = "
Class C
Private Const {|Rename:V|} As Integer = 3 + 3
Public Property Foo()
<Example(V)>
Public Property Bar()
End Class
"
Await TestInRegularAndScriptAsync(code, expected)
End Function
<WorkItem(28266, "https://github.com/dotnet/roslyn/issues/28266")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestCaretAtEndOfExpression1() As Task
Await TestInRegularAndScriptAsync(
"class C
sub Goo()
Bar(1[||], 2)
end sub
end class",
"class C
Private Const {|Rename:V|} As Integer = 1
sub Goo()
Bar(V, 2)
end sub
end class")
End Function
<WorkItem(28266, "https://github.com/dotnet/roslyn/issues/28266")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestCaretAtEndOfExpression2() As Task
Await TestInRegularAndScriptAsync(
"class C
sub Goo()
Bar(1, 2[||])
end sub
end class",
"class C
Private Const {|Rename:V|} As Integer = 2
sub Goo()
Bar(1, V)
end sub
end class")
End Function
<WorkItem(28266, "https://github.com/dotnet/roslyn/issues/28266")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestCaretAtEndOfExpression3() As Task
Await TestInRegularAndScriptAsync(
"class C
sub Goo()
Bar(1, (2[||]))
end sub
end class",
"class C
Private Const {|Rename:V|} As Integer = 2
sub Goo()
Bar(1, V)
end sub
end class")
End Function
<WorkItem(28266, "https://github.com/dotnet/roslyn/issues/28266")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
Public Async Function TestCaretAtEndOfExpression4() As Task
Await TestInRegularAndScriptAsync(
"class C
sub Goo()
Bar(1, Bar(2[||]))
end sub
end class",
"class C
Private Const {|Rename:V|} As Integer = 2
sub Goo()
Bar(1, Bar(V))
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
<WorkItem(27949, "https://github.com/dotnet/roslyn/issues/27949")>
Public Async Function TestWhitespaceSpanInAssignment() As Task
Await TestMissingAsync("
Class C
Dim x As Integer = [| |] 0
End Class
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
<WorkItem(28665, "https://github.com/dotnet/roslyn/issues/28665")>
Public Async Function TestWhitespaceSpanInAttribute() As Task
Await TestMissingAsync("
Class C
<Example( [| |] )>
Public Function Foo()
End Function
End Class
")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
<WorkItem(30207, "https://github.com/dotnet/roslyn/issues/30207")>
Public Async Function TestExplicitRecursiveInstanceMemberAccess_ForAllOccurrences() As Task
Dim source = "
Class C
Dim c As C
Sub Foo()
Dim y = [|c|].c.c
End Sub
End Class
"
Dim expected = "
Class C
Dim c As C
Sub Foo()
Dim {|Rename:c1|} As C = c
Dim y = c1.c.c
End Sub
End Class
"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
<WorkItem(30207, "https://github.com/dotnet/roslyn/issues/30207")>
Public Async Function TestImplicitRecursiveInstanceMemberAccess_ForAllOccurrences() As Task
Dim source = "
Class C
Dim c As C
Sub Foo()
Dim y = [|Me.c|].c.c
End Sub
End Class
"
Dim expected = "
Class C
Dim c As C
Sub Foo()
Dim {|Rename:c1|} As C = Me.c
Dim y = c1.c.c
End Sub
End Class
"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
<WorkItem(30207, "https://github.com/dotnet/roslyn/issues/30207")>
Public Async Function TestExpressionOfUndeclaredType() As Task
Dim source = "
Class C
Sub Test
Dim array As A() = [|A|].Bar()
End Sub
End Class"
Await TestMissingAsync(source)
End Function
End Class
End Namespace
|
DustinCampbell/roslyn
|
src/EditorFeatures/VisualBasicTest/CodeActions/IntroduceVariable/IntroduceVariableTests.vb
|
Visual Basic
|
apache-2.0
| 96,654
|
' 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.InteropServices
Imports System.Windows
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Notification
Imports Microsoft.VisualStudio.ComponentModelHost
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options
<Guid(Guids.VisualBasicOptionPageNamingStyleIdString)>
Friend Class NamingStylesOptionPage
Inherits AbstractOptionPage
Private _grid As NamingStyleOptionPageControl
Private _notificationService As INotificationService
Protected Overrides Function CreateOptionPage(serviceProvider As IServiceProvider, optionStore As OptionStore) As AbstractOptionPageControl
Dim componentModel = DirectCast(serviceProvider.GetService(GetType(SComponentModel)), IComponentModel)
Dim workspace = componentModel.GetService(Of VisualStudioWorkspace)
_notificationService = workspace.Services.GetService(Of INotificationService)
_grid = New NamingStyleOptionPageControl(optionStore, _notificationService, LanguageNames.VisualBasic)
Return _grid
End Function
Protected Overrides Sub OnApply(e As PageApplyEventArgs)
If _grid.ContainsErrors() Then
_notificationService.SendNotification(ServicesVSResources.Some_naming_rules_are_incomplete_Please_complete_or_remove_them)
e.ApplyBehavior = ApplyKind.Cancel
Return
End If
MyBase.OnApply(e)
End Sub
End Class
End Namespace
|
VSadov/roslyn
|
src/VisualStudio/VisualBasic/Impl/Options/NamingStylesOptionPage.vb
|
Visual Basic
|
apache-2.0
| 1,833
|
' 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.Rename.ConflictEngine
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp
Public Class LocalConflictTests
Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper
Public Sub New(outputHelper As Abstractions.ITestOutputHelper)
_outputHelper = outputHelper
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(539939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539939")>
Public Sub ConflictingLocalWithLocal()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] args)
{
int {|stmt1:$$x|} = 1;
int {|Conflict:y|} = 2;
}
}
</Document>
</Project>
</Workspace>, renameTo:="y")
result.AssertLabeledSpansAre("stmt1", "y", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(539939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539939")>
Public Sub ConflictingLocalWithParameter()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] {|Conflict:args|})
{
int {|stmt1:$$x|} = 1;
}
}
</Document>
</Project>
</Workspace>, renameTo:="args")
result.AssertLabeledSpansAre("stmt1", "args", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictingLocalWithForEachRangeVariable()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] args)
{
int {|stmt1:$$x|} = 1;
foreach (var {|Conflict:y|} in args) { }
}
}
</Document>
</Project>
</Workspace>, renameTo:="y")
result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictingLocalWithForLoopVariable()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] args)
{
int {|stmt1:$$x|} = 1;
for (int {|Conflict:y|} = 0; ; } { }
}
}
</Document>
</Project>
</Workspace>, renameTo:="y")
result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictingLocalWithUsingBlockVariable()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program : IDisposable
{
static void Main(string[] args)
{
int {|stmt1:$$x|} = 1;
using (var {|Conflict:y|} = new Program()) { }
}
}
</Document>
</Project>
</Workspace>, renameTo:="y")
result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictingLocalWithSimpleLambdaParameter()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class Program
{
static void Main(string[] args)
{
int {|stmt1:$$x|} = 1;
Func<int> lambda = {|Conflict:y|} => 42;
}
}
]]></Document>
</Project>
</Workspace>, renameTo:="y")
result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictingLocalWithParenthesizedLambdaParameter()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class Program
{
static void Main(string[] args)
{
int {|stmt1:$$x|} = 1;
Func<int> lambda = ({|Conflict:y|}) => 42;
}
}
]]></Document>
</Project>
</Workspace>, renameTo:="y")
result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictingFromClauseWithLetClause()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Linq;
class C
{
static void Main(string[] args)
{
var temp = from [|$$x|] in "abc"
let {|DeclarationConflict:y|} = [|x|].ToString()
select {|Conflict:y|};
}
}
</Document>
</Project>
</Workspace>, renameTo:="y")
' We have two kinds of conflicts here: we flag a declaration conflict on the let:
result.AssertLabeledSpansAre("DeclarationConflict", type:=RelatedLocationType.UnresolvedConflict)
' And also for the y in the select clause. The compiler binds the "y" to the let
' clause's y.
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenLabelsInSameMethod()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
public class C
{
public void Foo()
{
{|stmt1:$$Bar|}:;
{|Conflict:Foo|}:;
}
}
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenLabelInMethodAndLambda()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
public class C
{
public void Foo()
{
{|stmt1:$$Bar|}: ;
Action x = () => { {|Conflict:Foo|}:;};
}
}
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenLabelsInLambda()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
public class C
{
Action x = () =>
{
{|Conflict:Foo|}:;
{|stmt1:$$Bar|}: ;
};
}
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictBetweenLabelsInTwoNonNestedLambdas()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
public class C
{
public void Foo()
{
Action x = () => { Foo:; };
Action x = () => { {|stmt1:$$Bar|}:; };
}
}
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo", RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(545468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545468")>
Public Sub NoConflictsWithCatchBlockWithoutExceptionVariable()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Test
{
static void Main()
{
try
{
int {|stmt1:$$i|};
}
catch (System.Exception)
{
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(1081066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1081066")>
Public Sub NoConflictsBetweenCatchClauses()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class Test
{
static void Main()
{
try { } catch (Exception {|stmt1:$$ex|}) { }
try { } catch (Exception j) { }
}
}
</Document>
</Project>
</Workspace>, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(1081066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1081066")>
Public Sub ConflictsWithinCatchClause()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class Test
{
static void Main()
{
try { } catch (Exception {|stmt1:$$ex|}) { int {|stmt2:j|}; }
try { } catch (Exception j) { }
}
}
</Document>
</Project>
</Workspace>, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.UnresolvableConflict)
result.AssertLabeledSpansAre("stmt2", "j", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(546163, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546163")>
Public Sub NoConflictsWithCatchExceptionWithoutDeclaration()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Test
{
static void Main()
{
try
{
int {|stmt1:$$i|};
}
catch
{
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(992721, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/992721")>
Public Sub ConflictingLocalWithFieldWithExtensionMethodInvolved()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
private List<object> {|def:_list|};
public Program(IEnumerable<object> list)
{
{|stmt2:_list|} = list.ToList();
foreach (var i in {|stmt1:$$_list|}.OfType<int>()){}
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="list")
result.AssertLabeledSpansAre("def", "list", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt1", "foreach (var i in this.list.OfType<int>()){}", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("stmt2", "this.list = list.ToList();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(17177, "https://github.com/dotnet/roslyn/issues/17177")>
Public Sub ConflictsBetweenSwitchCaseStatementsWithoutBlocks()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Test
{
static void Main()
{
switch (true)
{
case true:
object {|stmt1:$$i|} = null;
break;
case false:
object {|stmt2:j|} = null;
break;
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "j", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(17177, "https://github.com/dotnet/roslyn/issues/17177")>
Public Sub NoConflictsBetweenSwitchCaseStatementsWithBlocks()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Test
{
static void Main()
{
switch (true)
{
case true:
{
object {|stmt1:$$i|} = null;
break;
}
case false:
{
object j = null;
break;
}
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(17177, "https://github.com/dotnet/roslyn/issues/17177")>
Public Sub NoConflictsBetweenSwitchCaseStatementFirstStatementWithBlock()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Test
{
static void Main()
{
switch (true)
{
case true:
{
object {|stmt1:$$i|} = null;
break;
}
case false:
object {|stmt2:j|} = null;
break;
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "j", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(17177, "https://github.com/dotnet/roslyn/issues/17177")>
Public Sub NoConflictsBetweenSwitchCaseStatementSecondStatementWithBlock()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Test
{
static void Main()
{
switch (true)
{
case true:
object {|stmt1:$$i|} = null;
break;
case false:
{
object {|stmt2:j|} = null;
break;
}
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "j", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
End Class
End Namespace
|
amcasey/roslyn
|
src/EditorFeatures/Test2/Rename/CSharp/LocalConflictTests.vb
|
Visual Basic
|
apache-2.0
| 20,257
|
' 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.Generic
Imports System.Collections.Immutable
Imports System.Diagnostics.CodeAnalysis
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Collections
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Describes anonymous type/delegate in terms of fields/parameters
''' </summary>
Friend Structure AnonymousTypeDescriptor
Implements IEquatable(Of AnonymousTypeDescriptor)
Public Shared ReadOnly SubReturnParameterName As String = "Sub"
Public Shared ReadOnly FunctionReturnParameterName As String = "Function"
Friend Shared Function GetReturnParameterName(isFunction As Boolean) As String
Return If(isFunction, FunctionReturnParameterName, SubReturnParameterName)
End Function
''' <summary> Anonymous type/delegate location </summary>
Public ReadOnly Location As Location
''' <summary> Anonymous type fields </summary>
Public ReadOnly Fields As ImmutableArray(Of AnonymousTypeField)
''' <summary>
''' Anonymous type descriptor Key
'''
''' The key is being used to separate anonymous type templates, for example in an anonymous type
''' symbol cache. The type descriptors with the same keys are supposed to map to 'the same' anonymous
''' type template in terms of the same generic type being used for their implementation.
''' </summary>
Public ReadOnly Key As String
''' <summary> Anonymous type is implicitly declared </summary>
Public ReadOnly IsImplicitlyDeclared As Boolean
''' <summary> Anonymous delegate parameters, including one for return type </summary>
Public ReadOnly Property Parameters As ImmutableArray(Of AnonymousTypeField)
Get
Return Fields
End Get
End Property
Public Sub New(fields As ImmutableArray(Of AnonymousTypeField), _location As Location, _isImplicitlyDeclared As Boolean)
Me.Fields = fields
Me.Location = _location
Me.IsImplicitlyDeclared = _isImplicitlyDeclared
Me.Key = ComputeKey(fields, Function(f) f.Name, Function(f) f.IsKey)
End Sub
Friend Shared Function ComputeKey(Of T)(fields As ImmutableArray(Of T), getName As Func(Of T, String), getIsKey As Func(Of T, Boolean)) As String
Dim pooledBuilder = PooledStringBuilder.GetInstance()
Dim builder = pooledBuilder.Builder
For Each field In fields
builder.Append("|"c)
builder.Append(getName(field))
builder.Append(If(getIsKey(field), "+"c, "-"c))
Next
IdentifierComparison.ToLower(builder)
Return pooledBuilder.ToStringAndFree()
End Function
''' <summary>
''' This is ONLY used for debugging purpose
''' </summary>
<Conditional("DEBUG")>
Friend Sub AssertGood()
' Fields exist
Debug.Assert(Not Fields.IsEmpty)
' All fields are good
For Each field In Fields
field.AssertGood()
Next
End Sub
Public Overloads Function Equals(other As AnonymousTypeDescriptor) As Boolean Implements IEquatable(Of AnonymousTypeDescriptor).Equals
' Comparing keys ensures field count, field names and keyness are equal
If Not Me.Key.Equals(other.Key) Then
Return False
End If
' Compare field types
Dim myFields As ImmutableArray(Of AnonymousTypeField) = Me.Fields
Dim count As Integer = myFields.Length
Dim otherFields As ImmutableArray(Of AnonymousTypeField) = other.Fields
For i = 0 To count - 1
If Not myFields(i).Type.Equals(otherFields(i).Type) Then
Return False
End If
Next
Return True
End Function
Public Overloads Overrides Function Equals(obj As Object) As Boolean
Return TypeOf obj Is AnonymousTypeDescriptor AndAlso Equals(DirectCast(obj, AnonymousTypeDescriptor))
End Function
Public Overrides Function GetHashCode() As Integer
Return Me.Key.GetHashCode()
End Function
''' <summary>
''' Performs internal substitution of types in anonymous type descriptor fields and returns True
''' if any of the fields was changed, in which case a new descriptor is returned in newDescriptor
''' </summary>
Public Function SubstituteTypeParametersIfNeeded(substitution As TypeSubstitution, <Out> ByRef newDescriptor As AnonymousTypeDescriptor) As Boolean
Dim fieldCount = Me.Fields.Length
Dim newFields(fieldCount - 1) As AnonymousTypeField
Dim anyChange As Boolean = False
For i = 0 To fieldCount - 1
Dim current As AnonymousTypeField = Me.Fields(i)
newFields(i) = New AnonymousTypeField(current.Name,
current.Type.InternalSubstituteTypeParameters(substitution),
current.Location,
current.IsKey)
If Not anyChange Then
anyChange = current.Type IsNot newFields(i).Type
End If
Next
If anyChange Then
newDescriptor = New AnonymousTypeDescriptor(newFields.AsImmutableOrNull(), Me.Location, Me.IsImplicitlyDeclared)
Else
newDescriptor = Nothing
End If
Return anyChange
End Function
End Structure
''' <summary>
''' Describes anonymous type field in terms of its name, type and other attributes.
''' Or describes anonymous delegate parameter, including "return" parameter, in terms
''' of its name, type and other attributes.
''' </summary>
Friend Structure AnonymousTypeField
''' <summary> Anonymous type field/parameter name, not nothing and not empty </summary>
Public ReadOnly Name As String
''' <summary>Location of the field</summary>
Public ReadOnly Location As Location
''' <summary> Anonymous type field/parameter type, must be not nothing when
''' the field is passed to anonymous type descriptor </summary>
Public ReadOnly Property Type As TypeSymbol
Get
Return Me._type
End Get
End Property
''' <summary>
''' Anonymous type field/parameter type, may be nothing when field descriptor is created,
''' must be assigned before passing the descriptor to anonymous type descriptor.
''' Once assigned, is considered to be 'sealed'.
''' </summary>
Private _type As TypeSymbol
''' <summary> Anonymous type field is declared as a 'Key' field </summary>
Public ReadOnly IsKey As Boolean
''' <summary>
''' Does this describe a ByRef parameter of an Anonymous Delegate type
''' </summary>
Public ReadOnly Property IsByRef As Boolean
Get
Return IsKey
End Get
End Property
Public Sub New(name As String, type As TypeSymbol, location As Location, Optional isKeyOrByRef As Boolean = False)
Me.Name = If(String.IsNullOrWhiteSpace(name), "<Empty Name>", name)
Me._type = type
Me.IsKey = isKeyOrByRef
Me.Location = location
End Sub
Public Sub New(name As String, location As Location, Optional isKey As Boolean = False)
Me.New(name, Nothing, location, isKey)
End Sub
''' <summary>
''' This is ONLY used for debugging purpose
''' </summary>
<Conditional("DEBUG")>
Friend Sub AssertGood()
Debug.Assert(Name IsNot Nothing AndAlso Me.Type IsNot Nothing AndAlso Me.Location IsNot Nothing)
End Sub
Friend Sub AssignFieldType(newType As TypeSymbol)
Debug.Assert(newType IsNot Nothing)
Debug.Assert(Me._type Is Nothing)
Me._type = newType
End Sub
End Structure
End Namespace
|
DavidKarlas/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/AnonymousTypeDescriptor.vb
|
Visual Basic
|
apache-2.0
| 8,557
|
' 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.Generic
Imports System.Collections.Immutable
Imports System.Reflection.Metadata
Imports Microsoft.Cci
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' A representation of a method symbol that is intended only to be used for comparison purposes
''' (esp in MethodSignatureComparer).
''' </summary>
Friend NotInheritable Class SignatureOnlyMethodSymbol
Inherits MethodSymbol
Private ReadOnly _name As String
Private ReadOnly _containingType As TypeSymbol
Private ReadOnly _methodKind As MethodKind
Private ReadOnly _callingConvention As CallingConvention
Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol)
Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol)
Private ReadOnly _returnsByRef As Boolean
Private ReadOnly _returnType As TypeSymbol
Private ReadOnly _returnTypeCustomModifiers As ImmutableArray(Of CustomModifier)
Private ReadOnly _explicitInterfaceImplementations As ImmutableArray(Of MethodSymbol)
Private ReadOnly _isOverrides As Boolean
Public Sub New(ByVal name As String, ByVal m_containingType As TypeSymbol, ByVal methodKind As MethodKind, ByVal callingConvention As CallingConvention, ByVal typeParameters As ImmutableArray(Of TypeParameterSymbol), ByVal parameters As ImmutableArray(Of ParameterSymbol),
ByVal returnsByRef As Boolean, ByVal returnType As TypeSymbol, ByVal returnTypeCustomModifiers As ImmutableArray(Of CustomModifier), ByVal explicitInterfaceImplementations As ImmutableArray(Of MethodSymbol),
Optional isOverrides As Boolean = False)
_callingConvention = callingConvention
_typeParameters = typeParameters
_returnsByRef = returnsByRef
_returnType = returnType
_returnTypeCustomModifiers = returnTypeCustomModifiers
_parameters = parameters
_explicitInterfaceImplementations = If(explicitInterfaceImplementations.IsDefault, ImmutableArray(Of MethodSymbol).Empty, explicitInterfaceImplementations)
_containingType = m_containingType
_methodKind = methodKind
_name = name
_isOverrides = isOverrides
End Sub
Friend Overrides ReadOnly Property CallingConvention() As CallingConvention
Get
Return _callingConvention
End Get
End Property
Public Overrides ReadOnly Property IsVararg() As Boolean
Get
Return New SignatureHeader(CByte(_callingConvention)).CallingConvention = SignatureCallingConvention.VarArgs
End Get
End Property
Public Overrides ReadOnly Property IsGenericMethod() As Boolean
Get
Return Arity > 0
End Get
End Property
Public Overrides ReadOnly Property Arity() As Integer
Get
Return _typeParameters.Length
End Get
End Property
Public Overrides ReadOnly Property TypeParameters() As ImmutableArray(Of TypeParameterSymbol)
Get
Return _typeParameters
End Get
End Property
Public Overrides ReadOnly Property ReturnsByRef As Boolean
Get
Return _returnsByRef
End Get
End Property
Public Overrides ReadOnly Property ReturnType() As TypeSymbol
Get
Return _returnType
End Get
End Property
Public Overrides ReadOnly Property ReturnTypeCustomModifiers() As ImmutableArray(Of CustomModifier)
Get
Return _returnTypeCustomModifiers
End Get
End Property
Public Overrides ReadOnly Property Parameters() As ImmutableArray(Of ParameterSymbol)
Get
Return _parameters
End Get
End Property
Public Overrides ReadOnly Property ExplicitInterfaceImplementations() As ImmutableArray(Of MethodSymbol)
Get
Return _explicitInterfaceImplementations
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol() As Symbol
Get
Return _containingType
End Get
End Property
Public Overrides ReadOnly Property MethodKind() As MethodKind
Get
Return _methodKind
End Get
End Property
Friend Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property Name() As String
Get
Return _name
End Get
End Property
Public Overrides ReadOnly Property IsSub As Boolean
Get
Return ReturnType.SpecialType = SpecialType.System_Void
End Get
End Property
Public Overrides ReadOnly Property IsAsync As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsIterator As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Nothing
End Get
End Property
#Region "Not used by MethodSignatureComparer"
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Public Overrides ReadOnly Property TypeArguments() As ImmutableArray(Of TypeSymbol)
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Public Overrides ReadOnly Property AssociatedSymbol() As Symbol
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Public Overrides ReadOnly Property IsExtensionMethod() As Boolean
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Public Overrides ReadOnly Property Locations() As ImmutableArray(Of Location)
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility() As Accessibility
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Public Overrides ReadOnly Property ContainingAssembly() As AssemblySymbol
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return _isOverrides
End Get
End Property
Friend Overrides ReadOnly Property Syntax As VisualBasicSyntaxNode
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Public Overrides ReadOnly Property IsOverloads As Boolean
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Public Overrides ReadOnly Property IsExternalMethod As Boolean
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Public Overrides Function GetDllImportData() As DllImportData
Return Nothing
End Function
Friend Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Friend Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean
Get
Return False
End Get
End Property
Friend Overrides Function GetSecurityInformation() As IEnumerable(Of SecurityAttribute)
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String)
Throw ExceptionUtilities.Unreachable
End Function
Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean
Throw ExceptionUtilities.Unreachable
End Function
Friend Overrides ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of MethodSymbol)
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Public Overrides ReadOnly Property OverriddenMethod As MethodSymbol
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer
Throw ExceptionUtilities.Unreachable
End Function
#End Region
End Class
End Namespace
|
MatthieuMEZIL/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/SignatureOnlyMethodSymbol.vb
|
Visual Basic
|
apache-2.0
| 10,982
|
' 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.Recommendations.Queries
Public Class AggregateKeywordRecommenderTests
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateNotInStatementTest() As Task
Await VerifyRecommendationsMissingAsync(<MethodBody>|</MethodBody>, "Aggregate")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterReturnTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Return |</MethodBody>, "Aggregate")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterArgument1Test() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Goo(|</MethodBody>, "Aggregate")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterArgument2Test() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Goo(bar, |</MethodBody>, "Aggregate")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterBinaryExpressionTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Goo(bar + |</MethodBody>, "Aggregate")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterNotTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Goo(Not |</MethodBody>, "Aggregate")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterTypeOfTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>If TypeOf |</MethodBody>, "Aggregate")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterDoWhileTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Do While |</MethodBody>, "Aggregate")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterDoUntilTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Do Until |</MethodBody>, "Aggregate")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterLoopWhileTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>
Do
Loop While |</MethodBody>, "Aggregate")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterLoopUntilTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>
Do
Loop Until |</MethodBody>, "Aggregate")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterIfTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>If |</MethodBody>, "Aggregate")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterElseIfTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>ElseIf |</MethodBody>, "Aggregate")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterElseSpaceIfTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Else If |</MethodBody>, "Aggregate")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterErrorTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Error |</MethodBody>, "Aggregate")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterThrowTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Throw |</MethodBody>, "Aggregate")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterArrayInitializerSquiggleTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = {|</MethodBody>, "Aggregate")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterArrayInitializerCommaTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = {0, |</MethodBody>, "Aggregate")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function SpecExample1Test() As Task
Await VerifyRecommendationsContainAsync(
<MethodBody>
Dim orderTotals = _
From cust In Customers _
Where cust.State = "WA" _
|
</MethodBody>, "Aggregate")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function SpecExample2Test() As Task
Await VerifyRecommendationsContainAsync(
<MethodBody>
Dim ordersTotal = _
|
</MethodBody>, "Aggregate")
End Function
<WorkItem(543173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543173")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterMultiLineFunctionLambdaExprTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim q2 = From i1 In arr Order By Function()
Return 5
End Function |</MethodBody>, "Aggregate")
End Function
<WorkItem(543174, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543174")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterAnonymousObjectCreationExprTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim q2 = From i1 In arr Order By New With {.Key = 10} |</MethodBody>, "Aggregate")
End Function
<WorkItem(543219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543219")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterIntoClauseTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim q1 = From i1 In arr Group By i1 Into Count |</MethodBody>, "Aggregate")
End Function
<WorkItem(543232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543232")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AggregateAfterNestedAggregateFromClauseTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim q1 = Aggregate i1 In arr From i4 In arr |</MethodBody>, "Aggregate")
End Function
<WorkItem(543270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543270")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function NotInDelegateCreationTest() As Task
Dim code =
<File>
Module Program
Sub Main(args As String())
Dim f1 As New Goo2( |
End Sub
Delegate Sub Goo2()
Function Bar2() As Object
Return Nothing
End Function
End Module
</File>
Await VerifyRecommendationsMissingAsync(code, "Aggregate")
End Function
End Class
End Namespace
|
OmarTawfik/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/Queries/AggregateKeywordRecommenderTests.vb
|
Visual Basic
|
apache-2.0
| 8,034
|
' 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.Diagnostics
Imports System.Globalization
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class LocalRewriter
Public Overrides Function VisitLabelStatement(node As BoundLabelStatement) As BoundNode
Dim statement = DirectCast(MyBase.VisitLabelStatement(node), BoundStatement)
' Keep track of line number if need to.
If _currentLineTemporary IsNot Nothing AndAlso _currentMethodOrLambda Is _topMethod AndAlso
Not node.WasCompilerGenerated AndAlso node.Syntax.Kind = SyntaxKind.LabelStatement Then
Dim labelSyntax = DirectCast(node.Syntax, LabelStatementSyntax)
If labelSyntax.LabelToken.Kind = SyntaxKind.IntegerLiteralToken Then
Dim lineNumber As Integer = 0
Integer.TryParse(labelSyntax.LabelToken.ValueText, NumberStyles.None, CultureInfo.InvariantCulture, lineNumber)
Dim trackLineNumber As BoundStatement = New BoundAssignmentOperator(node.Syntax,
New BoundLocal(node.Syntax, _currentLineTemporary, _currentLineTemporary.Type),
New BoundLiteral(node.Syntax, ConstantValue.Create(lineNumber), _currentLineTemporary.Type),
suppressObjectClone:=True).ToStatement()
' Need to update resume state when we track line numbers for labels.
If ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Then
trackLineNumber = RegisterUnstructuredExceptionHandlingResumeTarget(node.Syntax, trackLineNumber, canThrow:=False)
End If
statement = New BoundStatementList(node.Syntax, ImmutableArray.Create(statement, trackLineNumber))
End If
End If
' only labels from the source get their sequence points here
' synthetic labels are the responsibility of whoever created them
If node.Label.IsFromCompilation(_compilationState.Compilation) Then
statement = MarkStatementWithSequencePoint(statement)
End If
Return statement
End Function
End Class
End Namespace
|
droyad/roslyn
|
src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_Label.vb
|
Visual Basic
|
apache-2.0
| 2,864
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class RawFileViewer
Inherits System.Windows.Forms.UserControl
'UserControl overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(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.NumericUpDown1 = New System.Windows.Forms.NumericUpDown()
Me.ComboBox1 = New System.Windows.Forms.ComboBox()
Me.Label2 = New System.Windows.Forms.Label()
Me.NumericUpDown2 = New System.Windows.Forms.NumericUpDown()
Me.Label3 = New System.Windows.Forms.Label()
CType(Me.NumericUpDown1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.NumericUpDown2, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Location = New System.Drawing.Point(27, 34)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(90, 13)
Me.Label1.TabIndex = 0
Me.Label1.Text = "Default XIC PPM:"
'
'NumericUpDown1
'
Me.NumericUpDown1.DecimalPlaces = 1
Me.NumericUpDown1.Increment = New Decimal(New Integer() {5, 0, 0, 65536})
Me.NumericUpDown1.Location = New System.Drawing.Point(150, 32)
Me.NumericUpDown1.Maximum = New Decimal(New Integer() {30, 0, 0, 0})
Me.NumericUpDown1.Name = "NumericUpDown1"
Me.NumericUpDown1.Size = New System.Drawing.Size(120, 20)
Me.NumericUpDown1.TabIndex = 1
Me.NumericUpDown1.Value = New Decimal(New Integer() {20, 0, 0, 0})
'
'ComboBox1
'
Me.ComboBox1.FormattingEnabled = True
Me.ComboBox1.Items.AddRange(New Object() {"Relative Intensity Cutoff", "Quantile Intensity Cutoff"})
Me.ComboBox1.Location = New System.Drawing.Point(30, 130)
Me.ComboBox1.Name = "ComboBox1"
Me.ComboBox1.Size = New System.Drawing.Size(163, 21)
Me.ComboBox1.TabIndex = 2
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.Location = New System.Drawing.Point(27, 102)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(143, 13)
Me.Label2.TabIndex = 3
Me.Label2.Text = "Fragment Trimming Methods:"
'
'NumericUpDown2
'
Me.NumericUpDown2.DecimalPlaces = 2
Me.NumericUpDown2.Increment = New Decimal(New Integer() {1, 0, 0, 131072})
Me.NumericUpDown2.Location = New System.Drawing.Point(299, 130)
Me.NumericUpDown2.Maximum = New Decimal(New Integer() {1, 0, 0, 0})
Me.NumericUpDown2.Name = "NumericUpDown2"
Me.NumericUpDown2.Size = New System.Drawing.Size(82, 20)
Me.NumericUpDown2.TabIndex = 5
Me.NumericUpDown2.Value = New Decimal(New Integer() {5, 0, 0, 131072})
'
'Label3
'
Me.Label3.AutoSize = True
Me.Label3.Location = New System.Drawing.Point(227, 133)
Me.Label3.Name = "Label3"
Me.Label3.Size = New System.Drawing.Size(57, 13)
Me.Label3.TabIndex = 4
Me.Label3.Text = "Threshold:"
'
'RawFileViewer
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.Controls.Add(Me.NumericUpDown2)
Me.Controls.Add(Me.Label3)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.ComboBox1)
Me.Controls.Add(Me.NumericUpDown1)
Me.Controls.Add(Me.Label1)
Me.Name = "RawFileViewer"
Me.Size = New System.Drawing.Size(555, 413)
CType(Me.NumericUpDown1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.NumericUpDown2, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents Label1 As Label
Friend WithEvents NumericUpDown1 As NumericUpDown
Friend WithEvents ComboBox1 As ComboBox
Friend WithEvents Label2 As Label
Friend WithEvents NumericUpDown2 As NumericUpDown
Friend WithEvents Label3 As Label
End Class
|
xieguigang/MassSpectrum-toolkits
|
src/mzkit/mzkit/pages/Settings/RawFileViewer.Designer.vb
|
Visual Basic
|
mit
| 4,874
|
#Region "Microsoft.VisualBasic::298a037ae8b397b8e6f556f229ec7f6b, src\metadb\Massbank\Public\NCBI\PubChemDescriptorRepo.vb"
' Author:
'
' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.)
'
' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD.
'
'
' MIT License
'
'
' 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.
' /********************************************************************************/
' Summaries:
' Class PubChemDescriptorRepo
'
' Constructor: (+1 Overloads) Sub New
'
' Function: GetDescriptor
'
' Sub: (+2 Overloads) Dispose, Write
'
' Module BinaryHelper
'
' Sub: (+2 Overloads) Write
'
' /********************************************************************************/
#End Region
Imports System.IO
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports BioNovoGene.BioDeep.Chemoinformatics
Public Class PubChemDescriptorRepo : Implements IDisposable
ReadOnly stream As New Dictionary(Of String, FileStream)
ReadOnly base$
''' <summary>
'''
''' </summary>
''' <param name="dir">
''' The database file is consist with multiple db files:
'''
''' 1. cid index database
''' 2. chemical descriptor property values database files.
'''
''' </param>
Sub New(dir$)
base = dir
dir.MakeDir
For Each descriptor As PropertyInfo In ChemicalDescriptor.schema
stream(descriptor.Name) = File.Open(
path:=$"{dir}/{descriptor.Name}.db",
mode:=FileMode.OpenOrCreate,
access:=FileAccess.ReadWrite,
share:=FileShare.Read
)
Next
End Sub
Public Function GetDescriptor(cid As Long) As ChemicalDescriptor
Dim offset32Bits As Long = (cid - 1) * 4
Dim offset64Bits As Long = (cid - 1) * 8
Dim descriptor As New ChemicalDescriptor
Dim buffer As Byte() = New Byte(8 - 1) {}
stream(NameOf(descriptor.Complexity)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.Complexity)).Read(buffer, Scan0, 4)
descriptor.Complexity = BitConverter.ToInt32(buffer, Scan0)
stream(NameOf(descriptor.ExactMass)).Seek(offset64Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.ExactMass)).Read(buffer, Scan0, 8)
descriptor.ExactMass = BitConverter.ToDouble(buffer, Scan0)
stream(NameOf(descriptor.FormalCharge)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.FormalCharge)).Read(buffer, Scan0, 4)
descriptor.FormalCharge = BitConverter.ToInt32(buffer, Scan0)
stream(NameOf(descriptor.HeavyAtoms)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.HeavyAtoms)).Read(buffer, Scan0, 4)
descriptor.HeavyAtoms = BitConverter.ToInt32(buffer, Scan0)
stream(NameOf(descriptor.HydrogenAcceptor)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.HydrogenAcceptor)).Read(buffer, Scan0, 4)
descriptor.HydrogenAcceptor = BitConverter.ToInt32(buffer, Scan0)
stream(NameOf(descriptor.HydrogenDonors)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.HydrogenDonors)).Read(buffer, Scan0, 4)
descriptor.HydrogenDonors = BitConverter.ToInt32(buffer, Scan0)
stream(NameOf(descriptor.RotatableBonds)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.RotatableBonds)).Read(buffer, Scan0, 4)
descriptor.RotatableBonds = BitConverter.ToInt32(buffer, Scan0)
stream(NameOf(descriptor.TopologicalPolarSurfaceArea)).Seek(offset64Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.TopologicalPolarSurfaceArea)).Read(buffer, Scan0, 8)
descriptor.TopologicalPolarSurfaceArea = BitConverter.ToDouble(buffer, Scan0)
stream(NameOf(descriptor.XLogP3)).Seek(offset64Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.XLogP3)).Read(buffer, Scan0, 8)
descriptor.XLogP3 = BitConverter.ToDouble(buffer, Scan0)
stream(NameOf(descriptor.XLogP3_AA)).Seek(offset64Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.XLogP3_AA)).Read(buffer, Scan0, 8)
descriptor.XLogP3_AA = BitConverter.ToDouble(buffer, Scan0)
stream(NameOf(descriptor.AtomDefStereoCount)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.AtomDefStereoCount)).Read(buffer, Scan0, 4)
descriptor.AtomDefStereoCount = BitConverter.ToInt32(buffer, Scan0)
stream(NameOf(descriptor.AtomUdefStereoCount)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.AtomUdefStereoCount)).Read(buffer, Scan0, 4)
descriptor.AtomUdefStereoCount = BitConverter.ToInt32(buffer, Scan0)
stream(NameOf(descriptor.BondDefStereoCount)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.BondDefStereoCount)).Read(buffer, Scan0, 4)
descriptor.BondDefStereoCount = BitConverter.ToInt32(buffer, Scan0)
stream(NameOf(descriptor.BondUdefStereoCount)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.BondUdefStereoCount)).Read(buffer, Scan0, 4)
descriptor.BondUdefStereoCount = BitConverter.ToInt32(buffer, Scan0)
stream(NameOf(descriptor.ComponentCount)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.ComponentCount)).Read(buffer, Scan0, 4)
descriptor.ComponentCount = BitConverter.ToInt32(buffer, Scan0)
stream(NameOf(descriptor.IsotopicAtomCount)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.IsotopicAtomCount)).Read(buffer, Scan0, 4)
descriptor.IsotopicAtomCount = BitConverter.ToInt32(buffer, Scan0)
stream(NameOf(descriptor.TautoCount)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.TautoCount)).Read(buffer, Scan0, 4)
descriptor.TautoCount = BitConverter.ToInt32(buffer, Scan0)
Return descriptor
End Function
Public Sub Write(cid&, descriptor As ChemicalDescriptor)
Dim offset32Bits As Long = (cid - 1) * 4
Dim offset64Bits As Long = (cid - 1) * 8
stream(NameOf(descriptor.Complexity)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.Complexity)).Write(descriptor.Complexity)
' stream(NameOf(descriptor.Complexity)).Flush()
stream(NameOf(descriptor.ExactMass)).Seek(offset64Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.ExactMass)).Write(descriptor.ExactMass)
' stream(NameOf(descriptor.ExactMass)).Flush()
stream(NameOf(descriptor.FormalCharge)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.FormalCharge)).Write(descriptor.FormalCharge)
' stream(NameOf(descriptor.FormalCharge)).Flush()
stream(NameOf(descriptor.HeavyAtoms)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.HeavyAtoms)).Write(descriptor.HeavyAtoms)
' stream(NameOf(descriptor.HeavyAtoms)).Flush()
stream(NameOf(descriptor.HydrogenAcceptor)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.HydrogenAcceptor)).Write(descriptor.HydrogenAcceptor)
' stream(NameOf(descriptor.HydrogenAcceptor)).Flush()
stream(NameOf(descriptor.HydrogenDonors)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.HydrogenDonors)).Write(descriptor.HydrogenDonors)
' stream(NameOf(descriptor.HydrogenDonors)).Flush()
stream(NameOf(descriptor.RotatableBonds)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.RotatableBonds)).Write(descriptor.RotatableBonds)
' stream(NameOf(descriptor.RotatableBonds)).Flush()
stream(NameOf(descriptor.TopologicalPolarSurfaceArea)).Seek(offset64Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.TopologicalPolarSurfaceArea)).Write(descriptor.TopologicalPolarSurfaceArea)
' stream(NameOf(descriptor.TopologicalPolarSurfaceArea)).Flush()
stream(NameOf(descriptor.XLogP3)).Seek(offset64Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.XLogP3)).Write(descriptor.XLogP3)
' stream(NameOf(descriptor.XLogP3)).Flush()
stream(NameOf(descriptor.XLogP3_AA)).Seek(offset64Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.XLogP3_AA)).Write(descriptor.XLogP3_AA)
' stream(NameOf(descriptor.XLogP3_AA)).Flush()
stream(NameOf(descriptor.AtomDefStereoCount)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.AtomDefStereoCount)).Write(descriptor.AtomDefStereoCount)
stream(NameOf(descriptor.AtomUdefStereoCount)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.AtomUdefStereoCount)).Write(descriptor.AtomUdefStereoCount)
stream(NameOf(descriptor.BondDefStereoCount)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.BondDefStereoCount)).Write(descriptor.BondDefStereoCount)
stream(NameOf(descriptor.BondUdefStereoCount)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.BondUdefStereoCount)).Write(descriptor.BondUdefStereoCount)
stream(NameOf(descriptor.ComponentCount)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.ComponentCount)).Write(descriptor.ComponentCount)
stream(NameOf(descriptor.IsotopicAtomCount)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.IsotopicAtomCount)).Write(descriptor.IsotopicAtomCount)
stream(NameOf(descriptor.TautoCount)).Seek(offset32Bits, SeekOrigin.Begin)
stream(NameOf(descriptor.TautoCount)).Write(descriptor.TautoCount)
End Sub
#Region "IDisposable Support"
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
If Not disposedValue Then
If disposing Then
' TODO: dispose managed state (managed objects).
For Each file As FileStream In stream.Values
Call file.Flush()
Call file.Close()
Call file.Dispose()
Next
End If
' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
' TODO: set large fields to null.
End If
disposedValue = True
End Sub
' TODO: override Finalize() only if Dispose(disposing As Boolean) above has code to free unmanaged resources.
'Protected Overrides Sub Finalize()
' ' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
' Dispose(False)
' MyBase.Finalize()
'End Sub
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
Dispose(True)
' TODO: uncomment the following line if Finalize() is overridden above.
' GC.SuppressFinalize(Me)
End Sub
#End Region
End Class
Module BinaryHelper
<Extension>
Public Sub Write(fs As FileStream, int As Integer)
fs.Write(BitConverter.GetBytes(int), Scan0, 4)
End Sub
<Extension>
Public Sub Write(fs As FileStream, dbl As Double)
fs.Write(BitConverter.GetBytes(dbl), Scan0, 8)
End Sub
End Module
|
xieguigang/MassSpectrum-toolkits
|
src/metadb/Massbank/Public/NCBI/PubChemDescriptorRepo.vb
|
Visual Basic
|
mit
| 12,595
|
'------------------------------------------------------------------------------
' <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.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("VBHeaderRow.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
|
AndreKuzubov/Easy_Report
|
packages/Independentsoft.Office.Word.2.0.400/Tutorial/VBHeaderRow/My Project/Resources.Designer.vb
|
Visual Basic
|
apache-2.0
| 2,720
|
'Copyright 2019 Esri
'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.
Option Strict Off
Option Explicit On
Imports ESRI.ArcGIS.SystemUI
Imports ESRI.ArcGIS.esriSystem
Imports ESRI.ArcGIS.Controls
Imports ESRI.ArcGIS.Carto
Friend Class SpatialBookmarksMultiItem
Implements IMultiItem
Private m_pHookHelper As IHookHelper
Public Sub New()
MyBase.New()
m_pHookHelper = New HookHelperClass
End Sub
Protected Overrides Sub Finalize()
m_pHookHelper = Nothing
End Sub
Private ReadOnly Property IMultiItem_Caption() As String Implements IMultiItem.Caption
Get
Return "Spatial Bookmarks"
End Get
End Property
Private ReadOnly Property IMultiItem_HelpContextID() As Integer Implements IMultiItem.HelpContextID
Get
'Not implemented
End Get
End Property
Private ReadOnly Property IMultiItem_HelpFile() As String Implements IMultiItem.HelpFile
Get
Return ""
End Get
End Property
Private ReadOnly Property IMultiItem_ItemCaption(ByVal index As Integer) As String Implements IMultiItem.ItemCaption
Get
'Get the bookmarks of the focus map
Dim pMapBookmarks As IMapBookmarks
pMapBookmarks = m_pHookHelper.FocusMap
'Get bookmarks enumerator
Dim pEnumSpatialBookmarks As IEnumSpatialBookmark
pEnumSpatialBookmarks = pMapBookmarks.Bookmarks
pEnumSpatialBookmarks.Reset()
'Loop through the bookmarks to get bookmark names
Dim pSpatialBookmark As ISpatialBookmark
Dim bookmarkCount As Integer
pSpatialBookmark = pEnumSpatialBookmarks.Next
bookmarkCount = 0
Do Until pSpatialBookmark Is Nothing
'Get the correct bookmark
If bookmarkCount = index Then
'Return the bookmark name
Return pSpatialBookmark.Name
Exit Do
End If
bookmarkCount = bookmarkCount + 1
pSpatialBookmark = pEnumSpatialBookmarks.Next
Loop
Return ""
End Get
End Property
Private ReadOnly Property IMultiItem_ItemChecked(ByVal index As Integer) As Boolean Implements IMultiItem.ItemChecked
Get
'Not implemented
End Get
End Property
Private ReadOnly Property IMultiItem_ItemEnabled(ByVal index As Integer) As Boolean Implements IMultiItem.ItemEnabled
Get
Return True
End Get
End Property
Private ReadOnly Property IMultiItem_Message() As String Implements IMultiItem.Message
Get
Return "Spatial bookmarks in the focus map"
End Get
End Property
Private ReadOnly Property IMultiItem_Name() As String Implements IMultiItem.Name
Get
Return "Spatial Bookmarks"
End Get
End Property
Private Sub IMultiItem_OnItemClick(ByVal index As Integer) Implements IMultiItem.OnItemClick
'Get the bookmarks of the focus map
Dim pMapBookmarks As IMapBookmarks
pMapBookmarks = m_pHookHelper.FocusMap
'Get bookmarks enumerator
Dim pEnumSpatialBookmarks As IEnumSpatialBookmark
pEnumSpatialBookmarks = pMapBookmarks.Bookmarks
pEnumSpatialBookmarks.Reset()
'Loop through the bookmarks to get bookmark to zoom to
Dim pSpatialBookmark As ISpatialBookmark
Dim bookmarkCount As Integer
pSpatialBookmark = pEnumSpatialBookmarks.Next
bookmarkCount = 0
Do Until pSpatialBookmark Is Nothing
'Get the correct bookmark
If bookmarkCount = index Then
'Zoom to the bookmark
pSpatialBookmark.ZoomTo(m_pHookHelper.FocusMap)
'Refresh the map
m_pHookHelper.ActiveView.Refresh()
Exit Do
End If
bookmarkCount = bookmarkCount + 1
pSpatialBookmark = pEnumSpatialBookmarks.Next
Loop
End Sub
Private Function IMultiItem_OnPopup(ByVal hook As Object) As Integer Implements IMultiItem.OnPopup
m_pHookHelper.Hook = hook
'Get the bookmarks of the focus map
Dim pMapBookmarks As IMapBookmarks
pMapBookmarks = m_pHookHelper.FocusMap
'Get bookmarks enumerator
Dim pEnumSpatialBookmarks As IEnumSpatialBookmark
pEnumSpatialBookmarks = pMapBookmarks.Bookmarks
pEnumSpatialBookmarks.Reset()
'Loop through the bookmarks to count them
Dim pSpatialBookmark As ISpatialBookmark
Dim bookmarkCount As Integer
pSpatialBookmark = pEnumSpatialBookmarks.Next
bookmarkCount = 0
Do Until pSpatialBookmark Is Nothing
bookmarkCount = bookmarkCount + 1
pSpatialBookmark = pEnumSpatialBookmarks.Next
Loop
'Return the number of multiitems
IMultiItem_OnPopup = bookmarkCount
End Function
Public ReadOnly Property ItemBitmap(ByVal index As Integer) As Integer Implements ESRI.ArcGIS.SystemUI.IMultiItem.ItemBitmap
Get
End Get
End Property
End Class
|
Esri/arcobjects-sdk-community-samples
|
Net/Controls/ToolbarControlMultiItemBookmarks/VBNet/SpatialBookmarks.vb
|
Visual Basic
|
apache-2.0
| 5,733
|
Imports Microsoft.VisualBasic
Namespace Gears.DataSource
''' <summary>
''' ORDER の種類
''' </summary>
''' <remarks></remarks>
Public Enum OrderKind As Integer
ASC
DESC
NON
End Enum
''' <summary>
''' SQLの選択条件を管理するクラス
''' </summary>
''' <remarks></remarks>
<Serializable()>
Public Class SqlSelectItem
Inherits SqlItem
Private _colAlias As String = ""
''' <summary>選択列の別名(AS)</summary>
Public ReadOnly Property ColAlias() As String
Get
Return _colAlias
End Get
End Property
Private _isGroupBy As Boolean = False
''' <summary>Group BY句の対象か否か</summary>
Public Property IsGroupBy() As Boolean
Get
Return _isGroupBy
End Get
Set(ByVal value As Boolean)
_isGroupBy = value
End Set
End Property
Private _orderBy As OrderKind = OrderKind.NON
''' <summary>ORDER BY設定</summary>
Public Property OrderBy() As OrderKind
Get
Return _orderBy
End Get
Set(ByVal value As OrderKind)
_orderBy = value
End Set
End Property
Private _isNoSelect As Boolean = False
''' <summary>SELECT選択の対象としない(ORDER BYのみに使いたいなど)</summary>
Public Property IsNoSelect() As Boolean
Get
Return _isNoSelect
End Get
Set(ByVal value As Boolean)
_isNoSelect = value
End Set
End Property
Public Sub New(ByVal col As String, Optional ByVal paramName As String = "")
MyBase.New()
_column = col
Me.ParamName = paramName
End Sub
Public Sub New(ByVal sqls As SqlSelectItem, Optional ByVal val As Object = Nothing)
MyBase.New(sqls, val)
_colAlias = sqls.ColAlias
_isGroupBy = sqls.IsGroupBy
_orderBy = sqls.OrderBy
_isNoSelect = sqls.IsNoSelect
End Sub
''' <summary>
''' 別名を考慮したカラム名
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Public Function ColumnWithAlias() As String
If _colAlias <> "" Then
Return _colAlias
Else
Return _column
End If
End Function
''' <summary>前置詞を付与する</summary>
Public Function pf(ByVal pre As String) As SqlSelectItem
MyBase.basePf(pre)
Return Me
End Function
''' <summary>データソースから前置詞を付与する</summary>
Public Function pf(ByRef sds As SqlDataSource) As SqlSelectItem
MyBase.basePf(sds)
Return Me
End Function
''' <summary>キーを設定する</summary>
Public Function asKey() As SqlSelectItem
MyBase.baseAsKey()
Return Me
End Function
''' <summary>フォーマット処理を無効にし、設定したColumnをそのまま使用する</summary>
Public Function asNoFormat() As SqlSelectItem
MyBase.baseAsNoFormat()
Return Me
End Function
''' <summary>別名を設定する</summary>
''' <param name="colalias"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function asName(ByVal colalias As String) As SqlSelectItem
_colAlias = colalias
Return Me
End Function
''' <summary>Group by句に含む</summary>
''' <returns></returns>
''' <remarks></remarks>
Public Function inGroup() As SqlSelectItem
_isGroupBy = True
Return Me
End Function
''' <summary>昇順に設定</summary>
''' <returns></returns>
''' <remarks></remarks>
Public Function ASC() As SqlSelectItem
_orderBy = OrderKind.ASC
Return Me
End Function
''' <summary>降順に設定</summary>
''' <returns></returns>
''' <remarks></remarks>
Public Function DESC() As SqlSelectItem
_orderBy = OrderKind.DESC
Return Me
End Function
''' <summary>選択をしない</summary>
''' <returns></returns>
''' <remarks></remarks>
Public Function asNoSelect() As SqlSelectItem
_isNoSelect = True
Return Me
End Function
''' <summary>選択項目を条件項目に変換する</summary>
''' <returns></returns>
''' <remarks></remarks>
Public Function toFilter() As SqlFilterItem
Dim sf As SqlFilterItem = New SqlFilterItem(Me.Column)
sf.pf(Me.Prefix)
sf.eq(_value)
sf.IsKey = Me.IsKey
Return (sf)
End Function
''' <summary>パラメータの値を設定する</summary>
''' <param name="val"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function setValue(ByVal val As Object) As SqlSelectItem
_value = val
Return Me
End Function
''' <summary>
''' 値を保持しているか否かを判定する。IsNoSelectが設定された項目は値があってもFalseとなる
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Public Overrides Function hasValue() As Boolean
Dim result As Boolean = MyBase.hasValue
If result And Not IsNoSelect() Then
Return True
Else
Return False
End If
End Function
Public Overrides Function toString() As String
Dim str As String = ""
str += Column
If ColAlias <> "" Then
str += " AS " + ColAlias
End If
If Value IsNot Nothing Then
str += " -> value:" + Value.ToString
End If
Return str
End Function
End Class
End Namespace
|
icoxfog417/Gears
|
Gears/Code/DataSource/SqlSelectItem.vb
|
Visual Basic
|
apache-2.0
| 6,328
|
' 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.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGen
Partial Friend Class StackScheduler
''' <summary>
''' context of expression evaluation.
''' it will affect inference of stack behavior
''' it will also affect when expressions can be dup-reused
''' Example:
''' Foo(x, ref x) x cannot be duped as it is used in different context
''' </summary>
Private Enum ExprContext
None
Sideeffects
Value
Address
AssignmentTarget
Box
End Enum
''' <summary>
''' Analyses the tree trying to figure which locals may live on stack. It is
''' a fairly delicate process and must be very familiar with how CodeGen works.
''' It is essentially a part of CodeGen.
'''
''' NOTE: It is always safe to mark a local as not eligible as a stack local
''' so when situation gets complicated we just refuse to schedule and move on.
''' </summary>
Private NotInheritable Class Analyzer
Inherits BoundTreeRewriter
Private ReadOnly _container As Symbol
Private _counter As Integer = 0
Private ReadOnly _evalStack As ArrayBuilder(Of ValueTuple(Of BoundExpression, ExprContext))
Private ReadOnly _debugFriendly As Boolean
Private _context As ExprContext = ExprContext.None
Private _assignmentLocal As BoundLocal = Nothing
Private ReadOnly _locals As New Dictionary(Of LocalSymbol, LocalDefUseInfo)
''' <summary>
''' fake local that represents the eval stack. when we need to ensure that eval
''' stack is not blocked by stack Locals, we record an access to empty.
''' </summary>
Private ReadOnly _empty As DummyLocal
' we need to guarantee same stack patterns at branches and labels. we do that by placing
' a fake dummy local at one end of a branch and force that it is accessible at another.
' if any stack local tries to intervene and misbalance the stack, it will clash with
' the dummy and will be rejected.
Private ReadOnly _dummyVariables As New Dictionary(Of Object, DummyLocal)
Private Sub New(container As Symbol,
evalStack As ArrayBuilder(Of ValueTuple(Of BoundExpression, ExprContext)),
debugFriendly As Boolean)
Me._container = container
Me._evalStack = evalStack
Me._debugFriendly = debugFriendly
Me._empty = New DummyLocal(container)
' this is the top of eval stack
DeclareLocal(_empty, 0)
RecordVarWrite(_empty)
End Sub
Public Shared Function Analyze(
container As Symbol,
node As BoundNode,
debugFriendly As Boolean,
<Out> ByRef locals As Dictionary(Of LocalSymbol, LocalDefUseInfo)) As BoundNode
Dim evalStack = ArrayBuilder(Of ValueTuple(Of BoundExpression, ExprContext)).GetInstance()
Dim analyzer = New Analyzer(container, evalStack, debugFriendly)
Dim rewritten As BoundNode = analyzer.Visit(node)
evalStack.Free()
locals = analyzer._locals
Return rewritten
End Function
Public Overrides Function Visit(node As BoundNode) As BoundNode
Dim result As BoundNode
Dim expr = TryCast(node, BoundExpression)
If expr IsNot Nothing Then
Debug.Assert(expr.Kind <> BoundKind.Label)
result = VisitExpression(expr, ExprContext.Value)
Else
result = VisitStatement(node)
End If
Return result
End Function
Private Function VisitExpression(node As BoundExpression, context As ExprContext) As BoundExpression
If node Is Nothing Then
Me._counter += 1
Return node
End If
Dim prevContext As ExprContext = Me._context
Dim prevStack As Integer = Me.StackDepth()
Me._context = context
' Don not recurse into constant expressions. Their children do Not push any values.
Dim result = If(node.ConstantValueOpt Is Nothing,
DirectCast(MyBase.Visit(node), BoundExpression),
node)
_context = prevContext
_counter += 1
Select Case context
Case ExprContext.Sideeffects
SetStackDepth(prevStack)
Case ExprContext.AssignmentTarget
Exit Select
Case ExprContext.Value, ExprContext.Address, ExprContext.Box
SetStackDepth(prevStack)
PushEvalStack(node, context)
Case Else
Throw ExceptionUtilities.UnexpectedValue(context)
End Select
Return result
End Function
Private Sub PushEvalStack(result As BoundExpression, context As ExprContext)
_evalStack.Add(ValueTuple.Create(result, context))
End Sub
Private Function StackDepth() As Integer
Return _evalStack.Count
End Function
Private Function EvalStackIsEmpty() As Boolean
Return StackDepth() = 0
End Function
Private Sub SetStackDepth(depth As Integer)
_evalStack.Clip(depth)
End Sub
Private Sub PopEvalStack()
SetStackDepth(_evalStack.Count - 1)
End Sub
Private Sub ClearEvalStack()
_evalStack.Clear()
End Sub
Public Overrides Function VisitSpillSequence(node As BoundSpillSequence) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Private Function VisitStatement(node As BoundNode) As BoundNode
Debug.Assert(node Is Nothing OrElse EvalStackIsEmpty())
Dim origStack = StackDepth()
Dim prevContext As ExprContext = Me._context
Dim result As BoundNode = MyBase.Visit(node)
' prevent cross-statement local optimizations
' when emitting debug-friendly code.
If _debugFriendly Then
EnsureOnlyEvalStack()
End If
Me._context = prevContext
SetStackDepth(origStack)
_counter += 1
Return result
End Function
''' <summary>
''' here we have a case of indirect assignment: *t1 = expr;
''' normally we would need to push t1 and that will cause spilling of t2
'''
''' TODO: an interesting case arises in unused x[i]++ and ++x[i] :
''' we have trees that look like:
'''
''' t1 = &(x[0])
''' t2 = *t1
''' *t1 = t2 + 1
'''
''' t1 = &(x[0])
''' t2 = *t1 + 1
''' *t1 = t2
'''
''' in these cases, we could keep t2 on stack (dev10 does).
''' we are dealing with exactly 2 locals and access them in strict order
''' t1, t2, t1, t2 and we are not using t2 after that.
''' We may consider detecting exactly these cases and pretend that we do not need
''' to push either t1 or t2 in this case.
''' </summary>
Private Function LhsUsesStackWhenAssignedTo(node As BoundNode, context As ExprContext) As Boolean
Debug.Assert(context = ExprContext.AssignmentTarget)
If node Is Nothing Then
Return Nothing
End If
Select Case node.Kind
Case BoundKind.Local, BoundKind.Parameter
Return False
Case BoundKind.FieldAccess
Return Not DirectCast(node, BoundFieldAccess).FieldSymbol.IsShared
Case BoundKind.Sequence
Return LhsUsesStackWhenAssignedTo(DirectCast(node, BoundSequence).ValueOpt, context)
End Select
Return True
End Function
Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode
Debug.Assert(EvalStackIsEmpty(), "entering blocks when evaluation stack is not empty?")
' normally we would not allow stack locals
' when evaluation stack is not empty.
DeclareLocals(node.Locals, 0)
Return MyBase.VisitBlock(node)
End Function
Public Overrides Function VisitSequence(node As BoundSequence) As BoundNode
' Normally we can only use stack for local scheduling if stack is not used for evaluation.
' In a context of a regular block that simply means that eval stack must be empty.
' Sequences, can be entered on a nonempty evaluation stack
' Ex:
' a.b = Seq{var y, y = 1, y} // a is on the stack for the duration of the sequence.
'
' However evaluation stack at the entry cannot be used inside the sequence, so such stack
' works as effective "empty" for locals declared in sequence.
' Therefore sequence locals can be stack scheduled at same stack as at the entry to the sequence.
' it may seem attractive to relax the stack requirement to be:
' "all uses must agree on stack depth".
' The following example illustrates a case where x is safely used at "declarationStack + 1"
' Ex:
' Seq{var x; y.a = Seq{x = 1; x}; y} // x is used while y is on the eval stack
'
' It is, however not safe assumption in general since eval stack may be accessed between usages.
' Ex:
' Seq{var x; y.a = Seq{x = 1; x}; y.z = x; y} // x blocks access to y
'
'
' ---------------------------------------------------
' NOTE: The following is not implemented in VB
'
' There is one case where we want to tweak the "use at declaration stack" rule - in the case of
' compound assignment that involves ByRef operand captures (like: x[y]++ ) .
'
' Those cases produce specific sequences of the shapes:
'
' prefix: Seq{var temp, ref operand; operand initializers; *operand = Seq{temp = (T)(operand + 1); temp;} result: temp}
' postfix: Seq{var temp, ref operand; operand initializers; *operand = Seq{temp = operand; ; (T)(temp + 1);} result: temp}
'
' 1) temp is used as the result of the sequence (and that is the only reason why it is declared in the outer sequence).
' 2) all side-effects except the last one do not use the temp.
' 3) last side-effect is an indirect assignment of a sequence (and target does not involve the temp).
'
' Note that in a case of side-effects context, the result value will be ignored and therefore
' all usages of the nested temp will be confined to the nested sequence that is executed at +1 stack.
'
' We will detect such case and indicate +1 as the desired stack depth at local accesses.
' ---------------------------------------------------
'
Dim declarationStack As Integer = Me.StackDepth()
Dim locals = node.Locals
If Not locals.IsEmpty Then
If Me._context = ExprContext.Sideeffects Then
DeclareLocals(locals, declarationStack)
' ---------------------------------------------------
' NOTE: not implemented workaround from above
' foreach (var local in locals)
' {
' if (IsNestedLocalOfCompoundOperator(local, node))
' {
' // special case
' DeclareLocal(local, declarationStack + 1);
' }
' else
' {
' DeclareLocal(local, declarationStack);
' }
' }
' }
' ---------------------------------------------------
Else
DeclareLocals(locals, declarationStack)
End If
End If
' rewrite operands
Dim origContext As ExprContext = Me._context
Dim sideeffects As ImmutableArray(Of BoundExpression) = node.SideEffects
Dim rewrittenSideeffects As ArrayBuilder(Of BoundExpression) = Nothing
If Not sideeffects.IsDefault Then
For i = 0 To sideeffects.Length - 1
Dim sideeffect As BoundExpression = sideeffects(i)
Dim rewrittenSideeffect As BoundExpression = Me.VisitExpression(sideeffect, ExprContext.Sideeffects)
If rewrittenSideeffects Is Nothing AndAlso rewrittenSideeffect IsNot sideeffect Then
rewrittenSideeffects = ArrayBuilder(Of BoundExpression).GetInstance()
rewrittenSideeffects.AddRange(sideeffects, i)
End If
If rewrittenSideeffects IsNot Nothing Then
rewrittenSideeffects.Add(rewrittenSideeffect)
End If
Next
End If
Dim value As BoundExpression = Me.VisitExpression(node.ValueOpt, origContext)
Return node.Update(node.Locals,
If(rewrittenSideeffects IsNot Nothing, rewrittenSideeffects.ToImmutableAndFree(), sideeffects),
value, node.Type)
End Function
#If False Then
'// detect a pattern used in compound operators
'// where a temp is declared in the outer sequence
'// only because it must be returned, otherwise all uses are
'// confined to the nested sequence that is indirectly assigned (and therefore has +1 stack)
'// in such case the desired stack for this local is +1
'private bool IsNestedLocalOfCompoundOperator(LocalSymbol local, BoundSequence node)
'{
' var value = node.Value;
' // local must be used as the value of the sequence.
' if (value != null && value.Kind == BoundKind.Local && ((BoundLocal)value).LocalSymbol == local)
' {
' var sideeffects = node.SideEffects;
' var lastSideeffect = sideeffects.LastOrDefault();
' if (lastSideeffect != null)
' {
' // last side-effect must be an indirect assignment of a sequence.
' if (lastSideeffect.Kind == BoundKind.AssignmentOperator)
' {
' var assignment = (BoundAssignmentOperator)lastSideeffect;
' if (IsIndirectAssignment(assignment) &&
' assignment.Right.Kind == BoundKind.Sequence)
' {
' // and no other side-effects should use the variable
' var localUsedWalker = new LocalUsedWalker(local);
' for (int i = 0; i < sideeffects.Count - 1; i++)
' {
' if (localUsedWalker.IsLocalUsedIn(sideeffects[i]))
' {
' return false;
' }
' }
' // and local is not used on the left of the assignment
' // (extra check, but better be safe)
' if (localUsedWalker.IsLocalUsedIn(assignment.Left))
' {
' return false;
' }
' // it should be used somewhere
' Debug.Assert(localUsedWalker.IsLocalUsedIn(assignment.Right), "who assigns the temp?");
' return true;
' }
' }
' }
' }
' return false;
'}
'private class LocalUsedWalker : BoundTreeWalker
'{
' private readonly LocalSymbol local;
' private bool found;
' internal LocalUsedWalker(LocalSymbol local)
' {
' this.local = local;
' }
' public bool IsLocalUsedIn(BoundExpression node)
' {
' this.found = false;
' this.Visit(node);
' return found;
' }
' public override BoundNode Visit(BoundNode node)
' {
' if (!found)
' {
' return base.Visit(node);
' }
' return null;
' }
' public override BoundNode VisitLocal(BoundLocal node)
' {
' if (node.LocalSymbol == local)
' {
' this.found = true;
' }
' return null;
' }
'}
#End If
Public Overrides Function VisitExpressionStatement(node As BoundExpressionStatement) As BoundNode
Return node.Update(Me.VisitExpression(node.Expression, ExprContext.Sideeffects))
End Function
Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode
If node.ConstantValueOpt Is Nothing Then
Select Case Me._context
Case ExprContext.Address
If node.LocalSymbol.IsByRef Then
RecordVarRead(node.LocalSymbol)
Else
RecordVarRef(node.LocalSymbol)
End If
Case ExprContext.AssignmentTarget
Debug.Assert(Me._assignmentLocal Is Nothing)
' actual assignment will happen later, after Right is evaluated
' just remember what we are assigning to.
Me._assignmentLocal = node
Case ExprContext.Sideeffects
' do nothing
Case ExprContext.Value,
ExprContext.Box
RecordVarRead(node.LocalSymbol)
End Select
End If
Return MyBase.VisitLocal(node)
End Function
Public Overrides Function VisitReferenceAssignment(node As BoundReferenceAssignment) As BoundNode
' Visit a local in context of regular assignment
Dim left = DirectCast(VisitExpression(node.ByRefLocal, ExprContext.AssignmentTarget), BoundLocal)
Dim storedAssignmentLocal = Me._assignmentLocal
Me._assignmentLocal = Nothing
' Visit a l-value expression in context of 'address'
Dim right As BoundExpression = VisitExpression(node.LValue, ExprContext.Address)
' record the Write to the local
Debug.Assert(storedAssignmentLocal IsNot Nothing)
' this assert will fire if code relies on implicit CLR coercions
' - i.e assigns int value to a short local.
' in that case we should force lhs to be a real local
Debug.Assert(node.ByRefLocal.Type.IsSameTypeIgnoringCustomModifiers(node.LValue.Type),
"cannot use stack when assignment involves implicit coercion of the value")
RecordVarWrite(storedAssignmentLocal.LocalSymbol)
Return node.Update(left, right, node.IsLValue, node.Type)
End Function
Public Overrides Function VisitAssignmentOperator(node As BoundAssignmentOperator) As BoundNode
Dim isIndirect As Boolean = IsIndirectAssignment(node)
Dim left As BoundExpression = VisitExpression(node.Left,
If(isIndirect,
ExprContext.Address,
ExprContext.AssignmentTarget))
' must delay recording a write until after RHS is evaluated
Dim storedAssignmentLocal = Me._assignmentLocal
Me._assignmentLocal = Nothing
Debug.Assert(Me._context <> ExprContext.AssignmentTarget, "assignment expression cannot be a target of another assignment")
' Left on the right should be Nothing by this time
Debug.Assert(node.LeftOnTheRightOpt Is Nothing)
' Do not visit "Left on the right"
'Me.counter += 1
Dim rhsContext As ExprContext
If Me._context = ExprContext.Address Then
' we need the address of rhs so we cannot have it on the stack.
rhsContext = ExprContext.Address
Else
Debug.Assert(Me._context = ExprContext.Value OrElse
Me._context = ExprContext.Box OrElse
Me._context = ExprContext.Sideeffects, "assignment expression cannot be a target of another assignment")
' we only need a value of rhs, so if otherwise possible it can be a stack value.
rhsContext = ExprContext.Value
End If
Dim right As BoundExpression = node.Right
' if right is a struct ctor, it may be optimized into in-place call
' Such call will push the receiver ref before the arguments
' so we need to ensure that arguments cannot use stack temps
Dim leftType As TypeSymbol = left.Type
Dim cookie As Object = Nothing
If right.Kind = BoundKind.ObjectCreationExpression Then
Dim ctor = DirectCast(right, BoundObjectCreationExpression).ConstructorOpt
If ctor IsNot Nothing AndAlso ctor.ParameterCount <> 0 Then
cookie = GetStackStateCookie()
End If
End If
right = VisitExpression(node.Right, rhsContext)
' if assigning to a local, now it is the time to record the Write
If storedAssignmentLocal IsNot Nothing Then
' this assert will fire if code relies on implicit CLR coercions
' - i.e assigns int value to a short local.
' in that case we should force lhs to be a real local
Debug.Assert(node.Left.Type.IsSameTypeIgnoringCustomModifiers(node.Right.Type),
"cannot use stack when assignment involves implicit coercion of the value")
Debug.Assert(Not isIndirect, "indirect assignment is a read, not a write")
RecordVarWrite(storedAssignmentLocal.LocalSymbol)
End If
If cookie IsNot Nothing Then
' There is still RHS on the stack, adjust for that
Me.PopEvalStack()
EnsureStackState(cookie)
End If
Return node.Update(left, Nothing, right, node.SuppressObjectClone, node.Type)
End Function
''' <summary>
''' indirect assignment is assignment to a value referenced indirectly
''' it may only happen if lhs is a reference (must be a parameter or a local)
''' 1) lhs is a reference (must be a parameter or a local)
''' 2) it is not a ref/out assignment where the reference itself would be assigned
''' </summary>
Friend Shared Function IsIndirectAssignment(node As BoundAssignmentOperator) As Boolean
If Not IsByRefLocalOrParameter(node.Left) Then
Return False
End If
Return Not IsByRefLocalOrParameter(node.Right)
End Function
Private Shared Function IsByRefLocalOrParameter(node As BoundExpression) As Boolean
Select Case node.Kind
Case BoundKind.Parameter
Return DirectCast(node, BoundParameter).ParameterSymbol.IsByRef
Case BoundKind.Local
Return DirectCast(node, BoundLocal).LocalSymbol.IsByRef
Case Else
Return False
End Select
End Function
Private Shared Function IsVerifierRef(type As TypeSymbol) As Boolean
Return Not type.TypeKind = TypeKind.TypeParameter AndAlso type.IsReferenceType
End Function
Private Shared Function IsVerifierVal(type As TypeSymbol) As Boolean
Return Not type.TypeKind = TypeKind.TypeParameter AndAlso type.IsValueType
End Function
Public Overrides Function VisitCall(node As BoundCall) As BoundNode
Dim receiver = node.ReceiverOpt
' matches or a bit stronger than EmitReceiverRef
' if there are any doubts that receiver is a ref type,
' assume we will need an address (that will prevent scheduling of receiver).
If Not node.Method.IsShared Then
Dim receiverType = receiver.Type
Dim context As ExprContext
If receiverType.IsReferenceType Then
If (receiverType.IsTypeParameter()) Then
' type param receiver that we statically know Is a reference will be boxed
context = ExprContext.Box
Else
' reference receivers will be used as values
context = ExprContext.Value
End If
Else
' everything else will get an address taken
context = ExprContext.Address
End If
receiver = VisitExpression(receiver, context)
Else
Me._counter += 1
Debug.Assert(receiver Is Nothing OrElse receiver.Kind = BoundKind.TypeExpression)
End If
Dim method As MethodSymbol = node.Method
Dim rewrittenArguments As ImmutableArray(Of BoundExpression) = VisitArguments(node.Arguments, method.Parameters)
Debug.Assert(node.MethodGroupOpt Is Nothing)
Return node.Update(method, node.MethodGroupOpt, receiver, rewrittenArguments, node.ConstantValueOpt, node.SuppressObjectClone, node.Type)
End Function
Private Function VisitArguments(arguments As ImmutableArray(Of BoundExpression), parameters As ImmutableArray(Of ParameterSymbol)) As ImmutableArray(Of BoundExpression)
Debug.Assert(Not arguments.IsDefault)
Debug.Assert(Not parameters.IsDefault)
' If this is a varargs method then there will be one additional argument for the __arglist().
Debug.Assert(arguments.Length = parameters.Length OrElse arguments.Length = parameters.Length + 1)
Dim rewrittenArguments As ArrayBuilder(Of BoundExpression) = Nothing
For i = 0 To arguments.Length - 1
' Treat the __arglist() as a value parameter.
Dim context As ExprContext = If(i = parameters.Length OrElse Not parameters(i).IsByRef, ExprContext.Value, ExprContext.Address)
Dim arg As BoundExpression = arguments(i)
Dim rewrittenArg As BoundExpression = VisitExpression(arg, context)
If rewrittenArguments Is Nothing AndAlso arg IsNot rewrittenArg Then
rewrittenArguments = ArrayBuilder(Of BoundExpression).GetInstance()
rewrittenArguments.AddRange(arguments, i)
End If
If rewrittenArguments IsNot Nothing Then
rewrittenArguments.Add(rewrittenArg)
End If
Next
Return If(rewrittenArguments IsNot Nothing, rewrittenArguments.ToImmutableAndFree, arguments)
End Function
Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode
Dim constructor As MethodSymbol = node.ConstructorOpt
Debug.Assert(constructor IsNot Nothing OrElse node.Arguments.Length = 0)
Dim rewrittenArguments As ImmutableArray(Of BoundExpression) = If(constructor Is Nothing, node.Arguments,
VisitArguments(node.Arguments, constructor.Parameters))
Debug.Assert(node.InitializerOpt Is Nothing)
Me._counter += 1
Return node.Update(constructor, rewrittenArguments, Nothing, node.Type)
End Function
Public Overrides Function VisitArrayAccess(node As BoundArrayAccess) As BoundNode
' regardless of purpose, array access visits its children as values
' TODO: do we need to save/restore old context here?
Dim oldContext = Me._context
Me._context = ExprContext.Value
Dim result As BoundNode = MyBase.VisitArrayAccess(node)
Me._context = oldContext
Return result
End Function
Public Overrides Function VisitFieldAccess(node As BoundFieldAccess) As BoundNode
Dim field As FieldSymbol = node.FieldSymbol
Dim receiver As BoundExpression = node.ReceiverOpt
' if there are any doubts that receiver is a ref type, assume we will
' need an address. (that will prevent scheduling of receiver).
If Not field.IsShared Then
If receiver.Type.IsTypeParameter Then
' type parameters must be boxed to access fields.
receiver = VisitExpression(receiver, ExprContext.Box)
Else
' need address when assigning to a field and receiver is not a reference
' when accessing a field of a struct unless we only need Value and Value is preferred.
If receiver.Type.IsValueType AndAlso
(_context = ExprContext.AssignmentTarget OrElse
_context = ExprContext.Address OrElse
CodeGenerator.FieldLoadMustUseRef(receiver)) Then
receiver = VisitExpression(receiver, ExprContext.Address)
Else
receiver = VisitExpression(receiver, ExprContext.Value)
End If
End If
Else
Me._counter += 1
receiver = Nothing
End If
Return node.Update(receiver, field, node.IsLValue, node.SuppressVirtualCalls, node.ConstantsInProgressOpt, node.Type)
End Function
Public Overrides Function VisitLabelStatement(node As BoundLabelStatement) As BoundNode
RecordLabel(node.Label)
Return MyBase.VisitLabelStatement(node)
End Function
Public Overrides Function VisitGotoStatement(node As BoundGotoStatement) As BoundNode
Dim result As BoundNode = MyBase.VisitGotoStatement(node)
RecordBranch(node.Label)
Return result
End Function
Public Overrides Function VisitConditionalGoto(node As BoundConditionalGoto) As BoundNode
Dim result As BoundNode = MyBase.VisitConditionalGoto(node)
Me.PopEvalStack() ' condition gets consumed
RecordBranch(node.Label)
Return result
End Function
Public Overrides Function VisitBinaryConditionalExpression(node As BoundBinaryConditionalExpression) As BoundNode
Dim origStack = Me.StackDepth
Dim testExpression As BoundExpression = DirectCast(Me.Visit(node.TestExpression), BoundExpression)
Debug.Assert(node.ConvertedTestExpression Is Nothing)
' Me.counter += 1 '' This child is not visited
Debug.Assert(node.TestExpressionPlaceholder Is Nothing)
' Me.counter += 1 '' This child is not visited
' implicit branch here
Dim cookie As Object = GetStackStateCookie()
Me.SetStackDepth(origStack) ' else expression is evaluated with original stack
Dim elseExpression As BoundExpression = DirectCast(Me.Visit(node.ElseExpression), BoundExpression)
' implicit label here
EnsureStackState(cookie)
Return node.Update(testExpression, Nothing, Nothing, elseExpression, node.ConstantValueOpt, node.Type)
End Function
Public Overrides Function VisitTernaryConditionalExpression(node As BoundTernaryConditionalExpression) As BoundNode
Dim origStack As Integer = Me.StackDepth
Dim condition = DirectCast(Me.Visit(node.Condition), BoundExpression)
Dim cookie As Object = GetStackStateCookie() ' implicit goto here
Me.SetStackDepth(origStack) ' consequence is evaluated with original stack
Dim whenTrue = DirectCast(Me.Visit(node.WhenTrue), BoundExpression)
EnsureStackState(cookie) ' implicit label here
Me.SetStackDepth(origStack) ' alternative is evaluated with original stack
Dim whenFalse = DirectCast(Me.Visit(node.WhenFalse), BoundExpression)
EnsureStackState(cookie) ' implicit label here
Return node.Update(condition, whenTrue, whenFalse, node.ConstantValueOpt, node.Type)
End Function
Public Overrides Function VisitLoweredConditionalAccess(node As BoundLoweredConditionalAccess) As BoundNode
If Not node.ReceiverOrCondition.Type.IsBooleanType() Then
' We may need to load a reference to the receiver, or may need to
' reload it after the null check. This won't work well
' with a stack local.
EnsureOnlyEvalStack()
End If
Dim origStack = StackDepth()
Dim receiverOrCondition = DirectCast(Me.Visit(node.ReceiverOrCondition), BoundExpression)
Dim cookie = GetStackStateCookie() ' implicit branch here
' access Is evaluated with original stack
' (this Is Not entirely true, codegen will keep receiver on the stack, but that Is irrelevant here)
Me.SetStackDepth(origStack)
Dim whenNotNull = DirectCast(Me.Visit(node.WhenNotNull), BoundExpression)
EnsureStackState(cookie) ' implicit label here
Dim whenNull As BoundExpression = Nothing
If node.WhenNullOpt IsNot Nothing Then
Me.SetStackDepth(origStack)
whenNull = DirectCast(Me.Visit(node.WhenNullOpt), BoundExpression)
EnsureStackState(cookie) ' implicit label here
End If
Return node.Update(receiverOrCondition, node.CaptureReceiver, node.PlaceholderId, whenNotNull, whenNull, node.Type)
End Function
Public Overrides Function VisitConditionalAccessReceiverPlaceholder(node As BoundConditionalAccessReceiverPlaceholder) As BoundNode
Return MyBase.VisitConditionalAccessReceiverPlaceholder(node)
End Function
Public Overrides Function VisitComplexConditionalAccessReceiver(node As BoundComplexConditionalAccessReceiver) As BoundNode
EnsureOnlyEvalStack()
Dim origStack As Integer = Me.StackDepth
Me.PushEvalStack(Nothing, ExprContext.None)
Dim cookie As Object = GetStackStateCookie() ' implicit goto here
Me.SetStackDepth(origStack) ' consequence is evaluated with original stack
Dim valueTypeReceiver = DirectCast(Me.Visit(node.ValueTypeReceiver), BoundExpression)
EnsureStackState(cookie) ' implicit label here
Me.SetStackDepth(origStack) ' alternative is evaluated with original stack
Dim referenceTypeReceiver = DirectCast(Me.Visit(node.ReferenceTypeReceiver), BoundExpression)
EnsureStackState(cookie) ' implicit label here
Return node.Update(valueTypeReceiver, referenceTypeReceiver, node.Type)
End Function
Public Overrides Function VisitBinaryOperator(node As BoundBinaryOperator) As BoundNode
Select Case (node.OperatorKind And BinaryOperatorKind.OpMask)
Case BinaryOperatorKind.AndAlso, BinaryOperatorKind.OrElse
' Short-circuit operators need to emulate implicit branch/label
Dim origStack = Me.StackDepth
Dim left As BoundExpression = DirectCast(Me.Visit(node.Left), BoundExpression)
' implicit branch here
Dim cookie As Object = GetStackStateCookie()
Me.SetStackDepth(origStack) ' right is evaluated with original stack
Dim right As BoundExpression = DirectCast(Me.Visit(node.Right), BoundExpression)
' implicit label here
EnsureStackState(cookie)
Return node.Update(node.OperatorKind, left, right, node.Checked, node.ConstantValueOpt, node.Type)
Case Else
Return MyBase.VisitBinaryOperator(node)
End Select
End Function
Public Overrides Function VisitUnaryOperator(node As BoundUnaryOperator) As BoundNode
' checked(-x) is emitted as "0 - x"
If node.Checked AndAlso (node.OperatorKind And UnaryOperatorKind.OpMask) = UnaryOperatorKind.Minus Then
Dim storedStack = Me.StackDepth
Me.PushEvalStack(Nothing, ExprContext.None)
Dim operand = DirectCast(Me.Visit(node.Operand), BoundExpression)
Me.SetStackDepth(storedStack)
Return node.Update(node.OperatorKind, operand, node.Checked, node.ConstantValueOpt, node.Type)
Else
Return MyBase.VisitUnaryOperator(node)
End If
End Function
Public Overrides Function VisitSelectStatement(node As BoundSelectStatement) As BoundNode
' switch requires that key local stays local
EnsureOnlyEvalStack()
Dim expressionStatement As BoundExpressionStatement = DirectCast(Me.Visit(node.ExpressionStatement), BoundExpressionStatement)
If expressionStatement.Expression.Kind = BoundKind.Local Then
' It is required by code gen that if node.ExpressionStatement
' is a local it should not be optimized out
Dim local = DirectCast(expressionStatement.Expression, BoundLocal).LocalSymbol
ShouldNotSchedule(local)
End If
Dim origStack = Me.StackDepth
EnsureOnlyEvalStack()
Dim exprPlaceholderOpt As BoundRValuePlaceholder = DirectCast(Me.Visit(node.ExprPlaceholderOpt), BoundRValuePlaceholder)
' expression value is consumed by the switch
Me.SetStackDepth(origStack)
EnsureOnlyEvalStack()
' case blocks
Dim caseBlocks As ImmutableArray(Of BoundCaseBlock) = Me.VisitList(node.CaseBlocks)
' exit label
Dim exitLabel = node.ExitLabel
If exitLabel IsNot Nothing Then
Me.RecordLabel(exitLabel)
End If
EnsureOnlyEvalStack()
Return node.Update(expressionStatement, exprPlaceholderOpt, caseBlocks, node.RecommendSwitchTable, exitLabel)
End Function
Public Overrides Function VisitCaseBlock(node As BoundCaseBlock) As BoundNode
EnsureOnlyEvalStack()
Dim caseStatement As BoundCaseStatement = DirectCast(Me.Visit(node.CaseStatement), BoundCaseStatement)
EnsureOnlyEvalStack()
Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock)
EnsureOnlyEvalStack()
Return node.Update(caseStatement, body)
End Function
Public Overrides Function VisitUnstructuredExceptionOnErrorSwitch(node As BoundUnstructuredExceptionOnErrorSwitch) As BoundNode
Dim value = DirectCast(Visit(node.Value), BoundExpression)
Me.PopEvalStack() ' value gets consumed
Return node.Update(value, Me.VisitList(node.Jumps))
End Function
Public Overrides Function VisitUnstructuredExceptionResumeSwitch(node As BoundUnstructuredExceptionResumeSwitch) As BoundNode
Dim resumeLabel = DirectCast(Visit(node.ResumeLabel), BoundLabelStatement)
Dim resumeNextLabel = DirectCast(Visit(node.ResumeNextLabel), BoundLabelStatement)
Dim resumeTargetTemporary = DirectCast(Visit(node.ResumeTargetTemporary), BoundLocal)
Me.PopEvalStack() ' value gets consumed
Return node.Update(resumeTargetTemporary, resumeLabel, resumeNextLabel, node.Jumps)
End Function
Public Overrides Function VisitTryStatement(node As BoundTryStatement) As BoundNode
EnsureOnlyEvalStack()
Dim tryBlock = DirectCast(Me.Visit(node.TryBlock), BoundBlock)
EnsureOnlyEvalStack()
Dim catchBlocks As ImmutableArray(Of BoundCatchBlock) = Me.VisitList(node.CatchBlocks)
EnsureOnlyEvalStack()
Dim finallyBlock = DirectCast(Me.Visit(node.FinallyBlockOpt), BoundBlock)
EnsureOnlyEvalStack()
If node.ExitLabelOpt IsNot Nothing Then
RecordLabel(node.ExitLabelOpt)
End If
EnsureOnlyEvalStack()
Return node.Update(tryBlock, catchBlocks, finallyBlock, node.ExitLabelOpt)
End Function
Public Overrides Function VisitCatchBlock(node As BoundCatchBlock) As BoundNode
Dim origStack As Integer = Me.StackDepth
DeclareLocal(node.LocalOpt, origStack)
EnsureOnlyEvalStack()
Dim exceptionVariableOpt As BoundExpression = Me.VisitExpression(node.ExceptionSourceOpt, ExprContext.Value)
Me.SetStackDepth(origStack)
EnsureOnlyEvalStack()
Dim errorLineNumberOpt As BoundExpression = Me.VisitExpression(node.ErrorLineNumberOpt, ExprContext.Value)
Me.SetStackDepth(origStack)
EnsureOnlyEvalStack()
Dim exceptionFilterOpt As BoundExpression = Me.VisitExpression(node.ExceptionFilterOpt, ExprContext.Value)
Me.SetStackDepth(origStack)
EnsureOnlyEvalStack()
Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock)
EnsureOnlyEvalStack()
Return node.Update(node.LocalOpt, exceptionVariableOpt, errorLineNumberOpt, exceptionFilterOpt, body, node.IsSynthesizedAsyncCatchAll)
End Function
Public Overrides Function VisitArrayInitialization(node As BoundArrayInitialization) As BoundNode
' nontrivial construct - may use dups, metadata blob helpers etc..
EnsureOnlyEvalStack()
Dim initializers As ImmutableArray(Of BoundExpression) = node.Initializers
Dim rewrittenInitializers As ArrayBuilder(Of BoundExpression) = Nothing
If Not initializers.IsDefault Then
For i = 0 To initializers.Length - 1
' array itself will be pushed on the stack here.
EnsureOnlyEvalStack()
Dim initializer As BoundExpression = initializers(i)
Dim rewrittenInitializer As BoundExpression = Me.VisitExpression(initializer, ExprContext.Value)
If rewrittenInitializers Is Nothing AndAlso rewrittenInitializer IsNot initializer Then
rewrittenInitializers = ArrayBuilder(Of BoundExpression).GetInstance()
rewrittenInitializers.AddRange(initializers, i)
End If
If rewrittenInitializers IsNot Nothing Then
rewrittenInitializers.Add(rewrittenInitializer)
End If
Next
End If
Return node.Update(If(rewrittenInitializers IsNot Nothing, rewrittenInitializers.ToImmutableAndFree(), initializers), node.Type)
End Function
Public Overrides Function VisitReturnStatement(node As BoundReturnStatement) As BoundNode
Dim expressionOpt = TryCast(Me.Visit(node.ExpressionOpt), BoundExpression)
' must not have locals on stack when returning
EnsureOnlyEvalStack()
Return node.Update(expressionOpt, node.FunctionLocalOpt, node.ExitLabelOpt)
End Function
''' <summary>
''' Ensures that there are no stack locals. It is done by accessing
''' virtual "empty" local that is at the bottom of all stack locals.
''' </summary>
''' <remarks></remarks>
Private Sub EnsureOnlyEvalStack()
RecordVarRead(_empty)
End Sub
Private Function GetStackStateCookie() As Object
' create a dummy and start tracing it
Dim dummy As New DummyLocal(Me._container)
Me._dummyVariables.Add(dummy, dummy)
Me._locals.Add(dummy, New LocalDefUseInfo(Me.StackDepth))
RecordVarWrite(dummy)
Return dummy
End Function
Private Sub EnsureStackState(cookie As Object)
RecordVarRead(Me._dummyVariables(cookie))
End Sub
' called on branches and labels
Private Sub RecordBranch(label As LabelSymbol)
Dim dummy As DummyLocal = Nothing
If Me._dummyVariables.TryGetValue(label, dummy) Then
RecordVarRead(dummy)
Else
' create a dummy and start tracing it
dummy = New DummyLocal(Me._container)
Me._dummyVariables.Add(label, dummy)
Me._locals.Add(dummy, New LocalDefUseInfo(Me.StackDepth))
RecordVarWrite(dummy)
End If
End Sub
Private Sub RecordLabel(label As LabelSymbol)
Dim dummy As DummyLocal = Nothing
If Me._dummyVariables.TryGetValue(label, dummy) Then
RecordVarRead(dummy)
Else
' this is a backwards jump with nontrivial stack requirements
' just use empty.
dummy = _empty
Me._dummyVariables.Add(label, dummy)
RecordVarRead(dummy)
End If
End Sub
Private Sub RecordVarRef(local As LocalSymbol)
Debug.Assert(Not local.IsByRef, "can't tke a ref of a ref")
If Not CanScheduleToStack(local) Then
Return
End If
' if we ever take a reference of a local, it must be a real local.
ShouldNotSchedule(local)
End Sub
Private Sub RecordVarRead(local As LocalSymbol)
If Not CanScheduleToStack(local) Then
Return
End If
Dim locInfo As LocalDefUseInfo = _locals(local)
If locInfo.CannotSchedule Then
Return
End If
If locInfo.localDefs.Count = 0 Then
' reading before writing.
locInfo.ShouldNotSchedule()
Return
End If
' if accessing real val, check stack
If Not TypeOf local Is DummyLocal Then
If locInfo.StackAtDeclaration <> StackDepth() AndAlso
Not EvalStackHasLocal(local) Then
' reading at different eval stack.
locInfo.ShouldNotSchedule()
Return
End If
Else
' dummy must be accessed on same stack.
Debug.Assert(local Is _empty OrElse locInfo.StackAtDeclaration = StackDepth())
End If
Dim definedAt As LocalDefUseSpan = locInfo.localDefs.Last()
definedAt.SetEnd(Me._counter)
Dim locDef As New LocalDefUseSpan(_counter)
locInfo.localDefs.Add(locDef)
End Sub
Private Function EvalStackHasLocal(local As LocalSymbol) As Boolean
Dim top = _evalStack.Last()
Return top.Item2 = If(Not local.IsByRef, ExprContext.Value, ExprContext.Address) AndAlso
top.Item1.Kind = BoundKind.Local AndAlso
DirectCast(top.Item1, BoundLocal).LocalSymbol = local
End Function
Private Sub RecordVarWrite(local As LocalSymbol)
If Not CanScheduleToStack(local) Then
Return
End If
Dim locInfo = _locals(local)
If locInfo.CannotSchedule Then
Return
End If
' if accessing real val, check stack
If Not TypeOf local Is DummyLocal Then
' -1 because real assignment "consumes" value.
Dim evalStack = Me.StackDepth - 1
If locInfo.StackAtDeclaration <> evalStack Then
' writing at different eval stack.
locInfo.ShouldNotSchedule()
Return
End If
Else
' dummy must be accessed on same stack.
Debug.Assert(local Is _empty OrElse locInfo.StackAtDeclaration = StackDepth())
End If
Dim locDef = New LocalDefUseSpan(Me._counter)
locInfo.localDefs.Add(locDef)
End Sub
Private Sub ShouldNotSchedule(local As LocalSymbol)
Dim localDefInfo As LocalDefUseInfo = Nothing
If _locals.TryGetValue(local, localDefInfo) Then
localDefInfo.ShouldNotSchedule()
End If
End Sub
Private Function CanScheduleToStack(local As LocalSymbol) As Boolean
Return local.CanScheduleToStack AndAlso
(Not _debugFriendly OrElse Not local.SynthesizedKind.IsLongLived())
End Function
Private Sub DeclareLocals(locals As ImmutableArray(Of LocalSymbol), stack As Integer)
For Each local In locals
DeclareLocal(local, stack)
Next
End Sub
Private Sub DeclareLocal(local As LocalSymbol, stack As Integer)
If local IsNot Nothing Then
If CanScheduleToStack(local) Then
Me._locals.Add(local, New LocalDefUseInfo(stack))
End If
End If
End Sub
End Class
End Class
End Namespace
|
dovzhikova/roslyn
|
src/Compilers/VisualBasic/Portable/CodeGen/Optimizer/StackScheduler.Analyzer.vb
|
Visual Basic
|
apache-2.0
| 54,998
|
Imports Microsoft.VisualBasic
Imports System.Runtime.Serialization
Namespace Gears.DataSource
''' <summary>
''' SQL処理実行時の例外
''' </summary>
''' <remarks></remarks>
Public Class GearsSqlException
Inherits GearsException
Protected Const MSG_ATYPE As String = "MSG_ATYPE"
'コンストラクタ
Public Sub New()
MyBase.New()
End Sub
Public Sub New(ByVal msg As String)
MyBase.New(msg)
End Sub
Public Sub New(atype As ActionType, message As String, ByVal innerException As Exception)
MyBase.New(message, innerException)
setActionType(atype)
End Sub
Public Sub New(atype As ActionType, message As String, ByVal ParamArray detail() As String)
MyBase.New(message)
addDetail(detail)
setActionType(atype)
End Sub
'メソッド
Public Function getActionType() As String
Return toStringDetail(MSG_ATYPE)
End Function
Public Sub clearActionType()
clearDetail(MSG_ATYPE)
End Sub
Public Sub setActionType(ByVal a As ActionType)
addDetail(MSG_ATYPE, GearsDTO.ActionToString(a))
End Sub
End Class
End Namespace
|
icoxfog417/Gears
|
Gears/Code/DataSource/GearsSqlException.vb
|
Visual Basic
|
apache-2.0
| 1,310
|
'==============================================================================
' MyGeneration.dOOdads
'
' SQLiteDynamicQuery.vb
' Version 5.0
' Updated - 10/12/2005
'------------------------------------------------------------------------------
' Copyright 2004, 2005 by MyGeneration Software.
' All Rights Reserved.
'
' Permission to use, copy, modify, and distribute this software and its
' documentation for any purpose and without fee is hereby granted,
' provided that the above copyright notice appear in all copies and that
' both that copyright notice and this permission notice appear in
' supporting documentation.
'
' MYGENERATION SOFTWARE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
' SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
' AND FITNESS, IN NO EVENT SHALL MYGENERATION SOFTWARE BE LIABLE FOR ANY
' SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
' WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
' WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
' TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
' OR PERFORMANCE OF THIS SOFTWARE.
'==============================================================================
Imports System.Configuration
Imports System.Data
Imports Finisar.SQLite
Namespace MyGeneration.dOOdads
Public Class SQLiteDynamicQuery
Inherits DynamicQuery
Public Sub New(ByVal entity As BusinessEntity)
MyBase.New(entity)
End Sub
Public Overloads Overrides Sub AddOrderBy(ByVal column As String, ByVal direction As WhereParameter.Dir)
MyBase.AddOrderBy("[" + column + "]", direction)
End Sub
Public Overloads Overrides Sub AddOrderBy(ByVal countAll As DynamicQuery, ByVal direction As WhereParameter.Dir)
If countAll.CountAll Then
MyBase.AddOrderBy("COUNT(*)", direction)
End If
End Sub
Public Overloads Overrides Sub AddOrderBy(ByVal aggregate As AggregateParameter, ByVal direction As WhereParameter.Dir)
MyBase.AddOrderBy(GetAggregate(aggregate, False), direction)
End Sub
Public Overloads Overrides Sub AddGroupBy(ByVal column As String)
MyBase.AddGroupBy("[" + column + "]")
End Sub
Public Overloads Overrides Sub AddGroupBy(ByVal aggregate As AggregateParameter)
MyBase.AddGroupBy(GetAggregate(aggregate, False))
End Sub
Public Overrides Sub AddResultColumn(ByVal columnName As String)
MyBase.AddResultColumn(columnName)
End Sub
Protected Function GetAggregate(ByVal wItem As AggregateParameter, ByVal withAlias As Boolean) As String
Dim query As String = String.Empty
Select Case (wItem.Function)
Case AggregateParameter.Func.Avg
query += "AVG("
Case AggregateParameter.Func.Count
query += "COUNT("
Case AggregateParameter.Func.Max
query += "MAX("
Case AggregateParameter.Func.Min
query += "MIN("
Case AggregateParameter.Func.Sum
query += "SUM("
Case AggregateParameter.Func.StdDev
query += "STDDEV("
Case AggregateParameter.Func.Var
query += "VAR("
End Select
If wItem.Distinct Then
query += "DISTINCT "
End If
query += "[" + wItem.Column + "])"
If withAlias AndAlso Not wItem.Alias = String.Empty Then
query += " AS '" + wItem.Alias + "'"
End If
Return query
End Function
Protected Overrides Function _Load(Optional ByVal conjuction As String = "AND") As IDbCommand
Dim hasColumn As Boolean = False
Dim selectAll As Boolean = True
Dim query As String
Dim p As Integer = 1
query = "SELECT "
If Me._distinct Then query += " DISTINCT "
If Me._resultColumns.Length > 0 Then
query += Me._resultColumns
hasColumn = True
selectAll = False
End If
If Me._countAll Then
If hasColumn Then
query += ", "
End If
query += "COUNT(*)"
If Not Me._countAllAlias = String.Empty Then
' Need DBMS string delimiter here
query += " AS '" + Me._countAllAlias + "'"
End If
hasColumn = True
selectAll = False
End If
If Not _aggregateParameters Is Nothing AndAlso _aggregateParameters.Count > 0 Then
Dim isFirst As Boolean = True
If hasColumn Then
query += ", "
End If
Dim wItem As AggregateParameter
Dim obj As Object
For Each obj In _aggregateParameters
wItem = CType(obj, AggregateParameter)
If wItem.IsDirty Then
If isFirst Then
query += GetAggregate(wItem, True)
isFirst = False
Else
query += ", " + GetAggregate(wItem, True)
End If
End If
Next
selectAll = False
End If
If selectAll Then
query += "*"
End If
query += " FROM [" + Me._entity.QuerySource() + "]"
Dim cmd As New SQLiteCommand
If Not _whereParameters Is Nothing AndAlso _whereParameters.Count > 0 Then
query += " WHERE "
Dim first As Boolean = True
Dim requiresParam As Boolean
Dim obj As Object
Dim text As String
Dim wItem As WhereParameter
Dim skipConjuction As Boolean = False
Dim param As SQLiteParameter
Dim paramName As String
Dim columnName As String
Dim qCount As Integer = _whereParameters.Count - 1
Dim index As Integer = 0
For index = 0 To qCount
' Maybe we injected text or a WhereParameter
obj = _whereParameters(index)
If TypeOf obj Is String Then
text = CType(obj, String)
query += text
If text = "(" Then
skipConjuction = True
End If
Else
wItem = CType(obj, WhereParameter)
If wItem.IsDirty Then
If Not first AndAlso Not skipConjuction Then
If Not wItem.Conjuction = WhereParameter.Conj.UseDefault Then
If wItem.Conjuction = WhereParameter.Conj.AND_ Then
query += " AND "
Else
query += " OR "
End If
Else
query += " " + conjuction + " "
End If
End If
requiresParam = True
inc = inc + 1
columnName = "[" + wItem.Column + "]"
paramName = "@" + wItem.Column + inc.ToString()
wItem.Param.ParameterName = paramName
Select Case wItem.[Operator]
Case WhereParameter.Operand.Equal
query += columnName + " = " + paramName + " "
Case WhereParameter.Operand.NotEqual
query += columnName + " <> " + paramName + " "
Case WhereParameter.Operand.GreaterThan
query += columnName + " > " + paramName + " "
Case WhereParameter.Operand.LessThan
query += columnName + " < " + paramName + " "
Case WhereParameter.Operand.LessThanOrEqual
query += columnName + " <= " + paramName + " "
Case WhereParameter.Operand.GreaterThanOrEqual
query += columnName + " >= " + paramName + " "
Case WhereParameter.Operand.Like_
query += columnName + " LIKE " + paramName + " "
Case WhereParameter.Operand.NotLike
query += columnName + " NOT LIKE " + paramName + " "
Case WhereParameter.Operand.IsNull
query += columnName + " IS NULL "
requiresParam = False
Case WhereParameter.Operand.IsNotNull
query += columnName + " IS NOT NULL "
requiresParam = False
Case WhereParameter.Operand.In_
query += columnName + " IN (" + wItem.Value.ToString() + ") "
requiresParam = False
Case WhereParameter.Operand.NotIn
query += columnName + " NOT IN (" + wItem.Value.ToString() + ") "
requiresParam = False
Case WhereParameter.Operand.Between
query += columnName + " BETWEEN " + paramName
cmd.Parameters.Add(paramName, wItem.BetweenBeginValue)
inc = inc + 1
paramName = "@" + wItem.Column + inc.ToString()
query += " AND " + paramName
cmd.Parameters.Add(paramName, wItem.BetweenEndValue)
requiresParam = False
End Select
If requiresParam Then
Dim dbCmd As IDbCommand = CType(cmd, IDbCommand)
cmd.Parameters.Add(wItem.Param)
wItem.Param.Value = wItem.Value
p += 1
End If
first = False
skipConjuction = False
End If ' If wItem.IsDirty Then
End If ' Is WhereParameter
Next index
End If
If _groupBy.Length > 0 Then
query += " GROUP BY " + _groupBy
If Me._withRollup Then
query += " WITH ROLLUP"
End If
End If
If (_orderBy.Length > 0) Then
query += " ORDER BY " + _orderBy
End If
If Me._top >= 0 Then query += " LIMIT " + Me._top.ToString() + " "
cmd.CommandText = query
Return cmd
End Function
End Class
End Namespace
|
cafephin/mygeneration
|
src/doodads/VB.NET/MyGeneration.dOOdads/DbAdapters/SQLiteDynamicQuery.vb
|
Visual Basic
|
bsd-3-clause
| 10,981
|
' 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_140
''' <summary>
''' A DateTime extension method that converts this object to a full 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 ToFullDateTimeString(this As DateTime) As String
Return this.ToString("F", DateTimeFormatInfo.CurrentInfo)
End Function
''' <summary>
''' A DateTime extension method that converts this object to a full 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 ToFullDateTimeString(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 full 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 ToFullDateTimeString(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.ToFullDateTimeString.vb
|
Visual Basic
|
mit
| 1,837
|
' 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.Collections.Generic
Imports System.Data
Imports System.Dynamic
Imports System.Linq
Public Module Extensions_682
''' <summary>
''' An IDataReader extension method that converts the @this to an expando object.
''' </summary>
''' <param name="this">The @this to act on.</param>
''' <returns>@this as a dynamic.</returns>
<System.Runtime.CompilerServices.Extension> _
Public Function ToExpandoObject(this As IDataReader) As Object
Dim columnNames As Dictionary(Of Integer, KeyValuePair(Of Integer, String)) = Enumerable.Range(0, this.FieldCount).[Select](Function(x) New KeyValuePair(Of Integer, String)(x, this.GetName(x))).ToDictionary(Function(pair) pair.Key)
Dim entity As Object = New ExpandoObject()
Dim expandoDict = DirectCast(entity, IDictionary(Of String, Object))
Enumerable.Range(0, this.FieldCount).ToList().ForEach(Sub(x) expandoDict.Add(columnNames(x).Value, this(x)))
Return entity
End Function
End Module
|
huoxudong125/Z.ExtensionMethods
|
src (VB.NET)/Z.ExtensionMethods.VB/Z.Data/System.Data.IDataReader/IDataReader.ToExpandoObject.vb
|
Visual Basic
|
mit
| 1,381
|
' 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.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Wrapping
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Wrapping
Public Class ArgumentWrappingTests
Inherits AbstractWrappingTests
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New VisualBasicWrappingCodeRefactoringProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function TestMissingWithSyntaxError() As Task
Await TestMissingAsync(
"class C
sub Bar()
Goobar([||]i, j
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function TestMissingWithSelection() As Task
Await TestMissingAsync(
"class C
sub Bar()
Goobar([|i|], j)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function TestMissingBeforeName() As Task
Await TestMissingAsync(
"class C
sub Bar()
a.[||]b.Goobar(i, j)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function TestMissingWithSingleParameter() As Task
Await TestMissingAsync(
"class C
sub Bar()
Goobar([||]i)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function TestMissingWithMultiLineParameter() As Task
Await TestMissingAsync(
"class C
sub Bar()
Goobar([||]i, j +
k)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function TestInHeader1() As Task
Await TestInRegularAndScript1Async(
"class C
sub Bar()
[||]Goobar(i, j)
end sub
end class",
"class C
sub Bar()
Goobar(i,
j)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function TestInHeader2() As Task
Await TestInRegularAndScript1Async(
"class C
sub Bar()
a.[||]Goobar(i, j)
end sub
end class",
"class C
sub Bar()
a.Goobar(i,
j)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function TestInHeader4() As Task
Await TestInRegularAndScript1Async(
"class C
sub Bar()
a.Goobar(i, j[||])
end sub
end class",
"class C
sub Bar()
a.Goobar(i,
j)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function TestTwoParamWrappingCases() As Task
Await TestAllWrappingCasesAsync(
"class C
sub Bar()
a.Goobar([||]i, j)
end sub
end class",
"class C
sub Bar()
a.Goobar(i,
j)
end sub
end class",
"class C
sub Bar()
a.Goobar(
i,
j)
end sub
end class",
"class C
sub Bar()
a.Goobar(i,
j)
end sub
end class",
"class C
sub Bar()
a.Goobar(
i, j)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function TestThreeParamWrappingCases() As Task
Await TestAllWrappingCasesAsync(
"class C
sub Bar()
a.Goobar([||]i, j, k)
end sub
end class",
"class C
sub Bar()
a.Goobar(i,
j,
k)
end sub
end class",
"class C
sub Bar()
a.Goobar(
i,
j,
k)
end sub
end class",
"class C
sub Bar()
a.Goobar(i,
j,
k)
end sub
end class",
"class C
sub Bar()
a.Goobar(
i, j, k)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function Test_AllOptions_NoInitialMatches() As Task
Await TestAllWrappingCasesAsync(
"class C
sub Bar()
a.Goobar(
[||]i,
j,
k)
end sub
end class",
"class C
sub Bar()
a.Goobar(i,
j,
k)
end sub
end class",
"class C
sub Bar()
a.Goobar(
i,
j,
k)
end sub
end class",
"class C
sub Bar()
a.Goobar(i,
j,
k)
end sub
end class",
"class C
sub Bar()
a.Goobar(i, j, k)
end sub
end class",
"class C
sub Bar()
a.Goobar(
i, j, k)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function Test_LongWrapping_ShortIds() As Task
Await TestAllWrappingCasesAsync(
"class C
sub Goo()
me.Goobar([||]
i, j, k, l, m, n, o, p,
n)
end sub
end class",
GetIndentionColumn(30),
"class C
sub Goo()
me.Goobar(i,
j,
k,
l,
m,
n,
o,
p,
n)
end sub
end class",
"class C
sub Goo()
me.Goobar(
i,
j,
k,
l,
m,
n,
o,
p,
n)
end sub
end class",
"class C
sub Goo()
me.Goobar(i,
j,
k,
l,
m,
n,
o,
p,
n)
end sub
end class",
"class C
sub Goo()
me.Goobar(i, j, k, l, m, n, o, p, n)
end sub
end class",
"class C
sub Goo()
me.Goobar(
i, j, k, l, m, n, o, p, n)
end sub
end class",
"class C
sub Goo()
me.Goobar(i, j, k, l,
m, n, o, p,
n)
end sub
end class",
"class C
sub Goo()
me.Goobar(
i, j, k, l, m, n,
o, p, n)
end sub
end class",
"class C
sub Goo()
me.Goobar(i, j, k, l,
m, n, o, p, n)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function Test_LongWrapping_VariadicLengthIds() As Task
Await TestAllWrappingCasesAsync(
"class C
sub Goo()
me.Goobar([||]
i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm,
nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn)
end sub
end class",
GetIndentionColumn(30),
"class C
sub Goo()
me.Goobar(i,
jj,
kkkkk,
llllllll,
mmmmmmmmmmmmmmmmmm,
nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn)
end sub
end class",
"class C
sub Goo()
me.Goobar(
i,
jj,
kkkkk,
llllllll,
mmmmmmmmmmmmmmmmmm,
nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn)
end sub
end class",
"class C
sub Goo()
me.Goobar(i,
jj,
kkkkk,
llllllll,
mmmmmmmmmmmmmmmmmm,
nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn)
end sub
end class",
"class C
sub Goo()
me.Goobar(i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn)
end sub
end class",
"class C
sub Goo()
me.Goobar(
i, jj, kkkkk, llllllll, mmmmmmmmmmmmmmmmmm, nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn)
end sub
end class",
"class C
sub Goo()
me.Goobar(i, jj, kkkkk,
llllllll,
mmmmmmmmmmmmmmmmmm,
nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn)
end sub
end class",
"class C
sub Goo()
me.Goobar(
i, jj, kkkkk,
llllllll,
mmmmmmmmmmmmmmmmmm,
nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn)
end sub
end class",
"class C
sub Goo()
me.Goobar(i, jj, kkkkk,
llllllll,
mmmmmmmmmmmmmmmmmm,
nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function Test_DoNotOfferLongWrappingOptionThatAlreadyAppeared() As Task
Await TestAllWrappingCasesAsync(
"class C
sub Goo()
me.Goobar([||]
iiiii, jjjjj, kkkkk, lllll, mmmmm,
nnnnn)
end sub
end class",
GetIndentionColumn(25),
"class C
sub Goo()
me.Goobar(iiiii,
jjjjj,
kkkkk,
lllll,
mmmmm,
nnnnn)
end sub
end class",
"class C
sub Goo()
me.Goobar(
iiiii,
jjjjj,
kkkkk,
lllll,
mmmmm,
nnnnn)
end sub
end class",
"class C
sub Goo()
me.Goobar(iiiii,
jjjjj,
kkkkk,
lllll,
mmmmm,
nnnnn)
end sub
end class",
"class C
sub Goo()
me.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn)
end sub
end class",
"class C
sub Goo()
me.Goobar(
iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn)
end sub
end class",
"class C
sub Goo()
me.Goobar(
iiiii, jjjjj,
kkkkk, lllll,
mmmmm, nnnnn)
end sub
end class",
"class C
sub Goo()
me.Goobar(iiiii,
jjjjj, kkkkk,
lllll, mmmmm,
nnnnn)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function Test_DoNotOfferAllLongWrappingOptionThatAlreadyAppeared() As Task
Await TestAllWrappingCasesAsync(
"class C
sub Bar()
a.[||]Goobar(
iiiii, jjjjj, kkkkk, lllll, mmmmm,
nnnnn)
end sub
end class",
GetIndentionColumn(20),
"class C
sub Bar()
a.Goobar(iiiii,
jjjjj,
kkkkk,
lllll,
mmmmm,
nnnnn)
end sub
end class",
"class C
sub Bar()
a.Goobar(
iiiii,
jjjjj,
kkkkk,
lllll,
mmmmm,
nnnnn)
end sub
end class",
"class C
sub Bar()
a.Goobar(iiiii,
jjjjj,
kkkkk,
lllll,
mmmmm,
nnnnn)
end sub
end class",
"class C
sub Bar()
a.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn)
end sub
end class",
"class C
sub Bar()
a.Goobar(
iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function Test_LongWrapping_VariadicLengthIds2() As Task
Await TestAllWrappingCasesAsync(
"class C
sub Bar()
a.[||]Goobar(
i, jj, kkkk, lll, mm,
n)
end sub
end class",
GetIndentionColumn(30),
"class C
sub Bar()
a.Goobar(i,
jj,
kkkk,
lll,
mm,
n)
end sub
end class",
"class C
sub Bar()
a.Goobar(
i,
jj,
kkkk,
lll,
mm,
n)
end sub
end class",
"class C
sub Bar()
a.Goobar(i,
jj,
kkkk,
lll,
mm,
n)
end sub
end class",
"class C
sub Bar()
a.Goobar(i, jj, kkkk, lll, mm, n)
end sub
end class",
"class C
sub Bar()
a.Goobar(
i, jj, kkkk, lll, mm, n)
end sub
end class",
"class C
sub Bar()
a.Goobar(i, jj, kkkk,
lll, mm, n)
end sub
end class",
"class C
sub Bar()
a.Goobar(
i, jj, kkkk, lll,
mm, n)
end sub
end class",
"class C
sub Bar()
a.Goobar(i, jj, kkkk,
lll, mm, n)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function Test_DoNotOfferExistingOption1() As Task
Await TestAllWrappingCasesAsync(
"class C
sub Bar()
a.[||]Goobar(iiiii,
jjjjj,
kkkkk,
lllll,
mmmmm,
nnnnn)
end sub
end class",
GetIndentionColumn(30),
"class C
sub Bar()
a.Goobar(
iiiii,
jjjjj,
kkkkk,
lllll,
mmmmm,
nnnnn)
end sub
end class",
"class C
sub Bar()
a.Goobar(iiiii,
jjjjj,
kkkkk,
lllll,
mmmmm,
nnnnn)
end sub
end class",
"class C
sub Bar()
a.Goobar(iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn)
end sub
end class",
"class C
sub Bar()
a.Goobar(
iiiii, jjjjj, kkkkk, lllll, mmmmm, nnnnn)
end sub
end class",
"class C
sub Bar()
a.Goobar(iiiii, jjjjj,
kkkkk, lllll,
mmmmm, nnnnn)
end sub
end class",
"class C
sub Bar()
a.Goobar(
iiiii, jjjjj,
kkkkk, lllll,
mmmmm, nnnnn)
end sub
end class",
"class C
sub Bar()
a.Goobar(iiiii, jjjjj,
kkkkk, lllll,
mmmmm, nnnnn)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function Test_DoNotOfferExistingOption2() As Task
Await TestAllWrappingCasesAsync(
"class C
sub Bar()
a.Goobar([||]
i,
jj,
kkkk,
lll,
mm,
n)
end sub
end class",
GetIndentionColumn(30),
"class C
sub Bar()
a.Goobar(i,
jj,
kkkk,
lll,
mm,
n)
end sub
end class",
"class C
sub Bar()
a.Goobar(i,
jj,
kkkk,
lll,
mm,
n)
end sub
end class",
"class C
sub Bar()
a.Goobar(i, jj, kkkk, lll, mm, n)
end sub
end class",
"class C
sub Bar()
a.Goobar(
i, jj, kkkk, lll, mm, n)
end sub
end class",
"class C
sub Bar()
a.Goobar(i, jj, kkkk,
lll, mm, n)
end sub
end class",
"class C
sub Bar()
a.Goobar(
i, jj, kkkk, lll,
mm, n)
end sub
end class",
"class C
sub Bar()
a.Goobar(i, jj, kkkk,
lll, mm, n)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function TestInObjectCreation1() As Task
Await TestInRegularAndScript1Async(
"class C
sub Goo()
var v = [||]new Bar(a, b, c)
end sub
end class",
"class C
sub Goo()
var v = new Bar(a,
b,
c)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function TestInObjectCreation2() As Task
Await TestInRegularAndScript1Async(
"class C
sub Goo()
var v = new Bar([||]a, b, c)
end sub
end class",
"class C
sub Goo()
var v = new Bar(a,
b,
c)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)>
Public Async Function TestInConstructorInitializer1() As Task
Await TestInRegularAndScript1Async(
"class C
public sub new()
mybase.new([||]a, b, c)
end sub
end class",
"class C
public sub new()
mybase.new(a,
b,
c)
end sub
end class")
End Function
End Class
End Namespace
|
DustinCampbell/roslyn
|
src/EditorFeatures/VisualBasicTest/Wrapping/ArgumentWrappingTests.vb
|
Visual Basic
|
apache-2.0
| 16,646
|
' 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.CodeRefactorings.EncapsulateField
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.EncapsulateField
Public Class EncapsulateFieldTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace) As Object
Return New EncapsulateFieldRefactoringProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Sub EncapsulatePrivateFieldAndUpdateReferences()
Dim text = <File>
Class C
Private ReadOnly x[||] As Integer
Public Sub New()
x = 3
End Sub
Sub foo()
Dim z = x
End Sub
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Private ReadOnly x As Integer
Public Sub New()
x = 3
End Sub
Public ReadOnly Property X1 As Integer
Get
Return x
End Get
End Property
Sub foo()
Dim z = X1
End Sub
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False, index:=0)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Sub EncapsulateDimField()
Dim text = <File>
Class C
Dim x[||] As Integer
Sub foo()
Dim z = x
End Sub
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Dim x As Integer
Public Property X1 As Integer
Get
Return x
End Get
Set(value As Integer)
x = value
End Set
End Property
Sub foo()
Dim z = X1
End Sub
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Sub EncapsulateGenericField()
Dim text = <File>
Class C(Of T)
Dim x[||] As T
Sub foo()
Dim z = x
End Sub
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C(Of T)
Dim x As T
Public Property X1 As T
Get
Return x
End Get
Set(value As T)
x = value
End Set
End Property
Sub foo()
Dim z = X1
End Sub
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Sub EncapsulatePublicFieldIgnoringReferences()
Dim text = <File>
Class C
Public [|x|] As Integer
Sub foo()
x = 3
End Sub
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Private _x As Integer
Public Property X As Integer
Get
Return _x
End Get
Set(value As Integer)
_x = value
End Set
End Property
Sub foo()
x = 3
End Sub
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False, index:=1)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Sub EncapsulatePublicFieldUpdatingReferences()
Dim text = <File>
Class C
Public [|x|] As Integer
Sub foo()
x = 3
End Sub
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Private _x As Integer
Public Property X As Integer
Get
Return _x
End Get
Set(value As Integer)
_x = value
End Set
End Property
Sub foo()
X = 3
End Sub
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False, index:=0)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Sub EncapsulateMultiplePrivateFieldsWithReferences()
Dim text = <File>
Class C
Private [|x, y|] As Integer
Sub foo()
x = 3
y = 4
End Sub
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Private x, y As Integer
Public Property X1 As Integer
Get
Return x
End Get
Set(value As Integer)
x = value
End Set
End Property
Public Property Y1 As Integer
Get
Return y
End Get
Set(value As Integer)
y = value
End Set
End Property
Sub foo()
X1 = 3
Y1 = 4
End Sub
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False, index:=0)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Sub EncapsulateMultiplePublicFieldsWithReferences()
Dim text = <File>
Class C
[|Public x As String
Public y As Integer|]
Sub foo()
x = "foo"
y = 4
End Sub
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Private _x As String
Private _y As Integer
Public Property X As String
Get
Return _x
End Get
Set(value As String)
_x = value
End Set
End Property
Public Property Y As Integer
Get
Return _y
End Get
Set(value As Integer)
_y = value
End Set
End Property
Sub foo()
x = "foo"
y = 4
End Sub
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False, index:=1)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Sub NoSetterForConstField()
Dim text = <File>
Class Program
Private Const [|foo|] As Integer = 3
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class Program
Private Const foo As Integer = 3
Public Shared ReadOnly Property Foo1 As Integer
Get
Return foo
End Get
End Property
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False, index:=0)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Sub EncapsulateEscapedIdentifier()
Dim text = <File>
Class C
Private [|[Class]|] As String
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Private [Class] As String
Public Property Class1 As String
Get
Return [Class]
End Get
Set(value As String)
Me.Class = value
End Set
End Property
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False, index:=0)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Sub EncapsulateFieldNamedValue()
Dim text = <File>
Class C
Private [|value|] As Integer = 3
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Private value As Integer = 3
Public Property Value1 As Integer
Get
Return value
End Get
Set(value As Integer)
Me.value = value
End Set
End Property
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False, index:=0)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Sub EncapsulateFieldName__()
Dim text = <File>
Class D
Public [|__|] As Integer
End Class
</File>.ConvertTestSourceTag()
Dim expected = <File>
Class D
Private ___ As Integer
Public Property __ As Integer
Get
Return ___
End Get
Set(value As Integer)
___ = value
End Set
End Property
End Class
</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False)
End Sub
<WorkItem(694262)>
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Sub PreserveTrivia()
Dim text = <File>
Class AA
Private name As String : Public [|dsds|] As Integer
End Class
</File>.ConvertTestSourceTag()
Dim expected = <File>
Class AA
Private name As String : Private _dsds As Integer
Public Property Dsds As Integer
Get
Return _dsds
End Get
Set(value As Integer)
_dsds = value
End Set
End Property
End Class
</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False)
End Sub
<WorkItem(694241)>
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Sub NewPropertyNameIsUnique()
Dim text = <File>
Class AA
Private [|name|] As String
Property Name1 As String
Get
End Get
Set(value As String)
End Set
End Property
End Class
</File>.ConvertTestSourceTag()
Dim expected = <File>
Class AA
Private name As String
Property Name1 As String
Get
End Get
Set(value As String)
End Set
End Property
Public Property Name2 As String
Get
Return name
End Get
Set(value As String)
name = value
End Set
End Property
End Class
</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False)
End Sub
<WorkItem(695046)>
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Sub AvailableNotJustOnVariableName()
Dim text = <File>
Class C
Private [||] ReadOnly x As Integer
End Class</File>.ConvertTestSourceTag()
TestActionCount(text, 2)
End Sub
<WorkItem(705898)>
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Sub CopyAccessibility()
Dim text = <File>
Class C
Protected [|x|] As Integer
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Private _x As Integer
Protected Property X As Integer
Get
Return _x
End Get
Set(value As Integer)
_x = value
End Set
End Property
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False)
End Sub
<WorkItem(707080)>
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Sub BackingFieldStartsWithUnderscore()
Dim text = <File>
Public Class Class1
Public [|Name|] As String
Sub foo()
name = ""
End Sub
End Class
</File>.ConvertTestSourceTag()
Dim expected = <File>
Public Class Class1
Private _name As String
Public Property Name As String
Get
Return _name
End Get
Set(value As String)
_name = value
End Set
End Property
Sub foo()
Name = ""
End Sub
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Sub EncapsulateShadowingField()
Dim text = <File>
Class C
Protected _foo As Integer
Public Property Foo As Integer
Get
End Get
Set(value As Integer)
End Set
End Property
End Class
Class D
Inherits C
Protected Shadows [|_foo|] As Integer
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Protected _foo As Integer
Public Property Foo As Integer
Get
End Get
Set(value As Integer)
End Set
End Property
End Class
Class D
Inherits C
Private Shadows _foo As Integer
Protected Property Foo1 As Integer
Get
Return _foo
End Get
Set(value As Integer)
_foo = value
End Set
End Property
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False)
End Sub
End Class
End Namespace
|
DavidKarlas/roslyn
|
src/EditorFeatures/VisualBasicTest/CodeActions/EncapsulateField/EncapsulateFieldTests.vb
|
Visual Basic
|
apache-2.0
| 12,330
|
' 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 Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' A NoPiaMissingCanonicalTypeSymbol is a special kind of ErrorSymbol that represents
''' a NoPia embedded type symbol that was attempted to be substituted with canonical type,
''' but the canonocal type couldn't be found.
''' </summary>
Friend Class NoPiaMissingCanonicalTypeSymbol
Inherits ErrorTypeSymbol ' TODO: Should probably inherit from MissingMetadataType.TopLevel, but review TypeOf checks for MissingMetadataType.
Private ReadOnly _embeddingAssembly As AssemblySymbol
Private ReadOnly _guid As String
Private ReadOnly _scope As String
Private ReadOnly _identifier As String
Private ReadOnly _fullTypeName As String
Public Sub New(
embeddingAssembly As AssemblySymbol,
fullTypeName As String,
guid As String,
scope As String,
identifier As String
)
_fullTypeName = fullTypeName
_embeddingAssembly = embeddingAssembly
_guid = guid
_scope = scope
_identifier = identifier
End Sub
Public ReadOnly Property EmbeddingAssembly As AssemblySymbol
Get
Return _embeddingAssembly
End Get
End Property
Public ReadOnly Property FullTypeName As String
Get
Return _fullTypeName
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _fullTypeName
End Get
End Property
Friend Overrides ReadOnly Property MangleName As Boolean
Get
' Canonical type cannot be generic.
Debug.Assert(Arity = 0)
Return False
End Get
End Property
Public ReadOnly Property Guid As String
Get
Return _guid
End Get
End Property
Public ReadOnly Property Scope As String
Get
Return _scope
End Get
End Property
Public ReadOnly Property Identifier As String
Get
Return _identifier
End Get
End Property
Public Overrides Function GetHashCode() As Integer
Return RuntimeHelpers.GetHashCode(Me)
End Function
Public Overrides Function Equals(obj As Object) As Boolean
Return obj Is Me
End Function
Friend Overrides ReadOnly Property ErrorInfo As DiagnosticInfo
Get
Return ErrorFactory.ErrorInfo(ERRID.ERR_AbsentReferenceToPIA1, _fullTypeName)
End Get
End Property
End Class
End Namespace
|
paladique/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/NoPiaMissingCanonicalTypeSymbol.vb
|
Visual Basic
|
apache-2.0
| 3,155
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations
''' <summary>
''' Recommends the "Sub" keyword in member declaration contexts
''' </summary>
Friend Class SubKeywordRecommender
Inherits AbstractKeywordRecommender
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
If context.IsTypeMemberDeclarationKeywordContext OrElse context.IsInterfaceMemberDeclarationKeywordContext Then
Dim modifiers = context.ModifierCollectionFacts
If modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.Method) AndAlso
modifiers.IteratorKeyword.Kind = SyntaxKind.None Then
Return ImmutableArray.Create(New RecommendedKeyword("Sub", VBFeaturesResources.Declares_the_name_parameters_and_code_that_define_a_Sub_procedure_that_is_a_procedure_that_does_not_return_a_value_to_the_calling_code))
End If
End If
' Exit Sub
If context.FollowsEndOfStatement Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
Dim targetToken = context.TargetToken
If targetToken.IsKindOrHasMatchingText(SyntaxKind.ExitKeyword) AndAlso
context.IsInStatementBlockOfKind(SyntaxKind.SubBlock, SyntaxKind.MultiLineSubLambdaExpression) AndAlso
Not context.IsInStatementBlockOfKind(SyntaxKind.FinallyBlock) Then
Return ImmutableArray.Create(New RecommendedKeyword("Sub", VBFeaturesResources.Exits_a_Sub_procedure_and_transfers_execution_immediately_to_the_statement_following_the_call_to_the_Sub_procedure))
End If
Return ImmutableArray(Of RecommendedKeyword).Empty
End Function
End Class
End Namespace
|
CyrusNajmabadi/roslyn
|
src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/SubKeywordRecommender.vb
|
Visual Basic
|
mit
| 2,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 Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Public Class EntryPointTests
Inherits BasicTestBase
<Fact()>
Public Sub MainOverloads()
Dim source =
<compilation>
<file>
Public Class C
Public Shared Sub Main(goo As Integer)
System.Console.WriteLine(1)
End Sub
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe)
Dim verifier = CompileAndVerify(compilation, expectedOutput:="2")
verifier.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub MainOverloads_Dll()
Dim source =
<compilation>
<file>
Public Class C
Public Shared Sub Main(goo As Integer)
System.Console.WriteLine(1)
End Sub
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseDll)
Dim verifier = CompileAndVerify(compilation)
verifier.VerifyDiagnostics()
End Sub
''' <summary>
''' Dev10 reports the .exe full path in CS5001. We don't.
''' </summary>
<Fact()>
Public Sub ERR_NoEntryPoint_Overloads()
Dim source =
<compilation name="a">
<file>
Public Class C
Public Shared Sub Main(goo As Integer)
System.Console.WriteLine(1)
End Sub
Public Shared Sub Main(goo As Double)
System.Console.WriteLine(2)
End Sub
Public Shared Sub Main(goo As String(,))
System.Console.WriteLine(2)
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
''' <summary>
''' Dev10 reports the .exe full path in CS0017. We don't.
''' </summary>
<Fact()>
Public Sub ERR_MultipleEntryPoints()
Dim source =
<compilation name="a">
<file>
Public Class C
Public Shared Sub Main()
System.Console.WriteLine(1)
End Sub
Public Shared Sub Main(a As String())
System.Console.WriteLine(2)
End Sub
End Class
Public Class D
Public Shared Function Main() As String
System.Console.WriteLine(3)
Return Nothing
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_MoreThanOneValidMainWasFound2).WithArguments("a", "C.Main(), C.Main(a As String())"))
End Sub
<Fact()>
Public Sub ERR_MultipleEntryPoints_Script()
Dim vbx = <text>
Public Shared Sub Main()
System.Console.WriteLine(1)
End Sub
</text>
Dim vb = <text>
Public Class C
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
</text>
Dim compilation = CreateCompilationWithMscorlib(
{VisualBasicSyntaxTree.ParseText(vbx.Value, options:=TestOptions.Script),
VisualBasicSyntaxTree.ParseText(vb.Value, options:=VisualBasicParseOptions.Default)}, options:=TestOptions.ReleaseExe)
' TODO: compilation.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()"), Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("C.Main()"))
End Sub
<WorkItem(528677, "DevDiv")>
<Fact()>
Public Sub ERR_OneEntryPointAndOverload()
Dim source =
<compilation>
<file>
Public Class C
Shared Function Main() As Integer
Return 0
End Function
Shared Function Main(args As String(), i As Integer) As Integer
Return i
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub Namespaces()
Dim source =
<compilation>
<file>
Namespace N
Namespace M
End Namespace
End Namespace
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("N.M"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("N.M"))
End Sub
<Fact()>
Public Sub Modules()
Dim source =
<compilation>
<file>
Namespace N
Module M
Sub Main()
End Sub
End Module
End Namespace
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe.WithMainTypeName("N.M"))
compilation.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub Structures()
Dim source =
<compilation>
<file>
Structure C
Structure D
Public Shared Sub Main()
End Sub
End Structure
End Structure
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C.D"))
compilation.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub NestedGenericMainType()
Dim source =
<compilation>
<file>
Class C(Of T)
Structure D
Public Shared Sub Main()
End Sub
End Structure
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C.D"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("C(Of T).D"))
End Sub
<Fact()>
Public Sub GenericMainMethods()
Dim vb =
<compilation>
<file>
Imports System
Public Class C
Public Shared Sub Main(Of T)()
Console.WriteLine(1)
End Sub
Public Class CC(Of T)
Public Shared Sub Main()
Console.WriteLine(2)
End Sub
End Class
End Class
Public Class D(Of T)
Shared Sub Main()
Console.WriteLine(3)
End Sub
Public Class DD
Public Shared Sub Main()
Console.WriteLine(4)
End Sub
End Class
End Class
Public Class E
Public Shared Sub Main()
Console.WriteLine(5)
End Sub
End Class
Public Interface I
Sub Main()
End Interface
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(vb, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics()
CompileAndVerify(compilation, expectedOutput:="5")
compilation = CreateCompilationWithMscorlib(vb, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("C"))
compilation = CreateCompilationWithMscorlib(vb, options:=TestOptions.ReleaseExe.WithMainTypeName("D.DD"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("D(Of T).DD"))
compilation = CreateCompilationWithMscorlib(vb, options:=TestOptions.ReleaseExe.WithMainTypeName("I"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("I"))
End Sub
<Fact()>
Public Sub MultipleArities1()
Dim source =
<compilation>
<file>
Public Class A
Public Class B
Class C
Public Shared Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
End Class
Public Class B(Of T)
Class C
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
End Class
End Class
</file>
</compilation>
CompileAndVerify(source, options:=TestOptions.ReleaseExe.WithMainTypeName("A.B.C"), expectedOutput:="1")
End Sub
<Fact()>
Public Sub MultipleArities2()
Dim source =
<compilation>
<file>
Public Class A
Public Class B(Of T)
Class C
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
End Class
Public Class B
Class C
Public Shared Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
End Class
End Class
</file>
</compilation>
CompileAndVerify(source, options:=TestOptions.ReleaseExe.WithMainTypeName("A.B.C"), expectedOutput:="1")
End Sub
<Fact()>
Public Sub MultipleArities3()
Dim source =
<compilation>
<file>
Public Class A
Public Class B(Of S, T)
Class C
Public Shared Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
End Class
Public Class B(Of T)
Class C
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
End Class
End Class
</file>
</compilation>
' Dev10 reports error BC30420: 'Sub Main' was not found in 'A.B.C'.
' error BC30796: None of the accessible 'Main' methods with the appropriate signatures found in 'A.B(Of T).C'
' can be the startup method since they are all either generic or nested in generic types.
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("A.B.C")).VerifyDiagnostics(Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("A.B(Of T).C"))
End Sub
''' <summary>
''' The nongeneric is used.
''' </summary>
Public Sub ExplicitMainTypeName_GenericAndNonGeneric()
Dim source =
<compilation>
<file>
Class C(Of T)
Shared Sub Main()
End Sub
End Class
Class C
Shared Sub Main()
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
compilation.VerifyDiagnostics()
End Sub
''' <summary>
''' Dev10: the first definition of C is reported (i.e. C{S,T}). We report the one with the least arity (i.e. C{T}).
''' </summary>
<Fact()>
Public Sub ExplicitMainTypeName_GenericMultipleArities()
Dim source =
<compilation>
<file>
Class C(Of T)
Shared Sub Main()
End Sub
End Class
Class C(Of S, T)
Shared Sub Main()
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
' Dev10 reports: BC30420: 'Sub Main' was not found in 'C'.
' error BC30796: None of the accessible 'Main' methods with the appropriate signatures found in 'C(Of T)'
' can be the startup method since they are all either generic or nested in generic types.
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("C(Of T)"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeHasMultipleMains_NoViable()
Dim source =
<compilation>
<file>
Public Class C
Function Main(b As Boolean) As Integer
Return 1
End Function
Shared Function Main(a As String) As Integer
Return 1
End Function
Shared Function Main(a As Integer) As Integer
Return 1
End Function
Shared Function Main(Of T)() As Integer
Return 1
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("C"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeHasMultipleMains_SingleViable()
Dim source =
<compilation>
<file>
Public Class C
Function Main(b As Boolean) As Integer
Return 1
End Function
Shared Function Main() As Integer
Return 1
End Function
Shared Function Main(a As String) As Integer
Return 1
End Function
Shared Function Main(a As Integer) As Integer
Return 1
End Function
Shared Function Main(Of T)() As Integer
Return 1
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
compilation.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub ExplicitMainTypeHasMultipleMains_MultipleViable()
Dim source =
<compilation name="a">
<file>
Class C
Function Main(b As Boolean) As Integer
Return 1
End Function
Shared Function Main() As Integer
Return 1
End Function
Shared Function Main(a As String) As Integer
Return 1
End Function
Shared Function Main(a As Integer) As Integer
Return 1
End Function
Shared Function Main(a As String()) As Integer
Return 1
End Function
Shared Function Main(Of T)() As Integer
Return 1
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
' Dev10 displays return type, we don't; methods can't be overloaded on return type so the type is not necessary
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_MoreThanOneValidMainWasFound2).WithArguments("a", "C.Main(), C.Main(a As String())"))
End Sub
<Fact()>
Public Sub ERR_NoEntryPoint_NonMethod()
Dim source =
<compilation name="a">
<file>
Public Class G
Public Shared Main As Integer = 1
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub Script()
Dim vbx = <text>
System.Console.WriteLine(1)
</text>
Dim compilation = CreateCompilationWithMscorlib(
{VisualBasicSyntaxTree.ParseText(vbx.Value, options:=TestOptions.Script)}, options:=TestOptions.ReleaseExe, references:=LatestReferences)
CompileAndVerify(compilation, expectedOutput:="1")
End Sub
<Fact()>
Public Sub ScriptAndRegularFile_ExplicitMain()
Dim vbx = <text>
System.Console.WriteLine(1)
</text>
Dim vb = <text>
Public Class C
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
</text>
Dim compilation = CreateCompilationWithMscorlib(
{VisualBasicSyntaxTree.ParseText(vbx.Value, options:=TestOptions.Script),
VisualBasicSyntaxTree.ParseText(vb.Value, options:=VisualBasicParseOptions.Default)}, options:=TestOptions.ReleaseExe, references:=LatestReferences)
' TODO: compilation.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("C.Main()"))
CompileAndVerify(compilation, expectedOutput:="1")
End Sub
<Fact()>
Public Sub ScriptAndRegularFile_ExplicitMains()
Dim vbx = <text>
System.Console.WriteLine(1)
</text>
Dim vb = <text>
Public Class C
Public Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
Public Class D
Public Shared Sub Main()
System.Console.WriteLine(3)
End Sub
End Class
</text>
Dim compilation = CreateCompilationWithMscorlib(
{VisualBasicSyntaxTree.ParseText(vbx.Value, options:=TestOptions.Script),
VisualBasicSyntaxTree.ParseText(vb.Value, options:=VisualBasicParseOptions.Default)}, options:=TestOptions.ReleaseExe, references:=LatestReferences)
' TODO: compilation.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("C.Main()"), Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("D.Main()"))
CompileAndVerify(compilation, expectedOutput:="1")
End Sub
<Fact()>
Public Sub ExplicitMain()
Dim source =
<compilation>
<file>
Class C
Shared Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
Class D
Shared Sub Main()
System.Console.WriteLine(2)
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
CompileAndVerify(compilation, expectedOutput:="1")
compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("D"))
CompileAndVerify(compilation, expectedOutput:="2")
End Sub
<Fact()>
Public Sub ERR_MainClassNotFound()
Dim source =
<compilation>
<file>
Class C
Shared Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("D"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("D"))
End Sub
<Fact()>
Public Sub ERR_MainClassNotClass()
Dim source =
<compilation>
<file>
Enum C
Main = 1
End Enum
Delegate Sub D()
Interface I
End Interface
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("C"))
compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("D"))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("D"))
compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("I"))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("I"))
End Sub
<Fact()>
Public Sub ERR_NoMainInClass()
Dim source =
<compilation>
<file>
Class C
Sub Main()
End Sub
End Class
Class D
Shared Sub Main(args As Double)
End Sub
End Class
Class E
ReadOnly Property Main As Integer
Get
System.Console.WriteLine(1)
Return 1
End Get
End Property
End Class
Class F
Private Shared Sub Main()
End Sub
End Class
Class G
Private Class P
Public Shared Sub Main()
End Sub
Public Class Q
Public Shared Sub Main()
End Sub
End Class
End Class
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("C"))
compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("D"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("D"))
compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("E"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("E"))
compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("F"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("F"))
compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("G.P"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("G.P"))
compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("G.P.Q"))
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("G.P.Q"))
End Sub
<Fact()>
Public Sub ERR_NoMainInClass_Script()
Dim vbx = <text>
System.Console.WriteLine(2)
</text>
Dim vb = <text>
Class C
Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
</text>
Dim compilation = CreateCompilationWithMscorlib(
{VisualBasicSyntaxTree.ParseText(vbx.Value, options:=TestOptions.Script),
VisualBasicSyntaxTree.ParseText(vb.Value, options:=TestOptions.Regular)}, options:=TestOptions.ReleaseExe.WithMainTypeName("C"))
' TODO: compilation.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_MainIgnored).WithArguments("C"))
End Sub
<Fact()>
Public Sub RefParameterForMain()
Dim source =
<compilation name="a">
<file>
Public Class C
Shared Sub Main(ByRef args As String())
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ERR_InValidSubMainsFound1_PartialClass_1()
Dim source =
<compilation name="a">
<file>
Partial Public Class A
Private Shared Partial Sub Main()
End Sub
End Class
Partial Public Class A
End Class
</file>
</compilation>
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ERR_InValidSubMainsFound1_PartialClass_2()
Dim source =
<compilation name="a">
<file>
Partial Public Class A
Private Shared Partial Sub Main()
End Sub
End Class
Partial Public Class A
Private Shared Partial Sub Main(args As String(,))
End Sub
Private Shared Sub Main()
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ERR_InValidSubMainsFound1_JaggedArray()
Dim source =
<compilation name="a">
<file>
Public Class A
Public Shared Sub Main(args As String()())
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ERR_InValidSubMainsFound1_Array()
Dim source =
<compilation name="a">
<file>
Imports System
Public Class A
Public Shared Sub Main(args As Array)
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ERR_StartupCodeNotFound1_MainIsProperty()
Dim source =
<compilation name="a">
<file>
Public Class A
Property Main As String
Get
Return "Main"
End Get
Set(ByVal value As String)
End Set
End Property
End Class
</file>
</compilation>
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ERR_InValidSubMainsFound1_ReturnTypeOtherthanInteger()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main() As Integer()
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ParamParameterForMain()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main(ParamArray ByVal x As String()) As Integer
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub ParamParameterForMain_1()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main(ParamArray ByVal x As Integer()) As Integer
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ParamParameterForMain_2()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main(args as string(), ParamArray ByVal x As Integer()) As Integer
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub OptionalParameterForMain()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main(Optional ByRef x As String() = Nothing) As Integer
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub OptionalParameterForMain_1()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main(Optional ByRef x As integer = 1) As Integer
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub OptionalParameterForMain_2()
Dim source =
<compilation name="a">
<file>
Public Class A
Shared Function Main(Optional ByRef x As integer(,) = nothing) As Integer
Return Nothing
End Function
End Class
</file>
</compilation>
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub MainAsExtensionMethod()
Dim source =
<compilation name="a">
<file>
Imports System.Runtime.CompilerServices
Class B
End Class
Module Extension
<Extension()>
Public Sub Main(x As B, args As String())
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {SystemCoreRef}, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub MainAsExtensionMethod_1()
Dim source =
<compilation name="a">
<file>
Imports System.Runtime.CompilerServices
Class B
End Class
Module Extension
<Extension()>
Public Sub Main(x As B)
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {SystemCoreRef}, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub MainAsExtensionMethod_2()
Dim source =
<compilation name="a">
<file>
Imports System.Runtime.CompilerServices
Class B
End Class
Module Extension
<Extension()>
Public Sub Main(x As String)
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {SystemCoreRef}, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub MainIsNotCaseSensitive()
Dim source =
<compilation name="a">
<file>
Class A
Shared Function main(args As String()) As Integer
Return Nothing
End Function
End Class
Module M1
Sub mAIN()
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlibAndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_MoreThanOneValidMainWasFound2).WithArguments("a", "A.main(args As String()), M1.mAIN()"))
End Sub
<Fact()>
Public Sub MainIsNotCaseSensitive_1()
Dim source =
<compilation name="a">
<file>
Class A
Shared Sub mAIN()
End Sub
End Class
Module M1
Sub mAIN()
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlibAndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_MoreThanOneValidMainWasFound2).WithArguments("a", "A.mAIN(), M1.mAIN()"))
End Sub
<Fact, WorkItem(543591, "DevDiv")>
Public Sub MainInPrivateClass()
Dim source =
<compilation name="a">
<file>
Class A
Private Class A
Public Shared Sub Main()
End Sub
End Class
End Class
</file>
</compilation>
' Dev10 reports BC30420: 'Sub Main' was not found in 'a'.
' We report BC30737: No accessible 'Main' method with an appropriate signature was found in 'a'.
CreateCompilationWithMscorlibAndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact, WorkItem(543591, "DevDiv")>
Public Sub MainInPrivateClass_1()
Dim source =
<compilation>
<file>
Class A
Private Class A
Public Shared Sub Main()
End Sub
End Class
Public Shared Sub Main()
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlibAndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics()
End Sub
<Fact, WorkItem(543591, "DevDiv")>
Public Sub MainInPrivateClass_2()
Dim source =
<compilation>
<file>
Structure A
Private Structure A
Public Shared Sub Main()
End Sub
End Structure
End Structure
Module M1
Public Sub Main()
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlibAndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub PrivateMain()
Dim source =
<compilation name="a">
<file>
Structure A
Private Shared Sub Main()
End Sub
End Structure
Module M1
Private Sub Main()
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlibAndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub MultipleEntryPoint_Inherit()
Dim source =
<compilation name="a">
<file>
Class BaseClass
Public Shared Sub Main()
End Sub
End Class
Class Derived
Inherits BaseClass
Public Shared Overloads Sub Main()
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlibAndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_MoreThanOneValidMainWasFound2).WithArguments("a", "BaseClass.Main(), Derived.Main()"))
End Sub
<Fact()>
Public Sub MainMustBeStatic()
Dim source =
<compilation name="a">
<file>
Class BaseClass
Public Sub Main()
End Sub
End Class
Structure Derived
Public Function Main(args As String()) As Integer
Return Nothing
End Function
End Structure
</file>
</compilation>
CreateCompilationWithMscorlibAndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub MainAsTypeName()
Dim source =
<compilation name="a">
<file>
Class Main
Shared Sub New()
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlibAndVBRuntime(source, Nothing, options:=TestOptions.ReleaseExe).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("a"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_MainIsNotStatic()
Dim source =
<compilation>
<file>
Class Main
Sub Main()
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("Main")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("Main"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_ClassNameIsEmpty()
Dim source =
<compilation>
<file>
Class Main
shared Sub Main()
End Sub
End Class
</file>
</compilation>
AssertTheseDiagnostics(CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("")),
<expected>
BC2014: the value '' is invalid for option 'MainTypeName'
</expected>)
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_NoMainInClass()
Dim source =
<compilation>
<file>
Class Main
End Class
</file>
</compilation>
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("Main")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("Main"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_NotCaseSensitive()
Dim source =
<compilation>
<file>
Class Main
shared Sub Main()
End Sub
End Class
</file>
</compilation>
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("main")).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_Extension()
Dim source =
<compilation>
<file>
Imports System.Runtime.CompilerServices
Class B
End Class
Module Extension
<Extension()>
Public Sub Main(x As B, args As String())
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {SystemCoreRef}, options:=TestOptions.ReleaseExe.WithMainTypeName("B")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("B"))
CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {SystemCoreRef}, options:=TestOptions.ReleaseExe.WithMainTypeName("Extension")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InValidSubMainsFound1).WithArguments("Extension"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_InvalidType()
Dim source =
<compilation>
<file>
Interface i1
Sub main()
End Interface
Enum color
blue
End Enum
Delegate Sub mydelegate(args As String())
</file>
</compilation>
CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {SystemCoreRef}, options:=TestOptions.ReleaseExe.WithMainTypeName("I1")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("i1"))
CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {SystemCoreRef}, options:=TestOptions.ReleaseExe.WithMainTypeName("COLOR")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("color"))
CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {SystemCoreRef}, options:=TestOptions.ReleaseExe.WithMainTypeName("mydelegate")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("mydelegate"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_Numeric()
Dim source =
<compilation>
<file>
class a
end class
</file>
</compilation>
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("1")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("1"))
End Sub
<Fact()>
Public Sub ExplicitMainTypeName_InvalidChar()
Dim source =
<compilation>
<file>
class a
end class
</file>
</compilation>
CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("<")).VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("<"))
End Sub
<WorkItem(545803, "DevDiv")>
<Fact()>
Public Sub ExplicitMainTypeName_PublicInBase()
Dim source =
<compilation>
<file>
Class A
Public Shared Sub Main()
End Sub
End Class
Class B
Inherits A
End Class
</file>
</compilation>
Dim compilation As VisualBasicCompilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("B"))
compilation.VerifyDiagnostics()
Assert.Equal(compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A").GetMember(Of MethodSymbol)("Main"),
compilation.GetEntryPoint(Nothing))
End Sub
<WorkItem(545803, "DevDiv")>
<Fact()>
Public Sub ExplicitMainTypeName_ProtectedInBase()
Dim source =
<compilation>
<file>
Class A
Protected Shared Sub Main()
End Sub
End Class
Class B
Inherits A
End Class
</file>
</compilation>
Dim compilation As VisualBasicCompilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("B"))
compilation.VerifyDiagnostics()
Assert.Equal(compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A").GetMember(Of MethodSymbol)("Main"),
compilation.GetEntryPoint(Nothing))
End Sub
<WorkItem(545803, "DevDiv")>
<Fact()>
Public Sub ExplicitMainTypeName_PrivateInBase()
Dim source =
<compilation>
<file>
Class A
Private Shared Sub Main()
End Sub
End Class
Class B
Inherits A
End Class
</file>
</compilation>
Dim compilation As VisualBasicCompilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("B"))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("B"))
Assert.Null(compilation.GetEntryPoint(Nothing))
End Sub
<WorkItem(545803, "DevDiv")>
<Fact()>
Public Sub ExplicitMainTypeName_InGenericBase()
Dim source =
<compilation>
<file>
Class A(Of T)
Public Shared Sub Main()
End Sub
End Class
Class B
Inherits A(Of Integer)
End Class
</file>
</compilation>
Dim compilation As VisualBasicCompilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("B"))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_GenericSubMainsFound1).WithArguments("B"))
Assert.Null(compilation.GetEntryPoint(Nothing))
End Sub
<WorkItem(545803, "DevDiv")>
<Fact()>
Public Sub ExplicitMainTypeName_InBaseHiddenByField()
Dim source =
<compilation>
<file>
Class A
Public Shared Sub Main()
End Sub
End Class
Class B
Inherits A
Shadows Dim Main as Integer
End Class
</file>
</compilation>
Dim compilation As VisualBasicCompilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("B"))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("B"))
Assert.Null(compilation.GetEntryPoint(Nothing))
End Sub
<WorkItem(545803, "DevDiv")>
<Fact()>
Public Sub ExplicitMainTypeName_InBaseInOtherAssembly()
Dim source1 =
<compilation>
<file>
Public Class A
Public Shared Sub Main()
End Sub
End Class
</file>
</compilation>
Dim source2 =
<compilation>
<file>
Class B
Inherits A
End Class
</file>
</compilation>
Dim compilation1 As VisualBasicCompilation = CreateCompilationWithMscorlib(source1)
Dim compilation2 As VisualBasicCompilation = CreateCompilationWithMscorlibAndReferences(source2, {New VisualBasicCompilationReference(compilation1)}, options:=TestOptions.ReleaseExe.WithMainTypeName("B"))
compilation2.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StartupCodeNotFound1).WithArguments("B"))
Assert.Null(compilation2.GetEntryPoint(Nothing))
End Sub
<WorkItem(630763, "DevDiv")>
<Fact()>
Public Sub Bug630763()
Dim source =
<compilation>
<file>
Public Class C
Shared Function Main() As Integer
Return 0
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe)
compilation.VerifyDiagnostics()
Dim netModule = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseModule)
compilation = CreateCompilationWithMscorlibAndReferences(
<compilation name="Bug630763">
<file>
</file>
</compilation>, {netModule.EmitToImageReference()}, options:=TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC30420: 'Sub Main' was not found in 'Bug630763'.
</expected>)
End Sub
<WorkItem(753028, "DevDiv")>
<Fact>
Public Sub RootMemberNamedScript()
Dim comp As VisualBasicCompilation
comp = CompilationUtils.CreateCompilationWithMscorlib(options:=TestOptions.ReleaseExe, sources:=
<compilation name="20781949-2709-424e-b174-dec81a202016">
<file name="a.vb">
Namespace Script
End Namespace
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors>
BC30420: 'Sub Main' was not found in '20781949-2709-424e-b174-dec81a202016'.
</errors>)
comp = CompilationUtils.CreateCompilationWithMscorlib(options:=TestOptions.ReleaseExe, sources:=
<compilation name="20781949-2709-424e-b174-dec81a202017">
<file name="a.vb">
Class Script
End Class
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors>
BC30420: 'Sub Main' was not found in '20781949-2709-424e-b174-dec81a202017'.
</errors>)
comp = CompilationUtils.CreateCompilationWithMscorlib(options:=TestOptions.ReleaseExe, sources:=
<compilation name="20781949-2709-424e-b174-dec81a202018">
<file name="a.vb">
Structure Script
End Structure
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors>
BC30420: 'Sub Main' was not found in '20781949-2709-424e-b174-dec81a202018'.
</errors>)
comp = CompilationUtils.CreateCompilationWithMscorlib(options:=TestOptions.ReleaseExe, sources:=
<compilation name="20781949-2709-424e-b174-dec81a202019">
<file name="a.vb">
Interface Script(Of T)
End Interface
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors>
BC30420: 'Sub Main' was not found in '20781949-2709-424e-b174-dec81a202019'.
</errors>)
comp = CompilationUtils.CreateCompilationWithMscorlib(options:=TestOptions.ReleaseExe, sources:=
<compilation name="20781949-2709-424e-b174-dec81a202020">
<file name="a.vb">
Enum Script
A
End Enum
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors>
BC30420: 'Sub Main' was not found in '20781949-2709-424e-b174-dec81a202020'.
</errors>)
comp = CompilationUtils.CreateCompilationWithMscorlib(options:=TestOptions.ReleaseExe, sources:=
<compilation name="20781949-2709-424e-b174-dec81a202021">
<file name="a.vb">
Delegate Sub Script()
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors>
BC30420: 'Sub Main' was not found in '20781949-2709-424e-b174-dec81a202021'.
</errors>)
End Sub
End Class
End Namespace
|
droyad/roslyn
|
src/Compilers/VisualBasic/Test/Emit/Emit/EntryPointTests.vb
|
Visual Basic
|
apache-2.0
| 48,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 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
Public Class DelegateTests
Inherits BasicTestBase
<Fact>
Public Sub MissingTypes()
VisualBasicCompilation.Create("test", syntaxTrees:={Parse("Delegate Sub A()")}, options:=TestOptions.ReleaseDll).VerifyDiagnostics(
Diagnostic(ERRID.ERR_UndefinedType1, "Delegate Sub A()").WithArguments("System.Void"),
Diagnostic(ERRID.ERR_UndefinedType1, "Delegate Sub A()").WithArguments("System.Void"),
Diagnostic(ERRID.ERR_UndefinedType1, "Delegate Sub A()").WithArguments("System.IAsyncResult"),
Diagnostic(ERRID.ERR_UndefinedType1, "Delegate Sub A()").WithArguments("System.Object"),
Diagnostic(ERRID.ERR_UndefinedType1, "Delegate Sub A()").WithArguments("System.IntPtr"),
Diagnostic(ERRID.ERR_UndefinedType1, "Delegate Sub A()").WithArguments("System.AsyncCallback"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "A").WithArguments("System.MulticastDelegate", "test.dll"))
End Sub
<Fact>
Public Sub DelegateSymbolTest()
Dim source = <compilation name="C">
<file name="a.vb">
Imports System
' delegate as type
Delegate Sub SubDel(param1 as Integer, ByRef param2 as String)
Interface I1
End Interface
Class C2
implements I1
public intMember as Integer
End Class
Class C1
' delegate as nested type
Delegate Function FuncDel(param1 as Integer, param2 as String) as Char
Delegate Sub SubGenDel(Of T)(param1 as T)
Delegate Function FuncGenDel(Of T As I1)(param1 as integer) as T
Sub Main()
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
' --- test sub delegate ----------------------------------------------------------------------------
Dim subDel As NamedTypeSymbol = CType(compilation.SourceModule.GlobalNamespace.GetTypeMembers("SubDel").Single(), NamedTypeSymbol)
Assert.Equal("System.MulticastDelegate", subDel.BaseType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Dim delegateMembers = subDel.GetMembers()
Assert.Equal(4, delegateMembers.Length())
Dim delegateCtor = CType((From delegateMethod In delegateMembers Where delegateMethod.Name = ".ctor").Single(), SourceDelegateMethodSymbol)
Assert.True(delegateCtor.IsImplicitlyDeclared())
Assert.True(delegateCtor.IsSub())
Assert.Equal(2, delegateCtor.Parameters.Length())
Assert.Equal("System.Void", delegateCtor.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("TargetObject", delegateCtor.Parameters(0).Name)
Assert.Equal("System.Object", delegateCtor.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("TargetMethod", delegateCtor.Parameters(1).Name)
Assert.Equal("System.IntPtr", delegateCtor.Parameters(1).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.True(delegateCtor.IsRuntimeImplemented())
Dim delegateInvoke = CType((From delegateMethod In delegateMembers Where delegateMethod.Name = "Invoke").Single(), SourceDelegateMethodSymbol)
Assert.True(delegateInvoke.IsImplicitlyDeclared())
Assert.True(delegateInvoke.IsSub())
Assert.Equal(2, delegateInvoke.Parameters.Length())
Assert.Equal("System.Void", delegateInvoke.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param1", delegateInvoke.Parameters(0).Name)
Assert.False(delegateInvoke.Parameters(0).IsByRef())
Assert.Equal("System.Int32", delegateInvoke.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param2", delegateInvoke.Parameters(1).Name)
Assert.Equal("System.String", delegateInvoke.Parameters(1).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.True(delegateInvoke.Parameters(1).IsByRef())
Assert.True(delegateInvoke.IsRuntimeImplemented())
Dim delegateBeginInvoke = CType((From delegateMethod In delegateMembers Where delegateMethod.Name = "BeginInvoke").Single(), SourceDelegateMethodSymbol)
Assert.True(delegateBeginInvoke.IsImplicitlyDeclared())
Assert.False(delegateBeginInvoke.IsSub())
Assert.Equal(4, delegateBeginInvoke.Parameters.Length())
Assert.Equal("System.IAsyncResult", delegateBeginInvoke.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param1", delegateBeginInvoke.Parameters(0).Name)
Assert.Equal("System.Int32", delegateBeginInvoke.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.False(delegateInvoke.Parameters(0).IsByRef())
Assert.Equal("param2", delegateBeginInvoke.Parameters(1).Name)
Assert.Equal("System.String", delegateBeginInvoke.Parameters(1).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.True(delegateInvoke.Parameters(1).IsByRef())
Assert.Equal("System.AsyncCallback", delegateBeginInvoke.Parameters(2).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("DelegateCallback", delegateBeginInvoke.Parameters(2).Name)
Assert.False(delegateBeginInvoke.Parameters(2).IsByRef())
Assert.Equal("System.Object", delegateBeginInvoke.Parameters(3).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("DelegateAsyncState", delegateBeginInvoke.Parameters(3).Name)
Assert.False(delegateBeginInvoke.Parameters(3).IsByRef())
Assert.True(delegateBeginInvoke.IsRuntimeImplemented())
Dim delegateEndInvoke = CType((From delegateMethod In delegateMembers Where delegateMethod.Name = "EndInvoke").Single(), SourceDelegateMethodSymbol)
Assert.True(delegateEndInvoke.IsImplicitlyDeclared())
Assert.True(delegateEndInvoke.IsSub())
Assert.Equal("System.Void", delegateEndInvoke.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal(2, delegateEndInvoke.Parameters.Length)
Assert.Equal("System.String", delegateEndInvoke.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param2", delegateEndInvoke.Parameters(0).Name)
Assert.True(delegateEndInvoke.Parameters(0).IsByRef)
Assert.Equal("System.IAsyncResult", delegateEndInvoke.Parameters(1).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("DelegateAsyncResult", delegateEndInvoke.Parameters(1).Name)
Assert.False(delegateEndInvoke.Parameters(1).IsByRef)
Assert.True(delegateEndInvoke.IsRuntimeImplemented())
' --- test function delegate ----------------------------------------------------------------------------
Dim funcDel As NamedTypeSymbol = CType(compilation.SourceModule.GlobalNamespace.GetTypeMembers("C1").Single().GetMembers("FuncDel").Single(), NamedTypeSymbol)
Assert.Equal("System.MulticastDelegate", subDel.BaseType.ToDisplayString(SymbolDisplayFormat.TestFormat))
delegateMembers = funcDel.GetMembers()
delegateInvoke = CType((From delegateMethod In delegateMembers Where delegateMethod.Name = "Invoke").Single(), SourceDelegateMethodSymbol)
Assert.True(delegateInvoke.IsImplicitlyDeclared())
Assert.False(delegateInvoke.IsSub())
Assert.Equal(2, delegateInvoke.Parameters.Length())
Assert.Equal("System.Char", delegateInvoke.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param1", delegateInvoke.Parameters(0).Name)
Assert.False(delegateInvoke.Parameters(0).IsByRef())
Assert.Equal("System.Int32", delegateInvoke.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param2", delegateInvoke.Parameters(1).Name)
Assert.Equal("System.String", delegateInvoke.Parameters(1).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.False(delegateInvoke.Parameters(1).IsByRef())
delegateEndInvoke = CType((From delegateMethod In delegateMembers Where delegateMethod.Name = "EndInvoke").Single(), SourceDelegateMethodSymbol)
Assert.True(delegateEndInvoke.IsImplicitlyDeclared())
Assert.False(delegateEndInvoke.IsSub())
Assert.Equal("System.Char", delegateEndInvoke.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal(1, delegateEndInvoke.Parameters.Length)
Assert.Equal("System.IAsyncResult", delegateEndInvoke.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("DelegateAsyncResult", delegateEndInvoke.Parameters(0).Name)
Assert.False(delegateEndInvoke.Parameters(0).IsByRef)
' --- test generic sub delegate -------------------------------------------------------------------------
Dim genSubDel As NamedTypeSymbol = CType(compilation.SourceModule.GlobalNamespace.GetTypeMembers("C1").Single().GetMembers("SubGenDel").Single(), NamedTypeSymbol)
Assert.Equal("System.MulticastDelegate", genSubDel.BaseType.ToDisplayString(SymbolDisplayFormat.TestFormat))
delegateMembers = genSubDel.GetMembers()
delegateInvoke = CType((From delegateMethod In delegateMembers Where delegateMethod.Name = "Invoke").Single(), SourceDelegateMethodSymbol)
Assert.True(delegateInvoke.IsImplicitlyDeclared())
Assert.True(delegateInvoke.IsSub())
Assert.Equal(1, delegateInvoke.Parameters.Length())
Assert.Equal("System.Void", delegateInvoke.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param1", delegateInvoke.Parameters(0).Name)
Assert.False(delegateInvoke.Parameters(0).IsByRef())
Assert.Equal("T", delegateInvoke.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.True(delegateInvoke.IsRuntimeImplemented())
' --- test generic function delegate -------------------------------------------------------------------------
Dim genFuncDel As NamedTypeSymbol = CType(compilation.SourceModule.GlobalNamespace.GetTypeMembers("C1").Single().GetMembers("FuncGenDel").Single(), NamedTypeSymbol)
Assert.Equal("System.MulticastDelegate", genSubDel.BaseType.ToDisplayString(SymbolDisplayFormat.TestFormat))
delegateMembers = genFuncDel.GetMembers()
delegateInvoke = CType((From delegateMethod In delegateMembers Where delegateMethod.Name = "Invoke").Single(), SourceDelegateMethodSymbol)
Assert.True(delegateInvoke.IsImplicitlyDeclared())
Assert.False(delegateInvoke.IsSub())
Assert.Equal("T", delegateInvoke.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.True(delegateInvoke.IsRuntimeImplemented())
End Sub
<Fact>
Public Sub GenericDelegateSymbolTest()
Dim source = <compilation name="C">
<file name="a.vb">
Imports System
Delegate Sub SubGenDel(Of T)(param1 as T)
Delegate Function FuncGenDel(Of T As I1)(param1 as integer) as T
Class C1
Sub Main()
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
Dim subGenDel As NamedTypeSymbol = CType(compilation.SourceModule.GlobalNamespace.GetTypeMembers("SubGenDel").Single(), NamedTypeSymbol)
Dim param1Type = subGenDel.TypeParameters(0)
Assert.Equal(param1Type.ContainingSymbol(), subGenDel)
Assert.Equal(subGenDel.DelegateInvokeMethod.Parameters(0).Type, param1Type)
End Sub
<Fact>
Public Sub DelegateSymbolLocationTest()
Dim source = <compilation name="C">
<file name="a.vb">
Imports System
Delegate Sub SubDel(param1 as Integer, ByRef param2 as String)
Class C1
Delegate Function FuncDel(param1 as Integer, param2 as String) as Char
Sub Main()
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
Dim subDel As NamedTypeSymbol = CType(compilation.SourceModule.GlobalNamespace.GetTypeMembers("SubDel").Single(), NamedTypeSymbol)
Assert.Equal(subDel.Locations(0), subDel.DelegateInvokeMethod.Locations(0))
Assert.Equal(subDel.Locations(0), subDel.GetMembers(".ctor")(0).Locations(0))
Assert.Equal(subDel.Locations(0), subDel.GetMembers("Invoke")(0).Locations(0))
Assert.Equal(subDel.Locations(0), subDel.GetMembers("BeginInvoke")(0).Locations(0))
Assert.Equal(subDel.Locations(0), subDel.GetMembers("EndInvoke")(0).Locations(0))
End Sub
<Fact>
Public Sub MetadataDelegateField()
Dim source = <compilation name="C">
<file name="a.vb">
Imports System
Class C1
Public Field As System.Func(Of Integer)
Sub Main()
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
Dim fieldSym = CType(compilation.SourceModule.GlobalNamespace.GetTypeMembers("C1").Single().GetMembers("Field").Single(), SourceFieldSymbol)
Dim funcDel As NamedTypeSymbol = CType(fieldSym.Type, NamedTypeSymbol)
Assert.Equal(TypeKind.Delegate, funcDel.TypeKind)
Dim invoke = funcDel.DelegateInvokeMethod
Assert.Equal(MethodKind.DelegateInvoke, invoke.MethodKind)
Dim ctor = CType(funcDel.GetMembers(".ctor")(0), MethodSymbol)
Assert.Equal(2, ctor.Parameters.Length)
Assert.Equal(compilation.GetSpecialType(SpecialType.System_Object), ctor.Parameters(0).Type)
Assert.Equal(compilation.GetSpecialType(SpecialType.System_IntPtr), ctor.Parameters(1).Type)
End Sub
<Fact>
Public Sub DelegatesEverywhere()
Dim source = <compilation name="C">
<file name="a.vb">
Imports System
Delegate Sub del1(param As Integer)
Delegate Function del2(param As Integer) As Integer
Class C1
Delegate Sub del3(param As Integer)
Delegate Function del4(param As Integer) As Integer
Public Field As del3
Private del9 As del3
Function Func1(param As del3) As del3
Dim myDel As del3 = param
mydel = param
Field = myDel
myDel = Field
Dim d1 As System.Delegate = Field
Dim m1 As MulticastDelegate = del9
Dim o As Object = param
o = d1
param = myDel
Return param
End Function
End Class
Interface I1
Delegate Sub del5(param As Integer)
Delegate Function del6(param As Integer) As Integer
End Interface
Structure S1
Delegate Sub del7(param As Integer)
Delegate Function del8(param As Integer) As Integer
End Structure
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub DuplicateParamNamesInDelegateDeclaration()
' yes strange, but allowed, according to 9.2.5 of the VB Language Spec
Dim source = <compilation name="C">
<file name="a.vb">
Imports System
Delegate Sub del1(p As Integer, p as String, p as Object, p as String)
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompilationUtils.AssertNoErrors(compilation)
Dim del As NamedTypeSymbol = CType(compilation.SourceModule.GlobalNamespace.GetTypeMembers("del1").Single(), NamedTypeSymbol)
Assert.Equal(del.DelegateInvokeMethod.Parameters.Length, 4)
For Each param In del.DelegateInvokeMethod.Parameters
Assert.Equal("p", param.Name)
Next
End Sub
' Test module method, shared method, instance method, constructor, property with valid args for both function and sub delegate
<Fact>
Public Sub ValidDelegateAddressOfTest()
Dim source = <compilation name="C">
<file name="a.vb">
Imports System
Delegate Sub SubDel(p As String)
Delegate function FuncDel(p As String) as Integer
Module M1
Public Sub ds1(p As String)
End Sub
Public Function df1(p As String) As Integer
End Function
End Module
Class C1
Public Sub ds2(p As String)
End Sub
Public Function df2(p As String) As Integer
End Function
Public Shared Sub ds3(p As String)
End Sub
Public Shared Function df3(p As String) As Integer
End Function
End Class
Class c2
Public Sub AssignDelegates()
Dim ci As New C1()
Dim ds As SubDel
ds = AddressOf M1.ds1
ds = AddressOf ci.ds2
ds = AddressOf C1.ds3
End Sub
End Class
Module Program
Sub Main(args As String())
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<WorkItem(540948, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540948")>
<Fact>
Public Sub AddressOfGenericMethod()
Dim source = <compilation name="C">
<file name="a.vb">
Imports System
Module C
Sub Main()
Dim a As Action(Of Integer) = AddressOf Goo
End Sub
Sub Goo(Of T)(x As T)
End Sub
End Module
</file>
</compilation>
Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Off))
CompilationUtils.AssertNoErrors(comp1)
Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertNoErrors(comp2)
End Sub
<WorkItem(541002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541002")>
<Fact>
Public Sub TypeParameterCannotConflictWithDelegateMethod()
Dim source = <compilation name="F">
<file name="F.vb">
Delegate Sub F1(Of Invoke)
Class C1
Delegate Sub F2(Of Invoke)
End Class
</file>
</compilation>
Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Off))
CompilationUtils.AssertNoErrors(comp1)
Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertNoErrors(comp2)
End Sub
<WorkItem(541004, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541004")>
<Fact>
Public Sub DelegateParameterCanBeNamedInvoke()
Dim source = <compilation name="D">
<file name="D.vb">
Delegate Function D1(Invoke As Boolean) As Boolean
Class C1
Delegate Function D2(Invoke As Boolean) As Boolean
End Class
</file>
</compilation>
Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Off))
CompilationUtils.AssertNoErrors(comp1)
Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertNoErrors(comp2)
End Sub
End Class
End Namespace
|
physhi/roslyn
|
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/DelegateTests.vb
|
Visual Basic
|
apache-2.0
| 21,182
|
' 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.AddImports
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module CompilationUnitSyntaxExtensions
<Extension>
Public Function CanAddImportsStatements(contextNode As SyntaxNode, cancellationToken As CancellationToken) As Boolean
Dim root = contextNode.GetAncestorOrThis(Of CompilationUnitSyntax)()
If root.Imports.Count > 0 Then
Dim start = root.Imports.First.SpanStart
Dim [end] = root.Imports.Last.Span.End
Return Not contextNode.SyntaxTree.OverlapsHiddenPosition(TextSpan.FromBounds(start, [end]), cancellationToken)
Else
Dim start = 0
Dim [end] = If(root.Members.Count > 0,
root.Members.First.GetFirstToken().Span.End,
root.Span.End)
Return Not contextNode.SyntaxTree.OverlapsHiddenPosition(TextSpan.FromBounds(start, [end]), cancellationToken)
End If
End Function
<Extension()>
Public Function AddImportsStatement(root As CompilationUnitSyntax,
importStatement As ImportsStatementSyntax,
placeSystemNamespaceFirst As Boolean,
ParamArray annotations As SyntaxAnnotation()) As CompilationUnitSyntax
Return root.AddImportsStatements({importStatement}, placeSystemNamespaceFirst, annotations)
End Function
<Extension()>
Public Function AddImportsStatements(root As CompilationUnitSyntax,
importsStatements As IList(Of ImportsStatementSyntax),
placeSystemNamespaceFirst As Boolean,
ParamArray annotations As SyntaxAnnotation()) As CompilationUnitSyntax
If importsStatements.Count = 0 Then
Return root
End If
Dim systemFirstInstance = ImportsStatementComparer.SystemFirstInstance
Dim normalInstance = ImportsStatementComparer.NormalInstance
Dim comparers = If(placeSystemNamespaceFirst,
(systemFirstInstance, normalInstance),
(normalInstance, systemFirstInstance))
Dim [imports] = AddImportsStatements(root, importsStatements)
' First, see if the imports were sorted according to the user's preference. If so,
' keep the same sorting after we add the import. However, if the imports weren't sorted
' according to their preference, then see if they're sorted in the other way. If so
' preserve that sorting as well. That way if the user is working with a file that
' was written on a machine with a different default, the imports will stay in a
' reasonable order.
If root.Imports.IsSorted(comparers.Item1) Then
[imports].Sort(comparers.Item1)
ElseIf root.Imports.IsSorted(comparers.Item2) Then
[imports].Sort(comparers.Item2)
End If
root = AddImportHelpers.MoveTrivia(
VisualBasicSyntaxFactsService.Instance, root, root.Imports, [imports])
Return root.WithImports(
[imports].Select(Function(u) u.WithAdditionalAnnotations(annotations)).ToSyntaxList())
End Function
Private Function IsDocCommentOrElastic(t As SyntaxTrivia) As Boolean
Return t.Kind() = SyntaxKind.DocumentationCommentTrivia OrElse t.IsElastic()
End Function
Private Function AddImportsStatements(root As CompilationUnitSyntax, importsStatements As IList(Of ImportsStatementSyntax)) As List(Of ImportsStatementSyntax)
' We need to try and not place the using inside of a directive if possible.
Dim [imports] = New List(Of ImportsStatementSyntax)
Dim importsLength = root.Imports.Count
Dim endOfList = importsLength - 1
Dim startOfLastDirective = -1
Dim endOfLastDirective = -1
For index = 0 To endOfList
If root.Imports(index).GetLeadingTrivia().Any(Function(trivia) trivia.IsKind(SyntaxKind.IfDirectiveTrivia, SyntaxKind.ElseIfDirectiveTrivia, SyntaxKind.ElseDirectiveTrivia)) Then
startOfLastDirective = index
End If
If root.Imports(index).GetLeadingTrivia().Any(Function(trivia) trivia.IsKind(SyntaxKind.EndIfDirectiveTrivia)) Then
endOfLastDirective = index
End If
Next
' if the entire using Is in a directive Or there Is a using list at the end outside of the directive add the using at the end,
' else place it before the last directive.
[imports].AddRange(root.Imports)
If (startOfLastDirective = 0 AndAlso (endOfLastDirective = endOfList OrElse endOfLastDirective = -1)) OrElse
(startOfLastDirective = -1 AndAlso endOfLastDirective = -1) OrElse
(endOfLastDirective <> endOfList AndAlso endOfLastDirective <> -1) Then
[imports].AddRange(importsStatements)
Else
[imports].InsertRange(startOfLastDirective, importsStatements)
End If
Return [imports]
End Function
End Module
End Namespace
|
mmitche/roslyn
|
src/Workspaces/VisualBasic/Portable/Extensions/CompilationUnitSyntaxExtensions.vb
|
Visual Basic
|
apache-2.0
| 5,926
|
' 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.VisualBasic.KeywordHighlighting
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting
Public Class PropertyBlockHighlighterTests
Inherits AbstractVisualBasicKeywordHighlighterTests
Friend Overrides Function CreateHighlighter() As IHighlighter
Return New PropertyBlockHighlighter()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestPropertySample1_1() As Task
Await TestAsync(<Text>
Class C
{|Cursor:[|Public Property|]|} Goo As Integer [|Implements|] IGoo.Goo
Get
Return 1
End Get
Private Set(value As Integer)
Exit Property
End Set
[|End Property|]
End Class</Text>)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestPropertySample1_2() As Task
Await TestAsync(<Text>
Class C
[|Public Property|] Goo As Integer {|Cursor:[|Implements|]|} IGoo.Goo
Get
Return 1
End Get
Private Set(value As Integer)
Exit Property
End Set
[|End Property|]
End Class</Text>)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestPropertySample1_3() As Task
Await TestAsync(<Text>
Class C
[|Public Property|] Goo As Integer [|Implements|] IGoo.Goo
Get
Return 1
End Get
Private Set(value As Integer)
Exit Property
End Set
{|Cursor:[|End Property|]|}
End Class</Text>)
End Function
End Class
End Namespace
|
mmitche/roslyn
|
src/EditorFeatures/VisualBasicTest/KeywordHighlighting/PropertyBlockHighlighterTests.vb
|
Visual Basic
|
apache-2.0
| 1,830
|
' 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.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Module NamedTypeGenerator
Public Function AddNamedTypeTo(service As ICodeGenerationService,
destination As TypeBlockSyntax,
namedType As INamedTypeSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TypeBlockSyntax
Dim declaration = GenerateNamedTypeDeclaration(service, namedType, options)
Dim members = Insert(destination.Members, declaration, options, availableIndices)
Return FixTerminators(destination.WithMembers(members))
End Function
Public Function AddNamedTypeTo(service As ICodeGenerationService,
destination As NamespaceBlockSyntax,
namedType As INamedTypeSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As NamespaceBlockSyntax
Dim declaration = GenerateNamedTypeDeclaration(service, namedType, options)
Dim members = Insert(destination.Members, declaration, options, availableIndices)
Return destination.WithMembers(members)
End Function
Public Function AddNamedTypeTo(service As ICodeGenerationService,
destination As CompilationUnitSyntax,
namedType As INamedTypeSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As CompilationUnitSyntax
Dim declaration = GenerateNamedTypeDeclaration(service, namedType, options)
Dim members = Insert(destination.Members, declaration, options, availableIndices)
Return destination.WithMembers(members)
End Function
Public Function GenerateNamedTypeDeclaration(service As ICodeGenerationService,
namedType As INamedTypeSymbol,
options As CodeGenerationOptions) As StatementSyntax
options = If(options, CodeGenerationOptions.Default)
Dim declaration = GetDeclarationSyntaxWithoutMembers(namedType, options)
declaration = If(options.GenerateMembers AndAlso namedType.TypeKind <> TypeKind.Delegate,
service.AddMembers(declaration, GetMembers(namedType), options),
declaration)
Return AddCleanupAnnotationsTo(ConditionallyAddDocumentationCommentTo(declaration, namedType, options))
End Function
Public Function UpdateNamedTypeDeclaration(service As ICodeGenerationService,
declaration As StatementSyntax,
newMembers As IList(Of ISymbol),
options As CodeGenerationOptions,
cancellationToken As CancellationToken) As StatementSyntax
declaration = RemoveAllMembers(declaration)
declaration = service.AddMembers(declaration, newMembers, options, cancellationToken)
Return AddCleanupAnnotationsTo(declaration)
End Function
Private Function GetDeclarationSyntaxWithoutMembers(namedType As INamedTypeSymbol, options As CodeGenerationOptions) As StatementSyntax
Dim reusableDeclarationSyntax = GetReuseableSyntaxNodeForSymbol(Of StatementSyntax)(namedType, options)
If reusableDeclarationSyntax Is Nothing Then
Return GenerateNamedTypeDeclarationWorker(namedType, options)
End If
Return RemoveAllMembers(reusableDeclarationSyntax)
End Function
Private Function RemoveAllMembers(declaration As StatementSyntax) As StatementSyntax
Select Case declaration.Kind
Case SyntaxKind.EnumBlock
Return DirectCast(declaration, EnumBlockSyntax).WithMembers(Nothing)
Case SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ClassBlock
Return DirectCast(declaration, TypeBlockSyntax).WithMembers(Nothing)
Case Else
Return declaration
End Select
End Function
Private Function GenerateNamedTypeDeclarationWorker(namedType As INamedTypeSymbol, options As CodeGenerationOptions) As StatementSyntax
' TODO(cyrusn): Support enums/delegates.
If namedType.TypeKind = TypeKind.Enum Then
Return GenerateEnumDeclaration(namedType, options)
ElseIf namedType.TypeKind = TypeKind.Delegate Then
Return GenerateDelegateDeclaration(namedType, options)
End If
Dim isInterface = namedType.TypeKind = TypeKind.Interface
Dim isStruct = namedType.TypeKind = TypeKind.Struct
Dim isModule = namedType.TypeKind = TypeKind.Module
Dim blockKind =
If(isInterface, SyntaxKind.InterfaceBlock, If(isStruct, SyntaxKind.StructureBlock, If(isModule, SyntaxKind.ModuleBlock, SyntaxKind.ClassBlock)))
Dim statementKind =
If(isInterface, SyntaxKind.InterfaceStatement, If(isStruct, SyntaxKind.StructureStatement, If(isModule, SyntaxKind.ModuleStatement, SyntaxKind.ClassStatement)))
Dim keywordKind =
If(isInterface, SyntaxKind.InterfaceKeyword, If(isStruct, SyntaxKind.StructureKeyword, If(isModule, SyntaxKind.ModuleKeyword, SyntaxKind.ClassKeyword)))
Dim endStatement =
If(isInterface, SyntaxFactory.EndInterfaceStatement(), If(isStruct, SyntaxFactory.EndStructureStatement(), If(isModule, SyntaxFactory.EndModuleStatement, SyntaxFactory.EndClassStatement)))
Dim typeDeclaration =
SyntaxFactory.TypeBlock(
blockKind,
SyntaxFactory.TypeStatement(
statementKind,
attributes:=GenerateAttributes(namedType, options),
modifiers:=GenerateModifiers(namedType),
keyword:=SyntaxFactory.Token(keywordKind),
identifier:=namedType.Name.ToIdentifierToken(),
typeParameterList:=GenerateTypeParameterList(namedType)),
[inherits]:=GenerateInheritsStatements(namedType),
implements:=GenerateImplementsStatements(namedType),
end:=endStatement)
Return typeDeclaration
End Function
Private Function GenerateDelegateDeclaration(namedType As INamedTypeSymbol, options As CodeGenerationOptions) As StatementSyntax
Dim invokeMethod = namedType.DelegateInvokeMethod
Return SyntaxFactory.DelegateStatement(
kind:=If(invokeMethod.ReturnsVoid, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement),
attributeLists:=GenerateAttributes(namedType, options),
modifiers:=GenerateModifiers(namedType),
subOrFunctionKeyword:=If(invokeMethod.ReturnsVoid, SyntaxFactory.Token(SyntaxKind.SubKeyword), SyntaxFactory.Token(SyntaxKind.FunctionKeyword)),
identifier:=namedType.Name.ToIdentifierToken(),
typeParameterList:=GenerateTypeParameterList(namedType),
parameterList:=ParameterGenerator.GenerateParameterList(invokeMethod.Parameters, options),
asClause:=If(invokeMethod.ReturnsVoid, Nothing,
SyntaxFactory.SimpleAsClause(invokeMethod.ReturnType.GenerateTypeSyntax())))
End Function
Private Function GenerateEnumDeclaration(namedType As INamedTypeSymbol, options As CodeGenerationOptions) As StatementSyntax
Dim underlyingType =
If(namedType.EnumUnderlyingType IsNot Nothing AndAlso namedType.EnumUnderlyingType.SpecialType <> SpecialType.System_Int32,
SyntaxFactory.SimpleAsClause(namedType.EnumUnderlyingType.GenerateTypeSyntax()),
Nothing)
Return SyntaxFactory.EnumBlock(
SyntaxFactory.EnumStatement(
GenerateAttributes(namedType, options),
GenerateModifiers(namedType),
namedType.Name.ToIdentifierToken,
underlyingType))
End Function
Private Function GenerateAttributes(namedType As INamedTypeSymbol, options As CodeGenerationOptions) As SyntaxList(Of AttributeListSyntax)
Return AttributeGenerator.GenerateAttributeBlocks(namedType.GetAttributes(), options)
End Function
Private Function GenerateModifiers(namedType As INamedTypeSymbol) As SyntaxTokenList
Dim tokens = New List(Of SyntaxToken)
Select Case namedType.DeclaredAccessibility
Case Accessibility.Public
tokens.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
Case Accessibility.Protected
tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword))
Case Accessibility.Private
tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword))
Case Accessibility.ProtectedAndInternal, Accessibility.Internal
tokens.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword))
Case Accessibility.ProtectedOrInternal
tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword))
tokens.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword))
Case Accessibility.Internal
tokens.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword))
Case Else
End Select
If namedType.TypeKind = TypeKind.Class Then
If namedType.IsSealed Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.NotInheritableKeyword))
End If
If namedType.IsAbstract Then
tokens.Add(SyntaxFactory.Token(SyntaxKind.MustInheritKeyword))
End If
End If
Return SyntaxFactory.TokenList(tokens)
End Function
Private Function GenerateTypeParameterList(namedType As INamedTypeSymbol) As TypeParameterListSyntax
Return TypeParameterGenerator.GenerateTypeParameterList(namedType.TypeParameters)
End Function
Private Function GenerateInheritsStatements(namedType As INamedTypeSymbol) As SyntaxList(Of InheritsStatementSyntax)
If namedType.TypeKind = TypeKind.Struct OrElse
namedType.BaseType Is Nothing OrElse
namedType.BaseType.SpecialType = SpecialType.System_Object Then
Return Nothing
End If
Return SyntaxFactory.SingletonList(
SyntaxFactory.InheritsStatement(types:=SyntaxFactory.SingletonSeparatedList(namedType.BaseType.GenerateTypeSyntax())))
End Function
Private Function GenerateImplementsStatements(namedType As INamedTypeSymbol) As SyntaxList(Of ImplementsStatementSyntax)
If namedType.Interfaces.Length = 0 Then
Return Nothing
End If
Dim types = namedType.Interfaces.Select(Function(t) t.GenerateTypeSyntax())
Dim typeNodes = SyntaxFactory.SeparatedList(types)
Return SyntaxFactory.SingletonList(SyntaxFactory.ImplementsStatement(types:=typeNodes))
End Function
End Module
End Namespace
|
droyad/roslyn
|
src/Workspaces/VisualBasic/Portable/CodeGeneration/NamedTypeGenerator.vb
|
Visual Basic
|
apache-2.0
| 12,209
|
'vindu for blodtapping
Public Class BlodGivning2
Private Sub BlodGivning2_Closed(sender As Object, e As EventArgs) Handles Me.Closed
Me.Hide()
End Sub
'finner donor blod type
Private Sub BlodGivning2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim blodtype As String = find_blodtype(bruker.getPersonnr)
ComboBox1.Items.Add("O+")
ComboBox1.Items.Add("O-")
ComboBox1.Items.Add("A+")
ComboBox1.Items.Add("A-")
ComboBox1.Items.Add("B+")
ComboBox1.Items.Add("B-")
ComboBox1.Items.Add("AB+")
ComboBox1.Items.Add("AB-")
ComboBox1.Text = blodtype
End Sub
'sender info til db
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
blod = New Blod_pakke(giver_id, ComboBox1.Text, NumericUpDown1.Value, CheckHiv.Checked, CheckHepatittB.Checked, CheckHepatittC.Checked, TextBox1.Text)
blod.send()
Me.Close()
AnsattBrukerOversikt.Show()
End Sub
Private Sub btnLoggUt_Click(sender As Object, e As EventArgs) Handles btnLoggUt.Click
Main.Show()
Me.Close()
Ansatt.Close()
End Sub
'navigerings knapper
Private Sub btnKalender_Click(sender As Object, e As EventArgs) Handles btnKalender.Click
AnsattKalender.Show()
Me.Close()
End Sub
Private Sub btnBestill_Click(sender As Object, e As EventArgs) Handles btnBestill.Click
blodbank.Show()
Me.Close()
End Sub
Private Sub btnStatestikk_Click(sender As Object, e As EventArgs) Handles btnStatestikk.Click
statestikk.Show()
Me.Close()
End Sub
Private Sub btnSjekkBlod_Click(sender As Object, e As EventArgs) Handles btnSjekkBlod.Click
InnkallingBaserPaaBehov.Show()
Me.Close()
End Sub
Private Sub btnMinSide_Click(sender As Object, e As EventArgs) Handles btnMinSide.Click
Ansatt.Show()
Me.Close()
End Sub
Private Sub btnTilbake_Click(sender As Object, e As EventArgs) Handles btnTilbake.Click
BlodGivning.Show()
Me.Close()
End Sub
End Class
|
helliio/Aorta-DB
|
Aorta-DB/Aorta-DB/BlodGivning2.vb
|
Visual Basic
|
mit
| 2,150
|
Imports DotNetNuke.Data
Imports DotNetNuke.Framework
Imports System.Collections.Generic
imports System.ComponentModel
Namespace Connect.Modules.Kickstart.Entities
<DataObject(True)> _
Public Class ProjectController
#Region "Private Methods"
Public Shared Function GetNull(ByVal Field As Object) As Object
Return DotNetNuke.Common.Utilities.Null.GetNull(Field, DBNull.Value)
End Function
#End Region
#Region "Public Methods"
Public Shared Function [Get](ByVal projectId As Integer) As ProjectInfo
Return CType(CBO.FillObject(DotNetNuke.Data.DataProvider.Instance().ExecuteReader("Connect_Kickstart_Project_Get", projectId), GetType(ProjectInfo)), ProjectInfo)
End Function
<DataObjectMethod(DataObjectMethodType.Select, True)> _
Public Shared Function [List]() As List(Of ProjectInfo)
Return CBO.FillCollection(Of ProjectInfo)(CType(DotNetNuke.Data.DataProvider.Instance().ExecuteReader("Connect_Kickstart_Project_List"), IDataReader))
End Function
<DataObjectMethod(DataObjectMethodType.Select, True)> _
Public Shared Function [PublicProjectCount](ByVal ModuleId As Integer) As Integer
Return DotNetNuke.Data.DataProvider.Instance().ExecuteScalar(Of Integer)("Connect_Kickstart_Project_GetPublicProjectCount", ModuleId)
End Function
<DataObjectMethod(DataObjectMethodType.Select, True)> _
Public Shared Function [PublicList](ByVal ModuleId As Integer, ByVal SortColumn As String, ByVal PageNo As Integer, RecordsPerPage As Integer, IsVisible As Integer, IsDeleted As Integer, CreatedBy As Integer, LeadBy As Integer) As List(Of ProjectInfo)
Return CBO.FillCollection(Of ProjectInfo)(CType(DotNetNuke.Data.DataProvider.Instance().ExecuteReader("Connect_Kickstart_Project_GetPageByModules", SortColumn, PageNo, RecordsPerPage, ModuleId, GetNull(IsVisible), GetNull(IsDeleted), GetNull(CreatedBy), GetNull(LeadBy)), IDataReader))
End Function
<DataObjectMethod(DataObjectMethodType.Insert, True)> _
Public Shared Function Add(ByVal objProjectInfo As ProjectInfo) As Integer
Return DotNetNuke.Data.DataProvider.Instance().ExecuteScalar(Of Integer)("Connect_Kickstart_Project_Add", objProjectInfo.ModuleId, objProjectInfo.ContentItemId, objProjectInfo.Status, objProjectInfo.Subject, objProjectInfo.Summary, objProjectInfo.Content, GetNull(objProjectInfo.ProjectUrl), GetNull(objProjectInfo.ProjectPlatform), GetNull(objProjectInfo.PlatformRssUrl), GetNull(objProjectInfo.DateScheduled), GetNull(objProjectInfo.DateDelivered), objProjectInfo.DateCreated, GetNull(objProjectInfo.DateLocked), GetNull(objProjectInfo.DateDeleted), objProjectInfo.CreatedBy, GetNull(objProjectInfo.LockedBy), GetNull(objProjectInfo.DeletedBy), GetNull(objProjectInfo.LeadBy), objProjectInfo.IsVisible, objProjectInfo.IsLocked, objProjectInfo.IsDeleted, objProjectInfo.IsDelivered, objProjectInfo.Views, objProjectInfo.Comments, objProjectInfo.Votes, objProjectInfo.TeamMembers)
End Function
<DataObjectMethod(DataObjectMethodType.Update, True)> _
Public Shared Sub Update(ByVal objProjectInfo As ProjectInfo)
DotNetNuke.Data.DataProvider.Instance().ExecuteNonQuery("Connect_Kickstart_Project_Update", objProjectInfo.ProjectId, objProjectInfo.ModuleId, objProjectInfo.ContentItemId, objProjectInfo.Status, objProjectInfo.Subject, objProjectInfo.Summary, objProjectInfo.Content, GetNull(objProjectInfo.ProjectUrl), GetNull(objProjectInfo.ProjectPlatform), GetNull(objProjectInfo.PlatformRssUrl), GetNull(objProjectInfo.DateScheduled), GetNull(objProjectInfo.DateDelivered), objProjectInfo.DateCreated, GetNull(objProjectInfo.DateLocked), GetNull(objProjectInfo.DateDeleted), objProjectInfo.CreatedBy, GetNull(objProjectInfo.LockedBy), GetNull(objProjectInfo.DeletedBy), GetNull(objProjectInfo.LeadBy), objProjectInfo.IsVisible, objProjectInfo.IsLocked, objProjectInfo.IsDeleted, objProjectInfo.IsDelivered, objProjectInfo.Views, objProjectInfo.Comments, objProjectInfo.Votes, objProjectInfo.TeamMembers)
End Sub
Public Shared Sub Lock(objProject As ProjectInfo, UserId As Integer)
objProject.IsLocked = True
objProject.LockedBy = UserId
objProject.DateLocked = Date.Now
Update(objProject)
End Sub
Public Shared Sub UnLock(objProject As ProjectInfo, UserId As Integer)
objProject.IsLocked = False
objProject.LockedBy = Null.NullInteger
objProject.DateLocked = Null.NullDate
Update(objProject)
End Sub
Public Shared Sub Delete(objProject As ProjectInfo, UserId As Integer)
objProject.IsDeleted = True
objProject.DeletedBy = UserId
objProject.DateDeleted = Date.Now
Update(objProject)
End Sub
Public Shared Sub Restore(objProject As ProjectInfo, UserId As Integer)
objProject.IsDeleted = False
objProject.DeletedBy = Null.NullInteger
objProject.DateDeleted = Null.NullDate
Update(objProject)
End Sub
<DataObjectMethod(DataObjectMethodType.Delete, True)> _
Public Shared Sub HardDelete(ByVal ProjectId As Integer)
DotNetNuke.Data.DataProvider.Instance().ExecuteNonQuery("Connect_Kickstart_Project_Delete", ProjectId)
End Sub
#End Region
End Class
End Namespace
|
DNN-Connect/kickstart
|
Components/Controller/ProjectController.vb
|
Visual Basic
|
mit
| 5,500
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rTVentas_Marcas"
'-------------------------------------------------------------------------------------------'
Partial Class rTVentas_Marcas
Inherits vis2Formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1))
Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1))
Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2))
Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2))
Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3))
Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3))
Dim lcParametro4Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4))
Dim lcParametro4Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4))
Dim lcParametro5Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5))
Dim lcParametro5Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(5))
Dim lcParametro6Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(6))
Dim lcParametro6Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(6))
Dim lcParametro7Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(7))
Dim lcParametro7Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(7))
Dim lcParametro8Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(8))
Dim lcParametro8Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(8))
Dim lcParametro9Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(9))
Dim lcParametro9Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(9))
Dim lcParametro10Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(10))
Dim lcParametro10Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(10))
Dim leParametro11Desde As Integer = cusAplicacion.goReportes.paParametrosIniciales(11)
Dim lcParametro12Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(12))
Dim lcParametro12Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(12))
Dim lcParametro13Desde As String = cusAplicacion.goReportes.paParametrosIniciales(13)
Dim lcParametro14Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(14))
Dim lcParametro14Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(14))
Dim lcParametro15Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(15))
Dim lcParametro15Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(15))
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim lcSql As String
Dim loComandoSeleccionar As New StringBuilder()
If leParametro11Desde > 0 Then
lcSql = "Select Top " + leParametro11Desde.ToString
Else
lcSql = "Select "
End If
loComandoSeleccionar.AppendLine(" SELECT ")
loComandoSeleccionar.AppendLine(" Articulos.Cod_Mar AS Cod_Mar, ")
loComandoSeleccionar.AppendLine(" Marcas.Nom_Mar AS Nom_Mar, ")
loComandoSeleccionar.AppendLine(" Renglones_Facturas.Can_Art1 AS Can_Art, ")
loComandoSeleccionar.AppendLine(" Renglones_Facturas.Mon_Net AS Mon_Net, ")
loComandoSeleccionar.AppendLine(" Renglones_Facturas.Cos_Ult1 AS Mon_Cos ")
loComandoSeleccionar.AppendLine(" INTO #curTemporal ")
loComandoSeleccionar.AppendLine(" FROM Facturas ")
loComandoSeleccionar.AppendLine(" JOIN Renglones_Facturas ON Facturas.Documento = Renglones_Facturas.Documento ")
loComandoSeleccionar.AppendLine(" AND Renglones_Facturas.Cod_Art BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_Facturas.Cod_Alm BETWEEN " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" JOIN Articulos ON Renglones_Facturas.Cod_Art = Articulos.Cod_Art")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar BETWEEN " & lcParametro15Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro15Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Sec BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla BETWEEN " & lcParametro7Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro7Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip BETWEEN " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Pro BETWEEN " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" JOIN Clientes ON Facturas.Cod_Cli = Clientes.Cod_Cli ")
loComandoSeleccionar.AppendLine(" JOIN Marcas ON Articulos.Cod_Mar = Marcas.Cod_Mar")
loComandoSeleccionar.AppendLine(" WHERE Facturas.Status IN ('Confirmado','Afectado','Procesado')")
loComandoSeleccionar.AppendLine(" AND Facturas.Fec_Ini BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_Cli BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_Ven BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_Mon BETWEEN " & lcParametro10Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro10Hasta)
If lcParametro13Desde = "Igual" Then
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_Rev BETWEEN " & lcParametro12Desde)
Else
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_Rev NOT BETWEEN " & lcParametro12Desde)
End If
loComandoSeleccionar.AppendLine(" AND " & lcParametro12Hasta)
loComandoSeleccionar.AppendLine(" AND Facturas.Cod_Suc between " & lcParametro14Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro14Hasta)
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" SELECT SUM(Mon_Net) AS Tot_Net ")
loComandoSeleccionar.AppendLine(" INTO #curTemporal1 ")
loComandoSeleccionar.AppendLine(" FROM #curTemporal ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" SELECT Cod_Mar AS Cod_Mar, ")
loComandoSeleccionar.AppendLine(" Nom_Mar AS Nom_Mar, ")
loComandoSeleccionar.AppendLine(" SUM(Can_Art) AS Can_Art, ")
loComandoSeleccionar.AppendLine(" SUM(Mon_Net) AS Mon_Net, ")
loComandoSeleccionar.AppendLine(" SUM(Mon_Cos) AS Mon_Cos, ")
loComandoSeleccionar.AppendLine(" SUM(Mon_Net)-SUM(Mon_Cos) AS Mon_Gan, ")
loComandoSeleccionar.AppendLine(" (((SUM(Mon_Net)-SUM(Mon_Cos))/SUM(Mon_Net))*100) AS Por_Gan, ")
loComandoSeleccionar.AppendLine(" 12 AS Por_Ven ")
loComandoSeleccionar.AppendLine(" INTO #curTemporal2 ")
loComandoSeleccionar.AppendLine(" FROM #curTemporal ")
loComandoSeleccionar.AppendLine(" GROUP BY Cod_Mar, Nom_Mar ")
loComandoSeleccionar.AppendLine(" ORDER BY " & lcOrdenamiento)
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" Select #curTemporal2.*, #curTemporal1.Tot_Net into #curTemporal3 From #curTemporal2, #curTemporal1 ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(lcSql)
loComandoSeleccionar.AppendLine(" Cod_Mar AS Cod_Mar, ")
loComandoSeleccionar.AppendLine(" Nom_Mar AS Nom_Mar, ")
loComandoSeleccionar.AppendLine(" Can_Art AS Can_Art, ")
loComandoSeleccionar.AppendLine(" Mon_Net AS Mon_Net, ")
loComandoSeleccionar.AppendLine(" Mon_Cos AS Mon_Cos, ")
loComandoSeleccionar.AppendLine(" Mon_Gan AS Mon_Gan, ")
loComandoSeleccionar.AppendLine(" Por_Gan AS Por_Gan, ")
loComandoSeleccionar.AppendLine(" Tot_Net AS Tot_Net, ")
loComandoSeleccionar.AppendLine(" (Mon_Net/Tot_Net)*100 AS Por_Ven ")
loComandoSeleccionar.AppendLine(" FROM #curTemporal3 ")
'me.mEscribirConsulta(loComandoSeleccionar.ToString)
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes")
'-------------------------------------------------------------------------------------------------------
' Verificando si el select (tabla nº0) trae registros
'-------------------------------------------------------------------------------------------------------
If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
"No se Encontraron Registros para los Parámetros Especificados. ", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
"350px", _
"200px")
End If
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rTVentas_Marcas", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrTVentas_Marcas.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo
'-------------------------------------------------------------------------------------------'
' CMS: 28/08/09: Codigo inicial
'-------------------------------------------------------------------------------------------'
' MAT: 30/06/11: Ajuste del Select, Eliminación del filtro Status
'-------------------------------------------------------------------------------------------'
' MAT: 30/06/11: Mejora de la vista de diseño
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
rTVentas_Marcas.aspx.vb
|
Visual Basic
|
mit
| 15,926
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class JsRunner
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(JsRunner))
Me.network = New System.Windows.Forms.WebBrowser()
Me.SuspendLayout()
'
'network
'
Me.network.Dock = System.Windows.Forms.DockStyle.Fill
Me.network.Location = New System.Drawing.Point(0, 0)
Me.network.MinimumSize = New System.Drawing.Size(20, 20)
Me.network.Name = "network"
Me.network.Size = New System.Drawing.Size(716, 533)
Me.network.TabIndex = 0
'
'JsRunner
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(716, 533)
Me.Controls.Add(Me.network)
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.Name = "JsRunner"
Me.Text = "JsRunner"
Me.ResumeLayout(False)
End Sub
Friend WithEvents network As WebBrowser
End Class
|
yanivka/RazerJS
|
Source Code/JsRunner.Designer.vb
|
Visual Basic
|
mit
| 1,977
|
Imports System.Net
Public Class Form3
Public WithEvents download As New WebClient
End Class
|
MJGC-Jonathan/ComputerHelper
|
Computer Helper/Computer Helper/Form3.vb
|
Visual Basic
|
mit
| 98
|
Imports System
Imports System.IO
Imports Microsoft.Win32
Public Class MainForm
Dim ShownPro As Boolean = False
Dim NeedsDKP As Boolean = False
Dim CacheHasTinternet As Boolean = True
Function ScriptArgumentStringToType(ByVal Type As String) As Byte
If Type = "Integer" Then Return 0
If Type = "Boolean" Then Return 1
If Type = "Float" Then Return 2
If Type = "Signed Byte" Then Return 3
If Type = "Unsigned Byte" Then Return 4
If Type = "String" Then Return 5
Return 0
End Function
Sub PatchSetting(ByVal SettingName As String, ByVal SettingValue As String)
Dim DoTheAdd As Boolean = True
Dim FS As String = String.Empty
For Each SettingLine As String In File.ReadAllLines(SettingsPath)
'If SettingLine.Length = 0 Then Continue For
If SettingLine.StartsWith(SettingName + " ") Then DoTheAdd = False
FS += SettingLine + vbcrlf
Next
If DoTheAdd Then
FS += SettingName + " " + SettingValue
File.WriteAllText(SettingsPath, FS)
End If
End Sub
Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'If Not System.IO.Directory.Exists(System.IO.Path.GetTempPath + "DSGameMaker") Then
'My.Computer.FileSystem.CreateDirectory(System.IO.Path.GetTempPath + "DSGameMaker")
'End If
'Load plugins
'For Each X As String In File.ReadAllLines(AppPath + "pluginList.dat")
'PluginsToolStripMenuItem.DropDownItems.Add(X, Nothing, New EventHandler(AddressOf RunPlugin))
'PluginsToolStripMenuItem.DropDownItems.Add(X)
'PluginsToolStripMenuItem.DropDownItems.Item(PluginsToolStripMenuItem.DropDownItems.Count - 1)
'Next
'Initialize Apply Finders
With ApplyFinders
.Add("[X]")
.Add("[Y]")
.Add("[VX]")
.Add("[VY]")
.Add("[OriginalX]")
.Add("[OriginalY]")
.Add("[Screen]")
.Add("[Width]")
.Add("[Height]")
End With
'Initialize Variable Types
With VariableTypes
.Add("Integer")
.Add("Boolean")
.Add("Float")
.Add("Signed Byte")
.Add("Unsigned Byte")
.Add("String")
End With
AppPath = Application.StartupPath
If AppPath.EndsWith("\bin\Debug") Then AppPath = My.Computer.FileSystem.SpecialDirectories.ProgramFiles + "\" + Application.ProductName
AppPath += "\"
'Set Up Action icons
ActionBG = If(File.Exists(AppPath + "ActionBG.png"), PathToImage(AppPath + "ActionBG.png"), My.Resources.ActionBG)
ActionConditionalBG = If(File.Exists(AppPath + "ActionConditionalBG.png"), PathToImage(AppPath + "ActionConditionalBG.png"), My.Resources.ActionConditionalBG)
CDrive = AppPath.Substring(0, 3)
For Each ctl As Control In Me.Controls
If TypeOf ctl Is MdiClient Then ctl.BackgroundImage = My.Resources.MDIBG
Next ctl
Dim System32Path As String = Environment.GetFolderPath(Environment.SpecialFolder.System)
CacheHasTinternet = HasInternetConnection("http://invisionsoft.co.uk")
If Not File.Exists(System32Path + "\SciLexer.dll") Then
File.Copy(AppPath + "SciLexer.dll", System32Path + "\SciLexer.dll")
End If
If Not File.Exists(System32Path + "\ScintillaNet.dll") Then
File.Copy(AppPath + "ScintillaNet.dll", System32Path + "\ScintillaNet.dll")
End If
'Also into Windows... nasty, rare suggested fix
Dim WindowsPath As String = System32Path.Substring(0, System32Path.LastIndexOf("\"))
If Not File.Exists(WindowsPath + "\SciLexer.dll") Then
File.Copy(AppPath + "SciLexer.dll", WindowsPath + "\SciLexer.dll")
End If
If Not File.Exists(WindowsPath + "\ScintillaNet.dll") Then
File.Copy(AppPath + "ScintillaNet.dll", WindowsPath + "\ScintillaNet.dll")
End If
If Not File.Exists(AppPath + "devkitProUpdater-1.5.0.exe") Then
If CacheHasTinternet Then
Dim ReqURL As String = WC.DownloadString("http://dsgamemaker.com/DSGM5RegClient/murphy.php")
WC.DownloadFile(ReqURL, AppPath + "devkitProUpdater-1.5.0.exe")
End If
End If
Try
SetFileType(".dsgm", "DSGMFile")
SetFileDescription("DSGMFile", Application.ProductName + " Project")
AddAction("DSGMFile", "open", "Open")
SetExtensionCommandLine("open", "DSGMFile", """" + AppPath + Application.ProductName + ".exe"" ""%1""")
SetDefaultIcon("DSGMFile", """" + AppPath + "Icon.ico""")
Catch ex As Exception
MsgWarn("You should run " + Application.ProductName + " as an Administrator." + vbCrLf + vbCrLf + "(" + ex.Message + ")")
End Try
Dim VitalFiles As New Collection
With VitalFiles
.Add(AppPath + "Resources\NoSprite.png")
.Add(AppPath + "ActionIcons\Empty.png")
.Add(AppPath + "DefaultResources\Sprite.png")
.Add(AppPath + "DefaultResources\Background.png")
.Add(AppPath + "DefaultResources\Sound.wav")
End With
Dim VitalBuggered As Byte = 0
For Each X As String In VitalFiles
If Not File.Exists(X) Then VitalBuggered += 1
Next
If VitalBuggered = 1 Then MsgError("A vital file is missing. You must reinstall " + Application.ProductName + ".") : Exit Sub
If VitalBuggered > 1 Then MsgError("Some vital files are missing. You must reinstall " + Application.ProductName + ".") : Exit Sub
RebuildFontCache()
'Toolstrip Renderers
MainToolStrip.Renderer = New clsToolstripRenderer
DMainMenuStrip.Renderer = New clsMenuRenderer
ResRightClickMenu.Renderer = New clsMenuRenderer
'Resources Setup
ResourceTypes(0) = "Sprites"
MainImageList.Images.Add("SpriteIcon", My.Resources.SpriteIcon)
ResourceTypes(1) = "Objects"
MainImageList.Images.Add("ObjectIcon", My.Resources.ObjectIcon)
ResourceTypes(2) = "Backgrounds"
MainImageList.Images.Add("BackgroundIcon", My.Resources.BackgroundIcon)
ResourceTypes(3) = "Sounds"
MainImageList.Images.Add("SoundIcon", My.Resources.SoundIcon)
ResourceTypes(4) = "Rooms"
MainImageList.Images.Add("RoomIcon", My.Resources.RoomIcon)
ResourceTypes(5) = "Paths"
MainImageList.Images.Add("PathIcon", My.Resources.PathIcon)
ResourceTypes(6) = "Scripts"
MainImageList.Images.Add("ScriptIcon", My.Resources.ScriptIcon)
'Imagelist Setup
'MainImageList.Images.Add("ScriptIcon", My.Resources.ScriptIcon)
MainImageList.Images.Add("FolderIcon", My.Resources.FolderIcon)
'Resources Setup
For Resource As Byte = 0 To ResourceTypes.Length - 1
ResourcesTreeView.Nodes.Add(String.Empty, ResourceTypes(Resource), 7, 7)
Next
'Settings
If Not File.Exists(AppPath + "data.dat") Then
IO.File.Copy(AppPath + "restore.dat", AppPath + "data.dat")
End If
SettingsPath = AppPath + "data.dat"
PatchSetting("USE_EXTERNAL_SCRIPT_EDITOR", "0")
PatchSetting("RIGHT_CLICK", "1")
PatchSetting("HIDE_OLD_ACTIONS", "1")
PatchSetting("SHRINK_ACTIONS_LIST", "0")
LoadSettings()
'Fonts Setup
For Each FontFile As String In Directory.GetFiles(AppPath + "Fonts")
Dim FontName As String = FontFile.Substring(FontFile.LastIndexOf("\") + 1)
FontName = FontName.Substring(0, FontName.IndexOf("."))
FontNames.Add(FontName)
Next
'PiracyWorks()
If CacheHasTinternet Then
Dim Result As String = WC.DownloadString("http://dsgamemaker.com/DSGM5RegClient/version.php")
UpdateVersion = Convert.ToInt16(Result)
Result = WC.DownloadString("http://dsgamemaker.com/DSGM5RegClient/forcedupdate.php?id=" + IDVersion.ToString)
If Result.Length > 0 Then
MsgInfo("You are using a version of " + Application.ProductName + " that is widely pirated and therefore you must upgrade to the latest version as soon as possible." + vbCrLf + vbCrLf + "You will now be directed to the download page.")
URL("http://dsgamemaker.com/?dlchange")
End
End If
End If
'IsPro = ReallyPro()
'EquateProButton()
Text = TitleDataWorks()
End Sub
'Public Sub EquateProButton()
' If IsPro Then
' UpgradeToProButtonTool.Text = "Using Pro!"
' UpgradeToProButton.Text = "Pro Edition"
' Else
' UpgradeToProButtonTool.Text = "Upgrade to Pro"
' UpgradeToProButton.Text = "Upgrade to Pro"
' End If
'End Sub
Sub GenerateShite(ByVal DisplayResult As String)
Dim DW As Int16 = Convert.ToInt16(GetSetting("DEFAULT_ROOM_WIDTH"))
Dim DH As Int16 = Convert.ToInt16(GetSetting("DEFAULT_ROOM_HEIGHT"))
' FIX:
If DW < 256 Then DW = 256
If DW > 4096 Then DW = 4096
If DW < 192 Then DW = 192
If DH > 4096 Then DH = 4096
CurrentXDS = "ROOM Room_1," + DW.ToString + "," + DH.ToString + ",1,," + DW.ToString + "," + DH.ToString + ",1," + vbCrLf
CurrentXDS += "BOOTROOM Room_1" + vbCrLf
CurrentXDS += "SCORE 0" + vbCrLf
CurrentXDS += "LIVES 3" + vbCrLf
CurrentXDS += "HEALTH 100" + vbCrLf
CurrentXDS += "PROJECTNAME " + DisplayResult + vbCrLf
CurrentXDS += "TEXT2 " + vbCrLf
CurrentXDS += "TEXT3 " + vbCrLf
CurrentXDS += "FAT_CALL 0" + vbCrLf
CurrentXDS += "NITROFS_CALL 1" + vbCrLf
CurrentXDS += "MIDPOINT_COLLISIONS 0" + vbCrLf
CurrentXDS += "INCLUDE_WIFI_LIB 0" + vbCrLf
End Sub
Private Sub NewProject_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewProjectButton.Click, NewProjectButtonTool.Click
Shell(AppPath + ProductName + ".exe /skipauto")
End Sub
Private Sub MainForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
If BeingUsed Then
Dim WillExit As Boolean = False
Dim TheText As String = "Your new project"
If Not IsNewProject Then
TheText = "'" + CacheProjectName + "'"
End If
Dim Result As Integer = MessageBox.Show(TheText + " may have unsaved changes." + vbCrLf + vbCrLf + "Do you want to save just in case?", Application.ProductName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning)
If Result = MsgBoxResult.Yes Then : SaveButton_Click(New Object, New System.EventArgs) : WillExit = True
ElseIf Result = MsgBoxResult.No Then : e.Cancel = False : WillExit = True
ElseIf Result = MsgBoxResult.Cancel Then : e.Cancel = True
End If
Try
If WillExit Then
Directory.Delete(SessionPath, True)
Directory.Delete(CompilePath, True)
If IsNewProject Then IO.File.Delete(AppPath + "NewProjects\" + Session + ".dsgm")
End If
Catch : End Try
End If
End Sub
Public Sub InternalSave()
CleanInternalXDS()
SaveButton.Enabled = False
SaveButtonTool.Enabled = False
IO.File.WriteAllText(SessionPath + "XDS.xds", CurrentXDS)
Dim MyBAT As String = "zip.exe a save.zip Sprites Backgrounds Sounds Scripts IncludeFiles NitroFSFiles XDS.xds" + vbCrLf + "exit"
RunBatchString(MyBAT, SessionPath, True)
'File.Delete(ProjectPath)
File.Copy(SessionPath + "save.zip", ProjectPath, True)
File.Delete(SessionPath + "save.bat")
File.Delete(SessionPath + "save.zip")
SaveButton.Enabled = True
SaveButtonTool.Enabled = True
End Sub
Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveButton.Click, SaveButtonTool.Click
'If it's a new project, call Save As instead.
If IsNewProject Then
SaveAsButton_Click(New Object, New System.EventArgs)
Exit Sub
End If
InternalSave()
IsNewProject = False
End Sub
Private Sub AddSpriteButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddSpriteButton.Click, AddSpriteButtonTool.Click
Dim NewName As String = MakeResourceName("Sprite", "SPRITE")
File.Copy(AppPath + "DefaultResources\Sprite.png", SessionPath + "Sprites\0_" + NewName + ".png")
XDSAddLine("SPRITE " + NewName + ",32,32")
AddResourceNode(ResourceIDs.Sprite, NewName, "SpriteNode", True)
For Each X As Form In MdiChildren
If Not IsObject(X.Text) Then Continue For
DirectCast(X, DObject).AddSprite(NewName)
Next
RedoSprites = True
End Sub
Private Sub AddObjectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddObjectButton.Click, AddObjectButtonTool.Click
Dim ObjectCount As Byte = GetXDSFilter("OBJECT ").Length
If Not IsPro And ObjectCount >= 10 Then ProPlease("use more than 10 Objects") : Exit Sub
Dim NewName As String = MakeResourceName("Object", "OBJECT")
XDSAddLine("OBJECT " + NewName + ",None,0")
AddResourceNode(ResourceIDs.DObject, NewName, "ObjectNode", True)
For Each X As Form In MdiChildren
If Not X.Name = "Room" Then Continue For
DirectCast(X, Room).AddObjectToDropper(NewName)
Next
End Sub
Private Sub AddBackgroundButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddBackgroundButton.Click, AddBackgroundButtonTool.Click
Dim NewName As String = MakeResourceName("Background", "BACKGROUND")
File.Copy(AppPath + "DefaultResources\Background.png", SessionPath + "Backgrounds\" + NewName + ".png")
XDSAddLine("BACKGROUND " + NewName)
AddResourceNode(ResourceIDs.Background, NewName, "BackgroundNode", True)
For Each X As Form In MdiChildren
If Not IsRoom(X.Text) Then Continue For
For Each Y As Control In X.Controls
If Not Y.Name = "ObjectsTabControl" Then Continue For
For Each Z As Control In DirectCast(Y, TabControl).TabPages(0).Controls
If Z.Name = "TopScreenGroupBox" Or Z.Name = "BottomScreenGroupBox" Then
For Each I As Control In Z.Controls
If I.Name.EndsWith("BGDropper") Then
DirectCast(I, ComboBox).Items.Add(NewName)
End If
Next
End If
Next
Next
Next
BGsToRedo.Add(NewName)
End Sub
Private Sub AddSoundButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddSoundButton.Click, AddSoundButtonTool.Click
Dim NewName As String = MakeResourceName("Sound", "SOUND")
SoundType.ShowDialog()
Dim SB As Boolean = SoundType.IsSoundEffect
File.Copy(AppPath + "DefaultResources\Sound." + If(SB, "wav", "mp3"), SessionPath + "Sounds\" + NewName + "." + If(SB, "wav", "mp3"))
XDSAddLine("SOUND " + NewName + "," + If(SB, "0", "1"))
AddResourceNode(ResourceIDs.Sound, NewName, "SoundNode", True)
SoundsToRedo.Add(NewName)
End Sub
Private Sub AddRoomButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddRoomButton.Click, AddRoomButtonTool.Click
Dim RoomCount As Byte = GetXDSFilter("ROOM ").Length
If Not IsPro And RoomCount >= 5 Then ProPlease("use more than 5 Rooms") : Exit Sub
Dim NewName As String = MakeResourceName("Room", "ROOM")
Dim DW As Int16 = Convert.ToInt16(GetSetting("DEFAULT_ROOM_WIDTH"))
Dim DH As Int16 = Convert.ToInt16(GetSetting("DEFAULT_ROOM_HEIGHT"))
If DW < 256 Then DW = 256
If DW > 4096 Then DW = 4096
If DW < 192 Then DW = 192
If DH > 4096 Then DH = 4096
XDSAddLine("ROOM " + NewName + "," + DW.ToString + "," + DH.ToString + ",1,," + DW.ToString + "," + DH.ToString + ",1,")
AddResourceNode(ResourceIDs.Room, NewName, "RoomNode", True)
End Sub
Private Sub AddPathButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddPathButton.Click, AddPathButtonTool.Click
Dim NewName As String = MakeResourceName("Path", "PATH")
XDSAddLine("PATH " + NewName)
AddResourceNode(ResourceIDs.Path, NewName, "PathNode", True)
End Sub
Private Sub AddScriptButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddScriptButton.Click, AddScriptButtonTool.Click
Dim NewName As String = MakeResourceName("Script", "SCRIPT")
File.CreateText(SessionPath + "Scripts\" + NewName + ".dbas").Dispose()
XDSAddLine("SCRIPT " + NewName + ",1")
AddResourceNode(ResourceIDs.Script, NewName, "ScriptNode", True)
End Sub
Public Function OpenWarn() As Boolean
Dim TheText As String = "'" + CacheProjectName + "'"
If IsNewProject Then TheText = "your new Project"
Dim Answer As Byte = MessageBox.Show("Are you sure you want to open another Project?" + vbCrLf + vbCrLf + "You will lose any changes you have made to " + TheText + ".", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
If Answer = MsgBoxResult.Yes Then Return True Else Return False
End Function
Private Sub OpenProjectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenProjectButton.Click, OpenProjectButtonTool.Click
If BeingUsed Then : If Not OpenWarn() Then : Exit Sub : End If : End If
Dim Result As String = OpenFile(String.Empty, Application.ProductName + " Projects|*.dsgm")
If Result.Length = 0 Then Exit Sub
OpenProject(Result)
End Sub
Sub LoadLastProject(ByVal Automatic As Boolean)
'IsNewProject = False
Dim LastPath As String = GetSetting("LAST_PROJECT")
If Automatic Then
If File.Exists(LastPath) Then
OpenProject(LastPath)
End If
Exit Sub
End If
If BeingUsed Then
If LastPath = ProjectPath Then
'Same Project - Reload job
Dim Result As Byte = MessageBox.Show("Do you want to reload the current Project?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
If Result = MsgBoxResult.Yes Then CleanFresh(False) : OpenProject(ProjectPath) : Exit Sub
Else
'Loading a different project
If Not OpenWarn() Then Exit Sub
'Yes load a new file
If File.Exists(LastPath) Then
OpenProject(LastPath)
Exit Sub
Else
OpenProjectButton_Click(New Object, New System.EventArgs)
End If
End If
Else
'Fresh session
If File.Exists(LastPath) Then
OpenProject(LastPath)
Else
OpenProjectButton_Click(New Object, New System.EventArgs)
End If
End If
End Sub
Private Sub OpenLastProjectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenLastProjectButton.Click, OpenLastProjectButtonTool.Click
LoadLastProject(False)
End Sub
Private Sub SaveAsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveAsButton.Click, SaveAsButtonTool.Click
Dim Directory As String = ProjectPath
Directory = Directory.Substring(0, Directory.IndexOf("\"))
Dim Result As String = String.Empty
If IsNewProject Then
Result = SaveFile(Directory, Application.ProductName + " Projects|*.dsgm", "New Project.dsgm")
Else
Result = SaveFile(Directory, Application.ProductName + " Projects|*.dsgm", CacheProjectName + ".dsgm")
End If
If Result.Length = 0 Then Exit Sub
CleanInternalXDS()
SaveButton.Enabled = False
SaveButtonTool.Enabled = False
IO.File.WriteAllText(SessionPath + "XDS.xds", CurrentXDS)
Dim MyBAT As String = "zip.exe a save.zip Sprites Backgrounds Sounds Scripts IncludeFiles NitroFSFiles XDS.xds" + vbCrLf + "exit"
RunBatchString(MyBAT, SessionPath, True)
'File.Delete(ProjectPath)
ProjectPath = Result
File.Copy(SessionPath + "save.zip", ProjectPath, True)
File.Delete(SessionPath + "save.bat")
File.Delete(SessionPath + "save.zip")
SaveButton.Enabled = True
SaveButtonTool.Enabled = True
IsNewProject = False
Me.Text = TitleDataWorks()
End Sub
Private Sub ExitButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitButton.Click
MainForm_FormClosing(New Object, New FormClosingEventArgs(CloseReason.ApplicationExitCall, False))
End Sub
Private Sub OptionsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OptionsButton.Click, OptionsButtonTool.Click
Options.ShowDialog()
End Sub
Private Sub ResourcesTreeView_NodeMouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles ResourcesTreeView.NodeMouseDoubleClick
If Not e.Node.Parent Is Nothing Then
OpenResource(e.Node.Text, e.Node.Parent.Index, False)
End If
End Sub
Private Sub GameSettingsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GameSettingsButton.Click, GameSettingsButtonTool.Click
GameSettings.ShowDialog()
End Sub
Private Sub TestGameButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TestGameButton.Click, TestGameButtonTool.Click
If Not CompileWrapper() Then Exit Sub
Compile.HasDoneIt = False
Compile.ShowDialog()
If Compile.Success Then
NOGBAShizzle()
Else
CompileFail()
End If
End Sub
Private Sub CompileGameButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CompileGameButton.Click, CompileGameButtonTool.Click
If Not CompileWrapper() Then Exit Sub
Compile.HasDoneIt = False
Compile.ShowDialog()
If Compile.Success Then
With Compiled
.Text = CacheProjectName
.MainLabel.Text = CacheProjectName
.SubLabel.Text = "Compiled by " + Environment.UserName + " at " + GetTime()
.ShowDialog()
End With
Else
CompileFail()
End If
End Sub
Private Sub ActionEditorButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ActionEditorButton.Click
For Each X As Form In MdiChildren
If X.Text = "Action Editor" Then X.Focus() : Exit Sub
Next
'Dim ActionForm As New ActionEditor
ShowInternalForm(ActionEditor)
End Sub
Private Sub VariableManagerButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GlobalVariablesButton.Click, GlobalVariablesButtonTool.Click
GlobalVariables.ShowDialog()
End Sub
Sub ActuallyCleanUp()
For Each X As String In Directory.GetDirectories(CDrive)
If X = CompilePath.Substring(0, CompilePath.Length - 1) Then Continue For
Try
If X.StartsWith(CDrive + "DSGMTemp") Then Directory.Delete(X, True)
Catch : End Try
Next
For Each X As String In Directory.GetDirectories(AppPath + "ProjectTemp")
If X = SessionPath.Substring(0, SessionPath.Length - 1) Then Continue For
Try
Directory.Delete(X, True)
Catch : End Try
Next
'For Each X As String In Directory.GetFiles(AppPath + "NewProjects")
' If X.EndsWith(CacheProjectName + ".dsgm") Then Continue For
' File.Delete(X)
'Next
End Sub
Private Sub CleanUpButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CleanUpButton.Click
'If ProjectPath.Length > 0 Then MsgError("You have a project loaded, so temporary data may not be cleared.") : Exit Sub
MsgWarn("This will clean up all unused data created by the sessions system." + vbCrLf + vbCrLf + "Ensure you do not have other instances of the application open.")
ActuallyCleanUp()
MsgInfo("The process completed successfully.")
End Sub
Private Sub ProjectStatisticsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Statistics.ShowDialog()
End Sub
Private Sub OpenCompileTempButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenCompileTempButton.Click
System.Diagnostics.Process.Start("explorer", CompilePath)
End Sub
Private Sub OpenProjectTempButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenProjectTempButton.Click
System.Diagnostics.Process.Start("explorer", SessionPath)
End Sub
Private Sub WebsiteButton_Click() Handles WebsiteButton.Click
URL(Domain)
End Sub
Private Sub ForumButton_Click() Handles ForumButton.Click
URL(Domain + "dsgmforum")
End Sub
Private Sub EditInternalXDSButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EditInternalXDSButton.Click
If MdiChildren.Count > 0 Then MsgWarn("You must close all open windows to continue.") : Exit Sub
Dim Thing As New EditCode
With Thing
.CodeMode = CodeMode.XDS
.ImportExport = False
.ReturnableCode = CurrentXDS
.StartPosition = FormStartPosition.CenterParent
.Text = "Edit Internal XDS"
.ShowDialog()
CurrentXDS = .MainTextBox.Text
End With
End Sub
Private Sub FontViewerButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FontViewerButton.Click
For Each X As Form In MdiChildren
If X.Text = "Font Viewer" Then X.Focus() : Exit Sub
Next
'Dim ActionForm As New ActionEditor
ShowInternalForm(FontViewer)
'FontEditor.ShowDialog()
End Sub
Private Sub GlobalArraysButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GlobalArraysButton.Click, GlobalArraysButtonTool.Click
GlobalArrays.ShowDialog()
End Sub
Private Sub AboutDSGMButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutDSGMButton.Click
AboutDSGM.ShowDialog()
End Sub
Private Sub MainForm_Shown(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Shown
Dim BlankNew As Boolean = True
If UpdateVersion > IDVersion Then
DUpdate.ShowDialog()
End If
If Not Directory.Exists(CDrive + "devkitPro") Then
MsgInfo("Thank you for installing " + Application.ProductName + "." + vbCrLf + vbCrLf + "the toolchain will now be installed (to compile your games).")
RundevkitProUpdater()
End If
If Not IsPro Then
If HasInternetConnection("http://dsgamemaker.com") Then
If Not ShownPro Then Pro.ShowDialog() : ShownPro = True
End If
End If
Dim SkipAuto As Boolean = False
Dim Args As New List(Of String)
For Each X As String In My.Application.CommandLineArgs
If X = "/skipauto" Then SkipAuto = True : Continue For
Args.Add(X)
Next
If Args.Count > 1 Then
MsgWarn("You can only open one Project with " + Application.ProductName + " at once.")
ElseIf Args.Count = 1 Then
If File.Exists(Args(0)) Then OpenProject(Args(0))
BlankNew = False
Else
If Not SkipAuto Then
If Convert.ToByte(GetSetting("OPEN_LAST_PROJECT_STARTUP")) = 1 Then
LoadLastProject(True)
BlankNew = False
End If
End If
End If
If BlankNew Then
BeingUsed = True
Dim SessionName As String = String.Empty
For Looper As Byte = 0 To 10
SessionName = "NewProject" + MakeSessionName()
If Not IO.Directory.Exists(AppPath + "ProjectTemp\" + SessionName) Then Exit For
Next
FormSession(SessionName)
FormSessionFS()
IsNewProject = True
ProjectPath = AppPath + "NewProjects\" + SessionName + ".dsgm"
Me.Text = TitleDataWorks()
GenerateShite("<New Project>")
RedoAllGraphics = True
RedoSprites = True
BGsToRedo.Clear()
AddResourceNode(ResourceIDs.Room, "Room_1", "RoomNode", False)
InternalSave()
If CacheHasTinternet And GetSetting("SHOW_NEWS") = "1" Then
Newsline.Location = New Point(24, 24)
ShowInternalForm(Newsline)
End If
End If
End Sub
Private Sub UpgradeToProButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Pro.ShowDialog()
End Sub
Private Sub DeleteButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteButton.Click
DeleteResource(ActiveMdiChild.Text, ActiveMdiChild.Name)
End Sub
Private Sub CompilesToNitroFSButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CompilesToNitroFSButton.Click
RedoAllGraphics = True
RedoSprites = True
BGsToRedo.Clear()
Dim ResourceName As String = ResourcesTreeView.SelectedNode.Text
If File.Exists(CompilePath + "nitrofiles\" + ResourceName + ".c") Then
File.Delete(CompilePath + "nitrofiles\" + ResourceName + ".c")
End If
If File.Exists(CompilePath + "nitrofiles\" + ResourceName + "_Map.bin") Then
File.Delete(CompilePath + "nitrofiles\" + ResourceName + "_Map.bin")
End If
If File.Exists(CompilePath + "nitrofiles\" + ResourceName + "_Tiles.bin") Then
File.Delete(CompilePath + "nitrofiles\" + ResourceName + "_Tiles.bin")
End If
If File.Exists(CompilePath + "nitrofiles\" + ResourceName + "_Pal.bin") Then
File.Delete(CompilePath + "nitrofiles\" + ResourceName + "_Pal.bin")
End If
Dim OldLine As String = GetXDSLine(ResourcesTreeView.SelectedNode.Parent.Text.ToUpper.Substring(0, ResourcesTreeView.SelectedNode.Parent.Text.Length - 1) + " " + ResourcesTreeView.SelectedNode.Text)
Dim NewLine As String = GetXDSLine(ResourcesTreeView.SelectedNode.Parent.Text.ToUpper.Substring(0, ResourcesTreeView.SelectedNode.Parent.Text.Length - 1) + " " + ResourcesTreeView.SelectedNode.Text)
If ResourcesTreeView.SelectedNode.Parent.Text = "Sprites" Then
If iGet(NewLine, 3, ",") = "NoNitro" Then
NewLine = NewLine.Replace(",NoNitro", ",Nitro")
Else
NewLine = NewLine.Replace(",Nitro", ",NoNitro")
End If
If iGet(NewLine, 3, ",") = String.Empty Then
NewLine += ",Nitro"
End If
End If
If ResourcesTreeView.SelectedNode.Parent.Text = "Backgrounds" Then
If iGet(NewLine, 1, ",") = "NoNitro" Then
NewLine = NewLine.Replace(",NoNitro", ",Nitro")
Else
NewLine = NewLine.Replace(",Nitro", ",NoNitro")
End If
If iGet(NewLine, 1, ",") = String.Empty Then
NewLine += ",Nitro"
End If
End If
XDSChangeLine(OldLine, NewLine)
'MsgBox(ResourcesTreeView.SelectedNode.Parent.Text.ToUpper.Substring(0, ResourcesTreeView.SelectedNode.Parent.Text.Length - 1) + " " + ResourcesTreeView.SelectedNode.Text)
End Sub
Private Sub ManualButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HelpContentsButton.Click
HelpViewer.ShowDialog()
End Sub
Private Sub TutorialsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OnlineTutorialsButton.Click
URL(Domain + "dsgmforum/viewforum.php?f=6")
End Sub
Private Sub EnterSerialCodeButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
EnterSerial.ShowDialog()
End Sub
Private Sub GlobalStructuresButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GlobalStructuresButton.Click, GlobalStructuresButtonTool.Click
GlobalStructures.ShowDialog()
End Sub
Private Sub NewsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewsButton.Click
ShowInternalForm(Newsline)
End Sub
Private Sub RunDevkitProUpdaterButton(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReinstallToolchainButton.Click
RundevkitProUpdater()
End Sub
Private Sub EditMenu_DropDownOpening(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EditMenu.DropDownOpening
GoToLastFoundButton.Enabled = False
If LastResourceFound.Length > 0 Then GoToLastFoundButton.Enabled = True
Dim OuiOui As Boolean = Not (ActiveMdiChild Is Nothing)
DeleteButton.Enabled = OuiOui
DuplicateButton.Enabled = OuiOui
End Sub
Private Sub CompileChangeButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GraphicsChangeButton.Click, SoundChangeButton.Click
Select Case DirectCast(sender, ToolStripMenuItem).Name
Case "GraphicsChangeButton"
RedoAllGraphics = True
RedoSprites = True
BGsToRedo.Clear()
Case "SoundChangeButton"
BuildSoundsRedoFromFile()
End Select
End Sub
Private Sub RunNOGBAButton_Click() Handles RunNOGBAButton.Click
Diagnostics.Process.Start(FormNOGBAPath() + "\NO$GBA.exe")
End Sub
Private Sub ResRightClickMenu_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles ResRightClickMenu.Opening
Dim ToWorkFrom As TreeNode
Try
ToWorkFrom = ResourcesTreeView.SelectedNode.Parent
DeleteResourceRightClickButton.Enabled = True
OpenResourceRightClickButton.Enabled = True
DuplicateResourceRightClickButton.Enabled = True
CompilesToNitroFSButton.Enabled = True
CompilesToNitroFSButton.Image = DS_Game_Maker.My.Resources.Resources.DeleteIcon
If ToWorkFrom.Text = String.Empty Then Exit Try
Catch ex As Exception
ToWorkFrom = ResourcesTreeView.SelectedNode
DeleteResourceRightClickButton.Enabled = False
OpenResourceRightClickButton.Enabled = False
DuplicateResourceRightClickButton.Enabled = False
CompilesToNitroFSButton.Enabled = False
CompilesToNitroFSButton.Image = DS_Game_Maker.My.Resources.Resources.DeleteIcon
End Try
With AddResourceRightClickButton
.Image = My.Resources.PlusIcon
Select Case ToWorkFrom.Text.Substring(0, ToWorkFrom.Text.Length - 1)
Case "Sprite" : .Image = AddSpriteButton.Image
Case "Background" : .Image = AddBackgroundButton.Image
Case "Script" : .Image = AddScriptButton.Image
Case "Room" : .Image = AddRoomButton.Image
Case "Path" : .Image = AddPathButton.Image
Case "Object" : .Image = AddObjectButton.Image
Case "Sound" : .Image = AddSoundButton.Image
End Select
.Text = "Add " + ToWorkFrom.Text.Substring(0, ToWorkFrom.Text.Length - 1)
End With
With CompilesToNitroFSButton
If Not ToWorkFrom.Text.Substring(0, ToWorkFrom.Text.Length - 1) = "Sprite" And Not ToWorkFrom.Text.Substring(0, ToWorkFrom.Text.Length - 1) = "Background" Then
.Enabled = False
If Not ToWorkFrom.Text.Substring(0, ToWorkFrom.Text.Length - 1) = "Sound" Then
.Image = DS_Game_Maker.My.Resources.Resources.DeleteIcon
Else
.Image = DS_Game_Maker.My.Resources.Resources.AcceptIcon
End If
Else
If ToWorkFrom.Text.Substring(0, ToWorkFrom.Text.Length - 1) = "Sprite" Then
If iGet(GetXDSLine("SPRITE " + ResourcesTreeView.SelectedNode.Text), 3, ",") = "Nitro" Then
.Image = DS_Game_Maker.My.Resources.Resources.AcceptIcon
End If
End If
If ToWorkFrom.Text.Substring(0, ToWorkFrom.Text.Length - 1) = "Background" Then
If iGet(GetXDSLine("BACKGROUND " + ResourcesTreeView.SelectedNode.Text), 1, ",") = "Nitro" Then
.Image = DS_Game_Maker.My.Resources.Resources.AcceptIcon
End If
End If
End If
End With
End Sub
Private Sub ResourcesTreeView_NodeMouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles ResourcesTreeView.NodeMouseClick
ResourcesTreeView.SelectedNode = e.Node
End Sub
Private Sub DeleteResourceRightClickButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteResourceRightClickButton.Click
Dim Type As String = ResourcesTreeView.SelectedNode.Parent.Text.Substring(0, ResourcesTreeView.SelectedNode.Parent.Text.Length - 1)
If Type = "Object" Then Type = "DObject"
Type = Type.Replace(" ", String.Empty)
DeleteResource(ResourcesTreeView.SelectedNode.Text, Type)
End Sub
Private Sub OpenResourceRightClickButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenResourceRightClickButton.Click
OpenResource(ResourcesTreeView.SelectedNode.Text, ResourcesTreeView.SelectedNode.Parent.Index, False)
End Sub
Private Sub AddResourceRightClickButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddResourceRightClickButton.Click
Dim TheText As String = AddResourceRightClickButton.Text.Substring(4)
Select Case TheText
Case "Sprite" : AddSpriteButton_Click(New Object, New System.EventArgs)
Case "Background" : AddBackgroundButton_Click(New Object, New System.EventArgs)
Case "Object" : AddObjectButton_Click(New Object, New System.EventArgs)
Case "Sound" : AddSoundButton_Click(New Object, New System.EventArgs)
Case "Room" : AddRoomButton_Click(New Object, New System.EventArgs)
Case "Path" : AddPathButton_Click(New Object, New System.EventArgs)
Case "Script" : AddScriptButton_Click(New Object, New System.EventArgs)
End Select
End Sub
Private Sub DuplicateResourceRightClickButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DuplicateResourceRightClickButton.Click
Dim TheName As String = ResourcesTreeView.SelectedNode.Text
CopyResource(TheName, GenerateDuplicateResourceName(TheName), ResourcesTreeView.SelectedNode.Parent.Index)
End Sub
Private Sub FindResourceButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FindResourceButton.Click
Dim Result As String = GetInput("Which resource are you looking for?", LastResourceFound, ValidateLevel.None)
FindResource(Result)
End Sub
Private Sub GoToLastFoundButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GoToLastFoundButton.Click
FindResource(LastResourceFound)
End Sub
Private Sub FindInScriptsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FindInScriptsButton.Click
Dim Result As String = GetInput("Search term:", LastScriptTermFound, ValidateLevel.None)
Dim Shower As New FoundInScripts
With Shower
.Term = Result
.Text = "Searching Scripts for '" + Result + "'"
End With
ShowInternalForm(Shower)
End Sub
Private Sub DuplicateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DuplicateButton.Click
If ActiveMdiChild Is Nothing Then Exit Sub
Dim TheName As String = ActiveMdiChild.Text
Dim ResT As Byte = 0
Select Case ActiveMdiChild.Name
Case "Sprite"
ResT = ResourceIDs.Sprite
Case "Background"
ResT = ResourceIDs.Background
Case "DObject"
ResT = ResourceIDs.DObject
Case "Room"
ResT = ResourceIDs.Room
Case "Path"
ResT = ResourceIDs.Path
Case "Script"
ResT = ResourceIDs.Script
Case "Sound"
ResT = ResourceIDs.Sound
End Select
CopyResource(TheName, GenerateDuplicateResourceName(TheName), ResT)
End Sub
'Private Sub InstallPluginButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InstallPluginButton.Click, InstallPluginToolStripMenuItem.Click
' Dim FilePath As String = OpenFile(String.Empty, "DS Game Maker Plugins|*.dsgmp")
' If FilePath.Length = 0 Then Exit Sub
'Dim P As String = AppPath + "PluginInstall\"
' Directory.CreateDirectory(P)
' File.Copy(FilePath, P + "Plugin.zip")
'Dim MyBAT As String = "zip.exe x Plugin.zip -y" + vbCrLf + "exit"
' RunBatchString(MyBAT, P, True)
'Dim PName As String = String.Empty
'Dim PAuthor As String = String.Empty
'Dim PLink As String = String.Empty
'Dim Files As New List(Of String)
'Dim MakeLines As New List(Of String)
' For Each X As String In File.ReadAllLines(P + "data.txt")
' If X.StartsWith("NAME ") Then PName = X.Substring(5)
' If X.StartsWith("AUTHOR ") Then PAuthor = X.Substring(7)
' If X.StartsWith("LINK ") Then PLink = X.Substring(5)
' Next
' File.Copy(P + "Executable.exe", AppPath + "Plugins\" + PName + ".exe")
' File.WriteAllText(AppPath + "pluginList.dat", File.ReadAllText(AppPath + "pluginList.dat") + PName + vbCrLf)
' My.Computer.FileSystem.DeleteDirectory(P, FileIO.DeleteDirectoryOption.DeleteAllContents)
' End Sub
'Private Sub RunPlugin(ByVal sender As Object, ByVal e As System.EventArgs)
'DirectCast(sender, ToolStripMenuItem).Name
' Dim Plugins As Integer
'Dim SelectedPlugin As Integer
' For Each X As String In File.ReadAllLines(AppPath + "pluginList.dat")
' Plugins += 1
' Next
'If PluginsToolStripMenuItem.DropDownItems.Item(3).Pressed Then
' MsgBox("fdm")
'End If
'MsgBox(PluginsToolStripMenuItem.DropDownItems.Item(3).Text)
'For LoopVar As Integer = 2 To Plugins + 2
' If PluginsToolStripMenuItem.DropDownItems.Item(LoopVar).Pressed Then
' SelectedPlugin = LoopVar
' End If
' Next
' MsgInfo("Running Plugin " + PluginsToolStripMenuItem.DropDownItems.Item(SelectedPlugin).Text)
'End Sub
End Class
|
cfwprpht/dsgamemaker
|
MainForm.vb
|
Visual Basic
|
mit
| 44,956
|
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("VBCreateFolderPath")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("VBCreateFolderPath")>
<Assembly: AssemblyCopyright("Copyright © 2013")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("6f73de4d-4370-4be8-8332-2bb4cabb99a2")>
' 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")>
|
age-killer/Electronic-invoice-document-processing
|
MailSort_CSHARP/packages/Independentsoft.Exchange.3.0.400/Tutorial/VBCreateFolderPath/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,154
|
Imports System.Net
Imports System.IO
' Common types and variables for the program
Public Module Globals
Public CancelImport As Boolean = False
Public CancelDownload As Boolean = False
Public frmErrorText As String = ""
Public Lock As New Object
Public AllSettings As New ProgramSettings
Public UserApplicationSettings As ApplicationSettings
Public TestForSDEChanges As Boolean
Public RetryCall As Boolean = False
''' <summary>
''' Displays error message from Try/Catch Exceptions
''' </summary>
''' <param name="ex">Exepction variable for displaying exception text</param>
Public Sub ShowErrorMessage(ex As Exception)
Dim msg As String = ex.Message
If Not CancelImport Then
If Not IsNothing(ex.InnerException) Then
msg &= vbCrLf & vbCrLf & "Inner Exception: " & ex.InnerException.ToString
End If
Call MsgBox(msg, vbExclamation, Application.ProductName)
End If
End Sub
''' <summary>
''' Writes a sent message to the Errors.log file
''' </summary>
''' <param name="ErrorMsg">Message to write to log file</param>
Public Sub WriteMsgToErrorLog(ByVal ErrorMsg As String)
Call OutputToFile("Errors.log", ErrorMsg)
End Sub
''' <summary>
''' Writes a sent message to the OutputLog.log file
''' </summary>
''' <param name="OutputMessage">Message to write to log file</param>
Public Sub OutputMsgtoLog(ByVal OutputMessage As String)
Call OutputToFile("OutputLog.log", OutputMessage)
End Sub
''' <summary>
''' Outputs sent output text to the file path
''' </summary>
''' <param name="FilePath">Path of outputfile with name</param>
''' <param name="OutputText">Text to output to file</param>
Private Sub OutputToFile(FilePath As String, OutputText As String)
Dim AllText() As String
If Not IO.File.Exists(FilePath) Then
Dim sw As IO.StreamWriter = IO.File.CreateText(FilePath)
sw.Close()
End If
' This is an easier way to get all of the strings in the file.
AllText = IO.File.ReadAllLines(FilePath)
' This will append the string to the end of the file.
My.Computer.FileSystem.WriteAllText(FilePath, CStr(Now) & ", " & OutputText & Environment.NewLine, True)
End Sub
' Initializes the main form grid
Private Delegate Sub InitRow(ByVal Position As Integer)
Public Sub InitGridRow(ByVal Postion As Integer)
Dim f1 As frmMain = DirectCast(My.Application.OpenForms.Item("frmMain"), frmMain)
f1.Invoke(New InitRow(AddressOf f1.InitGridRow), Postion)
Application.DoEvents()
End Sub
' Updates the main form grid
Private Delegate Sub UpdateRowProgress(ByVal Position As Integer, ByVal Count As Integer, ByVal TotalRecords As Integer)
Public Sub UpdateGridRowProgress(ByVal Postion As Integer, ByVal Count As Integer, ByVal TotalRecords As Integer)
Dim f1 As frmMain = DirectCast(My.Application.OpenForms.Item("frmMain"), frmMain)
f1.Invoke(New UpdateRowProgress(AddressOf f1.UpdateGridRowProgress), Postion, Count, TotalRecords)
Application.DoEvents()
End Sub
''' <summary>
''' Downloads the sent file from server and saves it to the root directory as the sent file name
''' </summary>
''' <param name="DownloadURL">URL to download the file</param>
''' <param name="FileName">File name of downloaded file</param>
''' <returns>File Name of where the downloaded file was saved.</returns>
Public Function DownloadFileFromServer(ByVal DownloadURL As String, ByVal FileName As String, Optional PGBar As ProgressBar = Nothing) As String
'Creating the request and getting the response
Dim Response As HttpWebResponse
Dim Request As HttpWebRequest
' File sizes for progress bar
Dim FileSize As Double
' For reading in chunks of data
Dim readBytes(4095) As Byte
' Create directory if it doesn't exist already
If Not Directory.Exists(Path.GetDirectoryName(FileName)) Then
Directory.CreateDirectory(Path.GetDirectoryName(FileName))
End If
Dim writeStream As New FileStream(FileName, FileMode.Create)
Dim bytesread As Integer
'Replacement for Stream.Position (webResponse stream doesn't support seek)
Dim nRead As Long
If Not IsNothing(PGBar) Then
PGBar.Minimum = 0
PGBar.Value = 0
PGBar.Visible = True
Application.DoEvents()
End If
Try 'Checks if the file exist
Request = DirectCast(HttpWebRequest.Create(DownloadURL), HttpWebRequest)
Request.Proxy = Nothing
Request.Credentials = CredentialCache.DefaultCredentials ' Added 9/27 to attempt to fix error: (407) Proxy Authentication Required.
Request.Timeout = 50000
Response = CType(Request.GetResponse, HttpWebResponse)
Catch ex As Exception
' Set as empty and return
writeStream.Close()
Return ""
End Try
' Get size
FileSize = Response.ContentLength()
' Loop through and get the file in chunks, save out
Do
Application.DoEvents()
If CancelDownload Then 'If user abort download
Exit Do
End If
bytesread = Response.GetResponseStream.Read(readBytes, 0, 4096)
' No more bytes to read
If bytesread = 0 Then Exit Do
nRead = nRead + bytesread
' Update progress
If Not IsNothing(PGBar) Then
PGBar.Value = (nRead * 100) / FileSize
End If
writeStream.Write(readBytes, 0, bytesread)
Loop
'Close the streams
Response.GetResponseStream.Close()
writeStream.Close()
If Not IsNothing(PGBar) Then
PGBar.Value = 0
PGBar.Visible = False
End If
Return FileName
End Function
' Finalizes the main form grid
Private Delegate Sub FinalizeRow(ByVal Position As Integer)
Public Sub FinalizeGridRow(ByVal Postion As Integer)
Dim f1 As frmMain = DirectCast(My.Application.OpenForms.Item("frmMain"), frmMain)
f1.Invoke(New FinalizeRow(AddressOf f1.FinalizeGridRow), Postion)
Application.DoEvents()
End Sub
' Initializes the progressbar on the main form
Private Delegate Sub InitMainProgress(MaxCount As Long, UpdateText As String)
Public Sub InitalizeMainProgressBar(MaxCount As Long, UpdateText As String)
Dim f1 As frmMain = DirectCast(My.Application.OpenForms.Item("frmMain"), frmMain)
f1.Invoke(New InitMainProgress(AddressOf f1.InitalizeProgress), MaxCount, UpdateText)
Application.DoEvents()
End Sub
' Clears the progress bar and label on the main form
Private Delegate Sub ClearMainProgress()
Public Sub ClearMainProgressBar()
Dim f1 As frmMain = DirectCast(My.Application.OpenForms.Item("frmMain"), frmMain)
f1.Invoke(New ClearMainProgress(AddressOf f1.ClearProgress))
Application.DoEvents()
End Sub
' Updates the main progress bar and label on the main form
Private Delegate Sub UpdateMainProgress(ByVal Count As Long, ByVal UpdateText As String)
Public Sub UpdateMainProgressBar(Count As Long, UpdateText As String)
Dim f1 As frmMain = DirectCast(My.Application.OpenForms.Item("frmMain"), frmMain)
f1.Invoke(New UpdateMainProgress(AddressOf f1.UpdateProgress), Count, UpdateText)
Application.DoEvents()
End Sub
End Module
|
EVEIPH/EVE-SDE-Database-Builder
|
EVE SDE Database Builder/Globals.vb
|
Visual Basic
|
mit
| 7,727
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.36213
'
' 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("DotGitTests.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
|
robnasby/DotGit
|
tests/DotGitTests/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,720
|
Imports System.Web
Imports System.Runtime.Serialization.Json
''' <summary>
''' Microsoft Translator APIを使用した自動翻訳でAccessTokenを取得
''' </summary>
''' <remarks>
''' 参考
''' https://msdn.microsoft.com/en-us/library/ff512421
''' C#からVB.NETへ移植してます。
''' </remarks>
Public Class AdmAuthentication
''' <summary>
''' AccessUri
''' </summary>
Public Const DatamarketAccessUri As String = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"
''' <summary>
''' クライアントID
''' </summary>
Private ClientId As String
''' <summary>
''' 顧客の秘密
''' </summary>
Private CientSecret As String
''' <summary>
''' RequestURI
''' </summary>
Private Request As String
''' <summary>
''' インスタンスを生成
''' </summary>
''' <param name="clientId"></param>
''' <param name="clientSecret"></param>
Public Sub New(clientId As String, clientSecret As String)
Me.ClientId = clientId
Me.CientSecret = clientSecret
Me.Request = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com",
HttpUtility.UrlEncode(clientId), HttpUtility.UrlEncode(clientSecret))
End Sub
''' <summary>
''' GetAccessTokenを取得
''' </summary>
''' <returns></returns>
Public Function GetAccessToken() As AdmAccessToken
Return Me.HttpPost(DatamarketAccessUri, Me.Request)
End Function
''' <summary>
''' HttpPostでAccessTokenを取得する
''' </summary>
''' <param name="datamarketAccessUri"></param>
''' <param name="requestDetails"></param>
''' <returns></returns>
Private Function HttpPost(datamarketAccessUri As String, requestDetails As String) As AdmAccessToken
Dim webRequest As System.Net.WebRequest = System.Net.WebRequest.Create(datamarketAccessUri)
webRequest.ContentType = "application/x-www-form-urlencoded"
webRequest.Method = "POST"
Dim bytes() As Byte = System.Text.Encoding.ASCII.GetBytes(requestDetails)
webRequest.ContentLength = bytes.Length
Using outputStream As IO.Stream = webRequest.GetRequestStream()
outputStream.Write(bytes, 0, bytes.Length)
End Using
Using webResponse As Net.WebResponse = webRequest.GetResponse()
Dim serializer As DataContractJsonSerializer = New DataContractJsonSerializer(GetType(AdmAccessToken))
'Get deserialized object from JSON stream
Dim token As AdmAccessToken = CType(serializer.ReadObject(webResponse.GetResponseStream()), AdmAccessToken)
Return token
End Using
End Function
End Class
|
itom0717/KspTsTool
|
Translation/AdmAuthentication.vb
|
Visual Basic
|
mit
| 2,639
|
'------------------------------------------------------------------------------
' <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 admin
Partial Public Class Modify
'''<summary>
'''Form1 control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents Form1 As Global.System.Web.UI.HtmlControls.HtmlForm
'''<summary>
'''DataGrid1 control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents DataGrid1 As Global.System.Web.UI.WebControls.DataGrid
'''<summary>
'''cmdShowKingdoms control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents cmdShowKingdoms As Global.System.Web.UI.WebControls.Button
'''<summary>
'''txtkdID control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtkdID As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''txtUserName control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtUserName As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''cmdSubmit2 control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents cmdSubmit2 As Global.System.Web.UI.WebControls.Button
'''<summary>
'''txtUserPassword control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtUserPassword As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''cmdSubmit3 control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents cmdSubmit3 As Global.System.Web.UI.WebControls.Button
'''<summary>
'''txtKingdomName control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtKingdomName As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''cmdSubmit1 control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents cmdSubmit1 As Global.System.Web.UI.WebControls.Button
'''<summary>
'''txtRulerName control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtRulerName As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''cmdSubmit control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents cmdSubmit As Global.System.Web.UI.WebControls.Button
End Class
End Namespace
|
jamend/SKlone
|
SKlone/admin/Modify.aspx.designer.vb
|
Visual Basic
|
mit
| 4,433
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class UpdateWindow
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(UpdateWindow))
Me.pgbUpdateStatus = New System.Windows.Forms.ProgressBar()
Me.lblChecking = New System.Windows.Forms.Label()
Me.lblYourVersion = New System.Windows.Forms.Label()
Me.lblNewVersion = New System.Windows.Forms.Label()
Me.pnlNewDetails = New System.Windows.Forms.Panel()
Me.btnChangeUpdateDLloc = New System.Windows.Forms.Button()
Me.txtUpdateDLloc = New System.Windows.Forms.TextBox()
Me.chkLaunchAfterDL = New System.Windows.Forms.CheckBox()
Me.btnUpdate = New System.Windows.Forms.Button()
Me.NewChangeLog = New System.Windows.Forms.RichTextBox()
Me.lblNewChangelog = New System.Windows.Forms.Label()
Me.lblDLProgress = New System.Windows.Forms.Label()
Me.updateDLStats = New System.Windows.Forms.Timer(Me.components)
Me.dlLocDialog = New System.Windows.Forms.FolderBrowserDialog()
Me.pnlNewDetails.SuspendLayout()
Me.SuspendLayout()
'
'pgbUpdateStatus
'
Me.pgbUpdateStatus.Location = New System.Drawing.Point(12, 286)
Me.pgbUpdateStatus.MarqueeAnimationSpeed = 30
Me.pgbUpdateStatus.Name = "pgbUpdateStatus"
Me.pgbUpdateStatus.Size = New System.Drawing.Size(419, 14)
Me.pgbUpdateStatus.TabIndex = 0
'
'lblChecking
'
Me.lblChecking.AutoSize = True
Me.lblChecking.Location = New System.Drawing.Point(146, 270)
Me.lblChecking.Name = "lblChecking"
Me.lblChecking.Size = New System.Drawing.Size(146, 13)
Me.lblChecking.TabIndex = 1
Me.lblChecking.Text = "Checking the current version!"
'
'lblYourVersion
'
Me.lblYourVersion.AutoSize = True
Me.lblYourVersion.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.lblYourVersion.Location = New System.Drawing.Point(9, 9)
Me.lblYourVersion.Name = "lblYourVersion"
Me.lblYourVersion.Size = New System.Drawing.Size(82, 15)
Me.lblYourVersion.TabIndex = 2
Me.lblYourVersion.Text = "Your Version: "
'
'lblNewVersion
'
Me.lblNewVersion.AutoSize = True
Me.lblNewVersion.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.lblNewVersion.Location = New System.Drawing.Point(9, 31)
Me.lblNewVersion.Name = "lblNewVersion"
Me.lblNewVersion.Size = New System.Drawing.Size(94, 15)
Me.lblNewVersion.TabIndex = 3
Me.lblNewVersion.Text = "Current Version:"
'
'pnlNewDetails
'
Me.pnlNewDetails.Controls.Add(Me.btnChangeUpdateDLloc)
Me.pnlNewDetails.Controls.Add(Me.txtUpdateDLloc)
Me.pnlNewDetails.Controls.Add(Me.chkLaunchAfterDL)
Me.pnlNewDetails.Controls.Add(Me.btnUpdate)
Me.pnlNewDetails.Controls.Add(Me.NewChangeLog)
Me.pnlNewDetails.Controls.Add(Me.lblNewChangelog)
Me.pnlNewDetails.Location = New System.Drawing.Point(12, 49)
Me.pnlNewDetails.Name = "pnlNewDetails"
Me.pnlNewDetails.Size = New System.Drawing.Size(419, 231)
Me.pnlNewDetails.TabIndex = 4
Me.pnlNewDetails.Visible = False
'
'btnChangeUpdateDLloc
'
Me.btnChangeUpdateDLloc.Location = New System.Drawing.Point(128, 206)
Me.btnChangeUpdateDLloc.Name = "btnChangeUpdateDLloc"
Me.btnChangeUpdateDLloc.Size = New System.Drawing.Size(33, 22)
Me.btnChangeUpdateDLloc.TabIndex = 5
Me.btnChangeUpdateDLloc.Text = "..."
Me.btnChangeUpdateDLloc.UseVisualStyleBackColor = True
'
'txtUpdateDLloc
'
Me.txtUpdateDLloc.Location = New System.Drawing.Point(6, 207)
Me.txtUpdateDLloc.Name = "txtUpdateDLloc"
Me.txtUpdateDLloc.ReadOnly = True
Me.txtUpdateDLloc.Size = New System.Drawing.Size(122, 20)
Me.txtUpdateDLloc.TabIndex = 4
'
'chkLaunchAfterDL
'
Me.chkLaunchAfterDL.AutoSize = True
Me.chkLaunchAfterDL.Location = New System.Drawing.Point(173, 209)
Me.chkLaunchAfterDL.Name = "chkLaunchAfterDL"
Me.chkLaunchAfterDL.Size = New System.Drawing.Size(135, 17)
Me.chkLaunchAfterDL.TabIndex = 3
Me.chkLaunchAfterDL.Text = "Launch after download"
Me.chkLaunchAfterDL.UseVisualStyleBackColor = True
'
'btnUpdate
'
Me.btnUpdate.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(192, Byte), Integer), CType(CType(0, Byte), Integer))
Me.btnUpdate.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(0, Byte), Integer))
Me.btnUpdate.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Green
Me.btnUpdate.FlatStyle = System.Windows.Forms.FlatStyle.Flat
Me.btnUpdate.Location = New System.Drawing.Point(314, 205)
Me.btnUpdate.Name = "btnUpdate"
Me.btnUpdate.Size = New System.Drawing.Size(102, 23)
Me.btnUpdate.TabIndex = 2
Me.btnUpdate.Text = "Update"
Me.btnUpdate.UseVisualStyleBackColor = True
'
'NewChangeLog
'
Me.NewChangeLog.BackColor = System.Drawing.SystemColors.Control
Me.NewChangeLog.BorderStyle = System.Windows.Forms.BorderStyle.None
Me.NewChangeLog.DetectUrls = False
Me.NewChangeLog.Location = New System.Drawing.Point(3, 19)
Me.NewChangeLog.Name = "NewChangeLog"
Me.NewChangeLog.ReadOnly = True
Me.NewChangeLog.Size = New System.Drawing.Size(413, 167)
Me.NewChangeLog.TabIndex = 1
Me.NewChangeLog.Text = ""
'
'lblNewChangelog
'
Me.lblNewChangelog.AutoSize = True
Me.lblNewChangelog.Location = New System.Drawing.Point(3, 3)
Me.lblNewChangelog.Name = "lblNewChangelog"
Me.lblNewChangelog.Size = New System.Drawing.Size(65, 13)
Me.lblNewChangelog.TabIndex = 0
Me.lblNewChangelog.Text = "Change Log"
'
'lblDLProgress
'
Me.lblDLProgress.Location = New System.Drawing.Point(251, 291)
Me.lblDLProgress.Name = "lblDLProgress"
Me.lblDLProgress.Size = New System.Drawing.Size(184, 28)
Me.lblDLProgress.TabIndex = 5
Me.lblDLProgress.TextAlign = System.Drawing.ContentAlignment.MiddleRight
'
'updateDLStats
'
Me.updateDLStats.Interval = 150
'
'dlLocDialog
'
Me.dlLocDialog.RootFolder = System.Environment.SpecialFolder.MyComputer
'
'UpdateWindow
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(443, 312)
Me.Controls.Add(Me.pnlNewDetails)
Me.Controls.Add(Me.lblNewVersion)
Me.Controls.Add(Me.lblYourVersion)
Me.Controls.Add(Me.lblChecking)
Me.Controls.Add(Me.pgbUpdateStatus)
Me.Controls.Add(Me.lblDLProgress)
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.Name = "UpdateWindow"
Me.ShowIcon = False
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "Update Checker"
Me.pnlNewDetails.ResumeLayout(False)
Me.pnlNewDetails.PerformLayout()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents pgbUpdateStatus As System.Windows.Forms.ProgressBar
Friend WithEvents lblChecking As System.Windows.Forms.Label
Friend WithEvents lblYourVersion As System.Windows.Forms.Label
Friend WithEvents lblNewVersion As System.Windows.Forms.Label
Friend WithEvents pnlNewDetails As System.Windows.Forms.Panel
Friend WithEvents NewChangeLog As System.Windows.Forms.RichTextBox
Friend WithEvents lblNewChangelog As System.Windows.Forms.Label
Friend WithEvents btnUpdate As System.Windows.Forms.Button
Friend WithEvents lblDLProgress As System.Windows.Forms.Label
Friend WithEvents updateDLStats As System.Windows.Forms.Timer
Friend WithEvents chkLaunchAfterDL As System.Windows.Forms.CheckBox
Friend WithEvents btnChangeUpdateDLloc As System.Windows.Forms.Button
Friend WithEvents txtUpdateDLloc As System.Windows.Forms.TextBox
Friend WithEvents dlLocDialog As System.Windows.Forms.FolderBrowserDialog
End Class
|
TheDoxMedia/TDM-Hash-Calc
|
TDM Hash Calc/UpdateWindow.Designer.vb
|
Visual Basic
|
mit
| 9,863
|
Module Module1
Sub Main()
Dim ar As New ArrayList()
Dim opc As Char
Do
System.Console.WriteLine("Teclee un dato")
ar.Add(System.Console.ReadLine)
Do
System.Console.WriteLine("¿Desea seguir introduciendo datos? s/n")
opc = System.Console.ReadLine
Loop Until opc = "s" Or opc = "n"
Loop Until opc = "n"
ar.Sort()
System.Console.WriteLine("Los valores ordenados son:")
For index As Integer = 0 To ar.Count - 1
System.Console.WriteLine(ar(index))
Next
System.Console.ReadKey()
End Sub
End Module
|
ikerlorente11/Egibide
|
DAM/2-Desarrollo-de-aplicaciones-multiplataforma-master/DI/Ejercicios/Tema1/Entrega1/Entrega1-Ej5/Module1.vb
|
Visual Basic
|
apache-2.0
| 675
|
'------------------------------------------------------------------------------
' <auto-generated>
' Этот код создан программой.
' Исполняемая версия:4.0.30319.42000
'
' Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
' повторной генерации кода.
' </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", "15.0.1.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"
#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(sender As Global.System.Object, 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.Bwl.TextBoxEx.My.MySettings
Get
Return Global.Bwl.TextBoxEx.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
Lifemotion/Bwl.VsTools
|
Bwl.TextBox/My Project/Settings.Designer.vb
|
Visual Basic
|
apache-2.0
| 3,094
|
Imports System
Imports System.Data
Imports NUnit.Framework
Imports MyGeneration.dOOdads
Imports Npgsql
Namespace MyGeneration.dOOdads.Tests.Oracle
<TestFixture()> _
Public Class FirebirdAggregateFixture
Dim aggTest As AggregateTest = New AggregateTest
<TestFixtureSetUp()> _
Public Sub Init()
TransactionMgr.ThreadTransactionMgrReset()
aggTest.ConnectionString = Connections.OracleConnection
UnitTestBase.RefreshDatabase()
End Sub
<SetUp()> _
Public Sub Init2()
aggTest.FlushData()
End Sub
<Test()> _
Public Sub EmptyQueryReturnsSELLECTAll()
Assert.IsTrue(aggTest.Query.Load())
Assert.AreEqual(30, aggTest.RowCount)
End Sub
<Test()> _
Public Sub AddAggregateAvg()
aggTest.Aggregate.Salary.Function = AggregateParameter.Func.Avg
aggTest.Aggregate.Salary.Alias = "Avg"
Assert.IsTrue(aggTest.Query.Load())
Assert.AreEqual(1, aggTest.RowCount)
End Sub
<Test()> _
Public Sub AddAggregateCount()
aggTest.Aggregate.Salary.Function = AggregateParameter.Func.Count
aggTest.Aggregate.Salary.Alias = "Count"
Assert.IsTrue(aggTest.Query.Load())
Assert.AreEqual(1, aggTest.RowCount)
End Sub
<Test()> _
Public Sub AddAggregateMin()
aggTest.Aggregate.Salary.Function = AggregateParameter.Func.Min
aggTest.Aggregate.Salary.Alias = "Min"
Assert.IsTrue(aggTest.Query.Load())
Assert.AreEqual(1, aggTest.RowCount)
End Sub
<Test()> _
Public Sub AddAggregateMax()
aggTest.Aggregate.Salary.Function = AggregateParameter.Func.Max
aggTest.Aggregate.Salary.Alias = "Max"
Assert.IsTrue(aggTest.Query.Load())
Assert.AreEqual(1, aggTest.RowCount)
End Sub
<Test()> _
Public Sub AddAggregateSum()
aggTest.Aggregate.Salary.Function = AggregateParameter.Func.Sum
aggTest.Aggregate.Salary.Alias = "Sum"
Assert.IsTrue(aggTest.Query.Load())
Assert.AreEqual(1, aggTest.RowCount)
End Sub
<Test()> _
Public Sub AddAggregateStdDev()
aggTest.Aggregate.Salary.Function = AggregateParameter.Func.StdDev
aggTest.Aggregate.Salary.Alias = "Std Dev"
aggTest.Query.Load()
Assert.IsTrue(aggTest.Query.Load())
Assert.AreEqual(1, aggTest.RowCount)
End Sub
<Test()> _
Public Sub AddAggregateVar()
aggTest.Aggregate.Salary.Function = AggregateParameter.Func.Var
aggTest.Aggregate.Salary.Alias = "Var"
aggTest.Query.Load()
End Sub
<Test()> _
Public Sub AddAggregateCountAll()
aggTest.Query.CountAll = True
aggTest.Query.CountAllAlias = "Total"
Assert.IsTrue(aggTest.Query.Load())
Assert.AreEqual(1, aggTest.RowCount)
End Sub
<Test()> _
Public Sub AddTwoAggregates()
aggTest.Query.CountAll = True
aggTest.Query.CountAllAlias = "Total"
aggTest.Aggregate.Salary.Function = AggregateParameter.Func.Sum
aggTest.Aggregate.Salary.Alias = "Sum"
Assert.IsTrue(aggTest.Query.Load())
Assert.AreEqual(1, aggTest.RowCount)
End Sub
<Test()> _
Public Sub AggregateWithTearoff()
aggTest.Aggregate.Salary.Function = AggregateParameter.Func.Sum
aggTest.Aggregate.Salary.Alias = "Sum"
Dim ap As AggregateParameter = aggTest.Aggregate.TearOff.Salary
ap.Function = AggregateParameter.Func.Min
ap.Alias = "Min"
Assert.IsTrue(aggTest.Query.Load())
Assert.AreEqual(1, aggTest.RowCount)
End Sub
<Test()> _
Public Sub AggregateWithWhere()
aggTest.Query.CountAll = True
aggTest.Query.CountAllAlias = "Total"
aggTest.Where.IsActive.Operator = WhereParameter.Operand.Equal
aggTest.Where.IsActive.Value = True
Assert.IsTrue(aggTest.Query.Load())
Assert.AreEqual(1, aggTest.RowCount)
End Sub
<Test()> _
Public Sub EmptyAliasUsesColumnName()
aggTest.Aggregate.Salary.Function = AggregateParameter.Func.Sum
Assert.IsTrue(aggTest.Query.Load())
Assert.AreEqual("SALARY", aggTest.Aggregate.SALARY.Alias)
End Sub
<Test()> _
Public Sub DistinctAggregate()
aggTest.Aggregate.LastName.Function = AggregateParameter.Func.Count
aggTest.Aggregate.LastName.Distinct = True
Assert.IsTrue(aggTest.Query.Load())
Dim testTable As DataTable = aggTest.DefaultView.Table
Dim currRows As DataRow() = testTable.Select("", "", DataViewRowState.CurrentRows)
Dim testRow As DataRow = currRows(0)
Assert.AreEqual(10, testRow(0))
End Sub
End Class
End Namespace
|
cafephin/mygeneration
|
src/doodads/Tests/VBNet/Oracle/OracleAggregateFixture.vb
|
Visual Basic
|
bsd-3-clause
| 4,421
|
Imports System
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim documents As SolidEdgeFramework.Documents = Nothing
Dim partDocument As SolidEdgePart.PartDocument = Nothing
Dim refPlanes As SolidEdgePart.RefPlanes = Nothing
Dim profileSets As SolidEdgePart.ProfileSets = Nothing
Dim profileSet As SolidEdgePart.ProfileSet = Nothing
Dim profiles As SolidEdgePart.Profiles = Nothing
Dim profile As SolidEdgePart.Profile = Nothing
Dim ellipses2d As SolidEdgeFrameworkSupport.Ellipses2d = Nothing
Dim ellipse2d As SolidEdgeFrameworkSupport.Ellipse2d = Nothing
Try
' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register()
' Attempt to connect to a running instance of Solid Edge.
application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application)
documents = application.Documents
partDocument = CType(documents.Add("SolidEdge.PartDocument"), SolidEdgePart.PartDocument)
refPlanes = partDocument.RefPlanes
profileSets = partDocument.ProfileSets
profileSet = profileSets.Add()
profiles = profileSet.Profiles
profile = profiles.Add(refPlanes.Item(1))
ellipses2d = profile.Ellipses2d
Dim Orientation = SolidEdgeFrameworkSupport.Geom2dOrientationConstants.igGeom2dOrientClockwise
ellipse2d = ellipses2d.AddByCenter(0, 0, 0.01, 0.01, 0.5, Orientation)
For i As Integer = 1 To ellipses2d.Count
ellipse2d = ellipses2d.Item(i)
Next i
Catch ex As System.Exception
Console.WriteLine(ex)
Finally
OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgeFrameworkSupport.Ellipses2d.Item.vb
|
Visual Basic
|
mit
| 2,245
|
Public Enum ASCampaignStatus As Long
[New] = 10140000
Open = 10140001
Closed = 10140002
End Enum
|
EIDSS/EIDSS-Legacy
|
EIDSS v6/vb/EIDSS/EIDSS_Common/Enums/ASCampaignStatus.vb
|
Visual Basic
|
bsd-2-clause
| 114
|
' Licensed to the .NET Foundation under one or more 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.Concurrent
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.ErrorReporting
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents the primary module of an assembly being built by compiler.
''' </summary>
''' <remarks></remarks>
Partial Friend NotInheritable Class SourceModuleSymbol
Inherits NonMissingModuleSymbol
Implements IAttributeTargetSymbol
''' <summary>
''' Owning assembly.
''' </summary>
''' <remarks></remarks>
Private ReadOnly _assemblySymbol As SourceAssemblySymbol
' The declaration table for all the source files.
Private ReadOnly _declarationTable As DeclarationTable
' Options that control compilation
Private ReadOnly _options As VisualBasicCompilationOptions
' Module attributes
Private _lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData)
Private _lazyContainsExtensionMethods As Byte = ThreeState.Unknown
Private _lazyAssembliesToEmbedTypesFrom As ImmutableArray(Of AssemblySymbol)
Private _lazyContainsExplicitDefinitionOfNoPiaLocalTypes As ThreeState = ThreeState.Unknown
Private _locations As ImmutableArray(Of Location)
''' <summary>
''' Holds diagnostics not related to source code
''' in any particular source file
''' </summary>
Private ReadOnly _diagnosticBagDeclare As New DiagnosticBag()
Private _hasBadAttributes As Boolean
Friend ReadOnly Property Options As VisualBasicCompilationOptions
Get
Return _options
End Get
End Property
' A concurrent dictionary that hold SourceFile objects for each source file, created
' on demand. Each source file object holds information about the source that is specific to a particular
' compilation and doesn't survive edits in any way (unlike the declaration table, which is incrementally
' updated between compilations as edits occur.)
Private ReadOnly _sourceFileMap As New ConcurrentDictionary(Of SyntaxTree, SourceFile)
' lazily populated with the global namespace symbol
Private _lazyGlobalNamespace As SourceNamespaceSymbol
' lazily populated with the bound imports
Private _lazyBoundImports As BoundImports
' lazily populate with quick attribute checker that is initialized with the imports.
Private _lazyQuickAttributeChecker As QuickAttributeChecker
' lazily populate with diagnostics validating linked assemblies.
Private _lazyLinkedAssemblyDiagnostics As ImmutableArray(Of Diagnostic)
Private _lazyTypesWithDefaultInstanceAlias As Dictionary(Of NamedTypeSymbol, SynthesizedMyGroupCollectionPropertySymbol)
Private Shared ReadOnly s_noTypesWithDefaultInstanceAlias As New Dictionary(Of NamedTypeSymbol, SynthesizedMyGroupCollectionPropertySymbol)()
Friend Sub New(assemblySymbol As SourceAssemblySymbol,
declarationTable As DeclarationTable,
options As VisualBasicCompilationOptions,
nameAndExtension As String)
Debug.Assert(assemblySymbol IsNot Nothing)
_assemblySymbol = assemblySymbol
_declarationTable = declarationTable
_options = options
_nameAndExtension = nameAndExtension
End Sub
Friend Overrides ReadOnly Property Ordinal As Integer
Get
Return 0
End Get
End Property
Friend Overrides ReadOnly Property Machine As System.Reflection.PortableExecutable.Machine
Get
Select Case DeclaringCompilation.Options.Platform
Case Platform.Arm64
Return System.Reflection.PortableExecutable.Machine.Arm64
Case Platform.Arm
Return System.Reflection.PortableExecutable.Machine.ArmThumb2
Case Platform.X64
Return System.Reflection.PortableExecutable.Machine.Amd64
Case Platform.Itanium
Return System.Reflection.PortableExecutable.Machine.IA64
Case Else
Return System.Reflection.PortableExecutable.Machine.I386
End Select
End Get
End Property
Friend Overrides ReadOnly Property Bit32Required As Boolean
Get
Return DeclaringCompilation.Options.Platform = Platform.X86
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _assemblySymbol
End Get
End Property
Public Overrides ReadOnly Property ContainingAssembly As AssemblySymbol
Get
Return _assemblySymbol
End Get
End Property
Public ReadOnly Property ContainingSourceAssembly As SourceAssemblySymbol
Get
Return _assemblySymbol
End Get
End Property
''' <summary>
''' This override is essential - it's a base case of the recursive definition.
''' </summary>
Friend Overrides ReadOnly Property DeclaringCompilation As VisualBasicCompilation
Get
Return _assemblySymbol.DeclaringCompilation
End Get
End Property
Private ReadOnly _nameAndExtension As String
Public Overrides ReadOnly Property Name As String
Get
Return _nameAndExtension
End Get
End Property
''' <summary>
''' Get the SourceFile object associated with a root declaration.
''' Returns Nothing if the tree doesn't belong to the compilation.
''' </summary>
Friend Function TryGetSourceFile(tree As SyntaxTree) As SourceFile
Debug.Assert(tree IsNot Nothing)
Dim srcFile As SourceFile = Nothing
If _sourceFileMap.TryGetValue(tree, srcFile) Then
Return srcFile
ElseIf _assemblySymbol.DeclaringCompilation.AllSyntaxTrees.Contains(tree) Then
srcFile = New SourceFile(Me, tree)
Return _sourceFileMap.GetOrAdd(tree, srcFile)
Else
Return Nothing
End If
End Function
' Gets the global namespace for that merges the global namespace across all source files.
Public Overrides ReadOnly Property GlobalNamespace As NamespaceSymbol
Get
If _lazyGlobalNamespace Is Nothing Then
Dim globalNS = New SourceNamespaceSymbol(DeclaringCompilation.MergedRootDeclaration, Nothing, Me)
Interlocked.CompareExchange(_lazyGlobalNamespace, globalNS, Nothing)
End If
Return _lazyGlobalNamespace
End Get
End Property
' Get the "root" or default namespace that all source types are declared inside. This may be the global namespace
' or may be another namespace. This is a non-merged, source only namespace.
Friend ReadOnly Property RootNamespace As NamespaceSymbol
Get
Dim result = Me.GlobalNamespace.LookupNestedNamespace(Me.Options.GetRootNamespaceParts())
Debug.Assert(result IsNot Nothing, "Something is deeply wrong with the declaration table or the symbol table")
Return result
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
If _locations.IsDefault Then
ImmutableInterlocked.InterlockedInitialize(
_locations,
DeclaringCompilation.MergedRootDeclaration.Declarations.SelectAsArray(Function(d) d.Location))
End If
Return _locations
End Get
End Property
Friend ReadOnly Property SyntaxTrees As IEnumerable(Of SyntaxTree)
Get
Return _assemblySymbol.DeclaringCompilation.AllSyntaxTrees
End Get
End Property
Public ReadOnly Property DefaultAttributeLocation As AttributeLocation Implements IAttributeTargetSymbol.DefaultAttributeLocation
Get
Return AttributeLocation.Module
End Get
End Property
''' <summary>
''' Gets the attributes applied on this symbol.
''' Returns an empty array if there are no attributes.
''' </summary>
''' <remarks>
''' NOTE: This method should always be kept as a NotOverridable method.
''' If you want to override attribute binding logic for a sub-class, then override <see cref="GetAttributesBag"/> method.
''' </remarks>
Public Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData)
Return Me.GetAttributesBag().Attributes
End Function
Private Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData)
If _lazyCustomAttributesBag Is Nothing OrElse Not _lazyCustomAttributesBag.IsSealed Then
Dim mergedAttributes = DirectCast(Me.ContainingAssembly, SourceAssemblySymbol).GetAttributeDeclarations()
LoadAndValidateAttributes(OneOrMany.Create(mergedAttributes), _lazyCustomAttributesBag)
End If
Return _lazyCustomAttributesBag
End Function
Friend Function GetDecodedWellKnownAttributeData() As CommonModuleWellKnownAttributeData
Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me._lazyCustomAttributesBag
If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then
attributesBag = Me.GetAttributesBag()
End If
Return DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonModuleWellKnownAttributeData)
End Function
' Get a quick attribute checker that can be used for quick attributes checks, initialized with project-level
' aliases.
Public ReadOnly Property QuickAttributeChecker As QuickAttributeChecker
Get
If _lazyQuickAttributeChecker Is Nothing Then
Interlocked.CompareExchange(_lazyQuickAttributeChecker, CreateQuickAttributeChecker(), Nothing)
End If
Return _lazyQuickAttributeChecker
End Get
End Property
Friend ReadOnly Property AnyReferencedAssembliesAreLinked As Boolean
Get
Return GetAssembliesToEmbedTypesFrom().Length > 0
End Get
End Property
Friend Function MightContainNoPiaLocalTypes() As Boolean
Return AnyReferencedAssembliesAreLinked OrElse
ContainsExplicitDefinitionOfNoPiaLocalTypes
End Function
Friend Function GetAssembliesToEmbedTypesFrom() As ImmutableArray(Of AssemblySymbol)
If _lazyAssembliesToEmbedTypesFrom.IsDefault Then
AssertReferencesInitialized()
Dim assemblies = ArrayBuilder(Of AssemblySymbol).GetInstance()
For Each assembly In GetReferencedAssemblySymbols()
If assembly.IsLinked Then
assemblies.Add(assembly)
End If
Next
ImmutableInterlocked.InterlockedInitialize(_lazyAssembliesToEmbedTypesFrom, assemblies.ToImmutableAndFree())
End If
Debug.Assert(Not _lazyAssembliesToEmbedTypesFrom.IsDefault)
Return _lazyAssembliesToEmbedTypesFrom
End Function
Friend ReadOnly Property ContainsExplicitDefinitionOfNoPiaLocalTypes As Boolean
Get
If _lazyContainsExplicitDefinitionOfNoPiaLocalTypes = ThreeState.Unknown Then
_lazyContainsExplicitDefinitionOfNoPiaLocalTypes = NamespaceContainsExplicitDefinitionOfNoPiaLocalTypes(GlobalNamespace).ToThreeState()
End If
Debug.Assert(_lazyContainsExplicitDefinitionOfNoPiaLocalTypes <> ThreeState.Unknown)
Return _lazyContainsExplicitDefinitionOfNoPiaLocalTypes = ThreeState.True
End Get
End Property
Private Shared Function NamespaceContainsExplicitDefinitionOfNoPiaLocalTypes(ns As NamespaceSymbol) As Boolean
For Each s In ns.GetMembersUnordered()
Select Case s.Kind
Case SymbolKind.Namespace
If NamespaceContainsExplicitDefinitionOfNoPiaLocalTypes(DirectCast(s, NamespaceSymbol)) Then
Return True
End If
Case SymbolKind.NamedType
If DirectCast(s, NamedTypeSymbol).IsExplicitDefinitionOfNoPiaLocalType Then
Return True
End If
End Select
Next
Return False
End Function
Private Function CreateQuickAttributeChecker() As QuickAttributeChecker
' First, initialize for the predefined attributes.
Dim checker As New QuickAttributeChecker()
checker.AddName(AttributeDescription.CaseInsensitiveExtensionAttribute.Name, QuickAttributes.Extension)
checker.AddName(AttributeDescription.ObsoleteAttribute.Name, QuickAttributes.Obsolete)
checker.AddName(AttributeDescription.DeprecatedAttribute.Name, QuickAttributes.Obsolete)
checker.AddName(AttributeDescription.ExperimentalAttribute.Name, QuickAttributes.Obsolete)
checker.AddName(AttributeDescription.MyGroupCollectionAttribute.Name, QuickAttributes.MyGroupCollection)
checker.AddName(AttributeDescription.TypeIdentifierAttribute.Name, QuickAttributes.TypeIdentifier)
' Now process alias imports
For Each globalImport In Options.GlobalImports
If globalImport.Clause.Kind = SyntaxKind.SimpleImportsClause Then
Dim simpleImportsClause = DirectCast(globalImport.Clause, SimpleImportsClauseSyntax)
If simpleImportsClause.Alias IsNot Nothing Then
checker.AddAlias(simpleImportsClause)
End If
End If
Next
checker.Seal()
Return checker
End Function
' Make sure the project level imports are bound.
Private Sub EnsureImportsAreBound(cancellationToken As CancellationToken)
If _lazyBoundImports Is Nothing Then
If Interlocked.CompareExchange(_lazyBoundImports, BindImports(cancellationToken), Nothing) Is Nothing Then
ValidateImports(_lazyBoundImports.MemberImports, _lazyBoundImports.MemberImportsInfo, _lazyBoundImports.AliasImports, _lazyBoundImports.AliasImportsInfo, _lazyBoundImports.Diagnostics)
End If
End If
End Sub
' Bind the project level imports.
Private Function BindImports(cancellationToken As CancellationToken) As BoundImports
Dim diagBag As New BindingDiagnosticBag
Dim membersMap = New HashSet(Of NamespaceOrTypeSymbol)
Dim aliasesMap = New Dictionary(Of String, AliasAndImportsClausePosition)(IdentifierComparison.Comparer)
Dim membersBuilder = ArrayBuilder(Of NamespaceOrTypeAndImportsClausePosition).GetInstance()
Dim membersInfoBuilder = ArrayBuilder(Of GlobalImportInfo).GetInstance()
Dim aliasesBuilder = ArrayBuilder(Of AliasAndImportsClausePosition).GetInstance()
Dim aliasesInfoBuilder = ArrayBuilder(Of GlobalImportInfo).GetInstance()
Dim xmlNamespaces = New Dictionary(Of String, XmlNamespaceAndImportsClausePosition)
Dim diagBagForThisImport = BindingDiagnosticBag.GetInstance()
Try
For Each globalImport In Options.GlobalImports
cancellationToken.ThrowIfCancellationRequested()
diagBagForThisImport.Clear()
Dim data = New ModuleImportData(globalImport, membersMap, aliasesMap, membersBuilder, membersInfoBuilder, aliasesBuilder, aliasesInfoBuilder, xmlNamespaces, diagBagForThisImport.DependenciesBag)
Dim binder As Binder = BinderBuilder.CreateBinderForProjectImports(Me, VisualBasicSyntaxTree.Dummy)
binder.BindImportClause(globalImport.Clause, data, diagBagForThisImport.DiagnosticBag)
' Map diagnostics to new ones.
' Note, it is safe to resolve diagnostics here because we suppress obsolete diagnostics
' in ProjectImportsBinder.
For Each d As Diagnostic In diagBagForThisImport.DiagnosticBag.AsEnumerable()
' NOTE: Dev10 doesn't report 'ERR_DuplicateImport1' for project level imports.
If d.Code <> ERRID.ERR_DuplicateImport1 Then
diagBag.Add(globalImport.MapDiagnostic(d))
End If
Next
diagBag.AddDependencies(diagBagForThisImport)
Next
Return New BoundImports(
membersBuilder.ToImmutable(),
membersInfoBuilder.ToImmutable(),
aliasesMap,
aliasesBuilder.ToImmutable(),
aliasesInfoBuilder.ToImmutable(),
If(xmlNamespaces.Count > 0, xmlNamespaces, Nothing),
diagBag)
Finally
membersBuilder.Free()
membersInfoBuilder.Free()
aliasesBuilder.Free()
aliasesInfoBuilder.Free()
diagBagForThisImport.Free()
End Try
End Function
''' <summary>
''' Data for Binder.BindImportClause that maintains flat lists of members, aliases,
''' and corresponding syntax references in addition to the dictionaries needed by
''' BindImportClause. The syntax references, instances of GlobalImportInfo, are used
''' later, when validating constraints, to generate Locations for constraint errors.
''' </summary>
Private NotInheritable Class ModuleImportData
Inherits ImportData
Private ReadOnly _globalImport As GlobalImport
Private ReadOnly _membersBuilder As ArrayBuilder(Of NamespaceOrTypeAndImportsClausePosition)
Private ReadOnly _membersInfoBuilder As ArrayBuilder(Of GlobalImportInfo)
Private ReadOnly _aliasesBuilder As ArrayBuilder(Of AliasAndImportsClausePosition)
Private ReadOnly _aliasesInfoBuilder As ArrayBuilder(Of GlobalImportInfo)
Private ReadOnly _dependencies As ICollection(Of AssemblySymbol)
Public Sub New(globalImport As GlobalImport,
membersMap As HashSet(Of NamespaceOrTypeSymbol),
aliasesMap As Dictionary(Of String, AliasAndImportsClausePosition),
membersBuilder As ArrayBuilder(Of NamespaceOrTypeAndImportsClausePosition),
membersInfoBuilder As ArrayBuilder(Of GlobalImportInfo),
aliasesBuilder As ArrayBuilder(Of AliasAndImportsClausePosition),
aliasesInfoBuilder As ArrayBuilder(Of GlobalImportInfo),
xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition),
dependencies As ICollection(Of AssemblySymbol))
MyBase.New(membersMap, aliasesMap, xmlNamespaces)
_globalImport = globalImport
_membersBuilder = membersBuilder
_membersInfoBuilder = membersInfoBuilder
_aliasesBuilder = aliasesBuilder
_aliasesInfoBuilder = aliasesInfoBuilder
_dependencies = dependencies
End Sub
Public Overrides Sub AddMember(syntaxRef As SyntaxReference, member As NamespaceOrTypeSymbol, importsClausePosition As Integer, dependencies As IReadOnlyCollection(Of AssemblySymbol))
Dim pair = New NamespaceOrTypeAndImportsClausePosition(member, importsClausePosition, ImmutableArray(Of AssemblySymbol).Empty)
Members.Add(member)
_membersBuilder.Add(pair)
_membersInfoBuilder.Add(New GlobalImportInfo(_globalImport, syntaxRef))
AddDependencies(dependencies)
End Sub
Private Sub AddDependencies(dependencies As IReadOnlyCollection(Of AssemblySymbol))
For Each dependency In dependencies
_dependencies.Add(dependency)
Next
End Sub
Public Overrides Sub AddAlias(syntaxRef As SyntaxReference, name As String, [alias] As AliasSymbol, importsClausePosition As Integer, dependencies As IReadOnlyCollection(Of AssemblySymbol))
Dim pair = New AliasAndImportsClausePosition([alias], importsClausePosition, ImmutableArray(Of AssemblySymbol).Empty)
Aliases.Add(name, pair)
_aliasesBuilder.Add(pair)
_aliasesInfoBuilder.Add(New GlobalImportInfo(_globalImport, syntaxRef))
AddDependencies(dependencies)
End Sub
End Class
''' <summary>
''' Perform any validation of import statements that must occur
''' after the import statements have been added to the module.
''' </summary>
Private Sub ValidateImports(
memberImports As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition),
memberImportsInfo As ImmutableArray(Of GlobalImportInfo),
aliasImports As ImmutableArray(Of AliasAndImportsClausePosition),
aliasImportsInfo As ImmutableArray(Of GlobalImportInfo),
diagnostics As BindingDiagnosticBag)
' TODO: Dev10 reports error on specific type parts rather than the import
' (reporting error on Object rather than C in C = A(Of Object) for instance).
If Not memberImports.IsDefault Then
For i = 0 To memberImports.Length - 1
Dim namespaceOrType As NamespaceOrTypeSymbol = memberImports(i).NamespaceOrType
Dim type = TryCast(namespaceOrType, TypeSymbol)
If type IsNot Nothing Then
ValidateImport(type, memberImportsInfo(i), diagnostics)
Else
diagnostics.AddAssembliesUsedByNamespaceReference(DirectCast(namespaceOrType, NamespaceSymbol))
End If
Next
End If
If Not aliasImports.IsDefault Then
For i = 0 To aliasImports.Length - 1
Dim target As NamespaceOrTypeSymbol = aliasImports(i).Alias.Target
Dim type = TryCast(target, TypeSymbol)
If type IsNot Nothing Then
ValidateImport(type, aliasImportsInfo(i), diagnostics)
Else
diagnostics.AddAssembliesUsedByNamespaceReference(DirectCast(target, NamespaceSymbol))
End If
Next
End If
End Sub
''' <summary>
''' Perform validation of an import statement that must occur
''' after the statement has been added to the module. Specifically,
''' constraints are checked for generic type references.
''' </summary>
Private Sub ValidateImport(type As TypeSymbol, info As GlobalImportInfo, diagnostics As BindingDiagnosticBag)
Dim diagnosticsBuilder = ArrayBuilder(Of TypeParameterDiagnosticInfo).GetInstance()
Dim useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo) = Nothing
type.CheckAllConstraints(diagnosticsBuilder, useSiteDiagnosticsBuilder, template:=New CompoundUseSiteInfo(Of AssemblySymbol)(diagnostics, ContainingAssembly))
If useSiteDiagnosticsBuilder IsNot Nothing Then
diagnosticsBuilder.AddRange(useSiteDiagnosticsBuilder)
End If
For Each pair In diagnosticsBuilder
If pair.UseSiteInfo.DiagnosticInfo IsNot Nothing Then
diagnostics.Add(info.Import.MapDiagnostic(New VBDiagnostic(pair.UseSiteInfo.DiagnosticInfo, info.SyntaxReference.GetLocation())))
End If
diagnostics.AddDependencies(pair.UseSiteInfo)
Next
diagnosticsBuilder.Free()
End Sub
' Get the project-level member imports, or Nothing if none.
Friend ReadOnly Property MemberImports As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition)
Get
EnsureImportsAreBound(CancellationToken.None)
Return _lazyBoundImports.MemberImports
End Get
End Property
Friend ReadOnly Property AliasImports As ImmutableArray(Of AliasAndImportsClausePosition)
Get
EnsureImportsAreBound(CancellationToken.None)
Return _lazyBoundImports.AliasImports
End Get
End Property
' Get the project level alias imports, or Nothing if none.
Friend ReadOnly Property AliasImportsMap As Dictionary(Of String, AliasAndImportsClausePosition)
Get
EnsureImportsAreBound(CancellationToken.None)
Return _lazyBoundImports.AliasImportsMap
End Get
End Property
' Get the project level xmlns imports, or Nothing if none.
Friend ReadOnly Property XmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition)
Get
EnsureImportsAreBound(CancellationToken.None)
Return _lazyBoundImports.XmlNamespaces
End Get
End Property
''' <summary>
''' Get all the declaration errors in a single tree.
''' </summary>
Friend Function GetDeclarationErrorsInTree(tree As SyntaxTree,
filterSpanWithinTree As TextSpan?,
locationFilter As Func(Of IEnumerable(Of Diagnostic), SyntaxTree, TextSpan?, IEnumerable(Of Diagnostic)),
cancellationToken As CancellationToken) As ImmutableArray(Of Diagnostic)
Dim builder = ArrayBuilder(Of Diagnostic).GetInstance()
' Force source file to generate errors for Imports and the like.
Dim sourceFile As SourceFile = TryGetSourceFile(tree)
Debug.Assert(sourceFile IsNot Nothing)
If filterSpanWithinTree.HasValue Then
Dim diagnostics = sourceFile.GetDeclarationErrorsInSpan(filterSpanWithinTree.Value, cancellationToken)
diagnostics = locationFilter(diagnostics, tree, filterSpanWithinTree)
builder.AddRange(diagnostics)
Else
sourceFile.GenerateAllDeclarationErrors()
End If
' Force bind module and assembly attributes
Me.GetAttributes()
Me.ContainingAssembly.GetAttributes()
' Force all types to generate errors.
Dim tasks As ConcurrentStack(Of Task) = If(ContainingSourceAssembly.DeclaringCompilation.Options.ConcurrentBuild, New ConcurrentStack(Of Task)(), Nothing)
' Force all types that were declared in this tree to generate errors. We may also generate declaration
' errors for other parts of partials; that's OK and those errors will be retained, but won't be in the
' diagnostic bag for this particular file.
VisitAllSourceTypesAndNamespaces(Sub(typeOrNamespace As NamespaceOrTypeSymbol)
If Not typeOrNamespace.IsDefinedInSourceTree(tree, filterSpanWithinTree) Then
Return
End If
If typeOrNamespace.IsNamespace Then
DirectCast(typeOrNamespace, SourceNamespaceSymbol).GenerateDeclarationErrorsInTree(tree, filterSpanWithinTree, cancellationToken)
Else
' synthetic event delegates are not source types so use NamedTypeSymbol.
Dim sourceType = DirectCast(typeOrNamespace, NamedTypeSymbol)
sourceType.GenerateDeclarationErrors(cancellationToken)
End If
End Sub,
tasks, cancellationToken)
If tasks IsNot Nothing Then
Dim curTask As Task = Nothing
While tasks.TryPop(curTask)
curTask.GetAwaiter().GetResult()
End While
End If
' Get all the errors that were generated.
Dim declarationDiagnostics = sourceFile.DeclarationDiagnostics.AsEnumerable()
' Filter diagnostics outside the tree/span of interest.
If locationFilter IsNot Nothing Then
Debug.Assert(tree IsNot Nothing)
declarationDiagnostics = locationFilter(declarationDiagnostics, tree, filterSpanWithinTree)
End If
For Each d As Diagnostic In declarationDiagnostics
builder.Add(d)
Next
Return builder.ToImmutableAndFree()
End Function
''' <summary>
''' Get all the declaration errors.
''' </summary>
Friend Sub GetAllDeclarationErrors(diagnostics As BindingDiagnosticBag, cancellationToken As CancellationToken, ByRef hasExtensionMethods As Boolean)
' Bind project level imports
EnsureImportsAreBound(cancellationToken)
' Force all source files to generate errors for imports and the like.
If ContainingSourceAssembly.DeclaringCompilation.Options.ConcurrentBuild Then
Dim trees = ArrayBuilder(Of SyntaxTree).GetInstance()
trees.AddRange(SyntaxTrees)
RoslynParallel.For(
0,
trees.Count,
UICultureUtilities.WithCurrentUICulture(
Sub(i As Integer)
TryGetSourceFile(trees(i)).GenerateAllDeclarationErrors()
End Sub),
cancellationToken)
trees.Free()
Else
For Each tree In SyntaxTrees
cancellationToken.ThrowIfCancellationRequested()
TryGetSourceFile(tree).GenerateAllDeclarationErrors()
Next
End If
' Force bind module and assembly attributes
Dim unused = Me.GetAttributes()
unused = Me.ContainingAssembly.GetAttributes()
EnsureLinkedAssembliesAreValidated(cancellationToken)
' Force all types to generate errors.
Dim tasks As ConcurrentStack(Of Task) = If(ContainingSourceAssembly.DeclaringCompilation.Options.ConcurrentBuild,
New ConcurrentStack(Of Task)(), Nothing)
VisitAllSourceTypesAndNamespaces(Sub(typeOrNamespace As NamespaceOrTypeSymbol)
If typeOrNamespace.IsNamespace Then
DirectCast(typeOrNamespace, SourceNamespaceSymbol).GenerateDeclarationErrors(cancellationToken)
Else
' synthetic event delegates are not source types so use NamedTypeSymbol.
Dim sourceType = DirectCast(typeOrNamespace, NamedTypeSymbol)
sourceType.GenerateDeclarationErrors(cancellationToken)
End If
End Sub,
tasks, cancellationToken)
If tasks IsNot Nothing Then
Dim curTask As Task = Nothing
While tasks.TryPop(curTask)
curTask.GetAwaiter().GetResult()
End While
End If
' At this point we should have recorded presence of extension methods.
If _lazyContainsExtensionMethods = ThreeState.Unknown Then
_lazyContainsExtensionMethods = ThreeState.False
End If
hasExtensionMethods = _lazyContainsExtensionMethods = ThreeState.True
' Accumulate all the errors that were generated.
diagnostics.AddRange(Me._diagnosticBagDeclare)
diagnostics.AddRange(Me._lazyBoundImports.Diagnostics, allowMismatchInDependencyAccumulation:=True)
diagnostics.AddRange(Me._lazyLinkedAssemblyDiagnostics)
For Each tree In SyntaxTrees
diagnostics.AddRange(TryGetSourceFile(tree).DeclarationDiagnostics)
Next
End Sub
' Visit all of the source types within this source module.
Private Sub VisitAllSourceTypesAndNamespaces(visitor As Action(Of NamespaceOrTypeSymbol), tasks As ConcurrentStack(Of Task), cancellationToken As CancellationToken)
VisitTypesAndNamespacesWithin(Me.GlobalNamespace, visitor, tasks, cancellationToken)
End Sub
' Visit all source types and namespaces within this source namespace or type, inclusive of this source namespace or type
Private Sub VisitTypesAndNamespacesWithin(ns As NamespaceOrTypeSymbol, visitor As Action(Of NamespaceOrTypeSymbol), tasks As ConcurrentStack(Of Task), cancellationToken As CancellationToken)
Dim stack = ArrayBuilder(Of NamespaceOrTypeSymbol).GetInstance
Try
stack.Push(ns)
While stack.Count > 0
cancellationToken.ThrowIfCancellationRequested()
Dim symbol = stack.Pop()
If tasks IsNot Nothing Then
Dim worker As Task = Task.Run(
UICultureUtilities.WithCurrentUICulture(
Sub()
Try
visitor(symbol)
Catch e As Exception When FatalError.ReportAndPropagateUnlessCanceled(e)
Throw ExceptionUtilities.Unreachable
End Try
End Sub),
cancellationToken)
tasks.Push(worker)
Else
visitor(symbol)
End If
For Each child As Symbol In If(symbol.IsNamespace, symbol.GetMembers(), symbol.GetTypeMembers().Cast(Of Symbol))
stack.Push(DirectCast(child, NamespaceOrTypeSymbol))
Next
End While
Finally
stack.Free()
End Try
End Sub
Private Sub EnsureLinkedAssembliesAreValidated(cancellationToken As CancellationToken)
If _lazyLinkedAssemblyDiagnostics.IsDefault Then
Dim diagnostics = DiagnosticBag.GetInstance()
ValidateLinkedAssemblies(diagnostics, cancellationToken)
ImmutableInterlocked.InterlockedInitialize(_lazyLinkedAssemblyDiagnostics, diagnostics.ToReadOnlyAndFree)
End If
End Sub
Private Sub ValidateLinkedAssemblies(diagnostics As DiagnosticBag, cancellationToken As CancellationToken)
For Each assembly In GetReferencedAssemblySymbols()
cancellationToken.ThrowIfCancellationRequested()
If assembly.IsMissing OrElse Not assembly.IsLinked Then
Continue For
End If
Dim hasGuidAttribute = False
Dim hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute = False
For Each attrData In assembly.GetAttributes()
If attrData.IsTargetAttribute(assembly, AttributeDescription.GuidAttribute) Then
If attrData.CommonConstructorArguments.Length = 1 Then
Dim value = attrData.CommonConstructorArguments(0).ValueInternal
If value Is Nothing OrElse TypeOf value Is String Then
hasGuidAttribute = True
End If
End If
ElseIf attrData.IsTargetAttribute(assembly, AttributeDescription.ImportedFromTypeLibAttribute) Then
If attrData.CommonConstructorArguments.Length = 1 Then
hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute = True
End If
ElseIf attrData.IsTargetAttribute(assembly, AttributeDescription.PrimaryInteropAssemblyAttribute) Then
If attrData.CommonConstructorArguments.Length = 2 Then
hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute = True
End If
End If
If hasGuidAttribute AndAlso hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute Then
Exit For
End If
Next
If Not hasGuidAttribute Then
diagnostics.Add(ERRID.ERR_PIAHasNoAssemblyGuid1,
NoLocation.Singleton,
assembly,
AttributeDescription.GuidAttribute.FullName)
End If
If Not hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute Then
diagnostics.Add(ERRID.ERR_PIAHasNoTypeLibAttribute1,
NoLocation.Singleton,
assembly,
AttributeDescription.ImportedFromTypeLibAttribute.FullName,
AttributeDescription.PrimaryInteropAssemblyAttribute.FullName)
End If
Next
End Sub
' This lock is used in the implementation of AtomicStoreReferenceAndDiagnostics
Private ReadOnly _diagnosticLock As New Object()
' Checks if the given diagnostic bag has all lazy obsolete diagnostics.
Private Shared Function HasAllLazyDiagnostics(diagBag As DiagnosticBag) As Boolean
Debug.Assert(diagBag IsNot Nothing)
Debug.Assert(Not diagBag.IsEmptyWithoutResolution())
For Each diag In diagBag.AsEnumerable()
Dim cdiag = TryCast(diag, DiagnosticWithInfo)
If cdiag Is Nothing OrElse Not cdiag.HasLazyInfo Then
Return False
End If
Next
Return True
End Function
''' <summary>
''' Atomically store value into variable, and store the diagnostics away for later retrieval.
''' When this routine returns, variable is non-null. If this routine stored value into variable,
''' then the diagnostic bag is saved away before the variable is stored and it returns True.
''' Otherwise it returns False.
''' </summary>
Friend Function AtomicStoreReferenceAndDiagnostics(Of T As Class)(ByRef variable As T,
value As T,
diagBag As BindingDiagnosticBag,
Optional comparand As T = Nothing) As Boolean
Debug.Assert(value IsNot comparand)
If diagBag Is Nothing OrElse diagBag.IsEmpty Then
Return Interlocked.CompareExchange(variable, value, comparand) Is comparand AndAlso comparand Is Nothing
Else
Dim stored = False
SyncLock _diagnosticLock
If variable Is comparand Then
StoreDeclarationDiagnostics(diagBag)
stored = Interlocked.CompareExchange(variable, value, comparand) Is comparand
If Not stored AndAlso Not IsEmptyIgnoringLazyDiagnostics(diagBag) Then
' If this gets hit, then someone wrote to variable without going through this
' routine, or else someone wrote to variable with this routine but an empty
' diagnostic bag (they went through the above If part). Either is a bug.
Throw ExceptionUtilities.Unreachable
End If
End If
End SyncLock
Return stored AndAlso comparand Is Nothing
End If
End Function
Private Shared Function IsEmptyIgnoringLazyDiagnostics(diagBag As BindingDiagnosticBag) As Boolean
Return diagBag.DependenciesBag.IsNullOrEmpty() AndAlso
(Not diagBag.AccumulatesDiagnostics OrElse HasAllLazyDiagnostics(diagBag.DiagnosticBag))
End Function
' Atomically store value into variable, and store the diagnostics away for later retrieval.
' When this routine returns, variable is not equal to comparand. If this routine stored value into variable,
' then the diagnostic bag is saved away before the variable is stored.
Friend Sub AtomicStoreIntegerAndDiagnostics(ByRef variable As Integer,
value As Integer,
comparand As Integer,
diagBag As BindingDiagnosticBag)
If diagBag Is Nothing OrElse diagBag.IsEmpty Then
Interlocked.CompareExchange(variable, value, comparand)
Else
SyncLock _diagnosticLock
If variable = comparand Then
StoreDeclarationDiagnostics(diagBag)
If Interlocked.CompareExchange(variable, value, comparand) <> comparand AndAlso
Not IsEmptyIgnoringLazyDiagnostics(diagBag) Then
' If this gets hit, then someone wrote to variable without going through this
' routine, or else someone wrote to variable with this routine but an empty
' diagnostic bag (they went through the above If part). Either is a bug.
Throw ExceptionUtilities.Unreachable
End If
End If
End SyncLock
End If
End Sub
' Atomically set flag value into variable, and store the diagnostics away for later retrieval.
' When this routine returns, variable is not equal to comparand. If this routine stored value into variable,
' then the diagnostic bag is saved away before the variable is stored.
Friend Function AtomicSetFlagAndStoreDiagnostics(ByRef variable As Integer,
mask As Integer,
comparand As Integer,
diagBag As BindingDiagnosticBag) As Boolean
If diagBag Is Nothing OrElse diagBag.IsEmpty Then
Return ThreadSafeFlagOperations.Set(variable, mask)
Else
SyncLock _diagnosticLock
Dim change = (variable And mask) = comparand
If change Then
StoreDeclarationDiagnostics(diagBag)
If Not ThreadSafeFlagOperations.Set(variable, mask) AndAlso
Not IsEmptyIgnoringLazyDiagnostics(diagBag) Then
' If this gets hit, then someone wrote to variable without going through this
' routine, or else someone wrote to variable with this routine but an empty
' diagnostic bag (they went through the above If part). Either is a bug.
Throw ExceptionUtilities.Unreachable
End If
End If
Return change
End SyncLock
End If
End Function
' Atomically set flag value into variable, and raise the symbol declared event.
' When this routine returns, variable is not equal to comparand. If this routine stored value into variable,
' then the symbol declared event was raised for the symbol.
Friend Function AtomicSetFlagAndRaiseSymbolDeclaredEvent(ByRef variable As Integer,
mask As Integer,
comparand As Integer,
symbol As Symbol) As Boolean
Debug.Assert(Me.DeclaringCompilation.EventQueue IsNot Nothing)
SyncLock _diagnosticLock
Dim change = (variable And mask) = comparand
If change Then
Me.DeclaringCompilation.SymbolDeclaredEvent(symbol)
If Not ThreadSafeFlagOperations.Set(variable, mask) Then
' If this gets hit, then someone wrote to variable without going through this
' routine, which is a bug.
Throw ExceptionUtilities.Unreachable
End If
End If
Return change
End SyncLock
End Function
Friend Function AtomicStoreArrayAndDiagnostics(Of T)(ByRef variable As ImmutableArray(Of T),
value As ImmutableArray(Of T),
diagBag As BindingDiagnosticBag) As Boolean
Debug.Assert(Not value.IsDefault)
If diagBag Is Nothing OrElse diagBag.IsEmpty Then
Return ImmutableInterlocked.InterlockedInitialize(variable, value)
Else
SyncLock _diagnosticLock
If variable.IsDefault Then
StoreDeclarationDiagnostics(diagBag)
Dim stored = ImmutableInterlocked.InterlockedInitialize(variable, value)
If Not stored AndAlso Not IsEmptyIgnoringLazyDiagnostics(diagBag) Then
' If this gets hit, then someone wrote to variable without going through this
' routine, or else someone wrote to variable with this routine but an empty
' diagnostic bag (they went through the above If part). Either is a bug.
Throw ExceptionUtilities.Unreachable
End If
Return stored
Else
Return False
End If
End SyncLock
End If
End Function
Friend Sub AtomicStoreAttributesAndDiagnostics(attributesBag As CustomAttributesBag(Of VisualBasicAttributeData),
attributesToStore As ImmutableArray(Of VisualBasicAttributeData),
diagBag As BindingDiagnosticBag)
Debug.Assert(attributesBag IsNot Nothing)
Debug.Assert(Not attributesToStore.IsDefault)
RecordPresenceOfBadAttributes(attributesToStore)
If diagBag Is Nothing OrElse diagBag.IsEmpty Then
attributesBag.SetAttributes(attributesToStore)
Else
SyncLock _diagnosticLock
If Not attributesBag.IsSealed Then
StoreDeclarationDiagnostics(diagBag)
If Not attributesBag.SetAttributes(attributesToStore) AndAlso
Not IsEmptyIgnoringLazyDiagnostics(diagBag) Then
' If this gets hit, then someone set attributes in the bag without going through this
' routine, or else someone set attributes in the bag with this routine but an empty
' diagnostic bag (they went through the above If part). Either is a bug.
Throw ExceptionUtilities.Unreachable
End If
Debug.Assert(attributesBag.IsSealed)
End If
End SyncLock
End If
End Sub
Private Sub RecordPresenceOfBadAttributes(attributes As ImmutableArray(Of VisualBasicAttributeData))
If Not _hasBadAttributes Then
For Each attribute In attributes
If attribute.HasErrors Then
_hasBadAttributes = True
Exit For
End If
Next
End If
End Sub
Friend ReadOnly Property HasBadAttributes As Boolean
Get
Return _hasBadAttributes
End Get
End Property
' same as AtomicStoreReferenceAndDiagnostics, but without storing any references
Friend Sub AddDeclarationDiagnostics(diagBag As BindingDiagnosticBag)
If Not diagBag.IsEmpty Then
SyncLock _diagnosticLock
StoreDeclarationDiagnostics(diagBag)
End SyncLock
End If
End Sub
' Given a diagnostic bag, store the diagnostics into the correct bags.
' NOTE: This is called from AtomicStoreReferenceAndDiagnostics, which takes a lock.
' NOTE: It is important that it doesn't do any operation that wants to acquire another lock.
' NOTE: Copy without resolving diagnostics.
Private Sub StoreDeclarationDiagnostics(diagBag As BindingDiagnosticBag)
If Not diagBag.IsEmpty Then
If Not diagBag.DiagnosticBag?.IsEmptyWithoutResolution Then
For Each d As Diagnostic In diagBag.DiagnosticBag.AsEnumerableWithoutResolution()
Dim loc = d.Location
If loc.IsInSource Then
Dim tree = DirectCast(loc.SourceTree, VisualBasicSyntaxTree)
Dim sourceFile = TryGetSourceFile(tree)
Debug.Assert(sourceFile IsNot Nothing)
sourceFile.DeclarationDiagnostics.Add(d)
Else
Me._diagnosticBagDeclare.Add(d)
End If
Next
End If
If Not diagBag.DependenciesBag.IsNullOrEmpty() Then
DeclaringCompilation.AddUsedAssemblies(diagBag.DependenciesBag)
End If
End If
End Sub
Friend Overrides ReadOnly Property TypeNames As ICollection(Of String)
Get
Return _declarationTable.TypeNames
End Get
End Property
Friend Overrides ReadOnly Property NamespaceNames As ICollection(Of String)
Get
Return _declarationTable.NamespaceNames
End Get
End Property
Friend Overrides ReadOnly Property MightContainExtensionMethods As Boolean
Get
' Only primary module of an assembly marked with an Extension attribute
' can contain extension methods recognized by the language (Dev10 behavior).
If _lazyContainsExtensionMethods = ThreeState.Unknown Then
If Not (_assemblySymbol.Modules(0) Is Me) Then
_lazyContainsExtensionMethods = ThreeState.False
End If
End If
Return _lazyContainsExtensionMethods <> ThreeState.False
End Get
End Property
Friend Sub RecordPresenceOfExtensionMethods()
Debug.Assert(_lazyContainsExtensionMethods <> ThreeState.False)
_lazyContainsExtensionMethods = ThreeState.True
End Sub
Friend Overrides Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation))
Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing)
Dim attrData = arguments.Attribute
Debug.Assert(Not attrData.HasErrors)
Debug.Assert(arguments.SymbolPart = AttributeLocation.None)
If attrData.IsTargetAttribute(Me, AttributeDescription.TupleElementNamesAttribute) Then
DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location)
End If
If attrData.IsTargetAttribute(Me, AttributeDescription.DefaultCharSetAttribute) Then
Dim charSet As CharSet = attrData.GetConstructorArgument(Of CharSet)(0, SpecialType.System_Enum)
If Not CommonModuleWellKnownAttributeData.IsValidCharSet(charSet) Then
DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.ERR_BadAttribute1, arguments.AttributeSyntaxOpt.ArgumentList.Arguments(0).GetLocation(), attrData.AttributeClass)
Else
arguments.GetOrCreateData(Of CommonModuleWellKnownAttributeData)().DefaultCharacterSet = charSet
End If
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.DebuggableAttribute) Then
arguments.GetOrCreateData(Of CommonModuleWellKnownAttributeData).HasDebuggableAttribute = True
End If
MyBase.DecodeWellKnownAttribute(arguments)
End Sub
Friend Overrides ReadOnly Property HasAssemblyCompilationRelaxationsAttribute() As Boolean
Get
Dim decodedData As CommonAssemblyWellKnownAttributeData(Of NamedTypeSymbol) = DirectCast(Me.ContainingAssembly, SourceAssemblySymbol).GetSourceDecodedWellKnownAttributeData()
Return decodedData IsNot Nothing AndAlso decodedData.HasCompilationRelaxationsAttribute
End Get
End Property
Friend Overrides ReadOnly Property HasAssemblyRuntimeCompatibilityAttribute() As Boolean
Get
Dim decodedData As CommonAssemblyWellKnownAttributeData(Of NamedTypeSymbol) = DirectCast(Me.ContainingAssembly, SourceAssemblySymbol).GetSourceDecodedWellKnownAttributeData()
Return decodedData IsNot Nothing AndAlso decodedData.HasRuntimeCompatibilityAttribute
End Get
End Property
Friend Overrides ReadOnly Property DefaultMarshallingCharSet As CharSet?
Get
Dim data = GetDecodedWellKnownAttributeData()
Return If(data IsNot Nothing AndAlso data.HasDefaultCharSetAttribute, data.DefaultCharacterSet, DirectCast(Nothing, CharSet?))
End Get
End Property
Public Function GetMyGroupCollectionPropertyWithDefaultInstanceAlias(classType As NamedTypeSymbol) As SynthesizedMyGroupCollectionPropertySymbol
Debug.Assert(classType.IsDefinition AndAlso Not classType.IsGenericType)
If _lazyTypesWithDefaultInstanceAlias Is Nothing Then
_lazyTypesWithDefaultInstanceAlias = GetTypesWithDefaultInstanceAlias()
End If
Dim result As SynthesizedMyGroupCollectionPropertySymbol = Nothing
If _lazyTypesWithDefaultInstanceAlias IsNot s_noTypesWithDefaultInstanceAlias AndAlso
_lazyTypesWithDefaultInstanceAlias.TryGetValue(classType, result) Then
Return result
End If
Return Nothing
End Function
Private Function GetTypesWithDefaultInstanceAlias() As Dictionary(Of NamedTypeSymbol, SynthesizedMyGroupCollectionPropertySymbol)
Dim result As Dictionary(Of NamedTypeSymbol, SynthesizedMyGroupCollectionPropertySymbol) = Nothing
If _assemblySymbol.DeclaringCompilation.MyTemplate IsNot Nothing Then
GetTypesWithDefaultInstanceAlias(GlobalNamespace, result)
End If
If result Is Nothing Then
result = s_noTypesWithDefaultInstanceAlias
End If
Return result
End Function
Private Shared Sub GetTypesWithDefaultInstanceAlias(
namespaceOrType As NamespaceOrTypeSymbol,
<[In], Out> ByRef result As Dictionary(Of NamedTypeSymbol, SynthesizedMyGroupCollectionPropertySymbol)
)
For Each member As Symbol In namespaceOrType.GetMembersUnordered()
Select Case member.Kind
Case SymbolKind.Property
If member.IsMyGroupCollectionProperty Then
Dim prop = DirectCast(member, SynthesizedMyGroupCollectionPropertySymbol)
' See Semantics::GetDefaultInstanceBaseNameForMyGroupMember
If prop.DefaultInstanceAlias.Length > 0 Then
Dim targetType = DirectCast(prop.Type, NamedTypeSymbol)
If result Is Nothing Then
result = New Dictionary(Of NamedTypeSymbol, SynthesizedMyGroupCollectionPropertySymbol)(ReferenceEqualityComparer.Instance)
ElseIf result.ContainsKey(targetType) Then
' ambiguity
result(targetType) = Nothing
Exit Select
End If
result.Add(targetType, prop)
End If
End If
Case SymbolKind.NamedType
Dim named = TryCast(member, SourceNamedTypeSymbol)
If named IsNot Nothing Then
For Each syntaxRef As SyntaxReference In named.SyntaxReferences
If syntaxRef.SyntaxTree.IsMyTemplate Then
GetTypesWithDefaultInstanceAlias(named, result)
Exit For
End If
Next
End If
Case SymbolKind.Namespace
GetTypesWithDefaultInstanceAlias(DirectCast(member, NamespaceSymbol), result)
End Select
Next
End Sub
Public Overrides Function GetMetadata() As ModuleMetadata
Return Nothing
End Function
End Class
End Namespace
|
sharwell/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/Source/SourceModuleSymbol.vb
|
Visual Basic
|
mit
| 60,479
|
' 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.ComponentModel.Composition
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.CodeCleanup
Imports Microsoft.CodeAnalysis.CodeCleanup.Providers
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Internal.Log
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Formatting.Rules
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.VisualStudio.Text
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit
<Export(GetType(ICommitFormatter))>
Friend Class CommitFormatter
Implements ICommitFormatter
Private Shared ReadOnly codeCleanupPredicate As Func(Of ICodeCleanupProvider, Boolean) =
Function(p)
Return p.Name <> PredefinedCodeCleanupProviderNames.Simplification AndAlso
p.Name <> PredefinedCodeCleanupProviderNames.Format
End Function
Public Sub CommitRegion(spanToFormat As SnapshotSpan,
isExplicitFormat As Boolean,
useSemantics As Boolean,
dirtyRegion As SnapshotSpan,
baseSnapshot As ITextSnapshot,
baseTree As SyntaxTree,
cancellationToken As CancellationToken) Implements ICommitFormatter.CommitRegion
Using (Logger.LogBlock(FunctionId.LineCommit_CommitRegion, cancellationToken))
Dim buffer = spanToFormat.Snapshot.TextBuffer
Dim currentSnapshot = buffer.CurrentSnapshot
' make sure things are current
spanToFormat = spanToFormat.TranslateTo(currentSnapshot, SpanTrackingMode.EdgeInclusive)
dirtyRegion = dirtyRegion.TranslateTo(currentSnapshot, SpanTrackingMode.EdgeInclusive)
Dim document = currentSnapshot.GetOpenDocumentInCurrentContextWithChanges()
If document Is Nothing Then
Return
End If
Dim optionService = document.Project.Solution.Workspace.Services.GetService(Of IOptionService)()
If Not (isExplicitFormat OrElse optionService.GetOption(FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic)) Then
Return
End If
Dim textSpanToFormat = spanToFormat.Span.ToTextSpan()
' create commit formatting cleaup provider that has line commit specific behavior
Dim commitFormattingCleanup = GetCommitFormattingCleanupProvider(
document,
spanToFormat,
baseSnapshot, baseTree,
dirtyRegion, document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken),
cancellationToken)
Dim codeCleanups = CodeCleaner.GetDefaultProviders(document).Where(codeCleanupPredicate).Concat(commitFormattingCleanup)
Dim finalDocument As Document
If useSemantics OrElse isExplicitFormat Then
finalDocument = CodeCleaner.CleanupAsync(document,
textSpanToFormat,
codeCleanups,
cancellationToken).WaitAndGetResult(cancellationToken)
Else
Dim root = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken)
Dim newRoot = CodeCleaner.Cleanup(root, textSpanToFormat, document.Project.Solution.Workspace, codeCleanups, cancellationToken)
If root Is newRoot Then
finalDocument = document
Else
Dim text As SourceText = Nothing
If newRoot.SyntaxTree IsNot Nothing AndAlso newRoot.SyntaxTree.TryGetText(text) Then
finalDocument = document.WithText(text)
Else
finalDocument = document.WithSyntaxRoot(newRoot)
End If
End If
End If
finalDocument.Project.Solution.Workspace.ApplyDocumentChanges(finalDocument, cancellationToken)
End Using
End Sub
Private Function GetCommitFormattingCleanupProvider(
document As Document,
spanToFormat As SnapshotSpan,
oldSnapshot As ITextSnapshot,
oldTree As SyntaxTree,
newDirtySpan As SnapshotSpan,
newTree As SyntaxTree,
cancellationToken As CancellationToken) As ICodeCleanupProvider
Dim oldDirtySpan = newDirtySpan.TranslateTo(oldSnapshot, SpanTrackingMode.EdgeInclusive)
' based on changes made to dirty spans, get right formatting rules to apply
Dim rules = GetFormattingRules(document, spanToFormat, oldDirtySpan, oldTree, newDirtySpan, newTree, cancellationToken)
Return New SimpleCodeCleanupProvider(PredefinedCodeCleanupProviderNames.Format,
Function(doc, spans, c) FormatAsync(doc, spans, rules, c),
Function(r, spans, w, c) Format(r, spans, w, rules, c))
End Function
Private Async Function FormatAsync(document As Document, spans As IEnumerable(Of TextSpan), rules As IEnumerable(Of IFormattingRule), cancellationToken As CancellationToken) As Task(Of Document)
' if old text already exist, use fast path for formatting
Dim oldText As SourceText = Nothing
If document.TryGetText(oldText) Then
Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
Dim newText = oldText.WithChanges(Formatter.GetFormattedTextChanges(root, spans, document.Project.Solution.Workspace, rules:=rules, cancellationToken:=cancellationToken))
Return document.WithText(newText)
End If
Return Await Formatter.FormatAsync(document, spans, options:=Nothing, rules:=rules, cancellationToken:=cancellationToken).ConfigureAwait(False)
End Function
Private Function Format(root As SyntaxNode, spans As IEnumerable(Of TextSpan), workspace As Workspace, rules As IEnumerable(Of IFormattingRule), cancellationToken As CancellationToken) As SyntaxNode
' if old text already exist, use fast path for formatting
Dim oldText As SourceText = Nothing
If root.SyntaxTree IsNot Nothing AndAlso root.SyntaxTree.TryGetText(oldText) Then
Dim changes = Formatter.GetFormattedTextChanges(root, spans, workspace, rules:=rules, cancellationToken:=cancellationToken)
' no change
If changes.Count = 0 Then
Return root
End If
Return root.SyntaxTree.WithChangedText(oldText.WithChanges(changes)).GetRoot(cancellationToken)
End If
Return Formatter.Format(root, spans, workspace, options:=Nothing, rules:=rules, cancellationToken:=cancellationToken)
End Function
Private Function GetFormattingRules(
document As Document,
spanToFormat As SnapshotSpan,
oldDirtySpan As SnapshotSpan,
oldTree As SyntaxTree,
newDirtySpan As SnapshotSpan,
newTree As SyntaxTree,
cancellationToken As CancellationToken) As IEnumerable(Of IFormattingRule)
' if the span we are going to format is same as the span that got changed, don't bother to do anything special.
' just do full format of the span.
If spanToFormat = newDirtySpan Then
Return Formatter.GetDefaultFormattingRules(document)
End If
If oldTree Is Nothing OrElse newTree Is Nothing Then
Return Formatter.GetDefaultFormattingRules(document)
End If
' TODO: remove this in dev14
'
' workaround for VB razor case.
' if we are under VB razor, we always use anchor operation otherwise, due to our double formatting, everything will just get messed.
' this is really a hacky workaround we should remove this in dev14
Dim formattingRuleService = document.Project.Solution.Workspace.Services.GetService(Of IHostDependentFormattingRuleFactoryService)()
If formattingRuleService IsNot Nothing Then
If formattingRuleService.ShouldUseBaseIndentation(document) Then
Return Formatter.GetDefaultFormattingRules(document)
End If
End If
' when commit formatter formats given span, it formats the span with or without anchor operations.
' the way we determine which formatting rules are used for the span is based on whether the region user has changed would change indentation
' following the dirty (committed) region. if indentation has changed, we will format with anchor operations. if not, we will format without anchor operations.
'
' for example, for the code below
'[ ]|If True And
' False Then|
' Dim a = 1
' if the [] is changed, when line commit runs, it sees indentation right after the commit (|If .. Then|) is same, so formatter will run without anchor operations,
' meaning, "False Then" will stay as it is even if "If True And" is moved due to change in []
'
' if the [] is changed to
'[ If True Then
' ]|If True And
' False Then|
' Dim a = 1
' when line commit runs, it sees that indentation after the commit is changed (due to inserted "If True Then"), so formatter runs with anchor operations,
' meaning, "False Then" will move along with "If True And"
'
' for now, do very simple checking. basically, we see whether we get same number of indent operation for the give span. alternative, but little bit
' more expensive and complex, we can actually calculate indentation right after the span, and see whether that is changed. not sure whether that much granularity
' is needed.
If GetNumberOfIndentOperations(document, oldTree, oldDirtySpan, cancellationToken) =
GetNumberOfIndentOperations(document, newTree, newDirtySpan, cancellationToken) Then
Return (New NoAnchorFormatterRule()).Concat(Formatter.GetDefaultFormattingRules(document))
End If
Return Formatter.GetDefaultFormattingRules(document)
End Function
Private Function GetNumberOfIndentOperations(document As Document,
syntaxTree As SyntaxTree,
span As SnapshotSpan,
cancellationToken As CancellationToken) As Integer
Dim vbTree = syntaxTree
' find containing statement of the end point, and use its end point as position to get indent operation
Dim containingStatement = ContainingStatementInfo.GetInfo(span.End, vbTree, cancellationToken)
Dim endPosition = If(containingStatement Is Nothing, span.End.Position + 1, containingStatement.TextSpan.End + 1)
' get token right after given span
Dim token = vbTree.GetRoot(cancellationToken).FindToken(Math.Min(endPosition, syntaxTree.GetRoot(cancellationToken).FullSpan.End))
Dim node = token.Parent
Dim optionSet = document.Project.Solution.Workspace.Options
' collect all indent operation
Dim operations = New List(Of IndentBlockOperation)()
While node IsNot Nothing
operations.AddRange(FormattingOperations.GetIndentBlockOperations(Formatter.GetDefaultFormattingRules(document), node, optionSet))
node = node.Parent
End While
' get number of indent operation that affects the token.
Return operations.Where(Function(o) o.TextSpan.Contains(token.SpanStart)).Count()
End Function
Private Class NoAnchorFormatterRule
Inherits AbstractFormattingRule
Public Overrides Sub AddAnchorIndentationOperations(list As List(Of AnchorIndentationOperation), node As SyntaxNode, optionSet As OptionSet, nextOperation As NextAction(Of AnchorIndentationOperation))
' no anchor/relative formatting
Return
End Sub
End Class
End Class
End Namespace
|
ManishJayaswal/roslyn
|
src/EditorFeatures/VisualBasic/LineCommit/CommitFormatter.vb
|
Visual Basic
|
apache-2.0
| 13,327
|
' 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.Reflection.Metadata
Imports System.Reflection.Metadata.Ecma335
Imports System.Runtime.CompilerServices
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.MetadataUtilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class EditAndContinueTestBase
Inherits BasicTestBase
' PDB reader can only be accessed from a single thread, so avoid concurrent compilation:
Protected Shared ReadOnly ComSafeDebugDll As VisualBasicCompilationOptions = TestOptions.DebugDll.WithConcurrentBuild(False)
Friend Shared ReadOnly EmptyLocalsProvider As Func(Of MethodDefinitionHandle, EditAndContinueMethodDebugInformation) = Function(token) Nothing
Friend Shared Function MarkedSource(source As XElement, Optional fileName As String = "", Optional options As VisualBasicParseOptions = Nothing) As SourceWithMarkedNodes
Return New SourceWithMarkedNodes(source.Value, Function(s) Parse(s, fileName, options), Function(s) CInt(GetType(SyntaxKind).GetField(s).GetValue(Nothing)))
End Function
Friend Shared Function MarkedSource(source As String, Optional fileName As String = "", Optional options As VisualBasicParseOptions = Nothing) As SourceWithMarkedNodes
Return New SourceWithMarkedNodes(source, Function(s) Parse(s, fileName, options), Function(s) CInt(GetType(SyntaxKind).GetField(s).GetValue(Nothing)))
End Function
Friend Shared Function GetSyntaxMapFromMarkers(source0 As SourceWithMarkedNodes, source1 As SourceWithMarkedNodes) As Func(Of SyntaxNode, SyntaxNode)
Return SourceWithMarkedNodes.GetSyntaxMap(source0, source1)
End Function
Friend Function ToLocalInfo(local As Cci.ILocalDefinition) As ILVisualizer.LocalInfo
Dim signature = local.Signature
If signature Is Nothing Then
Return New ILVisualizer.LocalInfo(local.Name, local.Type, local.IsPinned, local.IsReference)
Else
' Decode simple types only.
Dim typeName = If(signature.Length = 1, GetTypeName(CType(signature(0), SignatureTypeCode)), Nothing)
Return New ILVisualizer.LocalInfo(Nothing, If(typeName, "[unchanged]"), False, False)
End If
End Function
Private Function GetTypeName(typeCode As SignatureTypeCode) As String
Select Case typeCode
Case SignatureTypeCode.Boolean
Return "Boolean"
Case SignatureTypeCode.Int32
Return "Integer"
Case SignatureTypeCode.String
Return "String"
Case SignatureTypeCode.Object
Return "Object"
Case Else
Return Nothing
End Select
End Function
Friend Shared Function GetAllLocals(compilation As VisualBasicCompilation, method As MethodSymbol) As ImmutableArray(Of LocalSymbol)
Dim methodSyntax = method.DeclaringSyntaxReferences(0).GetSyntax().Parent
Dim model = compilation.GetSemanticModel(methodSyntax.SyntaxTree)
Dim locals = ArrayBuilder(Of LocalSymbol).GetInstance()
For Each node In methodSyntax.DescendantNodes()
If node.Kind = SyntaxKind.VariableDeclarator Then
For Each name In DirectCast(node, VariableDeclaratorSyntax).Names
Dim local = DirectCast(model.GetDeclaredSymbol(name), LocalSymbol)
locals.Add(local)
Next
End If
Next
Return locals.ToImmutableAndFree()
End Function
Friend Shared Function GetAllLocals(compilation As VisualBasicCompilation, method As IMethodSymbol) As ImmutableArray(Of KeyValuePair(Of ILocalSymbol, Integer))
Dim locals = GetAllLocals(compilation, DirectCast(method, MethodSymbol))
Return locals.SelectAsArray(Function(local, index, arg) New KeyValuePair(Of ILocalSymbol, Integer)(local, index), DirectCast(Nothing, Object))
End Function
Friend Shared Function GetAllLocals(method As SourceMethodSymbol) As ImmutableArray(Of VisualBasicSyntaxNode)
Dim names = From name In LocalVariableDeclaratorsCollector.GetDeclarators(method).OfType(Of ModifiedIdentifierSyntax)
Select DirectCast(name, VisualBasicSyntaxNode)
Return names.AsImmutableOrEmpty
End Function
Friend Shared Function GetLocalName(node As SyntaxNode) As String
If node.Kind = SyntaxKind.ModifiedIdentifier Then
Return DirectCast(node, ModifiedIdentifierSyntax).Identifier.ToString()
End If
Throw New NotImplementedException()
End Function
Friend Shared Function GetSyntaxMapByKind(method As MethodSymbol, ParamArray kinds As SyntaxKind()) As Func(Of SyntaxNode, SyntaxNode)
Return Function(node As SyntaxNode)
For Each k In kinds
If node.IsKind(k) Then
Return method.DeclaringSyntaxReferences.Single().SyntaxTree.GetRoot().DescendantNodes().Single(Function(n) n.IsKind(k))
End If
Next
Return Nothing
End Function
End Function
Friend Shared Function GetEquivalentNodesMap(method1 As MethodSymbol, method0 As MethodSymbol) As Func(Of SyntaxNode, SyntaxNode)
Dim tree1 = method1.Locations(0).SourceTree
Dim tree0 = method0.Locations(0).SourceTree
Assert.NotEqual(tree1, tree0)
Dim sourceMethod0 = DirectCast(method0, SourceMethodSymbol)
Dim locals0 = GetAllLocals(sourceMethod0)
Return Function(s As SyntaxNode)
Dim s1 = s
Assert.Equal(s1.SyntaxTree, tree1)
' add mapping for result variable (it's declarator is the Function Statement)
If s.IsKind(SyntaxKind.FunctionStatement) Then
Assert.True(sourceMethod0.BlockSyntax.BlockStatement.IsKind(SyntaxKind.FunctionStatement))
Return sourceMethod0.BlockSyntax.BlockStatement
ElseIf s.IsKind(SyntaxKind.PropertyStatement) Then
Assert.True(sourceMethod0.BlockSyntax.IsKind(SyntaxKind.GetAccessorBlock))
Return DirectCast(sourceMethod0.BlockSyntax.Parent, PropertyBlockSyntax).PropertyStatement
End If
For Each s0 In locals0
If Not SyntaxFactory.AreEquivalent(s0, s1) Then
Continue For
End If
' Make sure the containing statements are the same.
Dim p0 = GetNearestStatement(s0)
Dim p1 = GetNearestStatement(s1)
If SyntaxFactory.AreEquivalent(p0, p1) Then
Return s0
End If
Next
Return Nothing
End Function
End Function
Friend Shared Function GetNearestStatement(node As SyntaxNode) As StatementSyntax
While node IsNot Nothing
Dim statement = TryCast(node, StatementSyntax)
If statement IsNot Nothing Then
Return statement
End If
node = node.Parent
End While
Return Nothing
End Function
Friend Shared Function Row(rowNumber As Integer, table As TableIndex, operation As EditAndContinueOperation) As EditAndContinueLogEntry
Return New EditAndContinueLogEntry(MetadataTokens.Handle(table, rowNumber), operation)
End Function
Friend Shared Function Handle(rowNumber As Integer, table As TableIndex) As Handle
Return MetadataTokens.Handle(table, rowNumber)
End Function
Friend Shared Sub CheckEncLog(reader As MetadataReader, ParamArray rows As EditAndContinueLogEntry())
AssertEx.Equal(rows, reader.GetEditAndContinueLogEntries(), itemInspector:=AddressOf EncLogRowToString)
End Sub
Friend Shared Sub CheckEncLogDefinitions(reader As MetadataReader, ParamArray rows As EditAndContinueLogEntry())
AssertEx.Equal(rows, reader.GetEditAndContinueLogEntries().Where(Function(entry) IsDefinition(entry)), itemInspector:=AddressOf EncLogRowToString)
End Sub
Friend Shared Function IsDefinition(entry As EditAndContinueLogEntry) As Boolean
Dim index As TableIndex
Assert.True(MetadataTokens.TryGetTableIndex(entry.Handle.Kind, index))
Select Case index
Case TableIndex.MethodDef,
TableIndex.Field,
TableIndex.Constant,
TableIndex.GenericParam,
TableIndex.GenericParamConstraint,
TableIndex.[Event],
TableIndex.CustomAttribute,
TableIndex.DeclSecurity,
TableIndex.Assembly,
TableIndex.MethodImpl,
TableIndex.Param,
TableIndex.[Property],
TableIndex.TypeDef,
TableIndex.ExportedType,
TableIndex.StandAloneSig,
TableIndex.ClassLayout,
TableIndex.FieldLayout,
TableIndex.FieldMarshal,
TableIndex.File,
TableIndex.ImplMap,
TableIndex.InterfaceImpl,
TableIndex.ManifestResource,
TableIndex.MethodSemantics,
TableIndex.[Module],
TableIndex.NestedClass,
TableIndex.EventMap,
TableIndex.PropertyMap
Return True
End Select
Return False
End Function
Friend Shared Sub CheckEncMap(reader As MetadataReader, ParamArray [handles] As Handle())
AssertEx.Equal([handles], reader.GetEditAndContinueMapEntries(), itemInspector:=AddressOf EncMapRowToString)
End Sub
Friend Shared Sub CheckNames(reader As MetadataReader, [handles] As StringHandle(), ParamArray expectedNames As String())
CheckNames({reader}, [handles], expectedNames)
End Sub
Friend Shared Sub CheckNames(readers As MetadataReader(), [handles] As StringHandle(), ParamArray expectedNames As String())
Dim actualNames = readers.GetStrings([handles])
AssertEx.Equal(expectedNames, actualNames)
End Sub
Friend Shared Sub CheckNamesSorted(readers As MetadataReader(), [handles] As StringHandle(), ParamArray expectedNames As String())
Dim actualNames = readers.GetStrings([handles])
Array.Sort(actualNames)
Array.Sort(expectedNames)
AssertEx.Equal(expectedNames, actualNames)
End Sub
Friend Shared Function EncLogRowToString(row As EditAndContinueLogEntry) As String
Dim index As TableIndex = 0
MetadataTokens.TryGetTableIndex(row.Handle.Kind, index)
Return String.Format(
"Row({0}, TableIndex.{1}, EditAndContinueOperation.{2})",
MetadataTokens.GetRowNumber(row.Handle),
index,
row.Operation)
End Function
Friend Shared Function EncMapRowToString(handle As Handle) As String
Dim index As TableIndex = 0
MetadataTokens.TryGetTableIndex(handle.Kind, index)
Return String.Format(
"Handle({0}, TableIndex.{1})",
MetadataTokens.GetRowNumber(handle),
index)
End Function
End Class
Public Module EditAndContinueTestExtensions
<Extension>
Public Function WithSource(compilation As VisualBasicCompilation, newSource As String) As VisualBasicCompilation
Return compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(VisualBasicSyntaxTree.ParseText(newSource))
End Function
<Extension>
Public Function WithSource(compilation As VisualBasicCompilation, newSource As XElement) As VisualBasicCompilation
Return compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(ToSourceTrees(newSource))
End Function
<Extension>
Public Function WithSource(compilation As VisualBasicCompilation, newTree As SyntaxTree) As VisualBasicCompilation
Return compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(newTree)
End Function
End Module
End Namespace
|
1234-/roslyn
|
src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinueTestBase.vb
|
Visual Basic
|
apache-2.0
| 13,360
|
' 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.Reflection.Metadata
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Emit
Friend MustInherit Class NamedTypeReference
Implements Cci.INamedTypeReference
Protected ReadOnly m_UnderlyingNamedType As NamedTypeSymbol
Public Sub New(underlyingNamedType As NamedTypeSymbol)
Debug.Assert(underlyingNamedType IsNot Nothing)
Me.m_UnderlyingNamedType = underlyingNamedType
End Sub
Private ReadOnly Property INamedTypeReferenceGenericParameterCount As UShort Implements Cci.INamedTypeReference.GenericParameterCount
Get
Return CType(m_UnderlyingNamedType.Arity, UShort)
End Get
End Property
Private ReadOnly Property INamedTypeReferenceMangleName As Boolean Implements Cci.INamedTypeReference.MangleName
Get
Return m_UnderlyingNamedType.MangleName
End Get
End Property
Private ReadOnly Property INamedEntityName As String Implements Cci.INamedEntity.Name
Get
' CCI automatically handles type suffix, so use Name instead of MetadataName
Return m_UnderlyingNamedType.Name
End Get
End Property
Private ReadOnly Property ITypeReferenceIsEnum As Boolean Implements Cci.ITypeReference.IsEnum
Get
Return m_UnderlyingNamedType.TypeKind = TypeKind.Enum
End Get
End Property
Private ReadOnly Property ITypeReferenceIsValueType As Boolean Implements Cci.ITypeReference.IsValueType
Get
Return m_UnderlyingNamedType.IsValueType
End Get
End Property
Private Function ITypeReferenceGetResolvedType(context As EmitContext) As Cci.ITypeDefinition Implements Cci.ITypeReference.GetResolvedType
Return Nothing
End Function
Private ReadOnly Property ITypeReferenceTypeCode As Cci.PrimitiveTypeCode Implements Cci.ITypeReference.TypeCode
Get
Return Cci.PrimitiveTypeCode.NotPrimitive
End Get
End Property
Private ReadOnly Property ITypeReferenceTypeDef As TypeDefinitionHandle Implements Cci.ITypeReference.TypeDef
Get
Return Nothing
End Get
End Property
Private ReadOnly Property ITypeReferenceAsGenericMethodParameterReference As Cci.IGenericMethodParameterReference Implements Cci.ITypeReference.AsGenericMethodParameterReference
Get
Return Nothing
End Get
End Property
Public MustOverride ReadOnly Property AsGenericTypeInstanceReference As Cci.IGenericTypeInstanceReference Implements Cci.ITypeReference.AsGenericTypeInstanceReference
Private ReadOnly Property ITypeReferenceAsGenericTypeParameterReference As Cci.IGenericTypeParameterReference Implements Cci.ITypeReference.AsGenericTypeParameterReference
Get
Return Nothing
End Get
End Property
Private Function ITypeReferenceAsNamespaceTypeDefinition(context As EmitContext) As Cci.INamespaceTypeDefinition Implements Cci.ITypeReference.AsNamespaceTypeDefinition
Return Nothing
End Function
Public MustOverride ReadOnly Property AsNamespaceTypeReference As Cci.INamespaceTypeReference Implements Cci.ITypeReference.AsNamespaceTypeReference
Private Function ITypeReferenceAsNestedTypeDefinition(context As EmitContext) As Cci.INestedTypeDefinition Implements Cci.ITypeReference.AsNestedTypeDefinition
Return Nothing
End Function
Public MustOverride ReadOnly Property AsNestedTypeReference As Cci.INestedTypeReference Implements Cci.ITypeReference.AsNestedTypeReference
Public MustOverride ReadOnly Property AsSpecializedNestedTypeReference As Cci.ISpecializedNestedTypeReference Implements Cci.ITypeReference.AsSpecializedNestedTypeReference
Private Function ITypeReferenceAsTypeDefinition(context As EmitContext) As Cci.ITypeDefinition Implements Cci.ITypeReference.AsTypeDefinition
Return Nothing
End Function
Public Overrides Function ToString() As String
Return m_UnderlyingNamedType.ToString()
End Function
Private Function IReferenceAttributes(context As EmitContext) As IEnumerable(Of Cci.ICustomAttribute) Implements Cci.IReference.GetAttributes
Return SpecializedCollections.EmptyEnumerable(Of Cci.ICustomAttribute)()
End Function
Public MustOverride Sub Dispatch(visitor As Cci.MetadataVisitor) Implements Cci.IReference.Dispatch
Private Function IReferenceAsDefinition(context As EmitContext) As Cci.IDefinition Implements Cci.IReference.AsDefinition
Return Nothing
End Function
End Class
End Namespace
|
mmitche/roslyn
|
src/Compilers/VisualBasic/Portable/Emit/NamedTypeReference.vb
|
Visual Basic
|
apache-2.0
| 5,146
|
' 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.UnitTests.FindReferences
Partial Public Class FindReferencesTests
<WorkItem(542553)>
<Fact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Sub TestAnonymousType1()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System
Module Program
Sub Main(args As String())
Dim namedCust = New With {.[|$${|Definition:Name|}|] = "Blue Yonder Airlines",
.City = "Snoqualmie"}
Dim product = New With {Key.Name = "paperclips", .Price = 1.29}
End Sub
End Module
</Document>
</Project>
</Workspace>
Test(input)
End Sub
<WorkItem(542553)>
<Fact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Sub TestAnonymousType2()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System
Module Program
Sub Main(args As String())
Dim namedCust = New With {.Name = "Blue Yonder Airlines",
.City = "Snoqualmie"}
Dim product = New With {Key.[|$${|Definition:Name|}|] = "paperclips", .Price = 1.29}
End Sub
End Module
</Document>
</Project>
</Workspace>
Test(input)
End Sub
<WorkItem(542553)>
<Fact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Sub TestAnonymousType3()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System
Module Program
Sub Main(args As String())
Dim namedCust1 = New With {.[|$${|Definition:Name|}|] = "Blue Yonder Airlines",
.City = "Snoqualmie"}
Dim namedCust2 = New With {.[|Name|] = "Blue Yonder Airlines",
.City = "Snoqualmie"}
Dim product = New With {Key.Name = "paperclips", .Price = 1.29}
End Sub
End Module
</Document>
</Project>
</Workspace>
Test(input)
End Sub
<WorkItem(542553)>
<Fact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Sub TestAnonymousType4()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System
Module Program
Sub Main(args As String())
Dim namedCust1 = New With {.[|Name|] = "Blue Yonder Airlines",
.City = "Snoqualmie"}
Dim namedCust2 = New With {.{|Definition:[|$$Name|]|} = "Blue Yonder Airlines",
.City = "Snoqualmie"}
Dim product = New With {Key.Name = "paperclips", .Price = 1.29}
End Sub
End Module
</Document>
</Project>
</Workspace>
Test(input)
End Sub
<WorkItem(542705)>
<Fact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Sub TestAnonymousType5()
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class Program1
Shared str As String = "abc"
Shared Sub Main(args As String())
Dim employee08 = New With {.[|$${|Definition:Category|}|] = Category(str), Key.Name = 2 + 1}
Dim employee01 = New With {Key.Category = 2 + 1, Key.Name = "Bob"}
End Sub
Shared Function Category(str As String)
Category = str
End Function
End Class
</Document>
</Project>
</Workspace>
Test(input)
End Sub
End Class
End Namespace
|
droyad/roslyn
|
src/EditorFeatures/Test2/FindReferences/FindReferencesTests.AnonymousTypeSymbols.vb
|
Visual Basic
|
apache-2.0
| 3,974
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rPedidos_Numeros"
'-------------------------------------------------------------------------------------------'
Partial Class rPedidos_Numeros
Inherits vis2Formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0))
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0))
Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2))
Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2))
Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3))
Dim lcParametro4Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4))
Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3))
Dim lcParametro5Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5))
Dim lcParametro5Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(5))
Dim lcParametro6Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(6))
Dim lcParametro6Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(6))
Dim lcParametro7Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(7))
Dim lcParametro7Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(7))
Dim lcParametro8Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(8))
Dim lcParametro8Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(8))
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim loConsulta As New StringBuilder()
loConsulta.AppendLine("SELECT Pedidos.Documento, ")
loConsulta.AppendLine(" Pedidos.Status, ")
loConsulta.AppendLine(" Pedidos.Fec_Ini, ")
loConsulta.AppendLine(" Pedidos.Fec_Fin, ")
loConsulta.AppendLine(" Pedidos.Cod_Cli, ")
loConsulta.AppendLine(" Clientes.Nom_Cli, ")
loConsulta.AppendLine(" Pedidos.Cod_Ven, ")
loConsulta.AppendLine(" Pedidos.Cod_Tra, ")
loConsulta.AppendLine(" Pedidos.Mon_Imp1, ")
loConsulta.AppendLine(" Pedidos.Control, ")
loConsulta.AppendLine(" Pedidos.Mon_Net, ")
loConsulta.AppendLine(" Pedidos.Mon_Bru ")
loConsulta.AppendLine("FROM Pedidos ")
loConsulta.AppendLine(" JOIN Clientes ON Clientes.Cod_Cli = Pedidos.Cod_Cli")
loConsulta.AppendLine("WHERE Pedidos.Documento BETWEEN " & lcParametro0Desde)
loConsulta.AppendLine(" AND " & lcParametro0Hasta)
loConsulta.AppendLine(" AND Pedidos.Fec_Ini BETWEEN " & lcParametro1Desde)
loConsulta.AppendLine(" AND " & lcParametro1Hasta)
loConsulta.AppendLine(" AND Pedidos.Cod_Cli BETWEEN " & lcParametro2Desde)
loConsulta.AppendLine(" AND " & lcParametro2Hasta)
loConsulta.AppendLine(" AND Pedidos.Cod_Ven BETWEEN " & lcParametro3Desde)
loConsulta.AppendLine(" AND " & lcParametro3Hasta)
loConsulta.AppendLine(" AND Pedidos.Status IN (" & lcParametro4Desde & ")")
loConsulta.AppendLine(" AND Pedidos.Cod_Tra BETWEEN " & lcParametro5Desde)
loConsulta.AppendLine(" AND " & lcParametro5Hasta)
loConsulta.AppendLine(" AND Pedidos.Cod_Mon BETWEEN " & lcParametro5Desde)
loConsulta.AppendLine(" AND " & lcParametro5Hasta)
loConsulta.AppendLine(" AND Pedidos.Cod_mon BETWEEN " & lcParametro6Desde)
loConsulta.AppendLine(" AND " & lcParametro6Hasta)
loConsulta.AppendLine(" AND Pedidos.Cod_Rev between " & lcParametro7Desde)
loConsulta.AppendLine(" AND " & lcParametro7Hasta)
loConsulta.AppendLine(" AND Pedidos.Cod_Suc between " & lcParametro8Desde)
loConsulta.AppendLine(" AND " & lcParametro8Hasta)
loConsulta.AppendLine("ORDER BY " & lcOrdenamiento)
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loConsulta.ToString(), "curReportes")
'-------------------------------------------------------------------------------------------------------
' Verificando si el select (tabla nº0) trae registros
'-------------------------------------------------------------------------------------------------------
If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
"No se Encontraron Registros para los Parámetros Especificados. ", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
"350px", _
"200px")
End If
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rPedidos_Numeros", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrPedidos_Numeros.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo
'-------------------------------------------------------------------------------------------'
' JJD: 24/07/08: Codigo inicial
'-------------------------------------------------------------------------------------------'
' MVP: 04/08/08: Cambios para multi idioma, mensaje de error y clase padre. '
'-------------------------------------------------------------------------------------------'
' CMS: 14/05/09: Filtro “Revisión:” y se le agrego el filtro moneda. '
'-------------------------------------------------------------------------------------------'
' AAP: 30/06/09: Filtro “Sucursal:”. '
'-------------------------------------------------------------------------------------------'
' CMS: 10/08/09: Metodo de ordenamiento, verificacionde registros. '
'-------------------------------------------------------------------------------------------'
' RJG: 23/07/14: Ajuste en consulta (se eliminaron tablas innecesarias). Ajustes en interfaz'
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
rPedidos_Numeros.aspx.vb
|
Visual Basic
|
mit
| 9,048
|
Imports System.Runtime.InteropServices
Public Class SmartDepthSlotThru
Private Sub btnSmartDepthSlotThru_Click(sender As System.Object, e As System.EventArgs) Handles btnSmartDepthSlotThru.Click
Dim objApplication As SolidEdgeFramework.Application = Nothing
Dim objDraftDoc As SolidEdgeDraft.DraftDocument = Nothing
Dim objDimStyles As SolidEdgeFrameworkSupport.DimensionStyles = Nothing
Dim objTempStyle As SolidEdgeFrameworkSupport.DimensionStyle = Nothing
Dim objType As Type = Nothing
Dim strThroughSlot As String
Try
' Create/get the application with specific settings
objApplication = Marshal.GetActiveObject("SolidEdge.Application")
If objApplication Is Nothing Then
' Get the type from the Solid Edge ProgID
objType = Type.GetTypeFromProgID("SolidEdge.Application")
' Start Solid Edge
objApplication = Activator.CreateInstance(objType)
' Make Solid Edge visible
objApplication.Visible = True
End If
objDraftDoc = objApplication.ActiveDocument
'Get the DimensionsStyles collection object
objDimStyles = objDraftDoc.DimensionStyles
'Get reference to first DimStyle.
objTempStyle = objDimStyles(0)
'Set the smart depth for Through slot
objTempStyle.SmartDepthSlotThru = "THRU"
'Get the smart depth for Through slot
strThroughSlot = objTempStyle.SmartDepthSlotThru
If strThroughSlot <> "THRU" Then
MsgBox("Error in SmartDepthSlotThru property for dimension style.")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgeFrameworkSupport.DimensionStyle.SmartDepthSlotThru.vb
|
Visual Basic
|
mit
| 1,840
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:2.0.50727.3053
'
' 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", "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("Autorun_Processor.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
Friend ReadOnly Property autorun_processor() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("autorun processor", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property background() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("background", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property background_6() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("background 6", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property background_red_warn() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("background-red-warn", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property background1() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("background1", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property background7() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("background7", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property ball_green_hover() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("ball_green.hover", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property ball_green_normal_back() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("ball_green.normal.back", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property ball_red_hover() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("ball red hover", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property ball_red_norm() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("ball red norm", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property ball_yellow_hover() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("ball_yellow_hover", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property ball_yellow_normal() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("ball_yellow_normal", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property button_hover() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("button_hover", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property button_press() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("button_press", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property changepass() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("changepass", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property close_red_mousedown() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("close_red mousedown", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property close_red_mousehover() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("close_red mousehover", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property close_red_normal() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("close_red normal", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property Danger() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("Danger", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property form4_background() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("form4_background", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property green_close_hover() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("green_close_hover", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property green_close_normal() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("green_close_normal", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property green_close_press() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("green_close_press", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property main_window_yellow() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("main_window_yellow", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property mainnav() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("mainnav", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property minimize_mousedown() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("minimize_mousedown", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property minimize_mousehover() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("minimize_mousehover", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property minimize_normal() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("minimize_normal", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property name() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("name", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property off_mouse_hover() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("off mouse hover", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property off_normal() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("off normal", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property off_select() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("off-select", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property on_mouse_hover() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("on mouse hover", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property on_normal() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("on normal", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property on_selected() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("on selected", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property scan_hover() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("scan_hover", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property scan_hover1() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("scan_hover1", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property scan_normal() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("scan_normal", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property scan_normal1() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("scan_normal1", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property scan_pressed() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("scan_pressed", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property scan_pressed1() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("scan_pressed1", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property shutdown() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("shutdown", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property shutdownglow() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("shutdownglow", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property shutdownpress() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("shutdownpress", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property taskmgr() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("taskmgr", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property tool_button__click() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("tool_button_ click", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property tool_button_hover() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("tool_button_hover", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
Friend ReadOnly Property tool_button_norm() As System.Drawing.Bitmap
Get
Dim obj As Object = ResourceManager.GetObject("tool_button_norm", resourceCulture)
Return CType(obj,System.Drawing.Bitmap)
End Get
End Property
End Module
End Namespace
|
pratheeshrussell/Autorun-Processor
|
Autorun Processor/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 17,195
|
'------------------------------------------------------------------------------
' <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
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.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.Email.Client.My.MySettings
Get
Return Global.Email.Client.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
versidyne/email-client
|
Email Client/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,914
|
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports System.Collections.Immutable
Imports System.Linq
Namespace Design
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Public Class NameOfAnalyzer
Inherits DiagnosticAnalyzer
Public Shared ReadOnly Id As String = DiagnosticId.NameOf.ToDiagnosticId()
Public Const Title As String = "You should use nameof instead of the parameter string"
Public Const MessageFormat As String = "Use 'NameOf({0})' instead of specifying the parameter name."
Public Const Category As String = SupportedCategories.Design
Public Const Description As String = "The NameOf() operator should be used to specify the name of a parameter instead of a string literal as it produces code that is easier to refactor."
Protected Shared Rule As DiagnosticDescriptor = New DiagnosticDescriptor(
Id,
Title,
MessageFormat,
Category,
DiagnosticSeverity.Warning,
isEnabledByDefault:=True,
description:=Description,
helpLinkUri:=HelpLink.ForDiagnostic(DiagnosticId.NameOf))
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule)
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(LanguageVersion.VisualBasic14, AddressOf Analyzer, SyntaxKind.StringLiteralExpression)
End Sub
Private Sub Analyzer(context As SyntaxNodeAnalysisContext)
If (context.IsGenerated()) Then Return
Dim stringLiteral = DirectCast(context.Node, LiteralExpressionSyntax)
If String.IsNullOrWhiteSpace(stringLiteral?.Token.ValueText) Then Return
Dim parameters = GetParameters(stringLiteral)
If Not parameters.Any() Then Return
Dim attribute = stringLiteral.FirstAncestorOfType(Of AttributeSyntax)()
Dim method = TryCast(stringLiteral.FirstAncestorOfType(GetType(MethodBlockSyntax), GetType(ConstructorBlockSyntax)), MethodBlockBaseSyntax)
If attribute IsNot Nothing AndAlso method.BlockStatement.AttributeLists.Any(Function(a) a.Attributes.Contains(attribute)) Then Return
If Not AreEqual(stringLiteral, parameters) Then Return
Dim diag = Diagnostic.Create(Rule, stringLiteral.GetLocation(), stringLiteral.Token.Value)
context.ReportDiagnostic(diag)
End Sub
Private Function AreEqual(stringLiteral As LiteralExpressionSyntax, paramaters As SeparatedSyntaxList(Of ParameterSyntax)) As Boolean
Return paramaters.Any(Function(p) p.Identifier?.Identifier.ValueText = stringLiteral.Token.ValueText)
End Function
Public Function GetParameters(node As SyntaxNode) As SeparatedSyntaxList(Of ParameterSyntax)
Dim methodDeclaration = node.FirstAncestorOfType(Of MethodBlockSyntax)()
Dim parameters As SeparatedSyntaxList(Of ParameterSyntax)
If methodDeclaration IsNot Nothing Then
parameters = methodDeclaration.SubOrFunctionStatement.ParameterList.Parameters
Else
Dim constructorDeclaration = node.FirstAncestorOfType(Of ConstructorBlockSyntax)()
If constructorDeclaration IsNot Nothing Then
parameters = constructorDeclaration.SubNewStatement.ParameterList.Parameters
Else
Return New SeparatedSyntaxList(Of ParameterSyntax)()
End If
End If
Return parameters
End Function
End Class
End Namespace
|
eirielson/code-cracker
|
src/VisualBasic/CodeCracker/Design/NameOfAnalyzer.vb
|
Visual Basic
|
apache-2.0
| 3,799
|
Public Class GrayData
Public data As Integer(,)
Public xDPI, yDPI As Integer
Public Sub New(width As Integer, height As Integer, xDPI As Integer, yDPI As Integer)
ReDim data(height - 1, width - 1)
Me.xDPI = xDPI
Me.yDPI = yDPI
End Sub
Default Public Property raw(y As Integer, x As Integer) As Integer
Get
Return data(y, x)
End Get
Set(value As Integer)
data(y, x) = value
End Set
End Property
Public ReadOnly Property Width As Integer
Get
Return data.GetUpperBound(1) + 1
End Get
End Property
Public ReadOnly Property Height As Integer
Get
Return data.GetUpperBound(0) + 1
End Get
End Property
Public Sub Average()
For y = 1 To Height - 1 - 1
For x = 1 To Width - 1 - 1
'If raw(y, x) <> 0 Then
Dim a As Integer = 0
a += data(y - 1, x - 1)
a += data(y - 1, x)
a += data(y - 1, x + 1)
a += data(y, x - 1)
a += data(y, x)
a += data(y, x + 1)
a += data(y + 1, x - 1)
a += data(y + 1, x)
a += data(y + 1, x + 1)
Dim b = a / 9
'If a <> 255 * 9 Then '周围不都是白色
' b = a / 12
'End If
If b > 255 Then
b = 255
End If
raw(y, x) = b
'End If
Next
Next
End Sub
Public Shared Function FromBitmap(bmp As Bitmap) As GrayData
Dim rd = RawData.FromBitmap(bmp)
Return FromRawData(rd)
End Function
Public Shared Function FromRawData(rd As RawData) As GrayData
Dim gr As New GrayData(rd.Width, rd.Height, rd.xDPI, rd.yDPI)
For y = 0 To rd.Height - 1
For x = 0 To rd.Width - 1
gr(y, x) = ImageProcessor.Gray(rd(y, x, 0), rd(y, x, 1), rd(y, x, 2))
Next
Next
Return gr
End Function
Public Function ToBitmap() As Bitmap
Dim rd = RawData.Create(Width, Height, xDPI, yDPI)
For y = 0 To rd.Height - 1
For x = 0 To rd.Width - 1
Dim a = data(y, x)
rd(y, x, 0) = a
rd(y, x, 1) = a
rd(y, x, 2) = a
Next
Next
Return rd.ToBitmap()
End Function
End Class
|
twd2/Project2
|
WTFKeyboard/GrayData.vb
|
Visual Basic
|
mit
| 2,527
|
' 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.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend NotInheritable Class InitializerSemanticModel
Inherits MemberSemanticModel
Private Sub New(root As VisualBasicSyntaxNode, binder As Binder, Optional parentSemanticModelOpt As SyntaxTreeSemanticModel = Nothing, Optional speculatedPosition As Integer = 0, Optional ignoreAccessibility As Boolean = False)
MyBase.New(root, binder, parentSemanticModelOpt, speculatedPosition, ignoreAccessibility)
End Sub
''' <summary>
''' Creates an InitializerSemanticModel that allows asking semantic questions about an initializer node.
''' </summary>
Friend Shared Function Create(binder As DeclarationInitializerBinder, Optional ignoreAccessibility As Boolean = False) As InitializerSemanticModel
Return New InitializerSemanticModel(binder.Root, binder, ignoreAccessibility:=ignoreAccessibility)
End Function
''' <summary>
''' Creates a speculative InitializerSemanticModel that allows asking semantic questions about an initializer node that did not appear in the original source code.
''' </summary>
Friend Shared Function CreateSpeculative(parentSemanticModel As SyntaxTreeSemanticModel, root As EqualsValueSyntax, binder As Binder, position As Integer) As InitializerSemanticModel
Debug.Assert(parentSemanticModel IsNot Nothing)
Debug.Assert(root IsNot Nothing)
Debug.Assert(binder IsNot Nothing)
Debug.Assert(binder.IsSemanticModelBinder)
Return New InitializerSemanticModel(root, binder, parentSemanticModel, position)
End Function
Friend Overrides Function Bind(binder As Binder, node As SyntaxNode, diagnostics As DiagnosticBag) As BoundNode
Debug.Assert(binder.IsSemanticModelBinder)
Dim boundInitializer As BoundNode = Nothing
Select Case node.Kind
Case SyntaxKind.FieldDeclaration
' get field symbol
If Me.MemberSymbol.Kind = SymbolKind.Field Then
Dim fieldSymbol = DirectCast(Me.MemberSymbol, SourceFieldSymbol)
boundInitializer = BindInitializer(binder, fieldSymbol.EqualsValueOrAsNewInitOpt, diagnostics)
Else
Dim propertySymbol = DirectCast(Me.MemberSymbol, SourcePropertySymbol)
Dim declSyntax As ModifiedIdentifierSyntax = DirectCast(propertySymbol.Syntax, ModifiedIdentifierSyntax)
Dim declarator = DirectCast(declSyntax.Parent, VariableDeclaratorSyntax)
Dim initSyntax As VisualBasicSyntaxNode = declarator.AsClause
If initSyntax Is Nothing OrElse initSyntax.Kind <> SyntaxKind.AsNewClause Then
initSyntax = declarator.Initializer
End If
boundInitializer = BindInitializer(binder, initSyntax, diagnostics)
End If
Case SyntaxKind.PropertyStatement
' get property symbol
Dim propertySymbol = DirectCast(Me.MemberSymbol, SourcePropertySymbol)
Dim declSyntax As PropertyStatementSyntax = DirectCast(propertySymbol.DeclarationSyntax, PropertyStatementSyntax)
Dim initSyntax As VisualBasicSyntaxNode = declSyntax.AsClause
If initSyntax Is Nothing OrElse initSyntax.Kind <> SyntaxKind.AsNewClause Then
initSyntax = declSyntax.Initializer
End If
boundInitializer = BindInitializer(binder, initSyntax, diagnostics)
Case SyntaxKind.Parameter
Dim parameterSyntax = DirectCast(node, ParameterSyntax)
boundInitializer = BindInitializer(binder, parameterSyntax.Default, diagnostics)
Case SyntaxKind.EnumMemberDeclaration
Dim enumSyntax = DirectCast(node, EnumMemberDeclarationSyntax)
boundInitializer = BindInitializer(binder, enumSyntax.Initializer, diagnostics)
Case SyntaxKind.EqualsValue, SyntaxKind.AsNewClause
boundInitializer = BindInitializer(binder, node, diagnostics)
End Select
If boundInitializer IsNot Nothing Then
Return boundInitializer
Else
Return MyBase.Bind(binder, node, diagnostics)
End If
End Function
Private Function BindInitializer(binder As Binder, initializer As SyntaxNode, diagnostics As DiagnosticBag) As BoundNode
Dim boundInitializer As BoundNode = Nothing
Select Case Me.MemberSymbol.Kind
Case SymbolKind.Field
' try to get enum field symbol
Dim enumFieldSymbol = TryCast(Me.MemberSymbol, SourceEnumConstantSymbol)
If enumFieldSymbol IsNot Nothing Then
Debug.Assert(initializer IsNot Nothing)
If initializer.Kind = SyntaxKind.EqualsValue Then
Dim enumSymbol = DirectCast(Me.MemberSymbol, SourceEnumConstantSymbol)
boundInitializer = binder.BindFieldAndEnumConstantInitializer(enumSymbol, DirectCast(initializer, EqualsValueSyntax), isEnum:=True, diagnostics:=diagnostics, constValue:=Nothing)
End If
Else
' get field symbol
Dim fieldSymbol = DirectCast(Me.MemberSymbol, SourceFieldSymbol)
Dim boundInitializers = ArrayBuilder(Of BoundInitializer).GetInstance
If initializer IsNot Nothing Then
' bind const and non const field initializers the same to get a bound expression back and not a constant value.
binder.BindFieldInitializer(ImmutableArray.Create(Of FieldSymbol)(fieldSymbol), initializer, boundInitializers, diagnostics, bindingForSemanticModel:=True)
Else
binder.BindArrayFieldImplicitInitializer(fieldSymbol, boundInitializers, diagnostics)
End If
boundInitializer = boundInitializers.First
boundInitializers.Free()
End If
Dim expressionInitializer = TryCast(boundInitializer, BoundExpression)
If expressionInitializer IsNot Nothing Then
Return New BoundFieldInitializer(initializer, ImmutableArray.Create(DirectCast(Me.MemberSymbol, FieldSymbol)), Nothing, expressionInitializer)
End If
Case SymbolKind.Property
' get property symbol
Dim propertySymbol = DirectCast(Me.MemberSymbol, PropertySymbol)
Dim boundInitializers = ArrayBuilder(Of BoundInitializer).GetInstance
binder.BindPropertyInitializer(ImmutableArray.Create(propertySymbol), initializer, boundInitializers, diagnostics)
boundInitializer = boundInitializers.First
boundInitializers.Free()
Dim expressionInitializer = TryCast(boundInitializer, BoundExpression)
If expressionInitializer IsNot Nothing Then
Return New BoundPropertyInitializer(initializer, ImmutableArray.Create(propertySymbol), Nothing, expressionInitializer)
End If
Case SymbolKind.Parameter
Debug.Assert(initializer IsNot Nothing)
If initializer.Kind = SyntaxKind.EqualsValue Then
Dim parameterSymbol = DirectCast(Me.RootBinder.ContainingMember, SourceComplexParameterSymbol)
boundInitializer = binder.BindParameterDefaultValue(parameterSymbol.Type, DirectCast(initializer, EqualsValueSyntax), diagnostics, constValue:=Nothing)
Dim expressionInitializer = TryCast(boundInitializer, BoundExpression)
If expressionInitializer IsNot Nothing Then
Return New BoundParameterEqualsValue(initializer, parameterSymbol, expressionInitializer)
End If
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(Me.MemberSymbol.Kind)
End Select
Return boundInitializer
End Function
Friend Overrides Function GetBoundRoot() As BoundNode
' In initializer the root bound node is sometimes not associated with Me.Root. Get the
' syntax that the root bound node should be associated with.
Dim rootSyntax = Me.Root
If rootSyntax.Kind = SyntaxKind.FieldDeclaration Then
Dim fieldSymbol = TryCast(Me.RootBinder.ContainingMember, SourceFieldSymbol)
If fieldSymbol IsNot Nothing Then
rootSyntax = If(fieldSymbol.EqualsValueOrAsNewInitOpt, fieldSymbol.Syntax)
Else
' 'WithEvents x As Y = ...'
Dim propertySymbol = TryCast(Me.RootBinder.ContainingMember, SourcePropertySymbol)
Debug.Assert(rootSyntax Is propertySymbol.DeclarationSyntax)
Dim propertyNameId = DirectCast(propertySymbol.Syntax, ModifiedIdentifierSyntax) ' serves as an assert
Dim declarator = DirectCast(propertyNameId.Parent, VariableDeclaratorSyntax) ' serves as an assert
Dim initSyntax As VisualBasicSyntaxNode = declarator.AsClause
If initSyntax Is Nothing OrElse initSyntax.Kind <> SyntaxKind.AsNewClause Then
initSyntax = declarator.Initializer
End If
If initSyntax IsNot Nothing Then
rootSyntax = initSyntax
End If
End If
ElseIf rootSyntax.Kind = SyntaxKind.PropertyStatement Then
Dim declSyntax As PropertyStatementSyntax = DirectCast(rootSyntax, PropertyStatementSyntax)
Dim initSyntax As VisualBasicSyntaxNode = declSyntax.AsClause
If initSyntax Is Nothing OrElse initSyntax.Kind <> SyntaxKind.AsNewClause Then
initSyntax = declSyntax.Initializer
End If
If initSyntax IsNot Nothing Then
rootSyntax = initSyntax
End If
End If
'TODO - Do parameters need to do anything here?
Return GetUpperBoundNode(rootSyntax)
End Function
Friend Overrides Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, initializer As EqualsValueSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
Dim binder = Me.GetEnclosingBinder(position)
If binder Is Nothing Then
speculativeModel = Nothing
Return False
End If
' wrap the binder with a Speculative binder
binder = SpeculativeBinder.Create(binder)
speculativeModel = CreateSpeculative(parentModel, initializer, binder, position)
Return True
End Function
Friend Overrides Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, statement As ExecutableStatementSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
speculativeModel = Nothing
Return False
End Function
Friend Overrides Function TryGetSpeculativeSemanticModelForMethodBodyCore(parentModel As SyntaxTreeSemanticModel, position As Integer, body As MethodBlockBaseSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
speculativeModel = Nothing
Return False
End Function
End Class
End Namespace
|
jkotas/roslyn
|
src/Compilers/VisualBasic/Portable/Binding/InitializerSemanticModel.vb
|
Visual Basic
|
apache-2.0
| 12,551
|
' 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.Diagnostics
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' A tuple of TypeParameterSymbol and DiagnosticInfo, created for errors
''' reported from ConstraintsHelper rather than creating Diagnostics directly.
''' This decouples constraints checking from syntax and Locations, and supports
''' callers that may want to create Location instances lazily or not at all.
''' </summary>
Friend Structure TypeParameterDiagnosticInfo
Public Sub New(typeParameter As TypeParameterSymbol, diagnostic As DiagnosticInfo)
Me.TypeParameter = typeParameter
Me.DiagnosticInfo = diagnostic
End Sub
Public Sub New(typeParameter As TypeParameterSymbol, constraint As TypeParameterConstraint, diagnostic As DiagnosticInfo)
Me.New(typeParameter, diagnostic)
Me.Constraint = constraint
End Sub
Public ReadOnly TypeParameter As TypeParameterSymbol
Public ReadOnly Constraint As TypeParameterConstraint
Public ReadOnly DiagnosticInfo As DiagnosticInfo
End Structure
<Flags()>
Friend Enum DirectConstraintConflictKind
None = 0
DuplicateTypeConstraint = 1 << 0
RedundantConstraint = 1 << 1
All = (1 << 2) - 1
End Enum
''' <summary>
''' Helper methods for generic type parameter constraints. There are two sets of methods: one
''' set for resolving constraint "bounds" (that is, determining the effective base type, interface set,
''' etc.), and another set for checking for constraint violations in type and method references.
'''
''' Bounds are resolved by calling one of the ResolveBounds overloads. Typically bounds are
''' resolved by each TypeParameterSymbol at, or before, one of the corresponding properties
''' (BaseType, Interfaces, etc.) is accessed. Resolving bounds may result in errors (cycles,
''' inconsistent constraints, etc.) and it is the responsibility of the caller to report any such
''' errors as declaration errors or use-site errors (depending on whether the type parameter
''' was from source or metadata) and to ensure bounds are resolved for source type parameters
''' even if the corresponding properties are never accessed directly.
'''
''' Constraints are checked by calling one of the CheckConstraints or CheckAllConstraints
''' overloads for any generic type or method reference from source. In some circumstances,
''' references are checked at the time the generic type or generic method is bound and constructed
''' by the Binder. In those case, it is sufficient to call one of the CheckConstraints overloads
''' since compound types (such as A(Of T).B(Of U) or A(Of B(Of T))) are checked incrementally
''' as each part is bound. In other cases however, constraint checking needs to be delayed to
''' prevent cycles where checking constraints requires binding the syntax that is currently
''' being bound (such as the constraint in Class C(Of T As C(Of T)). In those cases, the caller
''' must lazily check constraints, and since the types may be compound types, it is necessary
''' to call CheckAllConstraints.
''' </summary>
Friend Module ConstraintsHelper
''' <summary>
''' Enum used internally by RemoveDirectConstraintConflicts to
''' track what type constraint has been seen, to report conflicts
''' between { 'Structure', 'Class', [explicit type] }. The 'New'
''' constraint does not need to be tracked for those conflicts.
''' </summary>
Private Enum DirectTypeConstraintKind
None
ReferenceTypeConstraint
ValueTypeConstraint
ExplicitType
End Enum
''' <summary>
''' Return the constraints for the type parameter with any cycles
''' or conflicting constraints reported as errors and removed.
''' </summary>
<Extension()>
Public Function RemoveDirectConstraintConflicts(
typeParameter As TypeParameterSymbol,
constraints As ImmutableArray(Of TypeParameterConstraint),
inProgress As ConsList(Of TypeParameterSymbol),
reportConflicts As DirectConstraintConflictKind,
diagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo)) As ImmutableArray(Of TypeParameterConstraint)
If constraints.Length > 0 Then
Dim constraintsBuilder = ArrayBuilder(Of TypeParameterConstraint).GetInstance()
Dim containingSymbol = typeParameter.ContainingSymbol
Dim explicitKind = DirectTypeConstraintKind.None
Dim reportRedundantConstraints = (reportConflicts And DirectConstraintConflictKind.RedundantConstraint) <> 0
For Each constraint In constraints
' See Bindable::ValidateDirectConstraint.
Select Case constraint.Kind
Case TypeParameterConstraintKind.ReferenceType
If reportRedundantConstraints Then
If explicitKind = DirectTypeConstraintKind.None Then
explicitKind = DirectTypeConstraintKind.ReferenceTypeConstraint
Else
' Combinations of {Class, Structure} should have
' been caught and discarded during binding.
Debug.Assert(explicitKind = DirectTypeConstraintKind.ExplicitType)
' "'Class' constraint and a specific class type constraint cannot be combined."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter,
constraint,
ErrorFactory.ErrorInfo(ERRID.ERR_RefAndClassTypeConstrCombined)))
Continue For
End If
End If
Case TypeParameterConstraintKind.ValueType
If reportRedundantConstraints Then
If explicitKind = DirectTypeConstraintKind.None Then
explicitKind = DirectTypeConstraintKind.ValueTypeConstraint
Else
' Combinations of {Class, Structure} should have
' been caught and discarded during binding.
Debug.Assert(explicitKind = DirectTypeConstraintKind.ExplicitType)
' "'Structure' constraint and a specific class type constraint cannot be combined."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter,
constraint,
ErrorFactory.ErrorInfo(ERRID.ERR_ValueAndClassTypeConstrCombined)))
Continue For
End If
End If
Case TypeParameterConstraintKind.None
Dim constraintType = constraint.TypeConstraint
Dim duplicate As Boolean = ContainsTypeConstraint(constraintsBuilder, constraintType)
' Check for duplicate type constraints.
If duplicate Then
If (reportConflicts And DirectConstraintConflictKind.DuplicateTypeConstraint) <> 0 Then
' "Constraint type '{0}' already specified for this type parameter.'
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter,
constraint,
ErrorFactory.ErrorInfo(ERRID.ERR_ConstraintAlreadyExists1, constraintType)))
End If
' Continue with other checks for this constraint type, even
' though it's a duplicate, for consistency with Dev10.
End If
Select Case constraintType.TypeKind
Case TypeKind.Class
If reportRedundantConstraints Then
Select Case explicitKind
Case DirectTypeConstraintKind.None
Dim classType = DirectCast(constraintType, NamedTypeSymbol)
If classType.IsNotInheritable Then
' "Type constraint cannot be a 'NotInheritable' class."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter,
constraint,
ErrorFactory.ErrorInfo(ERRID.ERR_ClassConstraintNotInheritable1)))
Else
Select Case constraintType.SpecialType
Case SpecialType.System_Object,
SpecialType.System_ValueType,
SpecialType.System_Enum,
SpecialType.System_Delegate,
SpecialType.System_MulticastDelegate,
SpecialType.System_Array
' "'{0}' cannot be used as a type constraint."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter,
constraint,
ErrorFactory.ErrorInfo(ERRID.ERR_ConstraintIsRestrictedType1, constraintType)))
End Select
End If
explicitKind = DirectTypeConstraintKind.ExplicitType
Case DirectTypeConstraintKind.ReferenceTypeConstraint
' "'Class' constraint and a specific class type constraint cannot be combined."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter,
constraint,
ErrorFactory.ErrorInfo(ERRID.ERR_RefAndClassTypeConstrCombined)))
Continue For
Case DirectTypeConstraintKind.ValueTypeConstraint
' "'Structure' constraint and a specific class type constraint cannot be combined."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter,
constraint,
ErrorFactory.ErrorInfo(ERRID.ERR_ValueAndClassTypeConstrCombined)))
Continue For
Case DirectTypeConstraintKind.ExplicitType
' "Type parameter '{0}' can only have one constraint that is a class."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter,
constraint,
ErrorFactory.ErrorInfo(ERRID.ERR_MultipleClassConstraints1, typeParameter)))
Continue For
End Select
End If
Case TypeKind.Interface,
TypeKind.Error
Case TypeKind.Module
' No error reported for Module. If the type reference was in source, BC30371
' ERR_ModuleAsType1 will have been reported binding the type reference.
Case TypeKind.TypeParameter
Dim constraintTypeParameter = DirectCast(constraintType, TypeParameterSymbol)
If constraintTypeParameter.ContainingSymbol = containingSymbol Then
' The constraint type parameter is from the same containing type or method.
If inProgress.ContainsReference(constraintTypeParameter) Then
' "Type parameter '{0}' cannot be constrained to itself: {1}"
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(constraintTypeParameter,
constraint,
ErrorFactory.ErrorInfo(ERRID.ERR_ConstraintCycle2, constraintTypeParameter, GetConstraintCycleInfo(inProgress))))
Continue For
Else
' Traverse constraint type parameter constraints to detect cycles.
constraintTypeParameter.ResolveConstraints(inProgress)
End If
End If
If reportRedundantConstraints AndAlso constraintTypeParameter.HasValueTypeConstraint Then
' "Type parameter with a 'Structure' constraint cannot be used as a constraint."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(constraintTypeParameter,
constraint,
ErrorFactory.ErrorInfo(ERRID.ERR_TypeParamWithStructConstAsConst)))
Continue For
End If
Case TypeKind.Array,
TypeKind.Delegate,
TypeKind.Enum,
TypeKind.Structure
If reportRedundantConstraints Then
' "Type constraint '{0}' must be either a class, interface or type parameter."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter,
constraint,
ErrorFactory.ErrorInfo(ERRID.ERR_ConstNotClassInterfaceOrTypeParam1, constraintType)))
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(constraintType.TypeKind)
End Select
If duplicate Then
Continue For
End If
End Select
constraintsBuilder.Add(constraint)
Next
If constraintsBuilder.Count <> constraints.Length Then
constraints = constraintsBuilder.ToImmutable()
End If
constraintsBuilder.Free()
End If
Return constraints
End Function
' Currently, this method should be called for SourceTypeParameterSymbols
' only, not PETypeParameterSymbols. If that changes, and this method is
' called for type parameters from metadata, we need to ensure a use-site
' error is generated if conflicts are found. Add a unit test if that's the case.
' See Bindable::ValidateIndirectConstraints.
<Extension()>
Public Sub ReportIndirectConstraintConflicts(
typeParameter As SourceTypeParameterSymbol,
diagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo),
<[In], Out> ByRef useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo))
Dim constraints = ArrayBuilder(Of TypeParameterAndConstraint).GetInstance()
typeParameter.GetAllConstraints(constraints, fromConstraintOpt:=Nothing)
Dim n = constraints.Count
For i = 0 To n - 1
Dim pair1 = constraints(i)
If pair1.IsBad Then
Continue For
End If
For j = i + 1 To n - 1
Dim pair2 = constraints(j)
If pair2.IsBad Then
Continue For
End If
Dim bad = False
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
If (pair1.TypeParameter Is typeParameter) AndAlso (pair2.TypeParameter Is typeParameter) Then
' Check direct constraints to handle inherited constraints on overridden methods.
If HasConflict(pair1.Constraint, pair2.Constraint, useSiteDiagnostics) Then
' "Constraint '{0}' conflicts with the constraint '{1}' already specified for type parameter '{2}'."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter,
pair2.Constraint,
ErrorFactory.ErrorInfo(
ERRID.ERR_ConflictingDirectConstraints3,
pair2.Constraint.ToDisplayFormat(),
pair1.Constraint.ToDisplayFormat(),
typeParameter)))
bad = True
End If
ElseIf (pair1.TypeParameter Is pair2.TypeParameter) Then
' Skip other cases where both constraints are from the same type
' parameter but not the current type parameter since those cases
' will be reported directly on the other type parameter.
ElseIf HasConflict(pair1.Constraint, pair2.Constraint, useSiteDiagnostics) Then
If pair1.TypeParameter Is typeParameter Then
' "Constraint '{0}' conflicts with the indirect constraint '{1}' obtained from the type parameter constraint '{2}'."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter,
pair1.Constraint,
ErrorFactory.ErrorInfo(
ERRID.ERR_ConstraintClashDirectIndirect3,
pair1.Constraint.ToDisplayFormat(),
pair2.Constraint.ToDisplayFormat(),
pair2.TypeParameter)))
bad = True
ElseIf pair2.TypeParameter Is typeParameter Then
' "Indirect constraint '{0}' obtained from the type parameter constraint '{1}' conflicts with the constraint '{2}'."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter,
pair1.Constraint,
ErrorFactory.ErrorInfo(
ERRID.ERR_ConstraintClashIndirectDirect3,
pair1.Constraint.ToDisplayFormat(),
pair1.TypeParameter,
pair2.Constraint.ToDisplayFormat())))
bad = True
Else
' "Indirect constraint '{0}' obtained from the type parameter constraint '{1}' conflicts with the indirect constraint '{2}' obtained from the type parameter constraint '{3}'."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter,
pair2.Constraint,
ErrorFactory.ErrorInfo(
ERRID.ERR_ConstraintClashIndirectIndirect4,
pair2.Constraint.ToDisplayFormat(),
pair2.TypeParameter,
pair1.Constraint.ToDisplayFormat(),
pair1.TypeParameter)))
bad = True
End If
End If
If AppendUseSiteDiagnostics(useSiteDiagnostics, typeParameter, useSiteDiagnosticsBuilder) Then
bad = True
End If
If bad Then
constraints(j) = pair2.ToBad()
End If
Next
Next
constraints.Free()
End Sub
<Extension()>
Public Sub CheckAllConstraints(
type As TypeSymbol,
loc As Location,
diagnostics As DiagnosticBag)
Dim diagnosticsBuilder = ArrayBuilder(Of TypeParameterDiagnosticInfo).GetInstance()
Dim useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo) = Nothing
type.CheckAllConstraints(diagnosticsBuilder, useSiteDiagnosticsBuilder)
If useSiteDiagnosticsBuilder IsNot Nothing Then
diagnosticsBuilder.AddRange(useSiteDiagnosticsBuilder)
End If
For Each diagnostic In diagnosticsBuilder
diagnostics.Add(diagnostic.DiagnosticInfo, loc)
Next
diagnosticsBuilder.Free()
End Sub
''' <summary>
''' Check all generic constraints on the given type and any containing types
''' (such as A(Of T) in A(Of T).B(Of U)). This includes checking constraints
''' on generic types within the type (such as B(Of T) in A(Of B(Of T)())).
''' </summary>
<Extension()>
Public Sub CheckAllConstraints(
type As TypeSymbol,
diagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo),
<[In], Out> ByRef useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo))
Dim diagnostics As New CheckConstraintsDiagnosticsBuilders()
diagnostics.diagnosticsBuilder = diagnosticsBuilder
diagnostics.useSiteDiagnosticsBuilder = useSiteDiagnosticsBuilder
type.VisitType(s_checkConstraintsSingleTypeFunc, diagnostics)
useSiteDiagnosticsBuilder = diagnostics.useSiteDiagnosticsBuilder
End Sub
Private Class CheckConstraintsDiagnosticsBuilders
Public diagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo)
Public useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo)
End Class
Private ReadOnly s_checkConstraintsSingleTypeFunc As Func(Of TypeSymbol, CheckConstraintsDiagnosticsBuilders, Boolean) = AddressOf CheckConstraintsSingleType
Private Function CheckConstraintsSingleType(type As TypeSymbol, diagnostics As CheckConstraintsDiagnosticsBuilders) As Boolean
If type.Kind = SymbolKind.NamedType Then
DirectCast(type, NamedTypeSymbol).CheckConstraints(diagnostics.diagnosticsBuilder, diagnostics.useSiteDiagnosticsBuilder)
End If
Return False ' continue walking types
End Function
<Extension()>
Public Sub CheckConstraints(
tuple As TupleTypeSymbol,
syntaxNode As SyntaxNode,
elementLocations As ImmutableArray(Of Location),
diagnostics As DiagnosticBag)
Dim type As NamedTypeSymbol = tuple.TupleUnderlyingType
If Not RequiresChecking(type) Then
Return
End If
If syntaxNode.HasErrors Then
Return
End If
Dim diagnosticsBuilder = ArrayBuilder(Of TypeParameterDiagnosticInfo).GetInstance()
Dim underlyingTupleTypeChain = ArrayBuilder(Of NamedTypeSymbol).GetInstance
TupleTypeSymbol.GetUnderlyingTypeChain(type, underlyingTupleTypeChain)
Dim offset As Integer = 0
For Each underlyingTuple In underlyingTupleTypeChain
Dim useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo) = Nothing
CheckTypeConstraints(underlyingTuple, diagnosticsBuilder, useSiteDiagnosticsBuilder)
If useSiteDiagnosticsBuilder IsNot Nothing Then
diagnosticsBuilder.AddRange(useSiteDiagnosticsBuilder)
End If
For Each diagnostic In diagnosticsBuilder
Dim ordinal = diagnostic.TypeParameter.Ordinal
' If this is the TRest type parameter, we report it on
' the entire type syntax as it does not map to any tuple element.
Dim location = If(ordinal = TupleTypeSymbol.RestIndex, syntaxNode.Location, elementLocations(ordinal + offset))
diagnostics.Add(diagnostic.DiagnosticInfo, location)
Next
diagnosticsBuilder.Clear()
offset += TupleTypeSymbol.RestIndex
Next
underlyingTupleTypeChain.Free()
diagnosticsBuilder.Free()
End Sub
<Extension()>
Public Function CheckConstraintsForNonTuple(
type As NamedTypeSymbol,
typeArgumentsSyntax As SeparatedSyntaxList(Of TypeSyntax),
diagnostics As DiagnosticBag) As Boolean
Debug.Assert(Not type.IsTupleType)
Debug.Assert(typeArgumentsSyntax.Count = type.Arity)
If Not RequiresChecking(type) Then
Return True
End If
Dim diagnosticsBuilder = ArrayBuilder(Of TypeParameterDiagnosticInfo).GetInstance()
Dim useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo) = Nothing
Dim result = CheckTypeConstraints(type, diagnosticsBuilder, useSiteDiagnosticsBuilder)
If useSiteDiagnosticsBuilder IsNot Nothing Then
diagnosticsBuilder.AddRange(useSiteDiagnosticsBuilder)
End If
For Each diagnostic In diagnosticsBuilder
Dim ordinal = diagnostic.TypeParameter.Ordinal
Dim location = typeArgumentsSyntax(ordinal).GetLocation()
diagnostics.Add(diagnostic.DiagnosticInfo, location)
Next
diagnosticsBuilder.Free()
Return result
End Function
<Extension()>
Public Function CheckConstraints(
type As NamedTypeSymbol,
diagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo),
<[In], Out> ByRef useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo)) As Boolean
' We do not report element locations in method parameters and return types
' so we will simply unwrap the type if it was a tuple. We are relying on
' TypeSymbolExtensions.VisitType to dig into the "Rest" tuple so that they
' will be recursively unwrapped as well.
type = DirectCast(type.GetTupleUnderlyingTypeOrSelf(), NamedTypeSymbol)
If Not RequiresChecking(type) Then
Return True
End If
Return CheckTypeConstraints(type, diagnosticsBuilder, useSiteDiagnosticsBuilder)
End Function
<Extension()>
Public Function CheckConstraints(
method As MethodSymbol,
diagnosticLocation As Location,
diagnostics As DiagnosticBag) As Boolean
If Not RequiresChecking(method) Then
Return True
End If
Dim diagnosticsBuilder = ArrayBuilder(Of TypeParameterDiagnosticInfo).GetInstance()
Dim useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo) = Nothing
Dim result = CheckMethodConstraints(method, diagnosticsBuilder, useSiteDiagnosticsBuilder)
If useSiteDiagnosticsBuilder IsNot Nothing Then
diagnosticsBuilder.AddRange(useSiteDiagnosticsBuilder)
End If
For Each diagnostic In diagnosticsBuilder
diagnostics.Add(diagnostic.DiagnosticInfo, diagnosticLocation)
Next
diagnosticsBuilder.Free()
Return result
End Function
<Extension()>
Public Function CheckConstraints(
method As MethodSymbol,
diagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo),
<[In], Out> ByRef useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo)) As Boolean
If Not RequiresChecking(method) Then
Return True
End If
Return CheckMethodConstraints(method, diagnosticsBuilder, useSiteDiagnosticsBuilder)
End Function
Private Function CheckTypeConstraints(
type As NamedTypeSymbol,
diagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo),
<[In], Out> ByRef useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo)) As Boolean
Dim substitution = type.TypeSubstitution
Return CheckConstraints(type, substitution, type.OriginalDefinition.TypeParameters, type.TypeArgumentsNoUseSiteDiagnostics, diagnosticsBuilder, useSiteDiagnosticsBuilder)
End Function
Private Function CheckMethodConstraints(
method As MethodSymbol,
diagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo),
<[In], Out> ByRef useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo)) As Boolean
Dim substitution = DirectCast(method, SubstitutedMethodSymbol).TypeSubstitution
Return CheckConstraints(method, substitution, method.OriginalDefinition.TypeParameters, method.TypeArguments, diagnosticsBuilder, useSiteDiagnosticsBuilder)
End Function
''' <summary>
''' Check type parameters for the containing type or method symbol.
''' The type parameters are assumed to be the original definitions of type
''' parameters from the containing type or method, and the TypeSubstitution
''' instance is used for substituting type parameters within the constraints
''' of those type parameters, so the substitution should map from type
''' parameters to type arguments.
''' </summary>
<Extension()>
Public Function CheckConstraints(
constructedSymbol As Symbol,
substitution As TypeSubstitution,
typeParameters As ImmutableArray(Of TypeParameterSymbol),
typeArguments As ImmutableArray(Of TypeSymbol),
diagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo),
<[In], Out> ByRef useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo)) As Boolean
Debug.Assert(typeParameters.Length = typeArguments.Length)
Dim n = typeParameters.Length
Dim succeeded = True
For i = 0 To n - 1
Dim typeArgument = typeArguments(i)
Dim typeParameter = typeParameters(i)
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
If Not CheckConstraints(constructedSymbol, substitution, typeParameter, typeArgument, diagnosticsBuilder, useSiteDiagnostics) Then
succeeded = False
End If
If AppendUseSiteDiagnostics(useSiteDiagnostics, typeParameter, useSiteDiagnosticsBuilder) Then
succeeded = False
End If
Next
Return succeeded
End Function
Public Function CheckConstraints(
constructedSymbol As Symbol,
substitution As TypeSubstitution,
typeParameter As TypeParameterSymbol,
typeArgument As TypeSymbol,
diagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo),
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As Boolean
' The type parameters must be original definitions of type parameters from the containing symbol.
Debug.Assert(((constructedSymbol Is Nothing) AndAlso (substitution Is Nothing)) OrElse
(typeParameter.ContainingSymbol Is constructedSymbol.OriginalDefinition))
If typeArgument.IsErrorType() Then
Return True
End If
Dim succeeded = True
If typeArgument.IsRestrictedType() Then
If diagnosticsBuilder IsNot Nothing Then
' "'{0}' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter, ErrorFactory.ErrorInfo(ERRID.ERR_RestrictedType1, typeArgument)))
End If
succeeded = False
End If
If typeParameter.HasConstructorConstraint AndAlso Not SatisfiesConstructorConstraint(typeParameter, typeArgument, diagnosticsBuilder) Then
succeeded = False
End If
If typeParameter.HasReferenceTypeConstraint AndAlso Not SatisfiesReferenceTypeConstraint(typeParameter, typeArgument, diagnosticsBuilder) Then
succeeded = False
End If
If typeParameter.HasValueTypeConstraint AndAlso Not SatisfiesValueTypeConstraint(constructedSymbol, typeParameter, typeArgument, diagnosticsBuilder, useSiteDiagnostics) Then
succeeded = False
End If
' The type parameters for a constructed type/method are the type parameters of the ConstructedFrom
' type/method, so the constraint types are not substituted. For instance with "Class C(Of T As U, U)",
' the type parameter for T in "C(Of Object, Integer)" has constraint "U", not "Integer". We need to
' substitute the type parameter constraints from the original definition of the type parameters
' using the TypeSubstitution from the constructed type/method.
For Each t In typeParameter.ConstraintTypesWithDefinitionUseSiteDiagnostics(useSiteDiagnostics)
Dim constraintType = t.InternalSubstituteTypeParameters(substitution).Type
If Not SatisfiesTypeConstraint(typeArgument, constraintType, useSiteDiagnostics) Then
If diagnosticsBuilder IsNot Nothing Then
' "Type argument '{0}' does not inherit from or implement the constraint type '{1}'."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter, ErrorFactory.ErrorInfo(ERRID.ERR_GenericConstraintNotSatisfied2, typeArgument, constraintType)))
End If
succeeded = False
End If
Next
Return succeeded
End Function
Private Function AppendUseSiteDiagnostics(
useSiteDiagnostics As HashSet(Of DiagnosticInfo),
typeParameter As TypeParameterSymbol,
<[In], Out> ByRef useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo)
) As Boolean
If useSiteDiagnostics.IsNullOrEmpty Then
Return False
End If
If useSiteDiagnosticsBuilder Is Nothing Then
useSiteDiagnosticsBuilder = New ArrayBuilder(Of TypeParameterDiagnosticInfo)()
End If
For Each info In useSiteDiagnostics
Debug.Assert(info.Severity = DiagnosticSeverity.Error)
useSiteDiagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter, info))
Next
Return True
End Function
''' <summary>
''' Return the most derived type from the set of constraint types on this type
''' parameter and any type parameter it depends on. Returns Nothing if there
''' are no concrete constraint types. If there are multiple constraints, returns
''' the most derived, ignoring any subsequent constraints that are neither
''' more or less derived. This method assumes there are no constraint cycles.
''' </summary>
<Extension()>
Public Function GetNonInterfaceConstraint(typeParameter As TypeParameterSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As TypeSymbol
Dim result As TypeSymbol = Nothing
For Each constraint In typeParameter.ConstraintTypesWithDefinitionUseSiteDiagnostics(useSiteDiagnostics)
Dim candidate As TypeSymbol = Nothing
Select Case constraint.Kind
Case SymbolKind.ErrorType
Continue For
Case SymbolKind.TypeParameter
candidate = DirectCast(constraint, TypeParameterSymbol).GetNonInterfaceConstraint(useSiteDiagnostics)
Case Else
If Not constraint.IsInterfaceType() Then
candidate = constraint
End If
End Select
If result Is Nothing Then
result = candidate
ElseIf candidate IsNot Nothing Then
' Pick the most derived type
If result.IsClassType AndAlso Conversions.IsDerivedFrom(candidate, result, useSiteDiagnostics) Then
result = candidate
End If
End If
Next
Return result
End Function
''' <summary>
''' Return the most derived class type from the set of constraint types on this type
''' parameter and any type parameter it depends on. Returns Nothing if there are
''' no concrete constraint types. If there are multiple constraints, returns the most
''' derived, ignoring any subsequent constraints that are neither more or less derived.
''' This method assumes there are no constraint cycles. Unlike GetBaseConstraintType,
''' this method will always return a NamedTypeSymbol representing a class: returning
''' System.ValueType for value types, System.Array for arrays, and System.Enum for enums.
''' </summary>
<Extension()>
Public Function GetClassConstraint(typeParameter As TypeParameterSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As NamedTypeSymbol
Dim baseType = typeParameter.GetNonInterfaceConstraint(useSiteDiagnostics)
If baseType Is Nothing Then
Return Nothing
End If
Select Case baseType.TypeKind
Case TypeKind.Array,
TypeKind.Enum,
TypeKind.Structure
Return baseType.BaseTypeWithDefinitionUseSiteDiagnostics(useSiteDiagnostics)
Case Else
Debug.Assert(Not baseType.IsInterfaceType())
Debug.Assert(baseType.TypeKind <> TypeKind.TypeParameter)
Return DirectCast(baseType, NamedTypeSymbol)
End Select
End Function
''' <summary>
''' Populate the collection with all constraints for the type parameter, traversing
''' any constraints that are also type parameters. The result is a collection of type
''' and flag constraints, with no type parameter references. This method assumes
''' there are no constraint cycles.
''' </summary>
<Extension()>
Private Sub GetAllConstraints(
typeParameter As TypeParameterSymbol,
constraintsBuilder As ArrayBuilder(Of TypeParameterAndConstraint),
fromConstraintOpt As TypeParameterConstraint?)
Dim constraints = ArrayBuilder(Of TypeParameterConstraint).GetInstance()
typeParameter.GetConstraints(constraints)
For Each constraint In constraints
Dim type = constraint.TypeConstraint
If type IsNot Nothing Then
Select Case type.TypeKind
Case TypeKind.TypeParameter
' Add constraints from type parameter.
DirectCast(type, TypeParameterSymbol).GetAllConstraints(constraintsBuilder, If(fromConstraintOpt.HasValue, fromConstraintOpt.Value, constraint))
Continue For
Case TypeKind.Error
' Skip error types.
Continue For
End Select
End If
constraintsBuilder.Add(
If(fromConstraintOpt.HasValue,
New TypeParameterAndConstraint(DirectCast(fromConstraintOpt.Value.TypeConstraint, TypeParameterSymbol), constraint.AtLocation(fromConstraintOpt.Value.LocationOpt)),
New TypeParameterAndConstraint(typeParameter, constraint)))
Next
constraints.Free()
End Sub
''' <summary>
''' A tuple of type parameter and constraint type.
''' </summary>
Private Structure TypeParameterAndConstraint
Public Sub New(typeParameter As TypeParameterSymbol, constraint As TypeParameterConstraint, Optional isBad As Boolean = False)
Me.TypeParameter = typeParameter
Me.Constraint = constraint
Me.IsBad = isBad
End Sub
Public ReadOnly TypeParameter As TypeParameterSymbol
Public ReadOnly Constraint As TypeParameterConstraint
Public ReadOnly IsBad As Boolean
Public Function ToBad() As TypeParameterAndConstraint
Debug.Assert(Not IsBad)
Return New TypeParameterAndConstraint(TypeParameter, Constraint, True)
End Function
Public Overrides Function ToString() As String
Dim result = String.Format("{0} : {1}", TypeParameter, Constraint)
If IsBad Then
result = result & " (bad)"
End If
Return result
End Function
End Structure
Private Function SatisfiesTypeConstraint(
typeArgument As TypeSymbol,
constraintType As TypeSymbol,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As Boolean
If constraintType.IsErrorType() Then
constraintType.AddUseSiteDiagnostics(useSiteDiagnostics)
Return False
End If
Return Conversions.HasWideningDirectCastConversionButNotEnumTypeConversion(typeArgument, constraintType, useSiteDiagnostics)
End Function
' See Bindable::ValidateNewConstraintForType.
Private Function SatisfiesConstructorConstraint(
typeParameter As TypeParameterSymbol,
typeArgument As TypeSymbol,
diagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo)) As Boolean
Debug.Assert(typeParameter.HasConstructorConstraint)
Select Case typeArgument.TypeKind
Case TypeKind.Enum,
TypeKind.Structure
Return True
Case TypeKind.TypeParameter
If DirectCast(typeArgument, TypeParameterSymbol).HasConstructorConstraint OrElse typeArgument.IsValueType Then
Return True
Else
If diagnosticsBuilder IsNot Nothing Then
' "Type parameter '{0}' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter '{1}'."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter, ErrorFactory.ErrorInfo(ERRID.ERR_BadGenericParamForNewConstraint2, typeArgument, typeParameter)))
End If
Return False
End If
Case Else
If typeArgument.TypeKind = TypeKind.Class Then
Dim classType = DirectCast(typeArgument, NamedTypeSymbol)
If HasPublicParameterlessConstructor(classType) Then
If classType.IsMustInherit Then
If diagnosticsBuilder IsNot Nothing Then
' "Type argument '{0}' is declared 'MustInherit' and does not satisfy the 'New' constraint for type parameter '{1}'."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter, ErrorFactory.ErrorInfo(ERRID.ERR_MustInheritForNewConstraint2, typeArgument, typeParameter)))
End If
Return False
Else
Return True
End If
End If
End If
If diagnosticsBuilder IsNot Nothing Then
' "Type argument '{0}' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter '{1}'."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter, ErrorFactory.ErrorInfo(ERRID.ERR_NoSuitableNewForNewConstraint2, typeArgument, typeParameter)))
End If
Return False
End Select
End Function
' See Bindable::ValidateReferenceConstraintForType.
Private Function SatisfiesReferenceTypeConstraint(
typeParameter As TypeParameterSymbol,
typeArgument As TypeSymbol,
diagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo)) As Boolean
Debug.Assert((typeParameter Is Nothing) OrElse typeParameter.HasReferenceTypeConstraint)
If Not typeArgument.IsReferenceType Then
If diagnosticsBuilder IsNot Nothing Then
' "Type argument '{0}' does not satisfy the 'Class' constraint for type parameter '{1}'."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter, ErrorFactory.ErrorInfo(ERRID.ERR_BadTypeArgForRefConstraint2, typeArgument, typeParameter)))
End If
Return False
End If
Return True
End Function
' See Bindable::ValidateValueConstraintForType.
Private Function SatisfiesValueTypeConstraint(
constructedSymbol As Symbol,
typeParameter As TypeParameterSymbol,
typeArgument As TypeSymbol,
diagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo),
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As Boolean
Debug.Assert((typeParameter Is Nothing) OrElse typeParameter.HasValueTypeConstraint)
If Not typeArgument.IsValueType Then
If diagnosticsBuilder IsNot Nothing Then
Dim containingType = TryCast(constructedSymbol, TypeSymbol)
If (containingType IsNot Nothing) AndAlso containingType.IsNullableType() Then
' "Type '{0}' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter, ErrorFactory.ErrorInfo(ERRID.ERR_BadTypeArgForStructConstraintNull, typeArgument)))
Else
' "Type argument '{0}' does not satisfy the 'Structure' constraint for type parameter '{1}'."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter, ErrorFactory.ErrorInfo(ERRID.ERR_BadTypeArgForStructConstraint2, typeArgument, typeParameter)))
End If
End If
Return False
ElseIf IsNullableTypeOrTypeParameter(typeArgument, useSiteDiagnostics) Then
If diagnosticsBuilder IsNot Nothing Then
' "'System.Nullable' does not satisfy the 'Structure' constraint for type parameter '{0}'. Only non-nullable 'Structure' types are allowed."
diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter, ErrorFactory.ErrorInfo(ERRID.ERR_NullableDisallowedForStructConstr1, typeParameter)))
End If
Return False
End If
Return True
End Function
' See Bindable::ConstraintsConflict.
Private Function HasConflict(constraint1 As TypeParameterConstraint, constraint2 As TypeParameterConstraint, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As Boolean
Dim constraintType1 = constraint1.TypeConstraint
Dim constraintType2 = constraint2.TypeConstraint
If (constraintType1 IsNot Nothing) AndAlso (constraintType1.IsInterfaceType()) Then
Return False
End If
If (constraintType2 IsNot Nothing) AndAlso (constraintType2.IsInterfaceType()) Then
Return False
End If
If constraint1.IsValueTypeConstraint Then
If HasValueTypeConstraintConflict(constraint2, useSiteDiagnostics) Then
Return True
End If
ElseIf constraint2.IsValueTypeConstraint Then
If HasValueTypeConstraintConflict(constraint1, useSiteDiagnostics) Then
Return True
End If
End If
If constraint1.IsReferenceTypeConstraint Then
If HasReferenceTypeConstraintConflict(constraint2) Then
Return True
End If
ElseIf constraint2.IsReferenceTypeConstraint Then
If HasReferenceTypeConstraintConflict(constraint1) Then
Return True
End If
End If
If (constraintType1 IsNot Nothing) AndAlso
(constraintType2 IsNot Nothing) AndAlso
Not SatisfiesTypeConstraint(constraintType1, constraintType2, useSiteDiagnostics) AndAlso
Not SatisfiesTypeConstraint(constraintType2, constraintType1, useSiteDiagnostics) Then
Return True
End If
Return False
End Function
Private Function HasValueTypeConstraintConflict(constraint As TypeParameterConstraint, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As Boolean
Dim constraintType = constraint.TypeConstraint
If constraintType Is Nothing Then
Return False
End If
If SatisfiesValueTypeConstraint(constructedSymbol:=Nothing, typeParameter:=Nothing, typeArgument:=constraintType,
diagnosticsBuilder:=Nothing,
useSiteDiagnostics:=useSiteDiagnostics) Then
Return False
End If
Select Case constraintType.SpecialType
Case SpecialType.System_Object, SpecialType.System_ValueType
Return False
End Select
Return True
End Function
Private Function HasReferenceTypeConstraintConflict(constraint As TypeParameterConstraint) As Boolean
Dim constraintType = constraint.TypeConstraint
If constraintType Is Nothing Then
Return False
End If
If SatisfiesReferenceTypeConstraint(typeParameter:=Nothing, typeArgument:=constraintType, diagnosticsBuilder:=Nothing) Then
Return False
End If
Return True
End Function
Private Function IsNullableTypeOrTypeParameter(type As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As Boolean
If type.TypeKind = TypeKind.TypeParameter Then
Dim typeParameter = DirectCast(type, TypeParameterSymbol)
Dim constraintTypes = typeParameter.ConstraintTypesWithDefinitionUseSiteDiagnostics(useSiteDiagnostics)
For Each constraintType In constraintTypes
If IsNullableTypeOrTypeParameter(constraintType, useSiteDiagnostics) Then
Return True
End If
Next
Return False
Else
Return type.IsNullableType()
End If
End Function
Private Function GetConstraintCycleInfo(cycle As ConsList(Of TypeParameterSymbol)) As CompoundDiagnosticInfo
Debug.Assert(cycle.Any())
Dim previous As TypeParameterSymbol = Nothing
Dim builder = ArrayBuilder(Of DiagnosticInfo).GetInstance()
builder.Add(Nothing) ' Placeholder for first entry added later.
For Each typeParameter In cycle
If previous IsNot Nothing Then
builder.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ConstraintCycleLink2, typeParameter, previous))
End If
previous = typeParameter
Next
builder(0) = ErrorFactory.ErrorInfo(ERRID.ERR_ConstraintCycleLink2, cycle.Head, previous)
Dim diagnostics = builder.ToArrayAndFree()
Array.Reverse(diagnostics)
Return New CompoundDiagnosticInfo(diagnostics)
End Function
''' <summary>
''' Return true if the class type has a public parameterless constructor.
''' </summary>
Public Function HasPublicParameterlessConstructor(type As NamedTypeSymbol) As Boolean
type = type.OriginalDefinition
Debug.Assert(type.TypeKind = TypeKind.Class)
Dim sourceNamedType = TryCast(type, SourceNamedTypeSymbol)
If sourceNamedType IsNot Nothing AndAlso Not sourceNamedType.MembersHaveBeenCreated Then
' When we are dealing with group classes and synthetic entry points,
' we can end up here while we are building the set of members for the type.
' Using InstanceConstructors property will send us into an infinite loop.
Return sourceNamedType.InferFromSyntaxIfClassWillHavePublicParameterlessConstructor()
End If
For Each constructor In type.InstanceConstructors
If constructor.ParameterCount = 0 Then
Return constructor.DeclaredAccessibility = Accessibility.Public
End If
Next
Return False
End Function
''' <summary>
''' Return true if the constraints collection contains the given type constraint.
''' </summary>
Private Function ContainsTypeConstraint(constraints As ArrayBuilder(Of TypeParameterConstraint), constraintType As TypeSymbol) As Boolean
Debug.Assert(constraintType IsNot Nothing)
For Each constraint In constraints
Dim type = constraint.TypeConstraint
If (type IsNot Nothing) AndAlso constraintType.IsSameTypeIgnoringAll(type) Then
Return True
End If
Next
Return False
End Function
Private Function RequiresChecking(type As NamedTypeSymbol) As Boolean
If type.Arity = 0 Then
Return False
End If
' If type is the original definition, there is no need
' to check constraints. In the following for instance:
' Class A(Of T As Structure)
' Dim F As New A(Of T)()
' End Class
If type.OriginalDefinition Is type Then
Return False
End If
Debug.Assert(type.ConstructedFrom <> type)
Return True
End Function
Private Function RequiresChecking(method As MethodSymbol) As Boolean
If Not method.IsGenericMethod Then
Return False
End If
' If method is the original definition, there is no need
' to check constraints. In the following for instance:
' Sub M(Of T As Class)()
' M(Of T)()
' End Function
If method.OriginalDefinition Is method Then
Return False
End If
Debug.Assert(method.ConstructedFrom <> method)
Return True
End Function
End Module
End Namespace
|
mattscheffer/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/ConstraintsHelper.vb
|
Visual Basic
|
apache-2.0
| 62,849
|
' 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.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Base for synthesized Lambda methods.
''' Just provides a bunch of defaults
''' </summary>
Friend MustInherit Class SynthesizedMethod
Inherits SynthesizedMethodBase
Private ReadOnly _isShared As Boolean
Private ReadOnly _name As String
Private ReadOnly _syntaxNodeOpt As SyntaxNode
Friend Sub New(
syntaxNode As SyntaxNode,
containingSymbol As NamedTypeSymbol,
name As String,
isShared As Boolean
)
MyBase.New(containingSymbol)
Me._syntaxNodeOpt = syntaxNode
Me._isShared = isShared
Me._name = name
End Sub
Private Shared ReadOnly s_typeSubstitutionFactory As Func(Of Symbol, TypeSubstitution) =
Function(container) DirectCast(container, SynthesizedMethod).TypeMap
Friend Shared ReadOnly CreateTypeParameter As Func(Of TypeParameterSymbol, Symbol, TypeParameterSymbol) =
Function(typeParameter, container) New SynthesizedClonedTypeParameterSymbol(typeParameter, container, typeParameter.Name, s_typeSubstitutionFactory)
''' <summary>
''' Creates a clone of the local with a new containing symbol and type.
''' Note that the new parameter gets no syntaxRef as it is supposed to get
''' all the values it needs from the original parameter.
''' </summary>
Friend Shared Function WithNewContainerAndType(
newContainer As Symbol,
newType As TypeSymbol,
origParameter As ParameterSymbol) As ParameterSymbol
Dim flags As SourceParameterFlags = Nothing
If origParameter.IsByRef Then
flags = flags Or SourceParameterFlags.ByRef
Else
flags = flags Or SourceParameterFlags.ByVal
End If
If origParameter.IsParamArray Then
flags = flags Or SourceParameterFlags.ParamArray
End If
If origParameter.IsOptional Then
flags = flags Or SourceParameterFlags.Optional
End If
Return SourceComplexParameterSymbol.Create(
newContainer,
origParameter.Name,
origParameter.Ordinal,
newType,
origParameter.Locations.FirstOrDefault,
syntaxRef:=Nothing,
flags:=flags,
defaultValueOpt:=origParameter.ExplicitDefaultConstantValue)
End Function
Public Overrides ReadOnly Property Name As String
Get
Return _name
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return ImmutableArray(Of ParameterSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Dim type = ContainingAssembly.GetSpecialType(SpecialType.System_Void)
' WARN: We assume that if System_Void was not found we would never reach
' this point because the error should have been/processed generated earlier
Debug.Assert(type.GetUseSiteErrorInfo() Is Nothing)
Return type
End Get
End Property
Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))
MyBase.AddSynthesizedAttributes(compilationState, attributes)
Dim sourceType = TryCast(ContainingSymbol, SourceMemberContainerTypeSymbol)
' if parent is not from source, it must be a frame.
' frame is already marked as generated, no need to mark members.
If sourceType Is Nothing Then
Return
End If
' Attribute: System.Runtime.CompilerServices.CompilerGeneratedAttribute()
AddSynthesizedAttribute(attributes, sourceType.DeclaringCompilation.TrySynthesizeAttribute(
WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor))
End Sub
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.Public
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes
Get
Return Nothing
End Get
End Property
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverloads As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return _isShared
End Get
End Property
Public Overrides ReadOnly Property IsSub As Boolean
Get
Return ReturnType.IsVoidType()
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray(Of Location).Empty
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Dim node As SyntaxNode = Me.Syntax
Dim asLambda = TryCast(node, LambdaExpressionSyntax)
If asLambda IsNot Nothing Then
node = asLambda.SubOrFunctionHeader
Else
Dim asMethod = TryCast(node, MethodBlockBaseSyntax)
If asMethod IsNot Nothing Then
node = asMethod.BlockStatement
End If
End If
Return ImmutableArray.Create(Of SyntaxReference)(node.GetReference)
End Get
End Property
Public Overrides ReadOnly Property MethodKind As MethodKind
Get
Return MethodKind.Ordinary
End Get
End Property
Friend Overrides ReadOnly Property Syntax As SyntaxNode
Get
Return _syntaxNodeOpt
End Get
End Property
Friend Overridable ReadOnly Property TypeMap As TypeSubstitution
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
End Class
End Namespace
|
MattWindsor91/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedMethod.vb
|
Visual Basic
|
apache-2.0
| 7,782
|
' ****************************************************************
' This is free software licensed under the NUnit license. You
' may obtain a copy of the license as well as information regarding
' copyright ownership at http://nunit.org/?p=license&r=2.4.
' ****************************************************************
Option Explicit On
Imports System
Imports NUnit.Framework
Namespace NUnit.Samples
<TestFixture()> Public Class SimpleVBTest
Private fValue1 As Integer
Private fValue2 As Integer
Public Sub New()
MyBase.New()
End Sub
<SetUp()> Public Sub Init()
fValue1 = 2
fValue2 = 3
End Sub
<Test()> Public Sub Add()
Dim result As Double
result = fValue1 + fValue2
Assert.AreEqual(6, result)
End Sub
<Test()> Public Sub DivideByZero()
Dim zero As Integer
Dim result As Integer
zero = 0
result = 8 / zero
End Sub
<Test()> Public Sub TestEquals()
Assert.AreEqual(12, 12)
Assert.AreEqual(CLng(12), CLng(12))
Assert.AreEqual(12, 13, "Size")
Assert.AreEqual(12, 11.99, 0, "Capacity")
End Sub
<Test(), ExpectedException(GetType(Exception))> Public Sub ExpectAnException()
Throw New InvalidCastException()
End Sub
<Test(), Ignore("sample ignore")> Public Sub IgnoredTest()
' does not matter what we type the test is not run
Throw New ArgumentException()
End Sub
End Class
End Namespace
|
joshball/Lucene.In.Action.NET
|
vendor/lucene.net/lib/NUnit.org/NUnit/2.5.9/samples/vb/failures/SimpleVBTest.vb
|
Visual Basic
|
mit
| 1,643
|
Imports System.ServiceProcess
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Service1
Inherits System.ServiceProcess.ServiceBase
'UserService 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
' The main entry point for the process
<MTAThread()> _
<System.Diagnostics.DebuggerNonUserCode()> _
Shared Sub Main()
Dim ServicesToRun() As System.ServiceProcess.ServiceBase
' More than one NT Service may run within the same process. To add
' another service to this process, change the following line to
' create a second service object. For example,
'
' ServicesToRun = New System.ServiceProcess.ServiceBase () {New Service1, New MySecondUserService}
'
ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service1}
System.ServiceProcess.ServiceBase.Run(ServicesToRun)
End Sub
'Required by the Component Designer
Private components As System.ComponentModel.IContainer
' NOTE: The following procedure is required by the Component Designer
' It can be modified using the Component Designer.
' Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
components = New System.ComponentModel.Container()
Me.ServiceName = "Service1"
End Sub
End Class
|
evandixon/Sky-Editor
|
Sky Editor Service/Service1.Designer.vb
|
Visual Basic
|
mit
| 1,784
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.18051
'
' 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
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.HSPI_MEDIAPLAYER.My.MySettings
Get
Return Global.HSPI_MEDIAPLAYER.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
HomeSeer/HSPI_MEDIAPLAYER
|
My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,922
|
Imports WDMath
Imports System.ComponentModel
Imports WDList
Public Class ElementsPanel
Private Enum PanelState
None
MovingOrigin
PendingMovingElement
MovingElement
PendingDrawWire
DrawingWire
PendingDeleteWire
DeletingWire
End Enum
Public WithEvents picMain As PictureBox
Public Parent As frmMain
Public WithEvents Elements As MyList(Of Element)
Public Origin As New Point(0, 0)
Private _selectedId As Integer = -1
Private _image As Bitmap, _g As Graphics
Private _state As PanelState
Public Sub New(frm As frmMain, elements As MyList(Of Element))
Me.Elements = elements
Parent = frm
picMain = frm.picMain
Resize()
ResetOrigin()
End Sub
Public Sub Resize()
If picMain.Width > 0 AndAlso picMain.Height > 0 Then
_image = New Bitmap(picMain.Width, picMain.Height)
_g = Graphics.FromImage(_image)
_g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
picMain.Image = _image
End If
End Sub
Public Sub ResetOrigin()
Origin.X = _image.Size.Width / 2
Origin.Y = _image.Size.Height / 2
End Sub
Private Sub OnListChanged(sender As Object, e As ChangedEventArgs(Of Element)) Handles Elements.Changed
Select Case e.Type
Case ChangedType.AddOrInsert
Utilities.Info("ElementsPanel: On add element, updating")
OnAddElement(e.Item)
Case ChangedType.Remove
Utilities.Info("ElementsPanel: On remove element, updating")
OnRemoveElement(e.Item)
End Select
End Sub
Private Sub OnAddElement(e As Element)
e.UpdateProperties()
UpdateConnections(e)
End Sub
Private Sub OnRemoveElement(e As Element)
e.RemoveConnections()
End Sub
Private Sub InternalRender()
'Utilities.Info("Origin: " + Origin.ToString())
Dim state = _g.Save()
_g.TranslateTransform(Origin.X, Origin.Y)
_g.Clear(Color.White)
'坐标轴
_g.DrawLine(Pens.Gray, -10, 0, 10, 0)
_g.DrawLine(Pens.Gray, 0, -10, 0, 10)
'元件
For i = 0 To Elements.Count - 1
Dim element = Elements(i)
If Not MyMath.IsCoincide(ViewableBoundary, element.Boundary) Then
Continue For
End If
element.Draw(_g)
For Each c In element.Connectors
RenderConnection(c)
Next
If i = _selectedId Then
element.DrawBoundary(_g)
End If
Next
'正在绘制的导线
If _path.Count >= 2 Then
_g.DrawLines(Pens.Black, _path.ToArray())
End If
_g.Restore(state)
End Sub
Private Sub RenderConnection(a As Connector)
If a.To Is Nothing Then
Return
End If
Dim locationA = a.Location + a.Owner.Location
Dim locationTo = a.To.Location + a.To.Owner.Location
_g.DrawLine(Pens.Yellow, locationA, locationTo)
End Sub
Public Sub Render()
InternalRender()
picMain.Refresh()
End Sub
Public Sub StartDrawWire()
_state = PanelState.PendingDrawWire
End Sub
#Region "UI"
Private Sub onDoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles picMain.DoubleClick
Utilities.Info("Double Click")
If _selectedId >= 0 Then
Try
If Elements(_selectedId).Rotation = Element.RotationAngle.D270 Then
Elements(_selectedId).Rotation = Element.RotationAngle.D0
Else
Elements(_selectedId).Rotation += 1
End If
UpdateConnections(Elements(_selectedId))
Catch ex As NotImplementedException
End Try
End If
End Sub
''' <summary>
''' 旧的坐标, 原点则相对与picMain, 元件则相对于原点
''' </summary>
''' <remarks></remarks>
Private _oldObjectLocation As Point
''' <summary>
''' 按下鼠标时的坐标, 相对于picMain
''' </summary>
''' <remarks></remarks>
Private _downMouseLocation As Point
''' <summary>
''' 画导线的路径, 坐标相对于原点
''' </summary>
''' <remarks></remarks>
Private _path As New List(Of Point)
Private Sub [Select](id As Integer)
If id < 0 Then
_selectedId = -1
_oldObjectLocation = Origin
Else
_selectedId = id
_oldObjectLocation = Elements(_selectedId).Location
Parent.PropertyGrid1.SelectedObject = Elements(_selectedId)
End If
End Sub
Private Sub onMouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles picMain.MouseDown
Utilities.Info("Mouse down")
Dim p = ToRelative(e.Location)
_downMouseLocation = e.Location
If _state = PanelState.None Then
Utilities.Info("State is none")
Dim ids As New List(Of Integer)
For i = 0 To Elements.Count - 1
If Elements(i).Contains(p) Then
ids.Add(i)
End If
Next
If ids.Count = 0 Then
Utilities.Info("No element selected, changing state to MovingOrigin")
_state = PanelState.MovingOrigin
[Select](-1)
picMain.Cursor = Cursors.Hand
Else
If ids.Count = 1 Then
Utilities.Info("One element selected, changing state to MovingElement")
_state = PanelState.MovingElement
[Select](ids(0))
picMain.Cursor = Cursors.SizeAll
Else
Utilities.Info("More than one elements selected, waiting for menuPendingSelect to be clicked")
Dim menuPendingSelect As New ContextMenuStrip
menuPendingSelect.Hide()
menuPendingSelect.Items.Clear()
For i = 0 To ids.Count - 1
Dim item As New ToolStripMenuItem(String.Format("{0} (ID={1})", Elements(ids(i)).GetDescription(), ids(i)))
item.Tag = ids(i)
AddHandler item.Click, AddressOf onMenuItemClicked
menuPendingSelect.Items.Add(item)
Next
_state = PanelState.PendingMovingElement
menuPendingSelect.Show(picMain, e.X, e.Y)
End If
End If
ElseIf _state = PanelState.PendingDrawWire Then
Utilities.Info("State is PendingDrawLine, starting drawing line")
_state = PanelState.DrawingWire
_path.Clear()
_path.Add(p)
picMain.Cursor = Cursors.Cross
ElseIf _state = PanelState.PendingMovingElement Then
Utilities.Info("State is PendingMovingElement, changing it to none")
_state = PanelState.None
End If
Render()
End Sub
Private Sub onMenuItemClicked(ByVal sender As Object, ByVal e As EventArgs)
If Not TypeOf sender Is ToolStripMenuItem Then
Return
End If
Dim item = DirectCast(sender, ToolStripMenuItem)
Debug.Assert(TypeOf item.Tag Is Integer)
[Select](DirectCast(item.Tag, Integer))
Utilities.Info("menuPendingSelect clicked")
If _state = PanelState.PendingMovingElement Then
_state = PanelState.MovingElement
picMain.Cursor = Cursors.SizeAll
Utilities.Info("State is PendingMovingElement, so change it to MovingElement")
End If
Render()
End Sub
Private Sub onMouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) Handles picMain.MouseMove
'Utilities.Info("Mouse moving")
Parent.MainBoxPoint.Text = "(" & e.Location.X.ToString & ", " & e.Location.Y.ToString & ")"
Parent.OriPoint.Text = "(" & (e.Location - Origin).X.ToString & ", " & (e.Location - Origin).Y.ToString & ")"
Dim p = ToRelative(e.Location)
Dim mouseDelta = e.Location - _downMouseLocation
Select Case _state
Case PanelState.MovingOrigin
Origin = _oldObjectLocation + mouseDelta
Case PanelState.MovingElement
Debug.Assert(_selectedId >= 0)
Elements(_selectedId).Location = _oldObjectLocation + mouseDelta
UpdateConnections(Elements(_selectedId))
Case PanelState.DrawingWire
_path.Add(p)
End Select
Render()
End Sub
Private Sub onMouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles picMain.MouseUp
Utilities.Info("Mouse up")
Dim p = ToRelative(e.Location)
If _state = PanelState.PendingMovingElement Then
Utilities.Info("State is PendingMovingElement, do nothing")
Return
End If
If _state = PanelState.DrawingWire Then
_path.Add(p)
If _path.Count >= 3 Then
Dim wlocation = _path(0)
For i = 0 To _path.Count - 1
_path(i) -= wlocation
Next
Dim w As New Wire(_path, wlocation)
_Elements.Add(w)
End If
_path.Clear()
End If
Utilities.Info("Changing state to none")
_state = PanelState.None
picMain.Cursor = Cursors.Arrow
Render()
End Sub
''' <summary>
''' 把在PictureBox的坐标转换为相对于Origin的坐标
''' </summary>
''' <param name="p">PictureBox的坐标</param>
''' <returns>相对于Origin的坐标</returns>
''' <remarks></remarks>
Private Function ToRelative(p As Point) As Point
Return p - Origin
End Function
Public Sub DeleteSelected()
If _selectedId < 0 Then
Return
End If
Elements.RemoveAt(_selectedId)
[Select](-1)
End Sub
Public Function ViewableBoundary() As Rectangle
Return New Rectangle(Point.Empty - Origin, picMain.Size)
End Function
#End Region
Public Sub ForeachConnector(callback As Action(Of Connector))
For Each e In Elements
For Each c In e.Connectors
callback(c)
Next
Next
End Sub
''' <summary>
''' 更新所有的连接
''' </summary>
''' <remarks></remarks>
Public Sub UpdateConnections()
ForeachConnector(AddressOf UpdateConnections)
End Sub
''' <summary>
''' 更新一个连接器的连接
''' </summary>
''' <param name="a">连接器</param>
''' <remarks></remarks>
Public Sub UpdateConnections(a As Connector)
Dim locationA = a.Location + a.Owner.Location
'判断当前的连接是否还有效
If a.To IsNot Nothing Then
Dim locationTo = a.To.Location + a.To.Owner.Location
If MyMath.Distance2(locationA, locationTo) <= 25 Then
Return
End If
End If
a.RemoveConnection()
ForeachConnector(Sub(b)
If a.Owner.Equals(b.Owner) Then
Return
End If
Dim locationB = b.Location + b.Owner.Location
If MyMath.Distance2(locationA, locationB) <= 25 Then
a.MakeConnection(b)
End If
End Sub)
End Sub
''' <summary>
''' 更新一个元件的连接
''' </summary>
''' <param name="a">元件</param>
''' <remarks></remarks>
Public Sub UpdateConnections(a As Element)
For Each c In a.Connectors
UpdateConnections(c)
Next
End Sub
End Class
|
twd2/Circuit
|
Circuit/ElementsPanel.vb
|
Visual Basic
|
mit
| 12,082
|
'************************************* Module Header **************************************\
' Module Name: EditingControlHosting
' Project: VBWinFormDataGridView
' Copyright (c) Microsoft Corporation.
'
' This sample demonstrates how to host a control in the current DataGridViewCell for
' editing.
'
' This source is subject to the Microsoft Public License.
' See http://www.microsoft.com/en-us/openness/resources/licenses.aspx#MPL.
' All other rights reserved.
'
' THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
' WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
'**********************************************************************************/
Namespace VBWinFormDataGridView.EditingControlHosting
Public Class MainForm
Private maskedTextBoxForEditing As MaskedTextBox
Private IsKeyPressHandled As Boolean
Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.maskedTextBoxForEditing = New MaskedTextBox()
' The "000-00-0000" mask allows only digits can be input
Me.maskedTextBoxForEditing.Mask = "000-00-0000"
' Hide the MaskedTextBox
Me.maskedTextBoxForEditing.Visible = False
' Add the MaskedTextBox to the DataGridView's control collection
Me.dataGridView1.Controls.Add(Me.maskedTextBoxForEditing)
' Add a DataGridViewTextBoxColumn to the
Dim tc As DataGridViewTextBoxColumn = New DataGridViewTextBoxColumn()
tc.HeaderText = "Mask Column"
tc.Name = "MaskColumn"
Me.dataGridView1.Columns.Add(tc)
' Add some empty rows for testing purpose
For j As Integer = 0 To 29
Me.dataGridView1.Rows.Add()
Next
' Handle the CellBeginEdit event to show the MaskedTextBox on
' the current editing cell
End Sub
Private Sub dataGridView1_CellBeginEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles dataGridView1.CellBeginEdit
' If the current cell is on the "MaskColumn", we use the MaskedTextBox control
' for editing instead of the default TextBox control
If e.ColumnIndex = Me.dataGridView1.Columns("MaskColumn").Index Then
' Calculate the cell bounds of the current cell
Dim rect As Rectangle = Me.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, True)
' Adjust the MaskedTextBox's size and location to fit the cell
Me.maskedTextBoxForEditing.Size = rect.Size
Me.maskedTextBoxForEditing.Location = rect.Location
' Set value for the MaskedTextBox
If Me.dataGridView1.CurrentCell.Value IsNot Nothing Then
Me.maskedTextBoxForEditing.Text = Me.dataGridView1.CurrentCell.Value.ToString()
End If
' Show the MaskedTextBox
Me.maskedTextBoxForEditing.Visible = True
End If
End Sub
Private Sub dataGridView1_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dataGridView1.CellEndEdit
' When finish editing on the "MaskColumn", we replace the cell value with
' the text typed in the MaskedTextBox, and hide the MaskedTextBox
If e.ColumnIndex = Me.dataGridView1.Columns("MaskColumn").Index Then
Me.dataGridView1.CurrentCell.Value = Me.maskedTextBoxForEditing.Text
Me.maskedTextBoxForEditing.Text = ""
Me.maskedTextBoxForEditing.Visible = False
End If
End Sub
Private Sub dataGridView1_Scroll(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles dataGridView1.Scroll
If Me.dataGridView1.IsCurrentCellInEditMode = True Then
' Adjust the location for the MaskedTextBox while scrolling
Dim rect As Rectangle = Me.dataGridView1.GetCellDisplayRectangle(Me.dataGridView1.CurrentCell.ColumnIndex, Me.dataGridView1.CurrentCell.RowIndex, True)
Console.WriteLine(rect.ToString())
Console.WriteLine(Me.dataGridView1.CurrentCellAddress.ToString())
Console.WriteLine("")
If rect.X <= 0 OrElse rect.Y <= 0 Then
Me.maskedTextBoxForEditing.Visible = False
Else
Me.maskedTextBoxForEditing.Location = rect.Location
End If
End If
End Sub
Private Sub dataGridView1_EditingControlShowing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles dataGridView1.EditingControlShowing
If Not (Me.IsKeyPressHandled AndAlso Me.dataGridView1.CurrentCell.ColumnIndex = Me.dataGridView1.Columns("MaskColumn").Index) Then
Dim tb As TextBox = CType(e.Control, TextBox)
AddHandler tb.KeyPress, AddressOf tb_KeyPress
Me.IsKeyPressHandled = True
End If
End Sub
Private Sub tb_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
If Me.dataGridView1.CurrentCell.ColumnIndex = Me.dataGridView1.Columns("MaskColumn").Index Then
' Prevent the key char to be input in the editing control
e.Handled = True
' Set focus to the MaskedTextBox for editing.
Me.maskedTextBoxForEditing.Focus()
End If
End Sub
End Class
End Namespace
|
Neo-Desktop/Coleman-Code
|
COM350/Project3/VBWinFormDataGridView/EditingControlHosting/MainForm.vb
|
Visual Basic
|
mit
| 5,831
|
Imports BVSoftware.Bvc5.Core
Partial Class BVModules_ContentBlocks_Mailing_List_Signup_adminview
Inherits Content.BVModule
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim listID As String = SettingsManager.GetSetting("MailingListId")
If listID <> String.Empty Then
Dim m As Contacts.MailingList = Contacts.MailingList.FindByBvin(listID)
If m.Bvin <> String.Empty Then
Me.lblInfo.Text = "List: " & m.Name
Else
Me.lblInfo.Text = "Unknown mailing list selected."
End If
Else
Me.lblInfo.Text = "No mailing list selected."
End If
End Sub
End Class
|
ajaydex/Scopelist_2015
|
BVModules/ContentBlocks/Mailing List Signup/adminview.ascx.vb
|
Visual Basic
|
apache-2.0
| 731
|
Public Class EmptyNode
' Class used to return a value when my object is nothing.
End Class
Public Class TreeNodeDataManager
Inherits DevComponents.AdvTree.Node
#Region " Public Members "
' Public Shared _columnsMetaDataQuestionnaireSet, _columnsMetaDataQuestionnaire, _columnsMetaDataSection As New List(Of String)
'Private _columnsMetaData As List(Of String)
Public Shared _styles As DevComponents.AdvTree.ElementStyleCollection
#End Region
#Region " Public Properties "
Public Shadows ReadOnly Property TagGO() As BO.GenericObject
Get
Return CType(MyBase.Tag, BO.GenericObject)
End Get
End Property
''' <summary>
''' Returns the type of the contained object.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public ReadOnly Property TagType() As Type
Get
If Me.Tag Is Nothing Then
Return GetType(EmptyNode)
Else
Return Me.Tag.GetType
End If
End Get
End Property
''' <summary>
''' Overrites the parent property to return a TreeNodeDataManager instead of node.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public ReadOnly Property ParentTreeNodeDataManager() As TreeNodeDataManager
Get
Return CType(Me.Parent, TreeNodeDataManager)
End Get
End Property
''' <summary>
''' Overrites the previoussibling property to return a TreeNodeDataManager instead of node.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public ReadOnly Property PrevTreeNodeDataManager() As TreeNodeDataManager
Get
Return CType(Me.PrevNode, TreeNodeDataManager)
End Get
End Property
#End Region
#Region " Public Methods "
''' <summary>
''' Sets the string to show and the object to display in the property grid.
''' </summary>
''' <param name="_myObject"></param>
''' <remarks></remarks>
Public Sub New(ByVal _myObject As Object)
MyBase.Tag = _myObject
Me.Text = Tag.ToString()
Me.Checked = True
Me.CheckBoxVisible = True
End Sub
' Sets the parameters and initial conditions before generate structure childs.
Public Sub GenerateStructureChilds(ByVal showVariables As Boolean, ByVal metadataQuestionnaireSet As List(Of BO.Variable), _
ByVal metadataQuestionnaire As List(Of BO.Variable), ByVal metadataSection As List(Of BO.Variable))
' Clear the child nodes.
Me.Nodes.Clear()
If Me.TagType.BaseType.Equals(GetType(BO.SectionItem)) Then
' Check for previous numeration.
If Me.ParentTreeNodeDataManager.TagType.Equals(GetType(BO.Section)) Then
Me.ParentTreeNodeDataManager.GenerateStructureChilds(0, metadataQuestionnaireSet, metadataQuestionnaire, metadataSection)
Else
' Split number and prefix.
Dim sectionItemNumber As String = CType(Me.ParentTreeNodeDataManager.Tag, BO.SectionItem).Number
Dim index As Integer = sectionItemNumber.LastIndexOf(".")
Dim number As Integer = Integer.Parse(sectionItemNumber.Substring(index + 1))
' Focus parent node.
BO.ContextClass.CurrentTreeNode = Me.ParentTreeNodeDataManager
If index >= 0 Then
' If prefix, split it.
Dim prefix As String = sectionItemNumber.Remove(index)
Me.ParentTreeNodeDataManager.GenerateStructureChilds(number, metadataQuestionnaireSet, metadataQuestionnaire, _
metadataSection, prefix & ".")
Else
' No prefix.
Me.ParentTreeNodeDataManager.GenerateStructureChilds(number, metadataQuestionnaireSet, metadataQuestionnaire, metadataSection)
End If
End If
Else
' If is not a section item just generate.
Me.GenerateStructureChilds(0, metadataQuestionnaireSet, metadataQuestionnaire, metadataSection, , showVariables)
End If
Me.Expand()
End Sub
' Verifies if the node is child of the parameter or is the same node.
Public Function IsChildOrSelfOf(ByVal parent As TreeNodeDataManager) As Boolean
While parent IsNot Nothing And Not Me.Equals(parent) And parent.Level >= Me.Level
parent = CType(parent.Parent, TreeNodeDataManager)
End While
Return Me.Equals(parent)
End Function
' Sets the checked state to the node and its childrens.
Public Sub SetCheckedRecursive(ByVal checked As Windows.Forms.CheckState)
Dim stack As New Stack(Of TreeNodeDataManager)
stack.Push(Me)
While stack.Count > 0
Dim tmp As TreeNodeDataManager = stack.Pop
tmp.CheckState = checked
If tmp.NextNode IsNot Nothing Then stack.Push(CType(tmp.NextNode, TreeNodeDataManager))
If tmp.Nodes.Count > 0 Then stack.Push(CType(tmp.Nodes(0), TreeNodeDataManager))
End While
End Sub
' Insert childs of the MetaData
Public Sub CreateMetaDataChilds(ByVal metaData As TreeNodeDataManager, ByVal listOfFlieds As List(Of BO.Variable))
For Each field As BO.Variable In listOfFlieds
Dim node As New TreeNodeDataManager(field)
metaData.Nodes.Add(node)
Next
End Sub
#End Region
#Region " Private Method "
' Generates the childs for the current note and its childs for the structure tab.
Private Sub GenerateStructureChilds(ByVal number As Integer, ByVal metadataQuestionnaireSet As List(Of BO.Variable), _
ByVal metadataQuestionnaire As List(Of BO.Variable), ByVal metadataSection As List(Of BO.Variable), _
Optional ByVal prefix As String = "", Optional ByVal showVariables As Boolean = True)
Me.Nodes.Clear()
' Generate variable nodes.
If Me.TagGO.HasVariables Then
Dim node As New TreeNodeDataManager("Variables")
node.ImageKey = "Variables"
For Each variable As BO.Variable In Me.TagGO.Variables
Dim variableNode As New TreeNodeDataManager(variable)
variableNode.ImageKey = "Variable"
node.Nodes.Add(variableNode)
Next
Me.Nodes.Add(node)
End If
' Generate structure childs.
Select Case Me.Tag.GetType.ToString
Case GetType(BO.Study).ToString
' Set the study icon.
Me.ImageKey = "Study"
' Add study's childs.
Dim _study As BO.Study = CType(Me.Tag, BO.Study)
For Each _questionnaireSet As BO.QuestionnaireSet In _study.QuestionnarieSets
Dim node As New TreeNodeDataManager(_questionnaireSet)
Me.Nodes.Add(node)
node.GenerateStructureChilds(0, metadataQuestionnaireSet, metadataQuestionnaire, metadataSection)
Next
Case GetType(BO.QuestionnaireSet).ToString
' Set questionnaire set icon.
Me.ImageKey = "QuestionnaireSet"
' MetaData
Dim _metaData As New TreeNodeDataManager("Metadata")
CreateMetaDataChilds(_metaData, metadataQuestionnaireSet)
Me.Nodes.Add(_metaData)
' End MetaData
' Add questionnaire set's childs.
Dim _questionnaireSet As BO.QuestionnaireSet = CType(Me.Tag, BO.QuestionnaireSet)
For Each _questionnarie As BO.Questionnaire In _questionnaireSet.Questionnaires
Dim node As New TreeNodeDataManager(_questionnarie)
Me.Nodes.Add(node)
node.GenerateStructureChilds(0, metadataQuestionnaireSet, metadataQuestionnaire, metadataSection)
Next
Case GetType(BO.Questionnaire).ToString
' Set questionnaire icon.
Me.ImageKey = "Questionnaire"
' MetaData
Dim _metaData As New TreeNodeDataManager("Metadata")
CreateMetaDataChilds(_metaData, metadataQuestionnaire)
Me.Nodes.Add(_metaData)
' End MetaData
'Add Sections.
Dim _questionnarie As BO.Questionnaire = CType(Me.Tag, BO.Questionnaire)
For Each _section As BO.Section In _questionnarie.Sections
Dim node As New TreeNodeDataManager(_section)
Me.Nodes.Add(node)
node.GenerateStructureChilds(0, metadataQuestionnaireSet, metadataQuestionnaire, metadataSection)
Next
Case GetType(BO.Section).ToString
' Set Section icon.
Me.ImageKey = "Section"
' MetaData
Dim _metaData As New TreeNodeDataManager("Metadata")
CreateMetaDataChilds(_metaData, metadataSection)
Me.Nodes.Add(_metaData)
' End MetaData
'Add Questions.
Dim _section As BO.Section = CType(Me.Tag, BO.Section)
Dim count As Integer = 1
For Each _phase As BO.SectionItem In _section.SectionItems
Dim node As New TreeNodeDataManager(_phase)
Me.Nodes.Add(node)
node.GenerateStructureChilds(count, metadataQuestionnaireSet, metadataQuestionnaire, metadataSection)
count += 1
Next
Case GetType(BO.CheckPoint).ToString
' Set Checkpoint icon.
Me.ImageKey = "Checkpoint"
'Add Child Phases.
Dim _checkPoint As BO.CheckPoint = CType(Me.Tag, BO.CheckPoint)
_checkPoint.Number = prefix & number
Dim count As Integer = 1
For Each _phase As BO.SectionItem In _checkPoint.SectionItems
Dim node As New TreeNodeDataManager(_phase)
Me.Nodes.Add(node)
node.GenerateStructureChilds(count, metadataQuestionnaireSet, metadataQuestionnaire, metadataSection, prefix & number & ".")
count += 1
Next
Case GetType(BO.Question).ToString
' Set question icon.
Me.ImageKey = "Question"
' Sets the color to the question.
Dim _Question As BO.Question = CType(Me.Tag, BO.Question)
If _Question.Required Then
Me.Style = _styles("Required")
End If
' Sets the number.
_Question.Number = prefix & number
Case GetType(BO.Information).ToString
' Set information icon.
Me.ImageKey = "Information"
CType(Me.Tag, BO.SectionItem).Number = prefix & number
End Select
' Sets the text and the selected image.
Me.Text = Me.Tag.ToString
End Sub
#End Region
End Class
|
QMDevTeam/QMDesigner
|
DataManager/Classes/TreeNodeDataManager.vb
|
Visual Basic
|
apache-2.0
| 11,296
|
'
' (C) Copyright 2003-2011 by Autodesk, Inc.
'
' Permission to use, copy, modify, and distribute this software in
' object code form for any purpose and without fee is hereby granted,
' provided that the above copyright notice appears in all copies and
' that both that copyright notice and the limited warranty and
' restricted rights notice below appear in all supporting
' documentation.
'
' AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
' AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
' MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
' DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
' UNINTERRUPTED OR ERROR FREE.
'
' Use, duplication, or disclosure by the U.S. Government is subject to
' restrictions set forth in FAR 52.227-19 (Commercial Computer
' Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
' (Rights in Technical Data and Computer Software), as applicable.
'
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("")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("")>
<Assembly: AssemblyCopyright("")>
<Assembly: AssemblyTrademark("")>
<Assembly: CLSCompliant(True)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("5A0846D9-CBB3-4674-9ED9-894EEA0DFC72")>
' 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.*")>
|
AMEE/revit
|
samples/Revit 2012 SDK/Samples/HelloRevit/VB.NET/AssemblyInfo.vb
|
Visual Basic
|
bsd-3-clause
| 1,938
|
Imports OpenPop
Imports OpenPop.Mime
Imports OpenPop.Mime.Header
Imports OpenPop.Pop3
Imports OpenPop.Pop3.Exceptions
Imports OpenPop.Common.Logging
Imports System.Collections.Generic
Imports System.Data
Imports System.IO
Imports System.Text
Imports System.Object
Imports System.Security.Cryptography
Imports Message = OpenPop.Mime.Message
Imports GridcoinDotNet.Gridcoin
Imports System.Windows.Forms
Imports boinc.Gridcoin
Public Class frmMail
Public WithEvents cms As New ContextMenuStrip
Public saveFile As SaveFileDialog
Public p3 As Pop3.Pop3Client
'Dim messages As New Dictionary(Of Long, OpenPop.Mime.Message)
Public Sub Login()
Dim sHost As String = KeyValue("pophost")
Dim sUser As String = KeyValue("popuser")
Dim sPass As String = KeyValue("poppassword")
Dim iPort As Long = Val(KeyValue("popport"))
Dim bSSL As Boolean = IIf(Trim(LCase(KeyValue("popssl"))) = "true", True, False)
p3 = New Pop3.Pop3Client
'Add Handlers for Online Storage
AddHandler listMessages.AfterSelect, AddressOf ListMessagesMessageSelected
AddHandler listAttachments.AfterSelect, AddressOf ListAttachmentsAttachmentSelected
AddHandler listMessages.MouseDown, AddressOf MessagesContextHandler
'Add Handlers for Offline Storage
AddHandler listOfflineStorage.AfterSelect, AddressOf OfflineMessageSelected
AddHandler listOfflineStorage.AfterSelect, AddressOf OfflineAttachmentSelected
AddHandler listOfflineStorage.MouseDown, AddressOf OfflineContextHandler
If p3.Connected Then
Windows.Forms.Application.DoEvents()
p3.Disconnect()
Windows.Forms.Application.DoEvents()
End If
p3.Connect(sHost, iPort, bSSL, 7000, 7000, Nothing)
Windows.Forms.Application.DoEvents()
Try
p3.Authenticate(sUser, sPass)
Catch ex As Exception
End Try
Windows.Forms.Application.DoEvents()
End Sub
Public Sub RetrievePop3Emails(Optional ByVal bDisconnect As Boolean = False)
Try
ProgressBar1.Visible = True
listMessages.Height = 147
Windows.Forms.Application.DoEvents()
Dim count As Integer
Try
If bDisconnect Then If p3.Connected = True Then p3.Disconnect()
count = p3.GetMessageCount()
ProgressBar1.Maximum = 20
Catch ex As Exception
ProgressBar1.Value = 1
Login()
ProgressBar1.Value = 2
count = p3.GetMessageCount()
ProgressBar1.Value = 3
End Try
' messages.Clear()
Windows.Forms.Application.DoEvents()
listMessages.Nodes.Clear()
Windows.Forms.Application.DoEvents()
listAttachments.Nodes.Clear()
Windows.Forms.Application.DoEvents()
Dim success As Integer = 0
Dim fail As Integer = 0
ProgressBar1.Maximum = count + 2
For i As Integer = count To 1 Step -1
If IsDisposed Then
Return
End If
ProgressBar1.Value = count - i + 2
Windows.Forms.Application.DoEvents()
Try
Dim h As MessageHeader
h = p3.GetMessageHeaders(i)
'Dim message As OpenPop.Mime.Message = p3.GetMessage(i)
'If the message is encrypted, decrypt it and move it:
If h.Subject.Contains("encrypted") Then
Dim sRawBody As String = ""
Dim sBody As String
Dim bIsHTML As Boolean
Dim m As Message
m = p3.GetMessage(i)
GetBodyOfMessage(m, sRawBody, bIsHTML)
Dim sDecrypted = Decrypt(sRawBody)
Serialize(m, sDecrypted, i, bIsHTML)
GoTo dontaddit
End If
Windows.Forms.Application.DoEvents()
' Add the message to the dictionary using the messageNumber
'messages.Add(i, Message)
' Create a TreeNode tree that mimics the Message hierarchy
Dim node As TreeNode = New TreeNode(h.Subject + " - " + h.From.ToString() + " - " + Trim(h.DateSent))
node.Tag = i
listMessages.Nodes.Add(node)
dontaddit:
Application.DoEvents()
success += 1
Catch e As Exception
DefaultLogger.Log.LogError(("TestForm: Message fetching failed: " + e.Message & vbCr & vbLf & "Stack trace:" & vbCr & vbLf) + e.StackTrace)
fail += 1
End Try
Next
PopulateOffLineMessages()
ProgressBar1.Visible = False
listMessages.Height = 157
If fail > 0 Then
'Add Logging
End If
Catch generatedExceptionName As InvalidLoginException
MessageBox.Show(Me, "The server did not accept the user credentials!", "Authentication Failure")
Catch generatedExceptionName As PopServerNotFoundException
MessageBox.Show(Me, "The server could not be found", "POP3 Retrieval")
Catch generatedExceptionName As PopServerLockedException
MessageBox.Show(Me, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked")
Catch generatedExceptionName As LoginDelayException
MessageBox.Show(Me, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay")
Catch e As Exception
MessageBox.Show(Me, "Error occurred retrieving mail. " + e.Message, "POP3 Retrieval")
Finally
' Enable the Gridcoin buttons again
End Try
End Sub
Private Sub OfflineMessageSelected(ByVal sender As Object, ByVal e As TreeViewEventArgs)
Dim fn As String
fn = listOfflineStorage.SelectedNode.Tag
Dim sBody As String
sBody = GetOfflineBody(fn)
WebBrowser1.DocumentText = sBody
'Populate the Attachments:
Dim sFolder As String = GetGridPath("MailAttachments")
Dim sFG As String
sFG = Mid(fn, 1, Len(fn) - 4)
Dim di As New DirectoryInfo(sFolder)
Dim fiArr As FileInfo() = di.GetFiles()
Dim fri As FileInfo
Dim sFGP As String
listAttachments.Nodes.Clear()
Dim eFI As New FileInfo(fn)
For Each fri In fiArr
If Mid(fri.Name, 1, 35) = Mid(eFI.Name, 1, 35) Then
sFGP = Mid(fri.FullName, 1, 35)
Dim zx As New TreeNode
zx.Text = Mid(fri.FullName, 36, Len(fri.FullName))
zx.Tag = fri.FullName
listAttachments.Nodes.Add(zx)
End If
Next fri
End Sub
Private Sub OfflineAttachmentSelected(ByVal sender As Object, ByVal e As TreeViewEventArgs)
End Sub
Private Sub OfflineContextHandler(ByVal sender As Object, ByVal e As MouseEventArgs)
If e.Button = Windows.Forms.MouseButtons.Left Then
If listOfflineStorage.ContextMenuStrip Is Nothing Then Exit Sub
listOfflineStorage.ContextMenuStrip.Visible = False
End If
If e.Button = Windows.Forms.MouseButtons.Right Then
listOfflineStorage.SelectedNode = listOfflineStorage.GetNodeAt(e.X, e.Y)
cms.Items.Clear()
cms.Items.Add("Delete Message")
AddHandler cms.Items(0).Click, AddressOf OfflineDeleteMessageClick
'cms.Items.Add("Forward Message")
'AddHandler cms.Items(1).Click, AddressOf MenuForwardMessageClick
listOfflineStorage.ContextMenuStrip = cms
listOfflineStorage.ContextMenuStrip.Show()
End If
End Sub
Private Sub ListMessagesMessageSelected(ByVal sender As Object, ByVal e As TreeViewEventArgs)
' Fetch the selected message
Dim message As OpenPop.Mime.Message
Try
message = p3.GetMessage(listMessages.SelectedNode.Tag)
Catch ex As Exception
Login()
message = p3.GetMessage(listMessages.SelectedNode.Tag)
End Try
' Clear the attachment list from any previus shown attachments
listAttachments.Nodes.Clear()
Dim attachments As List(Of MessagePart) = message.FindAllAttachments()
For Each attachment As MessagePart In attachments
' Add the attachment to the list of attachments
Dim addedNode As TreeNode = listAttachments.Nodes.Add((attachment.FileName))
' Keep a reference to the attachment in the Tag property
addedNode.Tag = attachment
Next
' Only show that attachmentPanel if there is attachments in the message
Dim hadAttachments As Boolean = attachments.Count > 0
' Generate header table
Dim dataSet As New DataSet()
Dim table As DataTable = dataSet.Tables.Add("Headers")
table.Columns.Add("Header")
table.Columns.Add("Value")
Dim rows As DataRowCollection = table.Rows
' Add all known headers
'rows.Add(New Object() {"Content-Description", OpenPop.Mime.Message.Headers.ContentDescription})
'rows.Add(New Object() {"Content-Id", OpenPop.Mime.Message.Headers.ContentId})
'For Each keyword As String In OpenPop.Mime.Message.Headers.Keywords
' rows.Add(New Object() {"Keyword", keyword})
' Next
'For Each dispositionNotificationTo As RfcMailAddress In OpenPop.Mime.Message.Headers.DispositionNotificationTo
'rows.Add(New Object() {"Disposition-Notification-To", dispositionNotificationTo})
'Next
'For Each received As Received In OpenPop.Mime.Message.Headers.Received
'rows.Add(New Object() {"Received", Received.Raw})
'Next
'rows.Add(New Object() {"Importance", OpenPop.Mime.Message.Headers.Importance})
'rows.Add(New Object() {"Content-Transfer-Encoding", OpenPop.Mime.Message.Headers.ContentTransferEncoding})
'For Each cc As RfcMailAddress In OpenPop.Mime.Message.Headers.Cc
'rows.Add(New Object() {"Cc", cc})
'Next
'For Each bcc As RfcMailAddress In OpenPop.Mime.Message.Headers.Bcc
'rows.Add(New Object() {"Bcc", bcc})
'Next
'For Each [to] As RfcMailAddress In OpenPop.Mime.Message.Headers.[To]
' rows.Add(New Object() {"To", [to]})
' Next
'rows.Add(New Object() {"From", OpenPop.Mime.Message.Headers.From})
'rows.Add(New Object() {"Reply-To", OpenPop.Mime.Message.Headers.ReplyTo})
'For Each inReplyTo As String In OpenPop.Mime.Message.Headers.InReplyTo
'rows.Add(New Object() {"In-Reply-To", inReplyTo})
'Next
'For Each reference As String In OpenPop.Mime.Message.Headers.References
' rows.Add(New Object() {"References", reference})
'Next
'rows.Add(New Object() {"Sender", OpenPop.Mime.Message.Headers.Sender})
'rows.Add(New Object() {"Content-Type", OpenPop.Mime.Message.Headers.ContentType})
'rows.Add(New Object() {"Content-Disposition", OpenPop.Mime.Message.Headers.ContentDisposition})
'rows.Add(New Object() {"Date", OpenPop.Mime.Message.Headers.[Date]})
'rows.Add(New Object() {"Date", OpenPop.Mime.Message.Headers.DateSent})
'rows.Add(New Object() {"Message-Id", OpenPop.Mime.Message.Headers.MessageId})
'rows.Add(New Object() {"Mime-Version", OpenPop.Mime.Message.Headers.MimeVersion})
'rows.Add(New Object() {"Return-Path", OpenPop.Mime.Message.Headers.ReturnPath})
'rows.Add(New Object() {"Subject", OpenPop.Mime.Message.Headers.Subject})
' Add all unknown headers
'For Each key As String In OpenPop.Mime.Message.Headers.UnknownHeaders
' Dim values As String() = OpenPop.Mime.Message.Headers.UnknownHeaders.GetValues(key)
' If values IsNot Nothing Then
' For Each value As String In values
' rows.Add(New Object() {key, value})
' Next
'End If
'Next
Dim sBody As String
Dim sRawBody As String = ""
Dim bIsHTML As Boolean
sBody = GetBodyOfMessage(message, sRawBody, bIsHTML)
WebBrowser1.DocumentText = sBody
End Sub
Public Function GetBodyOfMessage(ByVal m As OpenPop.Mime.Message, ByRef sRawBody As String, ByRef bIsHTML As Boolean) As String
' Find the first text/plain version
Dim sHeader As String = "<PRE>"
sHeader = sHeader + "From: " + m.Headers.From.ToString() + vbCrLf
sHeader = sHeader + "To: " + MaToString(m.Headers.To) + vbCrLf
sHeader = sHeader + "Date: " + m.Headers.DateSent.ToString() + vbCrLf
sHeader = sHeader + "CC: " + MaToString(m.Headers.Cc) + vbCrLf
sHeader = sHeader + "</PRE>" + vbCrLf
Windows.Forms.Application.DoEvents()
Dim plainTextPart As MessagePart = m.FindFirstPlainTextVersion()
Dim htmlPart As MessagePart = m.FindFirstHtmlVersion()
Dim sBody As String
sRawBody = ""
If htmlPart IsNot Nothing Then
' The message had a text/plain version - show that one
sBody = sHeader + htmlPart.GetBodyAsText()
sRawBody = htmlPart.GetBodyAsText
bIsHTML = True
Else
If plainTextPart IsNot Nothing Then
sBody = sHeader + "<pre>" + plainTextPart.GetBodyAsText()
sRawBody = plainTextPart.GetBodyAsText
bIsHTML = False
Else
Dim textVersions As List(Of MessagePart) = m.FindAllTextVersions()
If textVersions.Count >= 1 Then
sBody = sHeader + "<pre>" + textVersions(0).GetBodyAsText()
sRawBody = textVersions(0).GetBodyAsText
bIsHTML = False
End If
End If
End If
Return sBody
End Function
Public Function Serialize(ByVal m As OpenPop.Mime.Message, ByVal sDecryptedBody As String, ByVal lMessageNumber As Long, ByVal bIsHTML As Boolean)
'Store the message offline
Dim sFN As String
Dim sFG As String
sFG = Guid.NewGuid.ToString
sFG = "TEMP"
sFN = sFG + ".eml"
Dim sPath As String
Dim sEmailFolder As String
sEmailFolder = GetGridPath("Email")
Try
If Not System.IO.Directory.Exists(sEmailFolder) Then MkDir(sEmailFolder)
Catch ex As Exception
End Try
Windows.Forms.Application.DoEvents()
sPath = sEmailFolder + "\" + sFN
Dim sw As New StreamWriter(sPath)
sw.WriteLine("FROM: " + m.Headers.From.ToString())
sw.WriteLine("TO: " + MaToString(m.Headers.To))
sw.WriteLine("CC: " + MaToString(m.Headers.Cc))
sw.WriteLine("SUBJECT: " + m.Headers.Subject)
sw.WriteLine("SENT: " + m.Headers.DateSent)
sw.WriteLine("TYPE: " + IIf(bIsHTML, "HTML", "PLAINTEXT"))
sw.WriteLine("BODY: " + vbCrLf + sDecryptedBody)
sw.Close()
Dim sMD5 As String
sMD5 = GetMd5(sPath)
sFG = sMD5
Dim sOldName As String
sOldName = sPath
sFN = sFG + ".eml"
sPath = sEmailFolder + "\" + sFN
Rename(sOldName, sPath)
'Save attachments
Dim attachments As List(Of MessagePart) = m.FindAllAttachments()
For Each attachment As MessagePart In attachments
' Add the attachment to the list of attachments
Dim sFile As String
sFile = GetGridPath("MailAttachments") + "\" + sFG + "_" + attachment.FileName
Dim file As New FileInfo(sFile)
If file.Exists Then file.Delete()
Try
attachment.Save(file)
Catch ex As Exception
End Try
Next
p3.DeleteMessage(lMessageNumber)
End Function
Public Function GetMd5(ByVal sFN As String) As String
Dim md5 As Object
md5 = System.Security.Cryptography.MD5.Create()
Dim fs As Stream
fs = File.OpenRead(sFN)
md5 = md5.ComputeHash(fs)
fs.Close()
Dim sOut As String
sOut = ByteArrayToHexString(md5)
Return sOut
End Function
Public Function ByteArrayToHexString(ByVal ba As Byte()) As String
Dim hex As StringBuilder
hex = New StringBuilder(ba.Length * 2)
For Each b As Byte In ba
hex.AppendFormat("{0:x2}", b)
Next
Return hex.ToString()
End Function
Public Sub PopulateOffLineMessages()
Dim sFolder As String = GetGridPath("Email")
Dim di As New DirectoryInfo(sFolder)
Dim fiArr As FileInfo() = di.GetFiles()
Dim fri As FileInfo
Dim sSubject As String
listOfflineStorage.Nodes.Clear()
For Each fri In fiArr
sSubject = GetOfflineSubject(fri.FullName)
Dim zx As New TreeNode
zx.Text = sSubject
zx.Tag = fri.FullName
listOfflineStorage.Nodes.Add(zx)
Next fri
End Sub
Public Function GetOfflineSubject(ByVal sFileName As String) As String
Dim sr As New StreamReader(sFileName)
Dim sSubject As String
For x = 1 To 4
sSubject = sr.ReadLine()
Next
sr.Close()
Return sSubject
End Function
Public Function GetOfflineBody(ByVal sFileName As String) As String
Dim sr As New StreamReader(sFileName)
Dim sSubject As String
'From, To, Subject, Sent, Type
Dim sHeader As String
Dim sTemp As String
sHeader = "<PRE>"
For x = 1 To 6
sTemp = sr.ReadLine()
sHeader = sHeader + sTemp + vbCrLf
Next
sHeader = sHeader + vbCrLf + "</PRE>"
sTemp = sr.ReadLine() 'Body
Dim sBody As String = ""
Dim sOut As String
Do While sr.EndOfStream = False
sBody = sBody + sr.ReadLine
Loop
sr.Close()
Return sHeader + sBody
End Function
Public Shared Function Decrypt(ByVal sIn As String) As String
Dim sChar As String
Dim lAsc As Long
For x = 1 To Len(sIn)
sChar = Mid(sIn, x, 1)
lAsc = Asc(sChar) - 1
Mid(sIn, x, 1) = Chr(lAsc)
Next
Return sIn
End Function
Public Shared Function Encrypt(ByVal sIn As String) As String
Dim sChar As String
Dim lAsc As Long
For x = 1 To Len(sIn)
sChar = Mid(sIn, x, 1)
lAsc = Asc(sChar) + 1
Mid(sIn, x, 1) = Chr(lAsc)
Next
Return sIn
End Function
Public Function MaToString(ByVal c As System.Collections.Generic.List(Of OpenPop.Mime.Header.RfcMailAddress)) As String
Dim sOut As String
For x = 0 To c.Count - 1
sOut = sOut + c(x).DisplayName + " [" + c(x).Address + "]; "
Next
Return sOut
End Function
Private Shared Function GetMessageNumberFromSelectedNode(ByVal node As TreeNode) As Integer
If node Is Nothing Then
Throw New ArgumentNullException("node")
End If
' Check if we are at the root, by seeing if it has the Tag property set to an int
If TypeOf node.Tag Is Integer Then
Return CInt(node.Tag)
End If
' Otherwise we are not at the root, move up the tree
Return GetMessageNumberFromSelectedNode(node.Parent)
End Function
Private Sub ListAttachmentsAttachmentSelected(ByVal sender As Object, ByVal args As TreeViewEventArgs)
' Fetch the attachment part which is currently selected
If TypeName(listAttachments.SelectedNode.Tag) = "String" Then
Exit Sub
End If
Dim attachment As MessagePart = DirectCast(listAttachments.SelectedNode.Tag, MessagePart)
saveFile = New SaveFileDialog
If attachment IsNot Nothing Then
saveFile.FileName = attachment.FileName
Dim result As DialogResult = saveFile.ShowDialog()
If result <> DialogResult.OK Then
Return
End If
' Now we want to save the attachment
Dim file As New FileInfo(saveFile.FileName)
If file.Exists Then
file.Delete()
End If
Try
attachment.Save(file)
MessageBox.Show(Me, "Attachment saved successfully")
Catch e As Exception
MessageBox.Show(Me, "Attachment saving failed. Exception message: " + e.Message)
End Try
Else
MessageBox.Show(Me, "Attachment object was null!")
End If
End Sub
Private Sub MessagesContextHandler(ByVal sender As Object, ByVal e As MouseEventArgs)
If e.Button = Windows.Forms.MouseButtons.Left Then
If listMessages.ContextMenuStrip Is Nothing Then Exit Sub
listMessages.ContextMenuStrip.Visible = False
End If
If e.Button = Windows.Forms.MouseButtons.Right Then
listMessages.SelectedNode = listMessages.GetNodeAt(e.X, e.Y)
cms.Items.Clear()
cms.Items.Add("Delete Message")
AddHandler cms.Items(0).Click, AddressOf MenuDeleteMessageClick
cms.Items.Add("Forward Message")
AddHandler cms.Items(1).Click, AddressOf MenuForwardMessageClick
listMessages.ContextMenuStrip = cms
listMessages.ContextMenuStrip.Show()
End If
End Sub
Private Sub MenuForwardMessageClick(ByVal sender As Object, ByVal e As System.EventArgs)
If listMessages.SelectedNode IsNot Nothing Then
Dim f As New frmNewEmail
f.DocumentTemplate = Me.WebBrowser1.DocumentText
Dim messageNumber As Integer = GetMessageNumberFromSelectedNode(listMessages.SelectedNode)
Dim m As OpenPop.Mime.Message
Try
m = p3.GetMessage(messageNumber)
Catch ex As Exception
Try
Login()
m = p3.GetMessage(messageNumber)
Catch ex2 As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Unable to retrieve source message")
Exit Sub
End Try
End Try
f.txtSubject.Text = m.Headers.Subject
f.txtTo.Text = m.Headers.From.Address
'Add the attachments
Dim attachments As List(Of MessagePart) = m.FindAllAttachments()
For Each attachment As MessagePart In attachments
' Add the attachment to the list of attachments
Dim sPath As String
'10-21-2013
sPath = GetGridPath("Temp") + "\" + attachment.FileName
Dim file As New FileInfo(sPath)
If file.Exists Then
Try
file.Delete()
Catch ex As Exception
End Try
End If
Try
attachment.Save(file)
Catch ex As Exception
End Try
Dim addedNode As TreeNode = f.listAttachments.Nodes.Add(sPath)
' Keep a reference to the attachment in the Tag property
addedNode.Tag = sPath
Try
f.listAttachments.Nodes.Add(addedNode)
Catch ex As Exception
End Try
Next
f.Show()
End If
End Sub
Private Sub OfflineDeleteMessageClick(ByVal sender As Object, ByVal e As EventArgs)
If listOfflineStorage.SelectedNode IsNot Nothing Then
' Dim drRet As DialogResult = MessageBox.Show(Me, "Are you sure to delete the email?", "Delete email", MessageBoxButtons.YesNo)
If 1 = 1 Then
Dim sFN As String = listOfflineStorage.SelectedNode.Tag
Try
Try
Kill(sFN)
Catch ex As Exception
End Try
'Delete the attachments
Try
Dim fi As New FileInfo(sFN)
Dim sAtt As String = GetGridPath("MailAttachments") + "\" + Mid(fi.Name, 1, 34) + "*.*"
Kill(sAtt)
Catch ex As Exception
End Try
listOfflineStorage.SelectedNode.Remove()
listOfflineStorage.Refresh()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error occurred while removing the message.")
End Try
End If
End If
End Sub
Private Sub MenuDeleteMessageClick(ByVal sender As Object, ByVal e As EventArgs)
If listMessages.SelectedNode IsNot Nothing Then
Dim drRet As DialogResult = MessageBox.Show(Me, "Are you sure to delete the email?", "Delete email", MessageBoxButtons.YesNo)
If drRet = DialogResult.Yes Then
Dim messageNumber As Integer = GetMessageNumberFromSelectedNode(listMessages.SelectedNode)
Try
Try
p3.DeleteMessage(messageNumber)
Catch ex As Exception
Login()
p3.DeleteMessage(messageNumber)
End Try
listMessages.SelectedNode.Remove()
listMessages.Refresh()
RetrievePop3Emails()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error occurred while removing the message.")
End Try
End If
End If
End Sub
Public Shared Function GetGridPath(ByVal sType As String) As String
Dim sTemp As String
sTemp = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\Gridcoin\" + sType
If System.IO.Directory.Exists(sTemp) = False Then
Try
System.IO.Directory.CreateDirectory(sTemp)
Catch ex As Exception
End Try
End If
Return sTemp
End Function
Private Sub UidlButtonClick(ByVal sender As Object, ByVal e As EventArgs)
Dim uids As List(Of String) = p3.GetMessageUids()
Dim stringBuilder As New StringBuilder()
stringBuilder.Append("UIDL:")
stringBuilder.Append(vbCr & vbLf)
For Each uid As String In uids
stringBuilder.Append(uid)
stringBuilder.Append(vbCr & vbLf)
Next
WebBrowser1.DocumentText = stringBuilder.ToString()
End Sub
Private Sub MenuViewSourceClick(ByVal sender As Object, ByVal e As EventArgs)
If listMessages.SelectedNode IsNot Nothing Then
Dim messageNumber As Integer = GetMessageNumberFromSelectedNode(listMessages.SelectedNode)
' Dim m As OpenPop.Mime.Message = messages(messageNumber)
' We do not know the encoding of the full message - and the parts could be differently
' encoded. Therefore we take a choice of simply using US-ASCII encoding on the raw bytes
' to get the source code for the message. Any bytes not in th US-ASCII encoding, will then be
' turned into question marks "?"
' Dim sourceForm As New ShowSourceForm(Encoding.ASCII.GetString(m.RawMessage))
End If
End Sub
Private Sub MenuStrip1_ItemClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles MenuStrip1.ItemClicked
End Sub
Private Sub ComposeNewMessageToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComposeNewMessageToolStripMenuItem.Click
Dim f As New frmNewEmail
f.Show()
End Sub
Private Sub RefreshToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RefreshToolStripMenuItem.Click
RetrievePop3Emails(True)
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Me.Close()
End Sub
Private Sub ProgressBar1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ProgressBar1.Click
End Sub
End Class
|
Lederstrumpf/Gridcoin-Research
|
contrib/Installer/boinc/boinc/OldAlgos/frmMail.vb
|
Visual Basic
|
mit
| 28,869
|
' 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.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
Imports Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking
Imports Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities.GoToHelpers
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Shared.TestHooks
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.Text.Shared.Extensions
Imports Microsoft.VisualStudio.Composition
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Operations
Imports Microsoft.VisualStudio.Text.Tagging
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename
Friend Module RenameTestHelpers
<ThreadStatic>
Friend _exportProvider As ExportProvider = MinimalTestExportProvider.CreateExportProvider(
TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithParts(GetType(MockDocumentNavigationServiceFactory), GetType(RenameWaiter)))
Friend ReadOnly Property ExportProvider As ExportProvider
Get
If _exportProvider Is Nothing Then
_exportProvider = MinimalTestExportProvider.CreateExportProvider(
TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithParts(GetType(MockDocumentNavigationServiceFactory), GetType(RenameWaiter)))
End If
Return _exportProvider
End Get
End Property
Private Function GetSessionInfo(workspace As TestWorkspace) As Tuple(Of Document, TextSpan)
Dim hostdoc = workspace.DocumentWithCursor
Dim caretPosition = hostdoc.CursorPosition.Value
Dim textBuffer = hostdoc.GetTextBuffer()
' Make sure the undo manager is hooked up to this text buffer. This is automatically
' done in any real editor.
workspace.GetService(Of ITextBufferUndoManagerProvider).GetTextBufferUndoManager(textBuffer)
Dim solution = workspace.CurrentSolution
Dim token = solution.GetDocument(hostdoc.Id).GetSyntaxRootAsync().Result.FindToken(caretPosition)
Return Tuple.Create(solution.GetDocument(hostdoc.Id), token.Span)
End Function
Public Function StartSession(workspace As TestWorkspace) As InlineRenameSession
Dim renameService = workspace.GetService(Of IInlineRenameService)()
Dim sessionInfo = GetSessionInfo(workspace)
Return DirectCast(renameService.StartInlineSession(sessionInfo.Item1, sessionInfo.Item2).Session, InlineRenameSession)
End Function
Public Sub AssertTokenRenamable(workspace As TestWorkspace)
Dim renameService = DirectCast(workspace.GetService(Of IInlineRenameService)(), InlineRenameService)
Dim sessionInfo = GetSessionInfo(workspace)
Dim editorService = sessionInfo.Item1.GetLanguageService(Of IEditorInlineRenameService)
Dim result = editorService.GetRenameInfoAsync(sessionInfo.Item1, sessionInfo.Item2.Start, CancellationToken.None).WaitAndGetResult(CancellationToken.None)
Assert.True(result.CanRename)
Assert.Null(result.LocalizedErrorMessage)
End Sub
Public Sub AssertTokenNotRenamable(workspace As TestWorkspace)
Dim renameService = DirectCast(workspace.GetService(Of IInlineRenameService)(), InlineRenameService)
Dim sessionInfo = GetSessionInfo(workspace)
Dim editorService = sessionInfo.Item1.GetLanguageService(Of IEditorInlineRenameService)
Dim result = editorService.GetRenameInfoAsync(sessionInfo.Item1, sessionInfo.Item2.Start, CancellationToken.None).WaitAndGetResult(CancellationToken.None)
Assert.False(result.CanRename)
Assert.NotNull(result.LocalizedErrorMessage)
End Sub
Public Sub VerifyTagsAreCorrect(workspace As TestWorkspace, newIdentifierName As String)
WaitForRename(workspace)
For Each document In workspace.Documents
For Each selectedSpan In document.SelectedSpans
Dim trackingSpan = document.InitialTextSnapshot.CreateTrackingSpan(selectedSpan.ToSpan(), SpanTrackingMode.EdgeInclusive)
Assert.Equal(newIdentifierName, trackingSpan.GetText(document.TextBuffer.CurrentSnapshot).Trim)
Next
Next
For Each document In workspace.Documents
For Each annotations In document.AnnotatedSpans
Dim expectedReplacementText = annotations.Key
If expectedReplacementText <> "CONFLICT" Then
For Each annotatedSpan In annotations.Value
Dim trackingSpan = document.InitialTextSnapshot.CreateTrackingSpan(annotatedSpan.ToSpan(), SpanTrackingMode.EdgeInclusive)
Assert.Equal(expectedReplacementText, trackingSpan.GetText(document.TextBuffer.CurrentSnapshot))
Next
End If
Next
Next
End Sub
Public Function CreateWorkspaceWithWaiter(workspace As XElement) As TestWorkspace
Dim testWorkspace = TestWorkspaceFactory.CreateWorkspace(
workspace,
exportProvider:=ExportProvider)
testWorkspace.GetOpenDocumentIds().Select(Function(id) testWorkspace.GetTestDocument(id).GetTextView()).ToList()
Return testWorkspace
End Function
Public Sub WaitForRename(workspace As TestWorkspace)
workspace.ExportProvider.GetExportedValues(Of IAsynchronousOperationWaiter) _
.Select(Function(waiter) waiter.CreateWaitTask()) _
.PumpingWaitAll()
End Sub
Public Function CreateRenameTrackingTagger(workspace As TestWorkspace, document As TestHostDocument) As ITagger(Of RenameTrackingTag)
Dim tracker = New RenameTrackingTaggerProvider(
workspace.ExportProvider.GetExport(Of ITextUndoHistoryRegistry)().Value,
workspace.ExportProvider.GetExport(Of IWaitIndicator)().Value,
workspace.ExportProvider.GetExport(Of IInlineRenameService)().Value,
workspace.ExportProvider.GetExport(Of IDiagnosticAnalyzerService)().Value,
SpecializedCollections.SingletonEnumerable(New MockRefactorNotifyService()),
DirectCast(workspace.ExportProvider.GetExports(Of IAsynchronousOperationListener, FeatureMetadata), IEnumerable(Of Lazy(Of IAsynchronousOperationListener, FeatureMetadata))))
Return tracker.CreateTagger(Of RenameTrackingTag)(document.GetTextBuffer())
End Function
Public Sub VerifyNoRenameTrackingTags(tagger As ITagger(Of RenameTrackingTag), workspace As TestWorkspace, document As TestHostDocument)
Dim tags = GetRenameTrackingTags(tagger, workspace, document)
Assert.Equal(0, tags.Count())
End Sub
Public Sub VerifyRenameTrackingTags(tagger As ITagger(Of RenameTrackingTag), workspace As TestWorkspace, document As TestHostDocument, expectedTagCount As Integer)
Dim tags = GetRenameTrackingTags(tagger, workspace, document)
Assert.Equal(expectedTagCount, tags.Count())
End Sub
Public Function GetRenameTrackingTags(tagger As ITagger(Of RenameTrackingTag), workspace As TestWorkspace, document As TestHostDocument) As IEnumerable(Of ITagSpan(Of RenameTrackingTag))
WaitForRename(workspace)
Dim view = document.GetTextView()
Return tagger.GetTags(view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection())
End Function
End Module
End Namespace
|
EricArndt/roslyn
|
src/EditorFeatures/Test2/Rename/RenameTestHelpers.vb
|
Visual Basic
|
apache-2.0
| 8,100
|
' 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.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module MethodBaseSyntaxExtensions
<Extension>
Public Function WithParameterList(method As MethodBaseSyntax, parameterList As ParameterListSyntax) As MethodBaseSyntax
Select Case method.Kind
Case SyntaxKind.SubNewStatement
Return DirectCast(method, SubNewStatementSyntax).WithParameterList(parameterList)
Case SyntaxKind.OperatorStatement
Return DirectCast(method, OperatorStatementSyntax).WithParameterList(parameterList)
Case SyntaxKind.PropertyStatement
Return DirectCast(method, PropertyStatementSyntax).WithParameterList(parameterList)
End Select
If TypeOf method Is MethodStatementSyntax Then
Return DirectCast(method, MethodStatementSyntax).WithParameterList(parameterList)
ElseIf TypeOf method Is AccessorStatementSyntax Then
Return DirectCast(method, AccessorStatementSyntax).WithParameterList(parameterList)
ElseIf TypeOf method Is DeclareStatementSyntax Then
Return DirectCast(method, DeclareStatementSyntax).WithParameterList(parameterList)
ElseIf TypeOf method Is DelegateStatementSyntax Then
Return DirectCast(method, DelegateStatementSyntax).WithParameterList(parameterList)
ElseIf TypeOf method Is EventStatementSyntax Then
Return DirectCast(method, EventStatementSyntax).WithParameterList(parameterList)
ElseIf TypeOf method Is LambdaHeaderSyntax Then
Return DirectCast(method, LambdaHeaderSyntax).WithParameterList(parameterList)
End If
Throw ExceptionUtilities.Unreachable
End Function
End Module
End Namespace
|
amcasey/roslyn
|
src/Workspaces/VisualBasic/Portable/Extensions/MethodBaseSyntaxExtensions.vb
|
Visual Basic
|
apache-2.0
| 2,260
|
' 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.InteropServices
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel
Partial Public MustInherit Class AbstractCodeElementTests(Of TCodeElement As Class)
Inherits AbstractCodeModelObjectTests(Of TCodeElement)
Protected Overridable ReadOnly Property TargetExternalCodeElements As Boolean
Get
Return False
End Get
End Property
Private Function GetCodeElement(state As CodeModelTestState) As TCodeElement
Dim codeElement = state.GetCodeElementAtCursor(Of TCodeElement)
Return If(codeElement IsNot Nothing AndAlso TargetExternalCodeElements,
codeElement.AsExternal(),
codeElement)
End Function
Protected Overloads Async Function TestElement(code As XElement, expected As Action(Of TCodeElement)) As Task
Using state = Await CreateCodeModelTestStateAsync(GetWorkspaceDefinition(code))
Dim codeElement = GetCodeElement(state)
Assert.NotNull(codeElement)
expected(codeElement)
End Using
End Function
Friend Overloads Async Function TestElement(code As XElement, expected As Action(Of CodeModelTestState, TCodeElement)) As Task
Using state = Await CreateCodeModelTestStateAsync(GetWorkspaceDefinition(code))
Dim codeElement = GetCodeElement(state)
Assert.NotNull(codeElement)
expected(state, codeElement)
End Using
End Function
Protected Overloads Async Function TestElementUpdate(code As XElement, expectedCode As XElement, updater As Action(Of TCodeElement)) As Task
Using state = Await CreateCodeModelTestStateAsync(GetWorkspaceDefinition(code))
Dim codeElement = GetCodeElement(state)
Assert.NotNull(codeElement)
updater(codeElement)
Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString()
Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim())
End Using
End Function
Friend Overloads Async Function TestElementUpdate(code As XElement, expectedCode As XElement, updater As Action(Of CodeModelTestState, TCodeElement)) As Task
Using state = Await CreateCodeModelTestStateAsync(GetWorkspaceDefinition(code))
Dim codeElement = GetCodeElement(state)
Assert.NotNull(codeElement)
updater(state, codeElement)
Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString()
Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim())
End Using
End Function
Protected Delegate Sub PartAction(part As EnvDTE.vsCMPart, textPointGetter As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint))
Protected Function Part(p As EnvDTE.vsCMPart, action As PartAction) As Action(Of Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint))
Return _
Sub(textPointGetter)
action(p, textPointGetter)
End Sub
End Function
Protected Function ThrowsNotImplementedException() As PartAction
Return Sub(part, textPointGetter)
Assert.Throws(Of NotImplementedException)(
Sub()
textPointGetter(part)
End Sub)
End Sub
End Function
Protected Const E_FAIL = &H80004005
Protected Function ThrowsCOMException(errorCode As Integer) As PartAction
Return _
Sub(part, textPointGetter)
Dim exception = Assert.Throws(Of COMException)(
Sub()
textPointGetter(part)
End Sub)
Assert.Equal(errorCode, exception.ErrorCode)
End Sub
End Function
Protected ReadOnly NullTextPoint As PartAction =
Sub(part, textPointGetter)
Dim tp As EnvDTE.TextPoint = Nothing
tp = textPointGetter(part)
Assert.Null(tp)
End Sub
Protected Function TextPoint(Optional line As Integer? = Nothing, Optional lineOffset As Integer? = Nothing, Optional absoluteOffset As Integer? = Nothing, Optional lineLength As Integer? = Nothing) As PartAction
Return _
Sub(part, textPointGetter)
Dim tp As EnvDTE.TextPoint = Nothing
tp = textPointGetter(part)
Assert.NotNull(tp)
If line IsNot Nothing Then
Assert.True(tp.Line = line.Value,
vbCrLf &
"TextPoint.Line was incorrect for " & part.ToString() & "." & vbCrLf &
"Expected: " & line & vbCrLf &
"But was: " & tp.Line)
End If
If lineOffset IsNot Nothing Then
Assert.True(tp.LineCharOffset = lineOffset.Value,
vbCrLf &
"TextPoint.LineCharOffset was incorrect for " & part.ToString() & "." & vbCrLf &
"Expected: " & lineOffset & vbCrLf &
"But was: " & tp.LineCharOffset)
End If
If absoluteOffset IsNot Nothing Then
Assert.True(tp.AbsoluteCharOffset = absoluteOffset.Value,
vbCrLf &
"TextPoint.AbsoluteCharOffset was incorrect for " & part.ToString() & "." & vbCrLf &
"Expected: " & absoluteOffset & vbCrLf &
"But was: " & tp.AbsoluteCharOffset)
End If
If lineLength IsNot Nothing Then
Assert.True(tp.LineLength = lineLength.Value,
vbCrLf &
"TextPoint.LineLength was incorrect for " & part.ToString() & "." & vbCrLf &
"Expected: " & lineLength & vbCrLf &
"But was: " & tp.LineLength)
End If
End Sub
End Function
Protected Friend Delegate Sub SetterAction(Of T)(newValue As T, valueSetter As Action(Of T))
Protected Function NoThrow(Of T)() As SetterAction(Of T)
Return _
Sub(value, valueSetter)
valueSetter(value)
End Sub
End Function
Protected Function ThrowsArgumentException(Of T)() As SetterAction(Of T)
Return _
Sub(value, valueSetter)
Assert.Throws(Of ArgumentException)(
Sub()
valueSetter(value)
End Sub)
End Sub
End Function
Protected Function ThrowsCOMException(Of T)(errorCode As Integer) As SetterAction(Of T)
Return _
Sub(value, valueSetter)
Dim exception = Assert.Throws(Of COMException)(
Sub()
valueSetter(value)
End Sub)
Assert.Equal(errorCode, exception.ErrorCode)
End Sub
End Function
Protected Function ThrowsInvalidOperationException(Of T)() As SetterAction(Of T)
Return _
Sub(value, valueSetter)
Assert.Throws(Of InvalidOperationException)(
Sub()
valueSetter(value)
End Sub)
End Sub
End Function
Protected Function ThrowsNotImplementedException(Of T)() As SetterAction(Of T)
Return _
Sub(value, valueSetter)
Assert.Throws(Of NotImplementedException)(
Sub()
valueSetter(value)
End Sub)
End Sub
End Function
Protected MustOverride Function GetStartPointFunc(codeElement As TCodeElement) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint)
Protected MustOverride Function GetEndPointFunc(codeElement As TCodeElement) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint)
Protected MustOverride Function GetFullName(codeElement As TCodeElement) As String
Protected MustOverride Function GetKind(codeElement As TCodeElement) As EnvDTE.vsCMElement
Protected MustOverride Function GetName(codeElement As TCodeElement) As String
Protected MustOverride Function GetNameSetter(codeElement As TCodeElement) As Action(Of String)
Protected Overridable Function GetNamespace(codeElement As TCodeElement) As EnvDTE.CodeNamespace
Throw New NotSupportedException
End Function
Protected Overridable Function GetAccess(codeElement As TCodeElement) As EnvDTE.vsCMAccess
Throw New NotSupportedException
End Function
Protected Overridable Function GetAttributes(codeElement As TCodeElement) As EnvDTE.CodeElements
Throw New NotSupportedException
End Function
Protected Overridable Function GetBases(codeElement As TCodeElement) As EnvDTE.CodeElements
Throw New NotSupportedException
End Function
Protected Overridable Function GetClassKind(codeElement As TCodeElement) As EnvDTE80.vsCMClassKind
Throw New NotSupportedException
End Function
Protected Overridable Function GetComment(codeElement As TCodeElement) As String
Throw New NotSupportedException
End Function
Protected Overridable Function GetCommentSetter(codeElement As TCodeElement) As Action(Of String)
Throw New NotSupportedException
End Function
Protected Overridable Function GetConstKind(codeElement As TCodeElement) As EnvDTE80.vsCMConstKind
Throw New NotSupportedException
End Function
Protected Overridable Function GetDataTypeKind(codeElement As TCodeElement) As EnvDTE80.vsCMDataTypeKind
Throw New NotSupportedException
End Function
Protected Overridable Function GetDocComment(codeElement As TCodeElement) As String
Throw New NotSupportedException
End Function
Protected Overridable Function GetDocCommentSetter(codeElement As TCodeElement) As Action(Of String)
Throw New NotSupportedException
End Function
Protected Overridable Function GetImplementedInterfaces(codeElement As TCodeElement) As EnvDTE.CodeElements
Throw New NotSupportedException
End Function
Protected Overridable Function GetInheritanceKind(codeElement As TCodeElement) As EnvDTE80.vsCMInheritanceKind
Throw New NotSupportedException
End Function
Protected Overridable Function GetIsAbstract(codeElement As TCodeElement) As Boolean
Throw New NotSupportedException
End Function
Protected Overridable Function GetIsDefault(codeElement As TCodeElement) As Boolean
Throw New NotSupportedException
End Function
Protected Overridable Function GetIsGeneric(codeElement As TCodeElement) As Boolean
Throw New NotSupportedException
End Function
Protected Overridable Function GetIsShared(codeElement As TCodeElement) As Boolean
Throw New NotSupportedException
End Function
Protected Overridable Function GetMustImplement(codeElement As TCodeElement) As Boolean
Throw New NotSupportedException
End Function
Protected Overridable Function GetOverrideKind(codeElement As TCodeElement) As EnvDTE80.vsCMOverrideKind
Throw New NotSupportedException
End Function
Protected Overridable Function GetParent(codeElement As TCodeElement) As Object
Throw New NotSupportedException
End Function
Protected Overridable Function GetParts(codeElement As TCodeElement) As EnvDTE.CodeElements
Throw New NotSupportedException
End Function
Protected Overridable Function GetPrototype(codeElement As TCodeElement, flags As EnvDTE.vsCMPrototype) As String
Throw New NotSupportedException
End Function
Protected Overridable Function GetReadWrite(codeElement As TCodeElement) As EnvDTE80.vsCMPropertyKind
Throw New NotSupportedException
End Function
Protected Overridable Overloads Function GetTypeProp(codeElement As TCodeElement) As EnvDTE.CodeTypeRef
Throw New NotSupportedException
End Function
Protected Overridable Function IsDerivedFrom(codeElement As TCodeElement, fullName As String) As Boolean
Throw New NotSupportedException
End Function
Protected Overridable Function AddAttribute(codeElement As TCodeElement, data As AttributeData) As EnvDTE.CodeAttribute
Throw New NotSupportedException
End Function
Protected Overridable Function AddEnumMember(codeElement As TCodeElement, data As EnumMemberData) As EnvDTE.CodeVariable
Throw New NotSupportedException
End Function
Protected Overridable Function AddEvent(codeElement As TCodeElement, data As EventData) As EnvDTE80.CodeEvent
Throw New NotSupportedException
End Function
Protected Overridable Function AddFunction(codeElement As TCodeElement, data As FunctionData) As EnvDTE.CodeFunction
Throw New NotSupportedException
End Function
Protected Overridable Function AddParameter(codeElement As TCodeElement, data As ParameterData) As EnvDTE.CodeParameter
Throw New NotSupportedException
End Function
Protected Overridable Function AddProperty(codeElement As TCodeElement, data As PropertyData) As EnvDTE.CodeProperty
Throw New NotSupportedException
End Function
Protected Overridable Function AddVariable(codeElement As TCodeElement, data As VariableData) As EnvDTE.CodeVariable
Throw New NotSupportedException
End Function
Protected Overridable Function GetAccessSetter(codeElement As TCodeElement) As Action(Of EnvDTE.vsCMAccess)
Throw New NotSupportedException
End Function
Protected Overridable Function GetClassKindSetter(codeElement As TCodeElement) As Action(Of EnvDTE80.vsCMClassKind)
Throw New NotSupportedException
End Function
Protected Overridable Function GetConstKindSetter(codeElement As TCodeElement) As Action(Of EnvDTE80.vsCMConstKind)
Throw New NotSupportedException
End Function
Protected Overridable Function GetDataTypeKindSetter(codeElement As TCodeElement) As Action(Of EnvDTE80.vsCMDataTypeKind)
Throw New NotSupportedException
End Function
Protected Overridable Function GetInheritanceKindSetter(codeElement As TCodeElement) As Action(Of EnvDTE80.vsCMInheritanceKind)
Throw New NotSupportedException
End Function
Protected Overridable Function GetIsAbstractSetter(codeElement As TCodeElement) As Action(Of Boolean)
Throw New NotSupportedException
End Function
Protected Overridable Function GetIsDefaultSetter(codeElement As TCodeElement) As Action(Of Boolean)
Throw New NotSupportedException
End Function
Protected Overridable Function GetIsSharedSetter(codeElement As TCodeElement) As Action(Of Boolean)
Throw New NotSupportedException
End Function
Protected Overridable Function GetMustImplementSetter(codeElement As TCodeElement) As Action(Of Boolean)
Throw New NotSupportedException
End Function
Protected Overridable Function GetOverrideKindSetter(codeElement As TCodeElement) As Action(Of EnvDTE80.vsCMOverrideKind)
Throw New NotSupportedException
End Function
Protected Overridable Function GetTypePropSetter(codeElement As TCodeElement) As Action(Of EnvDTE.CodeTypeRef)
Throw New NotSupportedException
End Function
Protected Overridable Sub RemoveChild(codeElement As TCodeElement, child As Object)
Throw New NotSupportedException
End Sub
Protected Overridable Function GenericNameExtender_GetBaseTypesCount(codeElement As TCodeElement) As Integer
Throw New NotSupportedException
End Function
Protected Overridable Function GenericNameExtender_GetImplementedTypesCount(codeElement As TCodeElement) As Integer
Throw New NotSupportedException
End Function
Protected Overridable Function GenericNameExtender_GetBaseGenericName(codeElement As TCodeElement, index As Integer) As String
Throw New NotSupportedException
End Function
Protected Overridable Function GenericNameExtender_GetImplTypeGenericName(codeElement As TCodeElement, index As Integer) As String
Throw New NotSupportedException
End Function
Protected Overridable Function AddBase(codeElement As TCodeElement, base As Object, position As Object) As EnvDTE.CodeElement
Throw New NotSupportedException
End Function
Protected Overridable Sub RemoveBase(codeElement As TCodeElement, element As Object)
Throw New NotSupportedException
End Sub
Protected Overridable Function AddImplementedInterface(codeElement As TCodeElement, base As Object, position As Object) As EnvDTE.CodeInterface
Throw New NotSupportedException
End Function
Protected Overridable Function GetParameters(codeElement As TCodeElement) As EnvDTE.CodeElements
Throw New NotSupportedException
End Function
Protected Overridable Sub RemoveImplementedInterface(codeElement As TCodeElement, element As Object)
Throw New NotSupportedException
End Sub
Protected Async Function TestPropertyDescriptors(code As XElement, ParamArray expectedPropertyNames As String()) As Task
Await TestElement(code,
Sub(codeElement)
Dim propertyDescriptors = ComponentModel.TypeDescriptor.GetProperties(codeElement)
Dim propertyNames = propertyDescriptors _
.OfType(Of ComponentModel.PropertyDescriptor) _
.Select(Function(pd) pd.Name) _
.ToArray()
Assert.Equal(expectedPropertyNames, propertyNames)
End Sub)
End Function
Protected Async Function TestGetStartPoint(code As XElement, ParamArray expectedParts() As Action(Of Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint))) As Task
Await TestElement(code,
Sub(codeElement)
Dim textPointGetter = GetStartPointFunc(codeElement)
For Each action In expectedParts
action(textPointGetter)
Next
End Sub)
End Function
Protected Async Function TestGetEndPoint(code As XElement, ParamArray expectedParts() As Action(Of Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint))) As Task
Await TestElement(code,
Sub(codeElement)
Dim textPointGetter = GetEndPointFunc(codeElement)
For Each action In expectedParts
action(textPointGetter)
Next
End Sub)
End Function
Protected Async Function TestAccess(code As XElement, expectedAccess As EnvDTE.vsCMAccess) As Task
Await TestElement(code,
Sub(codeElement)
Dim access = GetAccess(codeElement)
Assert.Equal(expectedAccess, access)
End Sub)
End Function
Protected Async Function TestAttributes(code As XElement, ParamArray expectedAttributes() As Action(Of Object)) As Task
Await TestElement(code,
Sub(codeElement)
Dim attributes = GetAttributes(codeElement)
Assert.Equal(expectedAttributes.Length, attributes.Count)
For i = 1 To attributes.Count
expectedAttributes(i - 1)(attributes.Item(i))
Next
End Sub)
End Function
Protected Async Function TestBases(code As XElement, ParamArray expectedBases() As Action(Of Object)) As Task
Await TestElement(code,
Sub(codeElement)
Dim bases = GetBases(codeElement)
Assert.Equal(expectedBases.Length, bases.Count)
For i = 1 To bases.Count
expectedBases(i - 1)(bases.Item(i))
Next
End Sub)
End Function
Protected Overrides Async Function TestChildren(code As XElement, ParamArray expectedChildren() As Action(Of Object)) As Task
Await TestElement(code,
Sub(codeElement)
Dim element = CType(codeElement, EnvDTE.CodeElement)
Assert.True(element IsNot Nothing, $"Could not cast {GetType(TCodeElement).FullName} to {GetType(EnvDTE.CodeElement).FullName}.")
Dim children = element.Children
Assert.Equal(expectedChildren.Length, children.Count)
For i = 1 To children.Count
expectedChildren(i - 1)(children.Item(i))
Next
End Sub)
End Function
Protected Async Function TestClassKind(code As XElement, expectedClassKind As EnvDTE80.vsCMClassKind) As Task
Await TestElement(code,
Sub(codeElement)
Dim classKind = GetClassKind(codeElement)
Assert.Equal(expectedClassKind, classKind)
End Sub)
End Function
Protected Async Function TestComment(code As XElement, expectedComment As String) As Task
Await TestElement(code,
Sub(codeElement)
Dim comment = GetComment(codeElement)
Assert.Equal(expectedComment, comment)
End Sub)
End Function
Protected Async Function TestConstKind(code As XElement, expectedConstKind As EnvDTE80.vsCMConstKind) As Task
Await TestElement(code,
Sub(codeElement)
Dim constKind = GetConstKind(codeElement)
Assert.Equal(expectedConstKind, constKind)
End Sub)
End Function
Protected Async Function TestDataTypeKind(code As XElement, expectedDataTypeKind As EnvDTE80.vsCMDataTypeKind) As Task
Await TestElement(code,
Sub(codeElement)
Dim dataTypeKind = GetDataTypeKind(codeElement)
Assert.Equal(expectedDataTypeKind, dataTypeKind)
End Sub)
End Function
Protected Async Function TestDocComment(code As XElement, expectedDocComment As String) As Task
Await TestElement(code,
Sub(codeElement)
Dim docComment = GetDocComment(codeElement)
Assert.Equal(expectedDocComment, docComment)
End Sub)
End Function
Protected Async Function TestFullName(code As XElement, expectedFullName As String) As Task
Await TestElement(code,
Sub(codeElement)
Dim fullName = GetFullName(codeElement)
Assert.Equal(expectedFullName, fullName)
End Sub)
End Function
Protected Async Function TestImplementedInterfaces(code As XElement, ParamArray expectedBases() As Action(Of Object)) As Task
Await TestElement(code,
Sub(codeElement)
Dim implementedInterfaces = GetImplementedInterfaces(codeElement)
Assert.Equal(expectedBases.Length, implementedInterfaces.Count)
For i = 1 To implementedInterfaces.Count
expectedBases(i - 1)(implementedInterfaces.Item(i))
Next
End Sub)
End Function
Protected Async Function TestInheritanceKind(code As XElement, expectedInheritanceKind As EnvDTE80.vsCMInheritanceKind) As Task
Await TestElement(code,
Sub(codeElement)
Dim inheritanceKind = GetInheritanceKind(codeElement)
Assert.Equal(expectedInheritanceKind, inheritanceKind)
End Sub)
End Function
Protected Async Function TestIsAbstract(code As XElement, expectedValue As Boolean) As Task
Await TestElement(code,
Sub(codeElement)
Dim value = GetIsAbstract(codeElement)
Assert.Equal(expectedValue, value)
End Sub)
End Function
Protected Async Function TestIsDefault(code As XElement, expectedValue As Boolean) As Task
Await TestElement(code,
Sub(codeElement)
Dim value = GetIsDefault(codeElement)
Assert.Equal(expectedValue, value)
End Sub)
End Function
Protected Async Function TestIsGeneric(code As XElement, expectedValue As Boolean) As Task
Await TestElement(code,
Sub(codeElement)
Dim value = GetIsGeneric(codeElement)
Assert.Equal(expectedValue, value)
End Sub)
End Function
Protected Async Function TestIsShared(code As XElement, expectedValue As Boolean) As Task
Await TestElement(code,
Sub(codeElement)
Dim value = GetIsShared(codeElement)
Assert.Equal(expectedValue, value)
End Sub)
End Function
Protected Async Function TestKind(code As XElement, expectedKind As EnvDTE.vsCMElement) As Task
Await TestElement(code,
Sub(codeElement)
Dim kind = GetKind(codeElement)
Assert.Equal(expectedKind, kind)
End Sub)
End Function
Protected Async Function TestMustImplement(code As XElement, expectedValue As Boolean) As Task
Await TestElement(code,
Sub(codeElement)
Dim value = GetMustImplement(codeElement)
Assert.Equal(expectedValue, value)
End Sub)
End Function
Protected Async Function TestName(code As XElement, expectedName As String) As Task
Await TestElement(code,
Sub(codeElement)
Dim name = GetName(codeElement)
Assert.Equal(expectedName, name)
End Sub)
End Function
Protected Async Function TestOverrideKind(code As XElement, expectedOverrideKind As EnvDTE80.vsCMOverrideKind) As Task
Await TestElement(code,
Sub(codeElement)
Dim overrideKind = GetOverrideKind(codeElement)
Assert.Equal(expectedOverrideKind, overrideKind)
End Sub)
End Function
Protected Async Function TestParts(code As XElement, expectedPartCount As Integer) As Task
Await TestElement(code,
Sub(codeElement)
Dim parts = GetParts(codeElement)
' TODO: Test the elements themselves, not just the count (PartialTypeCollection.Item is not fully implemented)
Assert.Equal(expectedPartCount, parts.Count)
End Sub)
End Function
Protected Async Function TestParent(code As XElement, expectedParent As Action(Of Object)) As Task
Await TestElement(code,
Sub(codeElement)
Dim parent = GetParent(codeElement)
expectedParent(parent)
End Sub)
End Function
Protected Async Function TestPrototype(code As XElement, flags As EnvDTE.vsCMPrototype, expectedPrototype As String) As Task
Await TestElement(code,
Sub(codeElement)
Dim prototype = GetPrototype(codeElement, flags)
Assert.Equal(expectedPrototype, prototype)
End Sub)
End Function
Protected Async Function TestPrototypeThrows(Of TException As Exception)(code As XElement, flags As EnvDTE.vsCMPrototype) As Task
Await TestElement(code,
Sub(codeElement)
Assert.Throws(Of TException)(Sub() GetPrototype(codeElement, flags))
End Sub)
End Function
Protected Async Function TestReadWrite(code As XElement, expectedOverrideKind As EnvDTE80.vsCMPropertyKind) As Task
Await TestElement(code,
Sub(codeElement)
Dim readWrite = GetReadWrite(codeElement)
Assert.Equal(expectedOverrideKind, readWrite)
End Sub)
End Function
Protected Async Function TestIsDerivedFrom(code As XElement, baseFullName As String, expectedIsDerivedFrom As Boolean) As Task
Await TestElement(code,
Sub(codeElement)
Dim actualIsDerivedFrom = IsDerivedFrom(codeElement, baseFullName)
Assert.Equal(expectedIsDerivedFrom, actualIsDerivedFrom)
End Sub)
End Function
Protected Async Function TestTypeProp(code As XElement, data As CodeTypeRefData) As Task
Await TestElement(code,
Sub(codeElement)
Dim codeTypeRef = GetTypeProp(codeElement)
TestCodeTypeRef(codeTypeRef, data)
End Sub)
End Function
Protected Overrides Async Function TestAddAttribute(code As XElement, expectedCode As XElement, data As AttributeData) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim attribute = AddAttribute(codeElement, data)
Assert.NotNull(attribute)
Assert.Equal(data.Name, attribute.Name)
End Sub)
End Function
Protected Overrides Async Function TestAddEnumMember(code As XElement, expectedCode As XElement, data As EnumMemberData) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim enumMember = AddEnumMember(codeElement, data)
Assert.NotNull(enumMember)
Assert.Equal(data.Name, enumMember.Name)
End Sub)
End Function
Protected Overrides Async Function TestAddEvent(code As XElement, expectedCode As XElement, data As EventData) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim ev = AddEvent(codeElement, data)
Assert.NotNull(ev)
Assert.Equal(data.Name, ev.Name)
End Sub)
End Function
Protected Overrides Async Function TestAddFunction(code As XElement, expectedCode As XElement, data As FunctionData) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim func = AddFunction(codeElement, data)
Assert.NotNull(func)
If data.Kind <> EnvDTE.vsCMFunction.vsCMFunctionDestructor Then
Assert.Equal(data.Name, func.Name)
End If
End Sub)
End Function
Protected Overrides Async Function TestAddParameter(code As XElement, expectedCode As XElement, data As ParameterData) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim name = GetName(codeElement)
Dim parameter = AddParameter(codeElement, data)
Assert.NotNull(parameter)
Assert.Equal(data.Name, parameter.Name)
' Verify we haven't screwed up any node keys by checking that we
' can still access the parent element after adding the parameter.
Assert.Equal(name, GetName(codeElement))
End Sub)
End Function
Protected Overrides Async Function TestAddProperty(code As XElement, expectedCode As XElement, data As PropertyData) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim prop = AddProperty(codeElement, data)
Assert.NotNull(prop)
Assert.True(data.GetterName = prop.Name OrElse data.PutterName = prop.Name)
End Sub)
End Function
Protected Overrides Async Function TestAddVariable(code As XElement, expectedCode As XElement, data As VariableData) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim variable = AddVariable(codeElement, data)
Assert.NotNull(variable)
Assert.Equal(data.Name, variable.Name)
End Sub)
End Function
Protected Overrides Async Function TestRemoveChild(code As XElement, expectedCode As XElement, child As Object) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim name = GetName(codeElement)
RemoveChild(codeElement, child)
' Verify we haven't screwed up any node keys by checking that we
' can still access the parent element after deleting the child.
Assert.Equal(name, GetName(codeElement))
End Sub)
End Function
Protected Async Function TestSetAccess(code As XElement, expectedCode As XElement, access As EnvDTE.vsCMAccess) As Task
Await TestSetAccess(code, expectedCode, access, NoThrow(Of EnvDTE.vsCMAccess)())
End Function
Protected Async Function TestSetAccess(code As XElement, expectedCode As XElement, access As EnvDTE.vsCMAccess, action As SetterAction(Of EnvDTE.vsCMAccess)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim accessSetter = GetAccessSetter(codeElement)
action(access, accessSetter)
End Sub)
End Function
Protected Async Function TestSetClassKind(code As XElement, expectedCode As XElement, kind As EnvDTE80.vsCMClassKind) As Task
Await TestSetClassKind(code, expectedCode, kind, NoThrow(Of EnvDTE80.vsCMClassKind)())
End Function
Protected Async Function TestSetClassKind(code As XElement, expectedCode As XElement, kind As EnvDTE80.vsCMClassKind, action As SetterAction(Of EnvDTE80.vsCMClassKind)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim classKindSetter = GetClassKindSetter(codeElement)
action(kind, classKindSetter)
End Sub)
End Function
Protected Async Function TestSetComment(code As XElement, expectedCode As XElement, value As String) As Task
Await TestSetComment(code, expectedCode, value, NoThrow(Of String)())
End Function
Protected Async Function TestSetComment(code As XElement, expectedCode As XElement, value As String, action As SetterAction(Of String)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim commentSetter = GetCommentSetter(codeElement)
action(value, commentSetter)
End Sub)
End Function
Protected Async Function TestSetConstKind(code As XElement, expectedCode As XElement, kind As EnvDTE80.vsCMConstKind) As Task
Await TestSetConstKind(code, expectedCode, kind, NoThrow(Of EnvDTE80.vsCMConstKind)())
End Function
Protected Async Function TestSetConstKind(code As XElement, expectedCode As XElement, kind As EnvDTE80.vsCMConstKind, action As SetterAction(Of EnvDTE80.vsCMConstKind)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim constKindSetter = GetConstKindSetter(codeElement)
action(kind, constKindSetter)
End Sub)
End Function
Protected Async Function TestSetDataTypeKind(code As XElement, expectedCode As XElement, kind As EnvDTE80.vsCMDataTypeKind) As Task
Await TestSetDataTypeKind(code, expectedCode, kind, NoThrow(Of EnvDTE80.vsCMDataTypeKind)())
End Function
Protected Async Function TestSetDataTypeKind(code As XElement, expectedCode As XElement, kind As EnvDTE80.vsCMDataTypeKind, action As SetterAction(Of EnvDTE80.vsCMDataTypeKind)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim dataTypeKindSetter = GetDataTypeKindSetter(codeElement)
action(kind, dataTypeKindSetter)
End Sub)
End Function
Protected Async Function TestSetDocComment(code As XElement, expectedCode As XElement, value As String) As Task
Await TestSetDocComment(code, expectedCode, value, NoThrow(Of String)())
End Function
Protected Async Function TestSetDocComment(code As XElement, expectedCode As XElement, value As String, action As SetterAction(Of String)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim docCommentSetter = GetDocCommentSetter(codeElement)
action(value, docCommentSetter)
End Sub)
End Function
Protected Async Function TestSetInheritanceKind(code As XElement, expectedCode As XElement, kind As EnvDTE80.vsCMInheritanceKind) As Task
Await TestSetInheritanceKind(code, expectedCode, kind, NoThrow(Of EnvDTE80.vsCMInheritanceKind)())
End Function
Protected Async Function TestSetInheritanceKind(code As XElement, expectedCode As XElement, kind As EnvDTE80.vsCMInheritanceKind, action As SetterAction(Of EnvDTE80.vsCMInheritanceKind)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim inheritanceKindSetter = GetInheritanceKindSetter(codeElement)
action(kind, inheritanceKindSetter)
End Sub)
End Function
Protected Async Function TestSetIsAbstract(code As XElement, expectedCode As XElement, value As Boolean) As Task
Await TestSetIsAbstract(code, expectedCode, value, NoThrow(Of Boolean)())
End Function
Protected Async Function TestSetIsAbstract(code As XElement, expectedCode As XElement, value As Boolean, action As SetterAction(Of Boolean)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim isAbstractSetter = GetIsAbstractSetter(codeElement)
action(value, isAbstractSetter)
End Sub)
End Function
Protected Async Function TestSetIsDefault(code As XElement, expectedCode As XElement, value As Boolean) As Task
Await TestSetIsDefault(code, expectedCode, value, NoThrow(Of Boolean)())
End Function
Protected Async Function TestSetIsDefault(code As XElement, expectedCode As XElement, value As Boolean, action As SetterAction(Of Boolean)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim isDefaultSetter = GetIsDefaultSetter(codeElement)
action(value, isDefaultSetter)
End Sub)
End Function
Protected Async Function TestSetIsShared(code As XElement, expectedCode As XElement, value As Boolean) As Task
Await TestSetIsShared(code, expectedCode, value, NoThrow(Of Boolean)())
End Function
Protected Async Function TestSetIsShared(code As XElement, expectedCode As XElement, value As Boolean, action As SetterAction(Of Boolean)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim isSharedSetter = GetIsSharedSetter(codeElement)
action(value, isSharedSetter)
End Sub)
End Function
Protected Async Function TestSetMustImplement(code As XElement, expectedCode As XElement, value As Boolean) As Task
Await TestSetMustImplement(code, expectedCode, value, NoThrow(Of Boolean)())
End Function
Protected Async Function TestSetMustImplement(code As XElement, expectedCode As XElement, value As Boolean, action As SetterAction(Of Boolean)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim mustImplementSetter = GetMustImplementSetter(codeElement)
action(value, mustImplementSetter)
End Sub)
End Function
Protected Async Function TestSetOverrideKind(code As XElement, expectedCode As XElement, kind As EnvDTE80.vsCMOverrideKind) As Task
Await TestSetOverrideKind(code, expectedCode, kind, NoThrow(Of EnvDTE80.vsCMOverrideKind)())
End Function
Protected Async Function TestSetOverrideKind(code As XElement, expectedCode As XElement, kind As EnvDTE80.vsCMOverrideKind, action As SetterAction(Of EnvDTE80.vsCMOverrideKind)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim overrideKindSetter = GetOverrideKindSetter(codeElement)
action(kind, overrideKindSetter)
End Sub)
End Function
Protected Async Function TestSetName(code As XElement, expectedCode As XElement, name As String, action As SetterAction(Of String)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim nameSetter = GetNameSetter(codeElement)
action(name, nameSetter)
End Sub)
End Function
Protected Async Function TestNamespaceName(code As XElement, name As String) As Task
Await TestElement(code,
Sub(codeElement)
Dim codeNamespaceElement = GetNamespace(codeElement)
Assert.NotNull(codeNamespaceElement)
Assert.Equal(name, codeNamespaceElement.Name)
End Sub)
End Function
Protected Async Function TestSetTypeProp(code As XElement, expectedCode As XElement, codeTypeRef As EnvDTE.CodeTypeRef) As Task
Await TestSetTypeProp(code, expectedCode, codeTypeRef, NoThrow(Of EnvDTE.CodeTypeRef)())
End Function
Protected Async Function TestSetTypeProp(code As XElement, expectedCode As XElement, codeTypeRef As EnvDTE.CodeTypeRef, action As SetterAction(Of EnvDTE.CodeTypeRef)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim typePropSetter = GetTypePropSetter(codeElement)
action(codeTypeRef, typePropSetter)
End Sub)
End Function
Protected Async Function TestSetTypeProp(code As XElement, expectedCode As XElement, typeName As String) As Task
Await TestSetTypeProp(code, expectedCode, typeName, NoThrow(Of EnvDTE.CodeTypeRef)())
End Function
Protected Async Function TestSetTypeProp(code As XElement, expectedCode As XElement, typeName As String, action As SetterAction(Of EnvDTE.CodeTypeRef)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(state, codeElement)
Dim codeTypeRef = state.RootCodeModel.CreateCodeTypeRef(typeName)
Dim typePropSetter = GetTypePropSetter(codeElement)
action(codeTypeRef, typePropSetter)
End Sub)
End Function
Protected Async Function TestGenericNameExtender_GetBaseTypesCount(code As XElement, expected As Integer) As Task
Await TestElement(code,
Sub(codeElement)
Assert.Equal(expected, GenericNameExtender_GetBaseTypesCount(codeElement))
End Sub)
End Function
Protected Async Function TestGenericNameExtender_GetImplementedTypesCount(code As XElement, expected As Integer) As Task
Await TestElement(code,
Sub(codeElement)
Assert.Equal(expected, GenericNameExtender_GetImplementedTypesCount(codeElement))
End Sub)
End Function
Protected Async Function TestGenericNameExtender_GetImplementedTypesCountThrows(Of TException As Exception)(code As XElement) As Task
Await TestElement(code,
Sub(codeElement)
Assert.Throws(Of TException)(Sub() GenericNameExtender_GetImplementedTypesCount(codeElement))
End Sub)
End Function
Protected Async Function TestGenericNameExtender_GetBaseGenericName(code As XElement, index As Integer, expected As String) As Task
Await TestElement(code,
Sub(codeElement)
Assert.Equal(expected, GenericNameExtender_GetBaseGenericName(codeElement, index))
End Sub)
End Function
Protected Async Function TestGenericNameExtender_GetImplTypeGenericName(code As XElement, index As Integer, expected As String) As Task
Await TestElement(code,
Sub(codeElement)
Assert.Equal(expected, GenericNameExtender_GetImplTypeGenericName(codeElement, index))
End Sub)
End Function
Protected Async Function TestGenericNameExtender_GetImplTypeGenericNameThrows(Of TException As Exception)(code As XElement, index As Integer) As Task
Await TestElement(code,
Sub(codeElement)
Assert.Throws(Of TException)(Sub() GenericNameExtender_GetImplTypeGenericName(codeElement, index))
End Sub)
End Function
Protected Async Function TestAddBase(code As XElement, base As Object, position As Object, expectedCode As XElement) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
AddBase(codeElement, base, position)
End Sub)
End Function
Protected Async Function TestAddBaseThrows(Of TException As Exception)(code As XElement, base As Object, position As Object) As Task
Await TestElement(code,
Sub(codeElement)
Assert.Throws(Of TException)(Sub() AddBase(codeElement, base, position))
End Sub)
End Function
Protected Async Function TestRemoveBase(code As XElement, element As Object, expectedCode As XElement) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
RemoveBase(codeElement, element)
End Sub)
End Function
Protected Async Function TestRemoveBaseThrows(Of TException As Exception)(code As XElement, element As Object) As Task
Await TestElement(code,
Sub(codeElement)
Assert.Throws(Of TException)(Sub() RemoveBase(codeElement, element))
End Sub)
End Function
Protected Async Function TestAddImplementedInterface(code As XElement, base As Object, position As Object, expectedCode As XElement) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
AddImplementedInterface(codeElement, base, position)
End Sub)
End Function
Protected Async Function TestAddImplementedInterfaceThrows(Of TException As Exception)(code As XElement, base As Object, position As Object) As Task
Await TestElement(code,
Sub(codeElement)
Assert.Throws(Of TException)(Sub() AddImplementedInterface(codeElement, base, position))
End Sub)
End Function
Protected Async Function TestRemoveImplementedInterface(code As XElement, element As Object, expectedCode As XElement) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
RemoveImplementedInterface(codeElement, element)
End Sub)
End Function
Protected Async Function TestRemoveImplementedInterfaceThrows(Of TException As Exception)(code As XElement, element As Object) As Task
Await TestElement(code,
Sub(codeElement)
Assert.Throws(Of TException)(Sub() RemoveImplementedInterface(codeElement, element))
End Sub)
End Function
Protected Async Function TestAllParameterNames(code As XElement, ParamArray expectedParameterNames() As String) As Task
Await TestElement(code,
Sub(codeElement)
Dim parameters = GetParameters(codeElement)
Assert.NotNull(parameters)
Assert.Equal(parameters.Count(), expectedParameterNames.Count())
If (expectedParameterNames.Any()) Then
TestAllParameterNamesByIndex(parameters, expectedParameterNames)
TestAllParameterNamesByName(parameters, expectedParameterNames)
End If
End Sub)
End Function
Private Sub TestAllParameterNamesByName(parameters As EnvDTE.CodeElements, expectedParameterNames() As String)
For index = 0 To expectedParameterNames.Count() - 1
Assert.NotNull(parameters.Item(expectedParameterNames(index)))
Next
End Sub
Private Sub TestAllParameterNamesByIndex(parameters As EnvDTE.CodeElements, expectedParameterNames() As String)
For index = 0 To expectedParameterNames.Count() - 1
' index + 1 for Item because Parameters are not zero indexed
Assert.Equal(expectedParameterNames(index), parameters.Item(index + 1).Name)
Next
End Sub
End Class
End Namespace
|
MatthieuMEZIL/roslyn
|
src/VisualStudio/Core/Test/CodeModel/AbstractCodeElementTests`1.vb
|
Visual Basic
|
apache-2.0
| 51,747
|
' 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 Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.Shared.Extensions
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Utilities
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Extenders
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.MethodXml
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel
Partial Friend Class VisualBasicCodeModelService
Inherits AbstractCodeModelService
Private ReadOnly _commitBufferManagerFactory As CommitBufferManagerFactory
Friend Sub New(provider As HostLanguageServices, editorOptionsFactoryService As IEditorOptionsFactoryService, refactorNotifyServices As IEnumerable(Of IRefactorNotifyService), commitBufferManagerFactory As CommitBufferManagerFactory)
MyBase.New(
provider,
editorOptionsFactoryService,
refactorNotifyServices,
New LineAdjustmentFormattingRule(),
New EndRegionFormattingRule())
Me._commitBufferManagerFactory = commitBufferManagerFactory
End Sub
Private Shared ReadOnly s_codeTypeRefAsFullNameFormat As SymbolDisplayFormat =
New SymbolDisplayFormat(
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.ExpandNullable)
Private Shared ReadOnly s_codeTypeRefAsStringFormat As SymbolDisplayFormat =
New SymbolDisplayFormat(
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes)
Private Shared ReadOnly s_fullNameFormat As SymbolDisplayFormat =
New SymbolDisplayFormat(
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:=SymbolDisplayMemberOptions.IncludeContainingType,
miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.ExpandNullable)
Private Shared ReadOnly s_setTypeFormat As SymbolDisplayFormat =
New SymbolDisplayFormat(
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.ExpandNullable Or SymbolDisplayMiscellaneousOptions.UseSpecialTypes)
Private Shared ReadOnly s_raiseEventSignatureFormat As SymbolDisplayFormat =
New SymbolDisplayFormat(
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
parameterOptions:=SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeParamsRefOut Or SymbolDisplayParameterOptions.IncludeType,
miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes)
Private Shared Function IsNameableNode(node As SyntaxNode) As Boolean
Select Case node.Kind
Case SyntaxKind.Attribute,
SyntaxKind.ClassBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.EnumBlock,
SyntaxKind.EnumMemberDeclaration,
SyntaxKind.EventBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.NamespaceBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.Parameter,
SyntaxKind.PropertyBlock,
SyntaxKind.StructureBlock,
SyntaxKind.SubBlock,
SyntaxKind.OptionStatement,
SyntaxKind.SimpleImportsClause,
SyntaxKind.InheritsStatement,
SyntaxKind.ImplementsStatement
Return True
Case SyntaxKind.NameColonEquals
Return True
Case SyntaxKind.SimpleArgument,
SyntaxKind.OmittedArgument
' Only arguments in attributes are valid
Return node.FirstAncestorOrSelf(Of AttributeSyntax) IsNot Nothing
Case SyntaxKind.ModifiedIdentifier
Return node.FirstAncestorOrSelf(Of FieldDeclarationSyntax)() IsNot Nothing
Case SyntaxKind.EventStatement
' Only top-level event statements that aren't included in an event block are valid (e.g. single line events)
Return node.FirstAncestorOrSelf(Of EventBlockSyntax)() Is Nothing
Case SyntaxKind.PropertyStatement
' Only top-level property statements that aren't included in an property block are valid (e.g. auto-properties)
Return node.FirstAncestorOrSelf(Of PropertyBlockSyntax)() Is Nothing
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
Return node.FirstAncestorOrSelf(Of MethodBlockSyntax)() Is Nothing
Case Else
Return False
End Select
End Function
Public Overrides Function GetElementKind(node As SyntaxNode) As EnvDTE.vsCMElement
Select Case node.Kind
Case SyntaxKind.ModuleBlock
Return EnvDTE.vsCMElement.vsCMElementModule
Case SyntaxKind.ClassBlock
Return EnvDTE.vsCMElement.vsCMElementClass
Case Else
Debug.Fail("Unsupported element kind" & CType(node.Kind, SyntaxKind))
Throw Exceptions.ThrowEInvalidArg()
End Select
End Function
Public Overrides Function MatchesScope(node As SyntaxNode, scope As EnvDTE.vsCMElement) As Boolean
'TODO: This has been copied from CSharpCodeModelService. Tweak to implement VB semantics.
Select Case node.Kind
Case SyntaxKind.NamespaceBlock
If scope = EnvDTE.vsCMElement.vsCMElementNamespace AndAlso
node.Parent IsNot Nothing Then
Return True
End If
Case SyntaxKind.ModuleBlock
If scope = EnvDTE.vsCMElement.vsCMElementModule Then
Return True
End If
Case SyntaxKind.ClassBlock
If scope = EnvDTE.vsCMElement.vsCMElementClass Then
Return True
End If
Case SyntaxKind.StructureBlock
If scope = EnvDTE.vsCMElement.vsCMElementStruct Then
Return True
End If
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
If scope = EnvDTE.vsCMElement.vsCMElementFunction AndAlso
node.FirstAncestorOrSelf(Of MethodBlockSyntax)() Is Nothing Then
Return True
End If
Case SyntaxKind.ConstructorBlock,
SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
If scope = EnvDTE.vsCMElement.vsCMElementFunction Then
Return True
End If
Case SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement
If scope = EnvDTE.vsCMElement.vsCMElementDeclareDecl Then
Return True
End If
Case SyntaxKind.EnumMemberDeclaration
If scope = EnvDTE.vsCMElement.vsCMElementVariable Then
Return True
End If
Case SyntaxKind.FieldDeclaration
If scope = EnvDTE.vsCMElement.vsCMElementVariable Then
Return True
End If
Case SyntaxKind.EventBlock
If scope = EnvDTE.vsCMElement.vsCMElementEvent Then
Return True
End If
Case SyntaxKind.EventStatement
If Not TypeOf node.Parent Is EventBlockSyntax Then
If scope = EnvDTE.vsCMElement.vsCMElementEvent Then
Return True
End If
End If
Case SyntaxKind.PropertyBlock
If scope = EnvDTE.vsCMElement.vsCMElementProperty Then
Return True
End If
Case SyntaxKind.PropertyStatement
If Not TypeOf node.Parent Is PropertyBlockSyntax Then
If scope = EnvDTE.vsCMElement.vsCMElementProperty Then
Return True
End If
End If
Case SyntaxKind.Attribute
If scope = EnvDTE.vsCMElement.vsCMElementAttribute Then
Return True
End If
Case SyntaxKind.InterfaceBlock
If scope = EnvDTE.vsCMElement.vsCMElementInterface Then
Return True
End If
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
If scope = EnvDTE.vsCMElement.vsCMElementDelegate Then
Return True
End If
Case SyntaxKind.EnumBlock
If scope = EnvDTE.vsCMElement.vsCMElementEnum Then
Return True
End If
Case SyntaxKind.StructureBlock
If scope = EnvDTE.vsCMElement.vsCMElementStruct Then
Return True
End If
Case SyntaxKind.SimpleImportsClause
If scope = EnvDTE.vsCMElement.vsCMElementImportStmt Then
Return True
End If
Case SyntaxKind.ModifiedIdentifier,
SyntaxKind.VariableDeclarator
If node.Parent.Kind <> SyntaxKind.Parameter Then
' The parent of an identifier/variable declarator may be a
' field. If the parent matches the desired scope, then this
' node matches as well.
Return MatchesScope(node.Parent, scope)
End If
Case SyntaxKind.Parameter
If scope = EnvDTE.vsCMElement.vsCMElementParameter Then
Return True
End If
Case SyntaxKind.OptionStatement
If scope = EnvDTE.vsCMElement.vsCMElementOptionStmt Then
Return True
End If
Case SyntaxKind.InheritsStatement
If scope = EnvDTE.vsCMElement.vsCMElementInheritsStmt Then
Return True
End If
Case SyntaxKind.ImplementsStatement
If scope = EnvDTE.vsCMElement.vsCMElementImplementsStmt Then
Return True
End If
Case Else
Return False
End Select
Return False
End Function
Public Overrides Function GetOptionNodes(parent As SyntaxNode) As IEnumerable(Of SyntaxNode)
If TypeOf parent Is CompilationUnitSyntax Then
Return DirectCast(parent, CompilationUnitSyntax).Options.AsEnumerable()
End If
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End Function
Private Overloads Shared Function GetImportNodes(parent As CompilationUnitSyntax) As IEnumerable(Of SyntaxNode)
Dim result = New List(Of SyntaxNode)
For Each importStatement In parent.Imports
For Each importClause In importStatement.ImportsClauses
' NOTE: XmlNamespaceImportsClause is not support by VB Code Model
If importClause.IsKind(SyntaxKind.SimpleImportsClause) Then
result.Add(importClause)
End If
Next
Next
Return result
End Function
Public Overrides Function GetImportNodes(parent As SyntaxNode) As IEnumerable(Of SyntaxNode)
If TypeOf parent Is CompilationUnitSyntax Then
Return GetImportNodes(DirectCast(parent, CompilationUnitSyntax))
End If
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End Function
Private Overloads Shared Function GetAttributeNodes(attributesBlockList As SyntaxList(Of AttributeListSyntax)) As IEnumerable(Of SyntaxNode)
Dim result = New List(Of SyntaxNode)
For Each attributeBlock In attributesBlockList
For Each attribute In attributeBlock.Attributes
result.Add(attribute)
Next
Next
Return result
End Function
Private Overloads Shared Function GetAttributeNodes(attributesStatementList As SyntaxList(Of AttributesStatementSyntax)) As IEnumerable(Of SyntaxNode)
Dim result = New List(Of SyntaxNode)
For Each attributesStatement In attributesStatementList
For Each attributeBlock In attributesStatement.AttributeLists
For Each attribute In attributeBlock.Attributes
result.Add(attribute)
Next
Next
Next
Return result
End Function
Public Overrides Function GetAttributeNodes(node As SyntaxNode) As IEnumerable(Of SyntaxNode)
If TypeOf node Is CompilationUnitSyntax Then
Return GetAttributeNodes(DirectCast(node, CompilationUnitSyntax).Attributes)
ElseIf TypeOf node Is TypeBlockSyntax Then
Return GetAttributeNodes(DirectCast(node, TypeBlockSyntax).BlockStatement.AttributeLists)
ElseIf TypeOf node Is EnumBlockSyntax Then
Return GetAttributeNodes(DirectCast(node, EnumBlockSyntax).EnumStatement.AttributeLists)
ElseIf TypeOf node Is DelegateStatementSyntax Then
Return GetAttributeNodes(DirectCast(node, DelegateStatementSyntax).AttributeLists)
ElseIf TypeOf node Is DeclareStatementSyntax Then
Return GetAttributeNodes(DirectCast(node, DeclareStatementSyntax).AttributeLists)
ElseIf TypeOf node Is MethodStatementSyntax Then
Return GetAttributeNodes(DirectCast(node, MethodStatementSyntax).AttributeLists)
ElseIf TypeOf node Is MethodBlockBaseSyntax Then
Return GetAttributeNodes(DirectCast(node, MethodBlockBaseSyntax).BlockStatement.AttributeLists)
ElseIf TypeOf node Is PropertyBlockSyntax Then
Return GetAttributeNodes(DirectCast(node, PropertyBlockSyntax).PropertyStatement.AttributeLists)
ElseIf TypeOf node Is PropertyStatementSyntax Then
Return GetAttributeNodes(DirectCast(node, PropertyStatementSyntax).AttributeLists)
ElseIf TypeOf node Is EventBlockSyntax Then
Return GetAttributeNodes(DirectCast(node, EventBlockSyntax).EventStatement.AttributeLists)
ElseIf TypeOf node Is EventStatementSyntax Then
Return GetAttributeNodes(DirectCast(node, EventStatementSyntax).AttributeLists)
ElseIf TypeOf node Is FieldDeclarationSyntax Then
Return GetAttributeNodes(DirectCast(node, FieldDeclarationSyntax).AttributeLists)
ElseIf TypeOf node Is ParameterSyntax Then
Return GetAttributeNodes(DirectCast(node, ParameterSyntax).AttributeLists)
ElseIf TypeOf node Is ModifiedIdentifierSyntax OrElse
TypeOf node Is VariableDeclaratorSyntax Then
Return GetAttributeNodes(node.Parent)
End If
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End Function
Public Overrides Function GetAttributeArgumentNodes(parent As SyntaxNode) As IEnumerable(Of SyntaxNode)
If TypeOf parent Is AttributeSyntax Then
Dim attribute = DirectCast(parent, AttributeSyntax)
If attribute.ArgumentList Is Nothing Then
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End If
Return attribute.ArgumentList.Arguments
End If
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End Function
Public Overrides Function GetInheritsNodes(parent As SyntaxNode) As IEnumerable(Of SyntaxNode)
If TypeOf parent Is TypeBlockSyntax Then
Dim typeBlock = DirectCast(parent, TypeBlockSyntax)
Return typeBlock.Inherits.AsEnumerable()
End If
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End Function
Public Overrides Function GetImplementsNodes(parent As SyntaxNode) As IEnumerable(Of SyntaxNode)
If TypeOf parent Is TypeBlockSyntax Then
Dim typeBlock = DirectCast(parent, TypeBlockSyntax)
Return typeBlock.Implements.AsEnumerable()
End If
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End Function
Private Shared Function IsContainerNode(container As SyntaxNode) As Boolean
Return TypeOf container Is CompilationUnitSyntax OrElse
TypeOf container Is NamespaceBlockSyntax OrElse
TypeOf container Is TypeBlockSyntax OrElse
TypeOf container Is EnumBlockSyntax
End Function
Private Shared Iterator Function GetChildMemberNodes(container As SyntaxNode) As IEnumerable(Of SyntaxNode)
If TypeOf container Is CompilationUnitSyntax Then
For Each member In DirectCast(container, CompilationUnitSyntax).Members
Yield member
Next
ElseIf TypeOf container Is NamespaceBlockSyntax
For Each member In DirectCast(container, NamespaceBlockSyntax).Members
Yield member
Next
ElseIf TypeOf container Is TypeBlockSyntax
For Each member In DirectCast(container, TypeBlockSyntax).Members
Yield member
Next
ElseIf TypeOf container Is EnumBlockSyntax
For Each member In DirectCast(container, EnumBlockSyntax).Members
Yield member
Next
End If
End Function
Private Shared Function NodeIsSupported(test As Boolean, node As SyntaxNode) As Boolean
Return Not test OrElse IsNameableNode(node)
End Function
''' <summary>
''' Retrieves the members of a specified <paramref name="container"/> node. The members that are
''' returned can be controlled by passing various parameters.
''' </summary>
''' <param name="container">The <see cref="SyntaxNode"/> from which to retrieve members.</param>
''' <param name="includeSelf">If true, the container Is returned as well.</param>
''' <param name="recursive">If true, members are recursed to return descendent members as well
''' as immediate children. For example, a namespace would return the namespaces And types within.
''' However, if <paramref name="recursive"/> Is true, members with the namespaces And types would
''' also be returned.</param>
''' <param name="logicalFields">If true, field declarations are broken into their respective declarators.
''' For example, the field "Dim x, y As Integer" would return two nodes, one for x And one for y in place
''' of the field.</param>
''' <param name="onlySupportedNodes">If true, only members supported by Code Model are returned.</param>
Public Overrides Iterator Function GetMemberNodes(container As SyntaxNode, includeSelf As Boolean, recursive As Boolean, logicalFields As Boolean, onlySupportedNodes As Boolean) As IEnumerable(Of SyntaxNode)
If Not IsContainerNode(container) Then
Exit Function
End If
If includeSelf AndAlso NodeIsSupported(onlySupportedNodes, container) Then
Yield container
End If
For Each member In GetChildMemberNodes(container)
If member.Kind = SyntaxKind.FieldDeclaration Then
' For fields, the 'logical' and 'supported' flags are intrinsically tied.
' * If 'logical' is true, only declarators should be returned, regardless of the value of 'supported'.
' * If 'logical' is false, the field should only be returned if 'supported' is also false.
If logicalFields Then
For Each declarator In DirectCast(member, FieldDeclarationSyntax).Declarators
' We know that declarators are supported, so there's no need to check them here.
For Each identifier In declarator.Names
Yield identifier
Next
Next
ElseIf Not onlySupportedNodes
' Only return fields if the supported flag Is false.
Yield member
End If
ElseIf NodeIsSupported(onlySupportedNodes, member)
Yield member
End If
If recursive AndAlso IsContainerNode(member) Then
For Each innerMember In GetMemberNodes(member, includeSelf:=False, recursive:=True, logicalFields:=logicalFields, onlySupportedNodes:=onlySupportedNodes)
Yield innerMember
Next
End If
Next
End Function
Public Overrides ReadOnly Property Language As String
Get
Return EnvDTE.CodeModelLanguageConstants.vsCMLanguageVB
End Get
End Property
Public Overrides ReadOnly Property AssemblyAttributeString As String
Get
Return "Assembly"
End Get
End Property
''' <summary>
''' Do not use this method directly! Instead, go through <see cref="FileCodeModel.CreateCodeElement(Of T)(SyntaxNode)"/>
''' </summary>
Public Overloads Overrides Function CreateInternalCodeElement(
state As CodeModelState,
fileCodeModel As FileCodeModel,
node As SyntaxNode
) As EnvDTE.CodeElement
Select Case node.Kind
Case SyntaxKind.Attribute
Return CType(CreateInternalCodeAttribute(state, fileCodeModel, node), EnvDTE.CodeElement)
Case SyntaxKind.NameColonEquals
Return Nothing
Case SyntaxKind.SimpleArgument
Return CType(CreateInternalCodeAttributeArgument(state, fileCodeModel, node), EnvDTE.CodeElement)
Case SyntaxKind.SimpleImportsClause
Return CType(CreateInternalCodeImport(state, fileCodeModel, node), EnvDTE.CodeElement)
Case SyntaxKind.ImportsStatement
Dim importsStatement = DirectCast(node, ImportsStatementSyntax)
Return CreateInternalCodeElement(state, fileCodeModel, importsStatement.ImportsClauses(0))
Case SyntaxKind.Parameter
Return CType(CreateInternalCodeParameter(state, fileCodeModel, node), EnvDTE.CodeElement)
Case SyntaxKind.OptionStatement
Return CType(CreateInternalCodeOptionStatement(state, fileCodeModel, node), EnvDTE.CodeElement)
Case SyntaxKind.InheritsStatement
Return CType(CreateInternalCodeInheritsStatement(state, fileCodeModel, node), EnvDTE.CodeElement)
Case SyntaxKind.ImplementsStatement
Return CType(CreateInternalCodeImplementsStatement(state, fileCodeModel, node), EnvDTE.CodeElement)
End Select
If IsAccessorNode(node) Then
Return CType(CreateInternalCodeAccessorFunction(state, fileCodeModel, node), EnvDTE.CodeElement)
End If
Dim nodeKey = GetNodeKey(node)
Select Case node.Kind
Case SyntaxKind.ClassBlock,
SyntaxKind.ModuleBlock
Return CType(CodeClass.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.StructureBlock
Return CType(CodeStruct.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.InterfaceBlock
Return CType(CodeInterface.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.EnumBlock
Return CType(CodeEnum.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return CType(CodeDelegate.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.ConstructorBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.SubBlock,
SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
Return CType(CodeFunctionWithEventHandler.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement
Return CType(CodeFunctionDeclareDecl.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.PropertyBlock,
SyntaxKind.PropertyStatement
Return CType(CodeProperty.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.EventBlock,
SyntaxKind.EventStatement
Return CType(CodeEvent.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.NamespaceBlock
Return CType(CodeNamespace.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.ModifiedIdentifier,
SyntaxKind.EnumMemberDeclaration
Return CType(CodeVariable.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case Else
Throw New NotImplementedException()
End Select
End Function
Public Overrides Function CreateUnknownCodeElement(state As CodeModelState, fileCodeModel As FileCodeModel, node As SyntaxNode) As EnvDTE.CodeElement
Select Case node.Kind
Case SyntaxKind.ClassBlock,
SyntaxKind.ModuleBlock
Return CType(CodeClass.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.StructureBlock
Return CType(CodeStruct.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.InterfaceBlock
Return CType(CodeInterface.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.EnumBlock
Return CType(CodeEnum.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return CType(CodeDelegate.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.ConstructorBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.SubBlock,
SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
Return CType(CodeFunctionWithEventHandler.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement
Return CType(CodeFunctionDeclareDecl.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.PropertyBlock,
SyntaxKind.PropertyStatement
Return CType(CodeProperty.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.EventBlock,
SyntaxKind.EventStatement
Return CType(CodeEvent.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.NamespaceBlock
Return CType(CodeNamespace.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.ModifiedIdentifier,
SyntaxKind.EnumMemberDeclaration
Return CType(CodeVariable.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.SimpleImportsClause
Return CType(CodeImport.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.OptionStatement
Return CType(CodeOptionsStatement.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.InheritsStatement
Return CType(CodeInheritsStatement.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.ImplementsStatement
Return CType(CodeImplementsStatement.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case Else
Throw New NotImplementedException()
End Select
End Function
Public Overrides Function CreateUnknownRootNamespaceCodeElement(state As CodeModelState, fileCodeModel As FileCodeModel) As EnvDTE.CodeElement
Dim compilation = CType(fileCodeModel.GetCompilation(), Compilation)
Dim rootNamespace = DirectCast(compilation.Options, VisualBasicCompilationOptions).RootNamespace
Return CType(CodeNamespace.CreateUnknown(state, fileCodeModel, SyntaxKind.NamespaceBlock, rootNamespace), EnvDTE.CodeElement)
End Function
Private Shared Function IsValidTypeRefKind(kind As EnvDTE.vsCMTypeRef) As Boolean
Return kind = EnvDTE.vsCMTypeRef.vsCMTypeRefVoid OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefObject OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefBool OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefByte OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefShort OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefInt OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefLong OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefDecimal OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefFloat OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefDouble OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefChar OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefString OrElse
kind = EnvDTE80.vsCMTypeRef2.vsCMTypeRefSByte OrElse
kind = EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedInt OrElse
kind = EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedLong OrElse
kind = EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedShort
End Function
Public Overrides Function CreateCodeTypeRef(state As CodeModelState, projectId As ProjectId, type As Object) As EnvDTE.CodeTypeRef
Dim project = state.Workspace.CurrentSolution.GetProject(projectId)
If project Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Dim compilation = project.GetCompilationAsync().Result
If TypeOf type Is Byte OrElse
TypeOf type Is Short OrElse
TypeOf type Is Integer Then
Dim typeRefKind = CType(type, EnvDTE.vsCMTypeRef)
If Not IsValidTypeRefKind(typeRefKind) Then
Throw Exceptions.ThrowEInvalidArg()
End If
Dim specialType = GetSpecialType(typeRefKind)
Return CodeTypeRef.Create(state, Nothing, projectId, compilation.GetSpecialType(specialType))
End If
Dim typeName As String
Dim parent As Object = Nothing
If TypeOf type Is String Then
typeName = CStr(type)
ElseIf TypeOf type Is EnvDTE.CodeType Then
typeName = CType(type, EnvDTE.CodeType).FullName
parent = type
Else
Throw Exceptions.ThrowEInvalidArg()
End If
Dim typeSymbol = GetTypeSymbolFromFullName(typeName, compilation)
If typeSymbol Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Return CodeTypeRef.Create(state, parent, projectId, typeSymbol)
End Function
Public Overrides Function GetTypeKindForCodeTypeRef(typeSymbol As ITypeSymbol) As EnvDTE.vsCMTypeRef
' Rough translation of CodeModelSymbol::GetTypeKind from vb\Language\VsPackage\CodeModelHelpers.cpp
If typeSymbol.SpecialType = SpecialType.System_Void Then
Return EnvDTE.vsCMTypeRef.vsCMTypeRefVoid
End If
If typeSymbol.TypeKind = TypeKind.Array Then
Return EnvDTE.vsCMTypeRef.vsCMTypeRefArray
End If
If typeSymbol.TypeKind = TypeKind.Pointer Then
typeSymbol = DirectCast(typeSymbol, IPointerTypeSymbol).PointedAtType
End If
If typeSymbol IsNot Nothing AndAlso Not typeSymbol.TypeKind = TypeKind.Error Then
If typeSymbol.SpecialType = SpecialType.System_Object Then
Return EnvDTE.vsCMTypeRef.vsCMTypeRefObject
End If
If typeSymbol.TypeKind = TypeKind.Enum Then
Return EnvDTE.vsCMTypeRef.vsCMTypeRefCodeType
End If
Select Case typeSymbol.SpecialType
Case SpecialType.System_Boolean
Return EnvDTE.vsCMTypeRef.vsCMTypeRefBool
Case SpecialType.System_SByte
Return CType(EnvDTE80.vsCMTypeRef2.vsCMTypeRefSByte, EnvDTE.vsCMTypeRef)
Case SpecialType.System_Byte
Return EnvDTE.vsCMTypeRef.vsCMTypeRefByte
Case SpecialType.System_Int16
Return EnvDTE.vsCMTypeRef.vsCMTypeRefShort
Case SpecialType.System_UInt16
Return CType(EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedShort, EnvDTE.vsCMTypeRef)
Case SpecialType.System_Int32
Return EnvDTE.vsCMTypeRef.vsCMTypeRefInt
Case SpecialType.System_UInt32
Return CType(EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedInt, EnvDTE.vsCMTypeRef)
Case SpecialType.System_Int64
Return EnvDTE.vsCMTypeRef.vsCMTypeRefLong
Case SpecialType.System_UInt64
Return CType(EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedLong, EnvDTE.vsCMTypeRef)
Case SpecialType.System_Decimal
Return EnvDTE.vsCMTypeRef.vsCMTypeRefDecimal
Case SpecialType.System_Single
Return EnvDTE.vsCMTypeRef.vsCMTypeRefFloat
Case SpecialType.System_Double
Return EnvDTE.vsCMTypeRef.vsCMTypeRefDouble
Case SpecialType.System_Char
Return EnvDTE.vsCMTypeRef.vsCMTypeRefChar
Case SpecialType.System_String
Return EnvDTE.vsCMTypeRef.vsCMTypeRefString
End Select
If typeSymbol.TypeKind = TypeKind.Pointer Then
Return EnvDTE.vsCMTypeRef.vsCMTypeRefPointer
End If
If typeSymbol.TypeKind = TypeKind.TypeParameter Then
Return EnvDTE.vsCMTypeRef.vsCMTypeRefOther
End If
Return EnvDTE.vsCMTypeRef.vsCMTypeRefCodeType
End If
Return EnvDTE.vsCMTypeRef.vsCMTypeRefOther
End Function
Public Overrides Function GetAsFullNameForCodeTypeRef(typeSymbol As ITypeSymbol) As String
Return typeSymbol.ToDisplayString(s_codeTypeRefAsFullNameFormat)
End Function
Public Overrides Function GetAsStringForCodeTypeRef(typeSymbol As ITypeSymbol) As String
Return typeSymbol.ToDisplayString(s_codeTypeRefAsStringFormat)
End Function
Public Overrides Function IsParameterNode(node As SyntaxNode) As Boolean
Return TypeOf node Is ParameterSyntax
End Function
Public Overrides Function IsAttributeNode(node As SyntaxNode) As Boolean
Return TypeOf node Is AttributeSyntax
End Function
Public Overrides Function IsAttributeArgumentNode(node As SyntaxNode) As Boolean
Return TypeOf node Is SimpleArgumentSyntax OrElse
TypeOf node Is OmittedArgumentSyntax
End Function
Public Overrides Function IsOptionNode(node As SyntaxNode) As Boolean
Return TypeOf node Is OptionStatementSyntax
End Function
Public Overrides Function IsImportNode(node As SyntaxNode) As Boolean
Return TypeOf node Is SimpleImportsClauseSyntax
End Function
Public Overrides Function GetUnescapedName(name As String) As String
Return If(name IsNot Nothing AndAlso name.Length > 2 AndAlso name.StartsWith("[", StringComparison.Ordinal) AndAlso name.EndsWith("]", StringComparison.Ordinal),
name.Substring(1, name.Length - 2),
name)
End Function
Private Function GetNormalizedName(node As SyntaxNode) As String
Dim nameBuilder = New StringBuilder()
Dim token = node.GetFirstToken(includeSkipped:=True)
While True
nameBuilder.Append(token.ToString())
Dim nextToken = token.GetNextToken(includeSkipped:=True)
If Not nextToken.IsDescendantOf(node) Then
Exit While
End If
If (token.IsKeyword() OrElse token.Kind = SyntaxKind.IdentifierToken) AndAlso
(nextToken.IsKeyword() OrElse nextToken.Kind = SyntaxKind.IdentifierToken) Then
nameBuilder.Append(" "c)
End If
token = nextToken
End While
Return nameBuilder.ToString().Trim()
End Function
Public Overrides Function GetName(node As SyntaxNode) As String
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
Debug.Assert(TypeOf node Is SyntaxNode)
Debug.Assert(IsNameableNode(node))
Select Case node.Kind
Case SyntaxKind.Attribute
Return GetNormalizedName(DirectCast(node, AttributeSyntax).Name)
Case SyntaxKind.ClassBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.StructureBlock
Return DirectCast(node, TypeBlockSyntax).BlockStatement.Identifier.ToString()
Case SyntaxKind.EnumBlock
Return DirectCast(node, EnumBlockSyntax).EnumStatement.Identifier.ToString()
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return DirectCast(node, DelegateStatementSyntax).Identifier.ToString()
Case SyntaxKind.NamespaceBlock
Return DirectCast(node, NamespaceBlockSyntax).NamespaceStatement.Name.ToString()
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock
Dim methodBlock = DirectCast(node, MethodBlockSyntax)
Return methodBlock.SubOrFunctionStatement.Identifier.ToString()
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
Return DirectCast(node, MethodStatementSyntax).Identifier.ToString()
Case SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement
Return DirectCast(node, DeclareStatementSyntax).Identifier.ToString()
Case SyntaxKind.ConstructorBlock
Dim methodBlock = DirectCast(node, ConstructorBlockSyntax)
Return methodBlock.SubNewStatement.NewKeyword.ToString()
Case SyntaxKind.OperatorBlock
Dim operatorBlock = DirectCast(node, OperatorBlockSyntax)
Return operatorBlock.OperatorStatement.OperatorToken.ToString()
Case SyntaxKind.PropertyBlock
Dim propertyBlock = DirectCast(node, PropertyBlockSyntax)
Return propertyBlock.PropertyStatement.Identifier.ToString()
Case SyntaxKind.PropertyStatement
Return DirectCast(node, PropertyStatementSyntax).Identifier.ToString()
Case SyntaxKind.EventBlock
Return DirectCast(node, EventBlockSyntax).EventStatement.Identifier.ToString()
Case SyntaxKind.EventStatement
Return DirectCast(node, EventStatementSyntax).Identifier.ToString()
Case SyntaxKind.ModifiedIdentifier
Return DirectCast(node, ModifiedIdentifierSyntax).Identifier.ToString()
Case SyntaxKind.EnumMemberDeclaration
Return DirectCast(node, EnumMemberDeclarationSyntax).Identifier.ToString()
Case SyntaxKind.SimpleArgument
Dim simpleArgument = DirectCast(node, SimpleArgumentSyntax)
Return If(simpleArgument.IsNamed,
simpleArgument.NameColonEquals.Name.ToString(),
String.Empty)
Case SyntaxKind.OmittedArgument
Return String.Empty
Case SyntaxKind.Parameter
Return DirectCast(node, ParameterSyntax).Identifier.Identifier.ToString()
Case SyntaxKind.OptionStatement
Return GetNormalizedName(node)
Case SyntaxKind.SimpleImportsClause
Return GetNormalizedName(DirectCast(node, ImportsClauseSyntax).GetName())
Case SyntaxKind.InheritsStatement
Return DirectCast(node, InheritsStatementSyntax).InheritsKeyword.ToString()
Case SyntaxKind.ImplementsStatement
Return DirectCast(node, ImplementsStatementSyntax).ImplementsKeyword.ToString()
Case Else
Debug.Fail(String.Format("Invalid node kind: {0}", node.Kind))
Throw New ArgumentException()
End Select
End Function
Public Overrides Function SetName(node As SyntaxNode, name As String) As SyntaxNode
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
Dim identifier As SyntaxToken = SyntaxFactory.Identifier(name)
Select Case node.Kind
Case SyntaxKind.Attribute
Return DirectCast(node, AttributeSyntax).WithName(SyntaxFactory.ParseTypeName(name))
Case SyntaxKind.ClassStatement
Return DirectCast(node, ClassStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.InterfaceStatement
Return DirectCast(node, InterfaceStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.ModuleStatement
Return DirectCast(node, ModuleStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.StructureStatement
Return DirectCast(node, StructureStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.EnumStatement
Return DirectCast(node, EnumStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return DirectCast(node, DelegateStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.NamespaceStatement
Return DirectCast(node, NamespaceStatementSyntax).WithName(SyntaxFactory.ParseName(name))
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.SubNewStatement
Return DirectCast(node, MethodStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareFunctionStatement
Return DirectCast(node, DeclareStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.PropertyStatement
Return DirectCast(node, PropertyStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.EventStatement
Return DirectCast(node, EventStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.ModifiedIdentifier
Return DirectCast(node, ModifiedIdentifierSyntax).WithIdentifier(identifier)
Case SyntaxKind.SimpleArgument
Return DirectCast(node, SimpleArgumentSyntax).WithNameColonEquals(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName(name)))
Case Else
Debug.Fail("Invalid node kind: " & CType(node.Kind, SyntaxKind))
Throw Exceptions.ThrowEFail()
End Select
End Function
Public Overrides Function GetNodeWithName(node As SyntaxNode) As SyntaxNode
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
If node.Kind = SyntaxKind.OperatorBlock Then
Throw Exceptions.ThrowEFail
End If
Debug.Assert(IsNameableNode(node))
Select Case node.Kind
Case SyntaxKind.Attribute
Return node
Case SyntaxKind.ClassBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.StructureBlock
Return DirectCast(node, TypeBlockSyntax).BlockStatement
Case SyntaxKind.EnumBlock
Return DirectCast(node, EnumBlockSyntax).EnumStatement
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return node
Case SyntaxKind.NamespaceBlock
Return DirectCast(node, NamespaceBlockSyntax).NamespaceStatement
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.ConstructorBlock
Return DirectCast(node, MethodBlockBaseSyntax).BlockStatement
Case SyntaxKind.PropertyBlock
Return DirectCast(node, PropertyBlockSyntax).PropertyStatement
Case SyntaxKind.EventBlock
Return DirectCast(node, EventBlockSyntax).EventStatement
Case SyntaxKind.ModifiedIdentifier
Return node
Case SyntaxKind.SimpleArgument
Dim simpleArgument = DirectCast(node, SimpleArgumentSyntax)
Return If(simpleArgument.IsNamed, simpleArgument.NameColonEquals.Name, node)
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement
Return node
Case SyntaxKind.EventStatement
Return node
Case Else
Debug.Fail("Invalid node kind: " & CType(node.Kind, SyntaxKind))
Throw New ArgumentException()
End Select
End Function
Public Overrides Function GetFullName(node As SyntaxNode, semanticModel As SemanticModel) As String
If node.Kind = SyntaxKind.SimpleImportsClause Then
Throw Exceptions.ThrowENotImpl()
End If
Dim symbol = If(TypeOf node Is AttributeSyntax,
semanticModel.GetTypeInfo(node).Type,
semanticModel.GetDeclaredSymbol(node))
Return GetFullName(symbol)
End Function
Public Overrides Function GetFullName(symbol As ISymbol) As String
If symbol Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Return symbol.ToDisplayString(s_fullNameFormat)
End Function
Public Overrides Function IsAccessorNode(node As SyntaxNode) As Boolean
Select Case node.Kind
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return True
End Select
Return False
End Function
Public Overrides Function GetAccessorKind(node As SyntaxNode) As MethodKind
Select Case node.Kind
Case SyntaxKind.GetAccessorBlock
Return MethodKind.PropertyGet
Case SyntaxKind.SetAccessorBlock
Return MethodKind.PropertySet
Case SyntaxKind.AddHandlerAccessorBlock
Return MethodKind.EventAdd
Case SyntaxKind.RemoveHandlerAccessorBlock
Return MethodKind.EventRemove
Case SyntaxKind.RaiseEventAccessorBlock
Return MethodKind.EventRaise
Case Else
Throw Exceptions.ThrowEUnexpected()
End Select
End Function
Private Overloads Shared Function GetAccessorKind(methodKind As MethodKind) As SyntaxKind
Select Case methodKind
Case MethodKind.PropertyGet
Return SyntaxKind.GetAccessorBlock
Case MethodKind.PropertySet
Return SyntaxKind.SetAccessorBlock
Case MethodKind.EventAdd
Return SyntaxKind.AddHandlerAccessorBlock
Case MethodKind.EventRemove
Return SyntaxKind.RemoveHandlerAccessorBlock
Case MethodKind.EventRaise
Return SyntaxKind.RaiseEventAccessorBlock
Case Else
Throw Exceptions.ThrowEUnexpected()
End Select
End Function
Private Shared Function GetAccessors(node As SyntaxNode) As SyntaxList(Of AccessorBlockSyntax)
Select Case node.Kind()
Case SyntaxKind.PropertyBlock
Return DirectCast(node, PropertyBlockSyntax).Accessors
Case SyntaxKind.EventBlock
Return DirectCast(node, EventBlockSyntax).Accessors
Case Else
Return Nothing
End Select
End Function
Public Overrides Function TryGetAccessorNode(parentNode As SyntaxNode, kind As MethodKind, ByRef accessorNode As SyntaxNode) As Boolean
Dim accessorKind = GetAccessorKind(kind)
For Each accessor In GetAccessors(parentNode)
If accessor.Kind = accessorKind Then
accessorNode = accessor
Return True
End If
Next
accessorNode = Nothing
Return False
End Function
Public Overrides Function TryGetParameterNode(parentNode As SyntaxNode, name As String, ByRef parameterNode As SyntaxNode) As Boolean
For Each parameter As ParameterSyntax In GetParameterNodes(parentNode)
Dim parameterName = GetNameFromParameter(parameter)
If String.Equals(parameterName, name, StringComparison.OrdinalIgnoreCase) Then
parameterNode = parameter
Return True
End If
Next
parameterNode = Nothing
Return False
End Function
Private Overloads Function GetParameterNodes(methodStatement As MethodBaseSyntax) As IEnumerable(Of ParameterSyntax)
Return If(methodStatement.ParameterList IsNot Nothing,
methodStatement.ParameterList.Parameters,
SpecializedCollections.EmptyEnumerable(Of ParameterSyntax))
End Function
Public Overloads Overrides Function GetParameterNodes(parent As SyntaxNode) As IEnumerable(Of SyntaxNode)
If TypeOf parent Is MethodBaseSyntax Then
Return GetParameterNodes(DirectCast(parent, MethodBaseSyntax))
ElseIf TypeOf parent Is MethodBlockBaseSyntax Then
Return GetParameterNodes(DirectCast(parent, MethodBlockBaseSyntax).BlockStatement)
ElseIf TypeOf parent Is PropertyBlockSyntax Then
Return GetParameterNodes(DirectCast(parent, PropertyBlockSyntax).PropertyStatement)
End If
Return SpecializedCollections.EmptyEnumerable(Of ParameterSyntax)()
End Function
Public Overrides Function TryGetImportNode(parentNode As SyntaxNode, dottedName As String, ByRef importNode As SyntaxNode) As Boolean
For Each node In GetImportNodes(parentNode)
If GetImportNamespaceOrType(node) = dottedName Then
importNode = node
Return True
End If
Next
importNode = Nothing
Return False
End Function
Public Overrides Function TryGetOptionNode(parentNode As SyntaxNode, name As String, ordinal As Integer, ByRef optionNode As SyntaxNode) As Boolean
Dim count = -1
For Each [option] As OptionStatementSyntax In GetOptionNodes(parentNode)
If [option].ToString() = name Then
count += 1
If count = ordinal Then
optionNode = [option]
Return True
End If
End If
Next
optionNode = Nothing
Return False
End Function
Public Overrides Function TryGetInheritsNode(parentNode As SyntaxNode, name As String, ordinal As Integer, ByRef inheritsNode As SyntaxNode) As Boolean
Dim count = -1
For Each [inherits] As InheritsStatementSyntax In GetInheritsNodes(parentNode)
If [inherits].Types.ToString() = name Then
count += 1
If count = ordinal Then
inheritsNode = [inherits]
Return True
End If
End If
Next
inheritsNode = Nothing
Return False
End Function
Public Overrides Function TryGetImplementsNode(parentNode As SyntaxNode, name As String, ordinal As Integer, ByRef implementsNode As SyntaxNode) As Boolean
Dim count = -1
For Each [implements] As ImplementsStatementSyntax In GetImplementsNodes(parentNode)
If [implements].Types.ToString() = name Then
count += 1
If count = ordinal Then
implementsNode = [implements]
Return True
End If
End If
Next
implementsNode = Nothing
Return False
End Function
Public Overrides Function TryGetAttributeNode(parentNode As SyntaxNode, name As String, ordinal As Integer, ByRef attributeNode As SyntaxNode) As Boolean
Dim count = -1
For Each attribute As AttributeSyntax In GetAttributeNodes(parentNode)
If attribute.Name.ToString() = name Then
count += 1
If count = ordinal Then
attributeNode = attribute
Return True
End If
End If
Next
attributeNode = Nothing
Return False
End Function
Public Overrides Function TryGetAttributeArgumentNode(attributeNode As SyntaxNode, index As Integer, ByRef attributeArgumentNode As SyntaxNode) As Boolean
Debug.Assert(TypeOf attributeNode Is AttributeSyntax)
Dim attribute = DirectCast(attributeNode, AttributeSyntax)
If attribute.ArgumentList IsNot Nothing AndAlso
attribute.ArgumentList.Arguments.Count > index Then
attributeArgumentNode = attribute.ArgumentList.Arguments(index)
Return True
End If
attributeArgumentNode = Nothing
Return False
End Function
Private Function DeleteMember(document As Document, node As SyntaxNode) As Document
Dim text = document.GetTextAsync(CancellationToken.None) _
.WaitAndGetResult(CancellationToken.None)
Dim deletionEnd = node.FullSpan.End
Dim deletionStart = node.SpanStart
Dim contiguousEndOfLines = 0
For Each trivia In node.GetLeadingTrivia().Reverse()
If trivia.IsDirective Then
Exit For
End If
If trivia.Kind = SyntaxKind.EndOfLineTrivia Then
If contiguousEndOfLines > 0 Then
Exit For
Else
contiguousEndOfLines += 1
End If
ElseIf trivia.Kind <> SyntaxKind.WhitespaceTrivia Then
contiguousEndOfLines = 0
End If
deletionStart = trivia.FullSpan.Start
Next
text = text.Replace(TextSpan.FromBounds(deletionStart, deletionEnd), String.Empty)
Return document.WithText(text)
End Function
Public Overrides Function Delete(document As Document, node As SyntaxNode) As Document
Select Case node.Kind
Case SyntaxKind.Attribute
Return Delete(document, DirectCast(node, AttributeSyntax))
Case SyntaxKind.SimpleArgument
Return Delete(document, DirectCast(node, ArgumentSyntax))
Case SyntaxKind.Parameter
Return Delete(document, DirectCast(node, ParameterSyntax))
Case SyntaxKind.ModifiedIdentifier
Return Delete(document, DirectCast(node, ModifiedIdentifierSyntax))
Case SyntaxKind.VariableDeclarator
Return Delete(document, DirectCast(node, VariableDeclaratorSyntax))
Case Else
Return DeleteMember(document, node)
End Select
End Function
Private Overloads Function Delete(document As Document, node As ModifiedIdentifierSyntax) As Document
Dim declarator = node.FirstAncestorOrSelf(Of VariableDeclaratorSyntax)()
' If this is the only name in declarator, then delete the entire
' declarator.
If declarator.Names.Count = 1 Then
Return Delete(document, declarator)
Else
Dim newDeclarator = declarator.RemoveNode(node, SyntaxRemoveOptions.KeepEndOfLine).WithAdditionalAnnotations(Formatter.Annotation)
Return document.ReplaceNodeAsync(declarator, newDeclarator, CancellationToken.None).WaitAndGetResult(CancellationToken.None)
End If
End Function
Private Overloads Function Delete(document As Document, node As VariableDeclaratorSyntax) As Document
Dim declaration = node.FirstAncestorOrSelf(Of FieldDeclarationSyntax)()
' If this is the only declarator in the declaration, then delete
' the entire declarator.
If declaration.Declarators.Count = 1 Then
Return Delete(document, declaration)
Else
Dim newDeclaration = declaration.RemoveNode(node, SyntaxRemoveOptions.KeepEndOfLine).WithAdditionalAnnotations(Formatter.Annotation)
Return document.ReplaceNodeAsync(declaration, newDeclaration, CancellationToken.None).WaitAndGetResult(CancellationToken.None)
End If
End Function
Private Overloads Function Delete(document As Document, node As AttributeSyntax) As Document
Dim attributeList = node.FirstAncestorOrSelf(Of AttributeListSyntax)()
' If we don't have anything left, then just delete the whole attribute list.
' Keep all leading trivia, but delete all trailing trivia.
If attributeList.Attributes.Count = 1 Then
Dim spanStart = attributeList.SpanStart
Dim spanEnd = attributeList.FullSpan.End
Dim text = document.GetTextAsync(CancellationToken.None) _
.WaitAndGetResult(CancellationToken.None)
text = text.Replace(TextSpan.FromBounds(spanStart, spanEnd), String.Empty)
Return document.WithText(text)
Else
Dim newAttributeList = attributeList.RemoveNode(node, SyntaxRemoveOptions.KeepEndOfLine)
Return document.ReplaceNodeAsync(attributeList, newAttributeList, CancellationToken.None) _
.WaitAndGetResult(CancellationToken.None)
End If
End Function
Private Overloads Function Delete(document As Document, node As ArgumentSyntax) As Document
Dim argumentList = node.FirstAncestorOrSelf(Of ArgumentListSyntax)()
Dim newArgumentList = argumentList.RemoveNode(node, SyntaxRemoveOptions.KeepEndOfLine).WithAdditionalAnnotations(Formatter.Annotation)
Return document.ReplaceNodeAsync(argumentList, newArgumentList, CancellationToken.None) _
.WaitAndGetResult(CancellationToken.None)
End Function
Private Overloads Function Delete(document As Document, node As ParameterSyntax) As Document
Dim parameterList = node.FirstAncestorOrSelf(Of ParameterListSyntax)()
Dim newParameterList = parameterList.RemoveNode(node, SyntaxRemoveOptions.KeepEndOfLine).WithAdditionalAnnotations(Formatter.Annotation)
Return document.ReplaceNodeAsync(parameterList, newParameterList, CancellationToken.None) _
.WaitAndGetResult(CancellationToken.None)
End Function
Public Overrides Function GetAccess(symbol As ISymbol) As EnvDTE.vsCMAccess
Debug.Assert(symbol IsNot Nothing)
Dim access As EnvDTE.vsCMAccess = 0
' TODO: Add vsCMAccessWithEvents for fields symbols defined as WithEvents
Select Case symbol.DeclaredAccessibility
Case Accessibility.Private
access = access Or EnvDTE.vsCMAccess.vsCMAccessPrivate
Case Accessibility.Protected
access = access Or EnvDTE.vsCMAccess.vsCMAccessProtected
Case Accessibility.Internal
access = access Or EnvDTE.vsCMAccess.vsCMAccessProject
Case Accessibility.ProtectedOrInternal
access = access Or EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected
Case Accessibility.Public
access = access Or EnvDTE.vsCMAccess.vsCMAccessPublic
Case Else
Throw Exceptions.ThrowEFail()
End Select
If symbol.IsKind(SymbolKind.Property) AndAlso
DirectCast(symbol, IPropertySymbol).IsWithEvents Then
access = access Or EnvDTE.vsCMAccess.vsCMAccessWithEvents
End If
Return access
End Function
Public Overrides Function GetAccess(node As SyntaxNode) As EnvDTE.vsCMAccess
Dim member = TryCast(Me.GetNodeWithModifiers(node), StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Dim flags = member.GetModifierFlags()
Dim access As EnvDTE.vsCMAccess = 0
If (flags And ModifierFlags.Public) <> 0 Then
access = EnvDTE.vsCMAccess.vsCMAccessPublic
ElseIf (flags And ModifierFlags.Protected) <> 0 AndAlso
(flags And ModifierFlags.Friend) <> 0 Then
access = EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected
ElseIf (flags And ModifierFlags.Friend) <> 0 Then
access = EnvDTE.vsCMAccess.vsCMAccessProject
ElseIf (flags And ModifierFlags.Protected) <> 0 Then
access = EnvDTE.vsCMAccess.vsCMAccessProtected
ElseIf (flags And ModifierFlags.Private) <> 0 Then
access = EnvDTE.vsCMAccess.vsCMAccessPrivate
Else
' The code does not specify the accessibility, so we need to
' determine the default accessibility
access = GetDefaultAccessibility(member)
End If
If (flags And ModifierFlags.WithEvents) <> 0 Then
access = access Or EnvDTE.vsCMAccess.vsCMAccessWithEvents
End If
Return access
End Function
Public Overrides Function GetNodeWithModifiers(node As SyntaxNode) As SyntaxNode
Return If(TypeOf node Is ModifiedIdentifierSyntax,
node.GetAncestor(Of DeclarationStatementSyntax)(),
node)
End Function
Public Overrides Function GetNodeWithType(node As SyntaxNode) As SyntaxNode
Return If(TypeOf node Is ModifiedIdentifierSyntax,
node.GetAncestor(Of VariableDeclaratorSyntax)(),
node)
End Function
Public Overrides Function GetNodeWithInitializer(node As SyntaxNode) As SyntaxNode
Return If(TypeOf node Is ModifiedIdentifierSyntax,
node.GetAncestor(Of VariableDeclaratorSyntax)(),
node)
End Function
Public Overrides Function SetAccess(node As SyntaxNode, newAccess As EnvDTE.vsCMAccess) As SyntaxNode
Dim member = TryCast(node, StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
If member.Parent.Kind = SyntaxKind.InterfaceBlock OrElse
member.Parent.Kind = SyntaxKind.EnumBlock Then
If newAccess = EnvDTE.vsCMAccess.vsCMAccessDefault OrElse
newAccess = EnvDTE.vsCMAccess.vsCMAccessPublic Then
Return node
Else
Throw Exceptions.ThrowEInvalidArg()
End If
End If
If TypeOf member Is TypeBlockSyntax OrElse
TypeOf member Is EnumBlockSyntax Then
If Not TypeOf member.Parent Is TypeBlockSyntax AndAlso
(newAccess = EnvDTE.vsCMAccess.vsCMAccessPrivate OrElse
newAccess = EnvDTE.vsCMAccess.vsCMAccessProtected OrElse
newAccess = EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) Then
Throw Exceptions.ThrowEInvalidArg()
End If
End If
Dim flags = member.GetModifierFlags() And Not (ModifierFlags.AccessModifierMask Or ModifierFlags.Dim Or ModifierFlags.WithEvents)
If (newAccess And EnvDTE.vsCMAccess.vsCMAccessPrivate) <> 0 Then
flags = flags Or ModifierFlags.Private
ElseIf (newAccess And EnvDTE.vsCMAccess.vsCMAccessProtected) <> 0 Then
flags = flags Or ModifierFlags.Protected
If (newAccess And EnvDTE.vsCMAccess.vsCMAccessProject) <> 0 Then
flags = flags Or ModifierFlags.Friend
End If
ElseIf (newAccess And EnvDTE.vsCMAccess.vsCMAccessPublic) <> 0 Then
flags = flags Or ModifierFlags.Public
ElseIf (newAccess And EnvDTE.vsCMAccess.vsCMAccessProject) <> 0 Then
flags = flags Or ModifierFlags.Friend
ElseIf (newAccess And EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) <> 0 Then
flags = flags Or ModifierFlags.Protected Or ModifierFlags.Friend
ElseIf (newAccess And EnvDTE.vsCMAccess.vsCMAccessDefault) <> 0 Then
' No change
End If
If (newAccess And EnvDTE.vsCMAccess.vsCMAccessWithEvents) <> 0 Then
flags = flags Or ModifierFlags.WithEvents
End If
If flags = 0 AndAlso member.IsKind(SyntaxKind.FieldDeclaration) Then
flags = flags Or ModifierFlags.Dim
End If
Return member.UpdateModifiers(flags)
End Function
Private Overloads Function GetDefaultAccessibility(node As SyntaxNode) As EnvDTE.vsCMAccess
If node.HasAncestor(Of StructureBlockSyntax)() Then
Return EnvDTE.vsCMAccess.vsCMAccessPublic
End If
If TypeOf node Is FieldDeclarationSyntax Then
Return EnvDTE.vsCMAccess.vsCMAccessPrivate
ElseIf (TypeOf node Is MethodBlockBaseSyntax OrElse
TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is EnumBlockSyntax OrElse
TypeOf node Is MethodBaseSyntax OrElse
TypeOf node Is EnumMemberDeclarationSyntax) Then
Return EnvDTE.vsCMAccess.vsCMAccessPublic
End If
Throw Exceptions.ThrowEFail()
End Function
Protected Overrides Function GetAttributeIndexInContainer(containerNode As SyntaxNode, predicate As Func(Of SyntaxNode, Boolean)) As Integer
Dim attributes = GetAttributeNodes(containerNode).ToArray()
Dim index = 0
While index < attributes.Length
Dim attribute = DirectCast(attributes(index), AttributeSyntax)
If predicate(attribute) Then
Dim attributeBlock = DirectCast(attribute.Parent, AttributeListSyntax)
' If this attribute is part of a block with multiple attributes,
' make sure to return the index of the last attribute in the block.
If attributeBlock.Attributes.Count > 1 Then
Dim indexOfAttributeInBlock = attributeBlock.Attributes.IndexOf(attribute)
Return index + (attributeBlock.Attributes.Count - indexOfAttributeInBlock)
End If
Return index + 1
End If
index += 1
End While
Return -1
End Function
Protected Overrides Function GetAttributeArgumentIndexInContainer(containerNode As SyntaxNode, predicate As Func(Of SyntaxNode, Boolean)) As Integer
Dim attributeArguments = GetAttributeArgumentNodes(containerNode).ToArray()
Dim index = 0
While index < attributeArguments.Length
If predicate(attributeArguments(index)) Then
Return index + 1
End If
index += 1
End While
Return -1
End Function
Protected Overrides Function GetImportIndexInContainer(containerNode As SyntaxNode, predicate As Func(Of SyntaxNode, Boolean)) As Integer
Dim importsClauses = GetImportNodes(containerNode).ToArray()
Dim index = 0
While index < importsClauses.Length
Dim importsClause = DirectCast(importsClauses(index), ImportsClauseSyntax)
If predicate(importsClause) Then
Dim importsStatement = DirectCast(importsClause.Parent, ImportsStatementSyntax)
' If this attribute is part of a block with multiple attributes,
' make sure to return the index of the last attribute in the block.
If importsStatement.ImportsClauses.Count > 1 Then
Dim indexOfImportClauseInStatement = importsStatement.ImportsClauses.IndexOf(importsClause)
Return index + (importsStatement.ImportsClauses.Count - indexOfImportClauseInStatement)
End If
Return index + 1
End If
index += 1
End While
Return -1
End Function
Protected Overrides Function GetParameterIndexInContainer(containerNode As SyntaxNode, predicate As Func(Of SyntaxNode, Boolean)) As Integer
Dim parameters = GetParameterNodes(containerNode).ToArray()
For index = 0 To parameters.Length - 1
If predicate(parameters(index)) Then
Return index + 1
End If
Next
Return -1
End Function
Protected Overrides Function GetMemberIndexInContainer(containerNode As SyntaxNode, predicate As Func(Of SyntaxNode, Boolean)) As Integer
Dim members = GetLogicalMemberNodes(containerNode).ToArray()
Dim index = 0
While index < members.Length
Dim member = members(index)
If predicate(member) Then
' Special case: if a modified identifier was specified, make sure we return the index
' of the last modified identifier of the last variable declarator in the parenting field
' declaration.
If member.Kind = SyntaxKind.ModifiedIdentifier Then
Dim modifiedIdentifier = DirectCast(member, ModifiedIdentifierSyntax)
Dim variableDeclarator = DirectCast(member.Parent, VariableDeclaratorSyntax)
Dim fieldDeclaration = DirectCast(variableDeclarator.Parent, FieldDeclarationSyntax)
Dim indexOfNameInDeclarator = variableDeclarator.Names.IndexOf(modifiedIdentifier)
Dim indexOfDeclaratorInField = fieldDeclaration.Declarators.IndexOf(variableDeclarator)
Dim indexOfNameInField = indexOfNameInDeclarator
If indexOfDeclaratorInField > 0 Then
For i = 0 To indexOfDeclaratorInField - 1
indexOfNameInField += fieldDeclaration.Declarators(i).Names.Count
Next
End If
Dim namesInFieldCount = fieldDeclaration.Declarators.SelectMany(Function(v) v.Names).Count()
Return index + (namesInFieldCount - indexOfNameInField)
End If
Return index + 1
End If
index += 1
End While
Return -1
End Function
Public Overrides Sub GetOptionNameAndOrdinal(parentNode As SyntaxNode, optionNode As SyntaxNode, ByRef name As String, ByRef ordinal As Integer)
Debug.Assert(TypeOf optionNode Is OptionStatementSyntax)
name = GetNormalizedName(DirectCast(optionNode, OptionStatementSyntax))
ordinal = -1
For Each [option] As OptionStatementSyntax In GetOptionNodes(parentNode)
If GetNormalizedName([option]) = name Then
ordinal += 1
End If
If [option].Equals(optionNode) Then
Exit For
End If
Next
End Sub
Public Overrides Sub GetInheritsNamespaceAndOrdinal(parentNode As SyntaxNode, inheritsNode As SyntaxNode, ByRef namespaceName As String, ByRef ordinal As Integer)
Debug.Assert(TypeOf inheritsNode Is InheritsStatementSyntax)
namespaceName = DirectCast(inheritsNode, InheritsStatementSyntax).Types.ToString()
ordinal = -1
For Each [inherits] As InheritsStatementSyntax In GetInheritsNodes(parentNode)
If [inherits].Types.ToString() = namespaceName Then
ordinal += 1
End If
If [inherits].Equals(inheritsNode) Then
Exit For
End If
Next
End Sub
Public Overrides Sub GetImplementsNamespaceAndOrdinal(parentNode As SyntaxNode, implementsNode As SyntaxNode, ByRef namespaceName As String, ByRef ordinal As Integer)
Debug.Assert(TypeOf implementsNode Is ImplementsStatementSyntax)
namespaceName = DirectCast(implementsNode, ImplementsStatementSyntax).Types.ToString()
ordinal = -1
For Each [implements] As ImplementsStatementSyntax In GetImplementsNodes(parentNode)
If [implements].Types.ToString() = namespaceName Then
ordinal += 1
End If
If [implements].Equals(implementsNode) Then
Exit For
End If
Next
End Sub
Public Overrides Sub GetAttributeNameAndOrdinal(parentNode As SyntaxNode, attributeNode As SyntaxNode, ByRef name As String, ByRef ordinal As Integer)
Debug.Assert(TypeOf attributeNode Is AttributeSyntax)
name = DirectCast(attributeNode, AttributeSyntax).Name.ToString()
ordinal = -1
For Each attribute As AttributeSyntax In GetAttributeNodes(parentNode)
If attribute.Name.ToString() = name Then
ordinal += 1
End If
If attribute.Equals(attributeNode) Then
Exit For
End If
Next
End Sub
Public Overrides Function GetAttributeTargetNode(attributeNode As SyntaxNode) As SyntaxNode
If TypeOf attributeNode Is AttributeSyntax Then
Return attributeNode
End If
Throw Exceptions.ThrowEUnexpected()
End Function
Public Overrides Function GetAttributeTarget(attributeNode As SyntaxNode) As String
Debug.Assert(TypeOf attributeNode Is AttributeSyntax)
Dim attribute = DirectCast(attributeNode, AttributeSyntax)
Return If(attribute.Target IsNot Nothing,
attribute.Target.AttributeModifier.ToString(),
String.Empty)
End Function
Public Overrides Function SetAttributeTarget(attributeNode As SyntaxNode, value As String) As SyntaxNode
Debug.Assert(TypeOf attributeNode Is AttributeSyntax)
Dim attribute = DirectCast(attributeNode, AttributeSyntax)
Dim target = attribute.Target
If Not String.IsNullOrEmpty(value) Then
' VB only supports Assembly and Module as attribute modifiers.
Dim newModifier As SyntaxToken
If String.Equals(value, "Assembly", StringComparison.OrdinalIgnoreCase) Then
newModifier = SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)
ElseIf String.Equals(value, "Module", StringComparison.OrdinalIgnoreCase) Then
newModifier = SyntaxFactory.Token(SyntaxKind.ModuleKeyword)
Else
Throw Exceptions.ThrowEInvalidArg()
End If
Dim newTarget = If(target IsNot Nothing,
target.WithAttributeModifier(newModifier),
SyntaxFactory.AttributeTarget(newModifier))
Return attribute.WithTarget(newTarget)
Else
Return attribute.WithTarget(Nothing)
End If
End Function
Public Overrides Function GetAttributeValue(attributeNode As SyntaxNode) As String
Debug.Assert(TypeOf attributeNode Is AttributeSyntax)
Dim attribute = DirectCast(attributeNode, AttributeSyntax)
Dim argumentList = attribute.ArgumentList
If argumentList IsNot Nothing Then
Return argumentList.Arguments.ToString()
End If
Return String.Empty
End Function
Public Overrides Function SetAttributeValue(attributeNode As SyntaxNode, value As String) As SyntaxNode
Debug.Assert(TypeOf attributeNode Is AttributeSyntax)
Dim attribute = DirectCast(attributeNode, AttributeSyntax)
Dim argumentList = attribute.ArgumentList
Dim parsedArgumentList = SyntaxFactory.ParseArgumentList("(" & value & ")")
Dim newArgumentList = If(argumentList IsNot Nothing,
argumentList.WithArguments(parsedArgumentList.Arguments),
parsedArgumentList)
Return attribute.WithArgumentList(newArgumentList)
End Function
Public Overrides Function GetNodeWithAttributes(node As SyntaxNode) As SyntaxNode
Return If(TypeOf node Is ModifiedIdentifierSyntax,
node.GetAncestor(Of FieldDeclarationSyntax),
node)
End Function
Public Overrides Function GetEffectiveParentForAttribute(node As SyntaxNode) As SyntaxNode
If node.HasAncestor(Of FieldDeclarationSyntax)() Then
Return node.GetAncestor(Of FieldDeclarationSyntax).Declarators.First().Names.First()
ElseIf node.HasAncestor(Of ParameterSyntax)() Then
Return node.GetAncestor(Of ParameterSyntax)()
Else
Return node.Parent
End If
End Function
Public Overrides Sub GetAttributeArgumentParentAndIndex(attributeArgumentNode As SyntaxNode, ByRef attributeNode As SyntaxNode, ByRef index As Integer)
Debug.Assert(TypeOf attributeArgumentNode Is ArgumentSyntax)
Dim argument = DirectCast(attributeArgumentNode, ArgumentSyntax)
Dim attribute = DirectCast(argument.Ancestors.FirstOrDefault(Function(n) n.Kind = SyntaxKind.Attribute), AttributeSyntax)
attributeNode = attribute
index = attribute.ArgumentList.Arguments.IndexOf(DirectCast(attributeArgumentNode, ArgumentSyntax))
End Sub
Public Overrides Function CreateAttributeNode(name As String, value As String, Optional target As String = Nothing) As SyntaxNode
Dim specifier As AttributeTargetSyntax = Nothing
If target IsNot Nothing Then
Dim contextualKeywordKind = SyntaxFacts.GetContextualKeywordKind(target)
If contextualKeywordKind = SyntaxKind.AssemblyKeyword OrElse
contextualKeywordKind = SyntaxKind.ModuleKeyword Then
specifier = SyntaxFactory.AttributeTarget(SyntaxFactory.Token(contextualKeywordKind, text:=target))
Else
specifier = SyntaxFactory.AttributeTarget(SyntaxFactory.ParseToken(target))
End If
End If
Return SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Attribute(
target:=specifier,
name:=SyntaxFactory.ParseName(name),
argumentList:=SyntaxFactory.ParseArgumentList("(" & value & ")"))))
End Function
Public Overrides Function CreateAttributeArgumentNode(name As String, value As String) As SyntaxNode
If Not String.IsNullOrEmpty(name) Then
Return SyntaxFactory.SimpleArgument(
SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName(name)),
SyntaxFactory.ParseExpression(value))
Else
Return SyntaxFactory.SimpleArgument(SyntaxFactory.ParseExpression(value))
End If
End Function
Public Overrides Function CreateImportNode(name As String, Optional [alias] As String = Nothing) As SyntaxNode
Dim nameSyntax = SyntaxFactory.ParseName(name)
Dim importsClause As ImportsClauseSyntax
If Not String.IsNullOrEmpty([alias]) Then
importsClause = SyntaxFactory.SimpleImportsClause(SyntaxFactory.ImportAliasClause([alias]), nameSyntax)
Else
importsClause = SyntaxFactory.SimpleImportsClause(nameSyntax)
End If
Return SyntaxFactory.ImportsStatement(SyntaxFactory.SingletonSeparatedList(importsClause))
End Function
Public Overrides Function CreateParameterNode(name As String, type As String) As SyntaxNode
Return SyntaxFactory.Parameter(SyntaxFactory.ModifiedIdentifier(name)).WithAsClause(SyntaxFactory.SimpleAsClause(SyntaxFactory.ParseTypeName(type)))
End Function
Public Overrides Function GetAttributeArgumentValue(attributeArgumentNode As SyntaxNode) As String
Select Case attributeArgumentNode.Kind
Case SyntaxKind.SimpleArgument
Return DirectCast(attributeArgumentNode, SimpleArgumentSyntax).Expression.ToString()
End Select
Throw New InvalidOperationException()
End Function
Public Overrides Function GetImportAlias(node As SyntaxNode) As String
Select Case node.Kind
Case SyntaxKind.SimpleImportsClause
Dim simpleImportsClause = DirectCast(node, SimpleImportsClauseSyntax)
Return If(simpleImportsClause.Alias IsNot Nothing,
simpleImportsClause.Alias.Identifier.ToString(),
String.Empty)
Case Else
Throw New InvalidOperationException()
End Select
End Function
Public Overrides Function GetImportNamespaceOrType(node As SyntaxNode) As String
Select Case node.Kind
Case SyntaxKind.SimpleImportsClause
Return GetNormalizedName(DirectCast(node, SimpleImportsClauseSyntax).Name)
Case Else
Throw New InvalidOperationException()
End Select
End Function
Public Overrides Sub GetImportParentAndName(node As SyntaxNode, ByRef parentNode As SyntaxNode, ByRef name As String)
parentNode = Nothing
Select Case node.Kind
Case SyntaxKind.SimpleImportsClause
name = GetNormalizedName(DirectCast(node, SimpleImportsClauseSyntax).Name)
Case Else
Throw New InvalidOperationException()
End Select
End Sub
Public Overrides Function GetParameterName(node As SyntaxNode) As String
Dim parameter = TryCast(node, ParameterSyntax)
If parameter IsNot Nothing Then
Return GetNameFromParameter(parameter)
End If
Throw New InvalidOperationException()
End Function
Private Function GetNameFromParameter(parameter As ParameterSyntax) As String
Dim parameterName As String = parameter.Identifier.Identifier.ToString()
Return If(Not String.IsNullOrEmpty(parameterName) AndAlso SyntaxFactsService.IsTypeCharacter(parameterName.Last()),
parameterName.Substring(0, parameterName.Length - 1),
parameterName)
End Function
Public Overrides Function GetParameterFullName(node As SyntaxNode) As String
Dim parameter = TryCast(node, ParameterSyntax)
If parameter IsNot Nothing Then
Return parameter.Identifier.ToString()
End If
Throw New InvalidOperationException()
End Function
Public Overrides Function GetParameterKind(node As SyntaxNode) As EnvDTE80.vsCMParameterKind
Dim parameter = TryCast(node, ParameterSyntax)
If parameter IsNot Nothing Then
Dim kind = EnvDTE80.vsCMParameterKind.vsCMParameterKindNone
Dim modifiers = parameter.Modifiers
If modifiers.Any(SyntaxKind.OptionalKeyword) Then
kind = kind Or EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional
End If
If modifiers.Any(SyntaxKind.ParamArrayKeyword) Then
kind = kind Or EnvDTE80.vsCMParameterKind.vsCMParameterKindParamArray
End If
If modifiers.Any(SyntaxKind.ByRefKeyword) Then
kind = kind Or EnvDTE80.vsCMParameterKind.vsCMParameterKindRef
Else
kind = kind Or EnvDTE80.vsCMParameterKind.vsCMParameterKindIn
End If
Return kind
End If
Throw New InvalidOperationException()
End Function
Public Overrides Function SetParameterKind(node As SyntaxNode, kind As EnvDTE80.vsCMParameterKind) As SyntaxNode
Dim parameter = TryCast(node, ParameterSyntax)
If parameter Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
If Not IsValidParameterKind(kind) Then
Throw Exceptions.ThrowEInvalidArg()
End If
Dim newModifierList = New List(Of SyntaxToken)
' TODO (tomescht): The Dev11 code allowed different sets of modifiers to be
' set when in batch mode vs non-batch mode.
If (kind And EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional) <> 0 Then
newModifierList.Add(SyntaxFactory.Token(SyntaxKind.OptionalKeyword))
End If
If (kind And EnvDTE80.vsCMParameterKind.vsCMParameterKindRef) <> 0 Then
newModifierList.Add(SyntaxFactory.Token(SyntaxKind.ByRefKeyword))
End If
If (kind And EnvDTE80.vsCMParameterKind.vsCMParameterKindParamArray) <> 0 Then
newModifierList.Add(SyntaxFactory.Token(SyntaxKind.ParamArrayKeyword))
End If
Return parameter.WithModifiers(SyntaxFactory.TokenList(newModifierList))
End Function
Private Function IsValidParameterKind(kind As EnvDTE80.vsCMParameterKind) As Boolean
Select Case kind
Case EnvDTE80.vsCMParameterKind.vsCMParameterKindNone,
EnvDTE80.vsCMParameterKind.vsCMParameterKindIn,
EnvDTE80.vsCMParameterKind.vsCMParameterKindRef,
EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional,
EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional Or EnvDTE80.vsCMParameterKind.vsCMParameterKindIn,
EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional Or EnvDTE80.vsCMParameterKind.vsCMParameterKindRef,
EnvDTE80.vsCMParameterKind.vsCMParameterKindParamArray,
EnvDTE80.vsCMParameterKind.vsCMParameterKindParamArray Or EnvDTE80.vsCMParameterKind.vsCMParameterKindIn
Return True
End Select
Return False
End Function
Public Overrides Function ValidateFunctionKind(containerNode As SyntaxNode, kind As EnvDTE.vsCMFunction, name As String) As EnvDTE.vsCMFunction
If kind = EnvDTE.vsCMFunction.vsCMFunctionSub Then
Return If(name = "New" AndAlso Not TypeOf containerNode Is InterfaceBlockSyntax,
EnvDTE.vsCMFunction.vsCMFunctionConstructor,
kind)
End If
If kind = EnvDTE.vsCMFunction.vsCMFunctionFunction Then
Return kind
End If
Throw Exceptions.ThrowEInvalidArg()
End Function
Public Overrides ReadOnly Property SupportsEventThrower As Boolean
Get
Return True
End Get
End Property
Public Overrides Function GetCanOverride(memberNode As SyntaxNode) As Boolean
Debug.Assert(TypeOf memberNode Is StatementSyntax)
Dim member = TryCast(memberNode, StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
If member.Parent.Kind = SyntaxKind.InterfaceBlock Then
Return True
End If
Dim flags = member.GetModifierFlags()
If (flags And ModifierFlags.NotOverridable) <> 0 Then
Return False
End If
If (flags And ModifierFlags.MustOverride) <> 0 Then
Return True
End If
If (flags And ModifierFlags.Overridable) <> 0 Then
Return True
End If
If (flags And ModifierFlags.Overrides) <> 0 Then
Return True
End If
Return False
End Function
Public Overrides Function SetCanOverride(memberNode As SyntaxNode, value As Boolean) As SyntaxNode
Dim overrideKind = If(value, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone)
Return SetOverrideKind(memberNode, overrideKind)
End Function
Public Overrides Function GetClassKind(typeNode As SyntaxNode, typeSymbol As INamedTypeSymbol) As EnvDTE80.vsCMClassKind
Debug.Assert(TypeOf typeNode Is ClassBlockSyntax OrElse
TypeOf typeNode Is ModuleBlockSyntax)
Dim result As EnvDTE80.vsCMClassKind = 0
Dim typeBlock = DirectCast(typeNode, TypeBlockSyntax)
If TypeOf typeBlock Is ModuleBlockSyntax Then
Return EnvDTE80.vsCMClassKind.vsCMClassKindModule
End If
Dim flags = typeBlock.GetModifierFlags()
If (flags And ModifierFlags.Partial) <> 0 Then
Return EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass
End If
If typeSymbol.DeclaringSyntaxReferences.Length > 1 Then
Return EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass
End If
Return EnvDTE80.vsCMClassKind.vsCMClassKindMainClass
End Function
Private Function IsValidClassKind(kind As EnvDTE80.vsCMClassKind) As Boolean
Return kind = EnvDTE80.vsCMClassKind.vsCMClassKindMainClass OrElse
kind = EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass
End Function
Public Overrides Function SetClassKind(typeNode As SyntaxNode, kind As EnvDTE80.vsCMClassKind) As SyntaxNode
Debug.Assert(TypeOf typeNode Is ClassBlockSyntax OrElse
TypeOf typeNode Is ModuleBlockSyntax)
Dim typeBlock = DirectCast(typeNode, StatementSyntax)
If TypeOf typeBlock Is ModuleBlockSyntax Then
If kind = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone Then
Return typeBlock
End If
Throw Exceptions.ThrowENotImpl()
End If
If Not IsValidClassKind(kind) Then
Throw Exceptions.ThrowEInvalidArg()
End If
Dim flags = typeBlock.GetModifierFlags()
flags = flags And Not ModifierFlags.Partial
If kind = EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass Then
flags = flags Or ModifierFlags.Partial
End If
Return typeBlock.UpdateModifiers(flags)
End Function
Private Shared Function CollectComments(triviaList As IList(Of SyntaxTrivia)) As IList(Of SyntaxTrivia)
Dim commentList = New List(Of SyntaxTrivia)
Dim firstCommentFound = False
For i = triviaList.Count - 1 To 0 Step -1
Dim trivia = triviaList(i)
Dim nextTrivia = If(i > 0, triviaList(i - 1), Nothing)
If trivia.Kind = SyntaxKind.CommentTrivia Then
firstCommentFound = True
commentList.Add(trivia)
ElseIf Not firstCommentFound AndAlso trivia.IsWhitespace() Then
Continue For
ElseIf firstCommentFound AndAlso trivia.Kind = SyntaxKind.EndOfLineTrivia AndAlso nextTrivia.Kind = SyntaxKind.CommentTrivia Then
Continue For
Else
Exit For
End If
Next
commentList.Reverse()
Return commentList
End Function
Public Overrides Function GetComment(node As SyntaxNode) As String
Debug.Assert(TypeOf node Is StatementSyntax)
Dim member = DirectCast(node, StatementSyntax)
Dim firstToken = member.GetFirstToken()
Dim triviaList = firstToken.LeadingTrivia
Dim commentList = CollectComments(firstToken.LeadingTrivia.ToArray())
If commentList.Count = 0 Then
Return String.Empty
End If
Dim textBuilder = New StringBuilder()
For Each trivia In commentList
Debug.Assert(trivia.ToString().StartsWith("'", StringComparison.Ordinal))
Dim commentText = trivia.ToString().Substring(1)
textBuilder.AppendLine(commentText)
Next
Return textBuilder.ToString().TrimEnd()
End Function
Public Overrides Function SetComment(node As SyntaxNode, value As String) As SyntaxNode
Debug.Assert(TypeOf node Is StatementSyntax)
Dim member = DirectCast(node, StatementSyntax)
Dim text = member.SyntaxTree.GetText(CancellationToken.None)
Dim newLine = GetNewLineCharacter(text)
Dim commentText = String.Empty
If value IsNot Nothing Then
Dim builder = New StringBuilder()
For Each line In value.Split({vbCr, vbLf}, StringSplitOptions.RemoveEmptyEntries)
builder.Append("' ")
builder.Append(line)
builder.Append(newLine)
Next
commentText = builder.ToString()
End If
Dim newTriviaList = SyntaxFactory.ParseLeadingTrivia(commentText)
Dim leadingTriviaList = member.GetLeadingTrivia().ToList()
Dim commentList = CollectComments(leadingTriviaList)
If commentList.Count > 0 Then
' In this case, we're going to replace the existing comment.
Dim firstIndex = leadingTriviaList.FindIndex(Function(t) t = commentList(0))
Dim lastIndex = leadingTriviaList.FindIndex(Function(t) t = commentList(commentList.Count - 1))
Dim count = lastIndex - firstIndex + 1
leadingTriviaList.RemoveRange(firstIndex, count)
' Note: single line comments have a trailing new-line but that won't be
' returned by CollectComments. So, we may need to remove an additional new line below.
If firstIndex < leadingTriviaList.Count AndAlso
leadingTriviaList(firstIndex).Kind = SyntaxKind.EndOfLineTrivia Then
leadingTriviaList.RemoveAt(firstIndex)
End If
For Each triviaElement In newTriviaList.Reverse()
leadingTriviaList.Insert(firstIndex, triviaElement)
Next
Else
' Otherwise, just add the comment to the end of the leading trivia.
leadingTriviaList.AddRange(newTriviaList)
End If
Return member.WithLeadingTrivia(leadingTriviaList)
End Function
Public Overrides Function GetConstKind(variableNode As SyntaxNode) As EnvDTE80.vsCMConstKind
If TypeOf variableNode Is EnumMemberDeclarationSyntax Then
Return EnvDTE80.vsCMConstKind.vsCMConstKindConst
End If
Dim member = TryCast(GetNodeWithModifiers(variableNode), StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Dim flags = member.GetModifierFlags()
If (flags And ModifierFlags.Const) <> 0 Then
Return EnvDTE80.vsCMConstKind.vsCMConstKindConst
End If
If (flags And ModifierFlags.ReadOnly) <> 0 Then
Return EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly
End If
Return EnvDTE80.vsCMConstKind.vsCMConstKindNone
End Function
Private Function IsValidConstKind(kind As EnvDTE80.vsCMConstKind) As Boolean
Return kind = EnvDTE80.vsCMConstKind.vsCMConstKindConst OrElse
kind = EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly OrElse
kind = EnvDTE80.vsCMConstKind.vsCMConstKindNone
End Function
Public Overrides Function SetConstKind(variableNode As SyntaxNode, kind As EnvDTE80.vsCMConstKind) As SyntaxNode
If TypeOf variableNode Is EnumMemberDeclarationSyntax Then
Throw Exceptions.ThrowENotImpl()
End If
If Not IsValidConstKind(kind) Then
Throw Exceptions.ThrowEInvalidArg()
End If
Dim member = TryCast(GetNodeWithModifiers(variableNode), StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Dim flags = member.GetModifierFlags()
flags = flags And Not (ModifierFlags.Const Or ModifierFlags.ReadOnly Or ModifierFlags.Dim)
If kind = EnvDTE80.vsCMConstKind.vsCMConstKindConst Then
flags = flags Or ModifierFlags.Const
ElseIf kind = EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly Then
flags = flags Or ModifierFlags.ReadOnly
End If
If flags = 0 Then
flags = flags Or ModifierFlags.Dim
End If
Return member.UpdateModifiers(flags)
End Function
Public Overrides Function GetDataTypeKind(typeNode As SyntaxNode, symbol As INamedTypeSymbol) As EnvDTE80.vsCMDataTypeKind
Debug.Assert(TypeOf typeNode Is ClassBlockSyntax OrElse
TypeOf typeNode Is InterfaceBlockSyntax OrElse
TypeOf typeNode Is ModuleBlockSyntax OrElse
TypeOf typeNode Is StructureBlockSyntax)
Dim typeBlock = DirectCast(typeNode, TypeBlockSyntax)
If TypeOf typeBlock Is ModuleBlockSyntax Then
Return EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindModule
End If
Dim flags = typeBlock.GetModifierFlags()
If (flags And ModifierFlags.Partial) <> 0 Then
Return EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindPartial
End If
If symbol.DeclaringSyntaxReferences.Length > 1 Then
Return EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindPartial
End If
Return EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindMain
End Function
Private Function IsValidDataTypeKind(kind As EnvDTE80.vsCMDataTypeKind, allowModule As Boolean) As Boolean
Return kind = EnvDTE80.vsCMClassKind.vsCMClassKindMainClass OrElse
kind = EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass OrElse
(allowModule AndAlso kind = EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindModule)
End Function
Public Overrides Function SetDataTypeKind(typeNode As SyntaxNode, kind As EnvDTE80.vsCMDataTypeKind) As SyntaxNode
Debug.Assert(TypeOf typeNode Is ClassBlockSyntax OrElse
TypeOf typeNode Is InterfaceBlockSyntax OrElse
TypeOf typeNode Is ModuleBlockSyntax OrElse
TypeOf typeNode Is StructureBlockSyntax)
Dim typeBlock = DirectCast(typeNode, TypeBlockSyntax)
If TypeOf typeBlock Is InterfaceBlockSyntax Then
Throw Exceptions.ThrowENotImpl()
End If
Dim allowModule = TypeOf typeBlock Is ClassBlockSyntax OrElse
TypeOf typeBlock Is ModuleBlockSyntax
If Not IsValidDataTypeKind(kind, allowModule) Then
Throw Exceptions.ThrowEFail()
End If
Dim flags = typeBlock.GetModifierFlags()
flags = flags And Not ModifierFlags.Partial
If kind = EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindPartial Then
flags = flags Or ModifierFlags.Partial
End If
' VB supports changing a Module to a Class and vice versa.
If TypeOf typeBlock Is ModuleBlockSyntax Then
If kind = EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindMain OrElse
kind = EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindPartial Then
Dim moduleBlock = DirectCast(typeBlock, ModuleBlockSyntax)
typeBlock = SyntaxFactory.ClassBlock(
classStatement:=SyntaxFactory.ClassStatement(
attributeLists:=moduleBlock.ModuleStatement.AttributeLists,
modifiers:=moduleBlock.ModuleStatement.Modifiers,
classKeyword:=SyntaxFactory.Token(moduleBlock.ModuleStatement.ModuleKeyword.LeadingTrivia, SyntaxKind.ClassKeyword, moduleBlock.ModuleStatement.ModuleKeyword.TrailingTrivia),
identifier:=moduleBlock.ModuleStatement.Identifier,
typeParameterList:=moduleBlock.ModuleStatement.TypeParameterList),
[inherits]:=moduleBlock.Inherits,
[implements]:=moduleBlock.Implements,
members:=moduleBlock.Members,
endClassStatement:=SyntaxFactory.EndClassStatement(
endKeyword:=moduleBlock.EndModuleStatement.EndKeyword,
blockKeyword:=SyntaxFactory.Token(moduleBlock.EndModuleStatement.BlockKeyword.LeadingTrivia, SyntaxKind.ClassKeyword, moduleBlock.EndModuleStatement.BlockKeyword.TrailingTrivia)))
End If
ElseIf TypeOf typeBlock Is ClassBlockSyntax Then
If kind = EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindModule Then
flags = flags And Not ModifierFlags.Shared
Dim classBlock = DirectCast(typeBlock, ClassBlockSyntax)
typeBlock = SyntaxFactory.ModuleBlock(
moduleStatement:=SyntaxFactory.ModuleStatement(
attributeLists:=classBlock.ClassStatement.AttributeLists,
modifiers:=classBlock.ClassStatement.Modifiers,
moduleKeyword:=SyntaxFactory.Token(classBlock.ClassStatement.ClassKeyword.LeadingTrivia, SyntaxKind.ModuleKeyword, classBlock.ClassStatement.ClassKeyword.TrailingTrivia),
identifier:=classBlock.ClassStatement.Identifier,
typeParameterList:=classBlock.ClassStatement.TypeParameterList),
[inherits]:=Nothing,
[implements]:=Nothing,
members:=classBlock.Members,
endModuleStatement:=SyntaxFactory.EndModuleStatement(
endKeyword:=classBlock.EndClassStatement.EndKeyword,
blockKeyword:=SyntaxFactory.Token(classBlock.EndClassStatement.BlockKeyword.LeadingTrivia, SyntaxKind.ModuleKeyword, classBlock.EndClassStatement.BlockKeyword.TrailingTrivia)))
End If
End If
Return typeBlock.UpdateModifiers(flags)
End Function
Private Shared Function GetDocCommentNode(memberDeclaration As StatementSyntax) As DocumentationCommentTriviaSyntax
Dim docCommentTrivia = memberDeclaration _
.GetLeadingTrivia() _
.Reverse() _
.FirstOrDefault(Function(t) t.Kind = SyntaxKind.DocumentationCommentTrivia)
If docCommentTrivia.Kind <> SyntaxKind.DocumentationCommentTrivia Then
Return Nothing
End If
Return DirectCast(docCommentTrivia.GetStructure(), DocumentationCommentTriviaSyntax)
End Function
Public Overrides Function GetDocComment(node As SyntaxNode) As String
Debug.Assert(TypeOf node Is StatementSyntax)
Dim member = DirectCast(node, StatementSyntax)
Dim documentationComment = GetDocCommentNode(member)
If documentationComment Is Nothing Then
Return String.Empty
End If
Dim text = member.SyntaxTree.GetText(CancellationToken.None)
Dim newLine = GetNewLineCharacter(text)
Dim lines = documentationComment.ToString().Split({newLine}, StringSplitOptions.None)
' trim off leading whitespace and exterior trivia.
Dim lengthToStrip = lines(0).GetLeadingWhitespace().Length
Dim linesCount = lines.Length
For i = 1 To lines.Length - 1
Dim line = lines(i).TrimStart()
If line.StartsWith("'''", StringComparison.Ordinal) Then
lines(i) = line.Substring(3)
End If
Next
Return lines.Join(newLine).TrimEnd()
End Function
Public Overrides Function SetDocComment(node As SyntaxNode, value As String) As SyntaxNode
Debug.Assert(TypeOf node Is StatementSyntax)
Dim member = DirectCast(node, StatementSyntax)
Dim triviaList = CType(Nothing, SyntaxTriviaList)
If value IsNot Nothing Then
Dim text = member.SyntaxTree.GetText(CancellationToken.None)
Dim newLine = GetNewLineCharacter(text)
Dim builder = New StringBuilder()
For Each line In value.Split({vbCr, vbLf}, StringSplitOptions.RemoveEmptyEntries)
builder.Append("''' ")
builder.Append(line)
builder.Append(newLine)
Next
triviaList = SyntaxFactory.ParseLeadingTrivia(builder.ToString())
End If
Dim leadingTriviaList = member.GetLeadingTrivia().ToList()
Dim documentationComment = GetDocCommentNode(member)
If documentationComment IsNot Nothing Then
' In this case, we're going to replace the existing XML doc comment.
Dim index = leadingTriviaList.FindIndex(Function(t) t = documentationComment.ParentTrivia)
leadingTriviaList.RemoveAt(index)
For Each triviaElement In triviaList.Reverse()
leadingTriviaList.Insert(index, triviaElement)
Next
Else
' Otherwise, just add the XML doc comment to the end of the leading trivia.
leadingTriviaList.AddRange(triviaList)
End If
Return member.WithLeadingTrivia(leadingTriviaList)
End Function
Public Overrides Function GetFunctionKind(symbol As IMethodSymbol) As EnvDTE.vsCMFunction
If symbol.IsOverride AndAlso symbol.Name = "Finalize" Then
Return EnvDTE.vsCMFunction.vsCMFunctionDestructor
End If
Select Case symbol.MethodKind
Case MethodKind.Ordinary,
MethodKind.DeclareMethod
Return If(symbol.ReturnsVoid, EnvDTE.vsCMFunction.vsCMFunctionSub, EnvDTE.vsCMFunction.vsCMFunctionFunction)
Case MethodKind.Constructor,
MethodKind.StaticConstructor
Return EnvDTE.vsCMFunction.vsCMFunctionConstructor
Case MethodKind.UserDefinedOperator
Return EnvDTE.vsCMFunction.vsCMFunctionOperator
Case MethodKind.PropertyGet
Return EnvDTE.vsCMFunction.vsCMFunctionPropertyGet
Case MethodKind.PropertySet
Return EnvDTE.vsCMFunction.vsCMFunctionPropertySet
Case MethodKind.EventAdd
Return CType(EnvDTE80.vsCMFunction2.vsCMFunctionAddHandler, EnvDTE.vsCMFunction)
Case MethodKind.EventRemove
Return CType(EnvDTE80.vsCMFunction2.vsCMFunctionRemoveHandler, EnvDTE.vsCMFunction)
Case MethodKind.EventRaise
Return CType(EnvDTE80.vsCMFunction2.vsCMFunctionRaiseEvent, EnvDTE.vsCMFunction)
End Select
Throw Exceptions.ThrowEUnexpected()
End Function
Public Overrides Function GetInheritanceKind(typeNode As SyntaxNode, typeSymbol As INamedTypeSymbol) As EnvDTE80.vsCMInheritanceKind
Dim result As EnvDTE80.vsCMInheritanceKind = 0
If typeSymbol.IsSealed Then
result = result Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed
ElseIf typeSymbol.IsAbstract Then
result = result Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract
End If
' Old VB code model had a special case to check other parts for Shadows, so we'll do that here..
Dim statements = typeSymbol.DeclaringSyntaxReferences _
.Select(Function(r) TryCast(r.GetSyntax(), StatementSyntax)) _
.Where(Function(s) s IsNot Nothing)
For Each statement In statements
Dim modifiers = SyntaxFactory.TokenList(statement.GetModifiers())
If modifiers.Any(SyntaxKind.ShadowsKeyword) Then
result = result Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew
Exit For
End If
Next
Return result
End Function
Private Function IsValidInheritanceKind(kind As EnvDTE80.vsCMInheritanceKind) As Boolean
Return kind = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract OrElse
kind = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone OrElse
kind = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed OrElse
kind = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew OrElse
kind = (EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract) OrElse
kind = (EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed)
End Function
Public Overrides Function SetInheritanceKind(typeNode As SyntaxNode, kind As EnvDTE80.vsCMInheritanceKind) As SyntaxNode
Debug.Assert(TypeOf typeNode Is ClassBlockSyntax OrElse
TypeOf typeNode Is ModuleBlockSyntax)
If TypeOf typeNode Is ModuleBlockSyntax Then
If kind = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone Then
Return typeNode
End If
Throw Exceptions.ThrowENotImpl()
End If
If Not IsValidInheritanceKind(kind) Then
Throw Exceptions.ThrowEInvalidArg()
End If
Dim member = TryCast(typeNode, StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Dim flags = member.GetModifierFlags()
flags = flags And Not (ModifierFlags.MustInherit Or ModifierFlags.NotInheritable Or ModifierFlags.Shadows)
If kind <> EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone Then
If (kind And EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract) <> 0 Then
flags = flags Or ModifierFlags.MustInherit
ElseIf (kind And EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed) <> 0 Then
flags = flags Or ModifierFlags.NotInheritable
End If
If (kind And EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew) <> 0 Then
flags = flags Or ModifierFlags.Shadows
End If
End If
Return member.UpdateModifiers(flags)
End Function
Public Overrides Function GetMustImplement(memberNode As SyntaxNode) As Boolean
Debug.Assert(TypeOf memberNode Is StatementSyntax)
Dim member = TryCast(memberNode, StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
If member.Parent.Kind = SyntaxKind.InterfaceBlock Then
Return True
End If
Dim flags = member.GetModifierFlags()
Return (flags And ModifierFlags.MustOverride) <> 0
End Function
Public Overrides Function SetMustImplement(memberNode As SyntaxNode, value As Boolean) As SyntaxNode
Dim overrideKind = If(value, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone)
Return SetOverrideKind(memberNode, overrideKind)
End Function
Public Overrides Function GetOverrideKind(memberNode As SyntaxNode) As EnvDTE80.vsCMOverrideKind
Debug.Assert(TypeOf memberNode Is DeclarationStatementSyntax)
Dim member = TryCast(memberNode, DeclarationStatementSyntax)
If member IsNot Nothing Then
Dim modifiers = SyntaxFactory.TokenList(member.GetModifiers())
Dim result As EnvDTE80.vsCMOverrideKind = 0
If modifiers.Any(SyntaxKind.ShadowsKeyword) Then
result = result Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew
End If
If modifiers.Any(SyntaxKind.OverridesKeyword) Then
result = result Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride
End If
If modifiers.Any(SyntaxKind.MustOverrideKeyword) Or member.IsParentKind(SyntaxKind.InterfaceBlock) Then
result = result Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract
End If
If modifiers.Any(SyntaxKind.OverridableKeyword) Then
result = result Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual
ElseIf modifiers.Any(SyntaxKind.NotOverridableKeyword) Then
result = result Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed
End If
Return result
End If
Throw New InvalidOperationException
End Function
Private Function IsValidOverrideKind(kind As EnvDTE80.vsCMOverrideKind) As Boolean
Return kind = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed OrElse
kind = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew OrElse
kind = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride OrElse
kind = (EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed) OrElse
kind = (EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew) OrElse
kind = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract OrElse
kind = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual OrElse
kind = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone
End Function
Public Overrides Function SetOverrideKind(memberNode As SyntaxNode, kind As EnvDTE80.vsCMOverrideKind) As SyntaxNode
Dim member = TryCast(memberNode, StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
If TypeOf memberNode.Parent Is ModuleBlockSyntax OrElse
TypeOf memberNode.Parent Is InterfaceBlockSyntax OrElse
TypeOf memberNode.Parent Is PropertyBlockSyntax OrElse
TypeOf memberNode.Parent Is PropertyStatementSyntax Then
Throw Exceptions.ThrowENotImpl()
End If
If Not IsValidOverrideKind(kind) Then
Throw Exceptions.ThrowEInvalidArg()
End If
Dim flags = member.GetModifierFlags()
flags = flags And Not (ModifierFlags.NotOverridable Or ModifierFlags.Shadows Or ModifierFlags.Overrides Or ModifierFlags.MustOverride Or ModifierFlags.Overridable)
Select Case kind
Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed
flags = flags Or ModifierFlags.NotOverridable
Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew
flags = flags Or ModifierFlags.Shadows
Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride
flags = flags Or ModifierFlags.Overrides
Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract
flags = flags Or ModifierFlags.MustOverride
Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual
flags = flags Or ModifierFlags.Overridable
Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed
flags = flags Or ModifierFlags.NotOverridable Or ModifierFlags.Overrides
Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew
flags = flags Or ModifierFlags.Overridable Or ModifierFlags.Shadows
End Select
Dim resultMember = member.UpdateModifiers(flags)
If (flags And ModifierFlags.MustOverride) <> 0 Then
If TypeOf resultMember Is MethodBlockBaseSyntax Then
resultMember = DirectCast(resultMember, MethodBlockBaseSyntax).BlockStatement
ElseIf TypeOf resultMember Is PropertyBlockSyntax Then
resultMember = DirectCast(resultMember, PropertyBlockSyntax).PropertyStatement
End If
Else
If TypeOf resultMember Is MethodStatementSyntax Then
If resultMember.Kind = SyntaxKind.FunctionStatement Then
resultMember = SyntaxFactory.FunctionBlock(
subOrFunctionStatement:=DirectCast(resultMember, MethodStatementSyntax),
statements:=Nothing,
endSubOrFunctionStatement:=SyntaxFactory.EndFunctionStatement())
ElseIf resultMember.Kind = SyntaxKind.SubStatement Then
resultMember = SyntaxFactory.SubBlock(
subOrFunctionStatement:=DirectCast(resultMember, MethodStatementSyntax),
statements:=Nothing,
endSubOrFunctionStatement:=SyntaxFactory.EndSubStatement())
End If
ElseIf TypeOf resultMember Is PropertyStatementSyntax Then
Dim propertyStatement = DirectCast(resultMember, PropertyStatementSyntax)
Dim parameterName = "value"
If propertyStatement.Identifier.GetTypeCharacter() <> TypeCharacter.None Then
parameterName &= propertyStatement.Identifier.GetTypeCharacter().GetTypeCharacterString()
End If
Dim returnType = propertyStatement.GetReturnType()
Dim asClauseText = If(returnType IsNot Nothing,
" As " & returnType.ToString(),
String.Empty)
resultMember = SyntaxFactory.PropertyBlock(
propertyStatement:=propertyStatement,
accessors:=SyntaxFactory.List(Of AccessorBlockSyntax)({
SyntaxFactory.GetAccessorBlock(
accessorStatement:=SyntaxFactory.GetAccessorStatement(),
statements:=Nothing,
endAccessorStatement:=SyntaxFactory.EndGetStatement()),
SyntaxFactory.SetAccessorBlock(
accessorStatement:=SyntaxFactory.SetAccessorStatement(
attributeLists:=Nothing,
modifiers:=Nothing,
parameterList:=SyntaxFactory.ParseParameterList("(" & parameterName & asClauseText & ")")),
statements:=Nothing,
endAccessorStatement:=SyntaxFactory.EndSetStatement())
}))
End If
End If
Return resultMember
End Function
Public Overrides Function GetIsAbstract(memberNode As SyntaxNode, symbol As ISymbol) As Boolean
Return symbol.IsAbstract
End Function
Public Overrides Function SetIsAbstract(memberNode As SyntaxNode, value As Boolean) As SyntaxNode
If TypeOf memberNode Is StructureBlockSyntax OrElse
TypeOf memberNode Is ModuleBlockSyntax Then
Throw Exceptions.ThrowENotImpl()
End If
Dim member = TryCast(memberNode, StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Dim flags = member.GetModifierFlags()
If value Then
If TypeOf memberNode Is TypeBlockSyntax Then
flags = flags Or ModifierFlags.MustInherit
Else
flags = flags Or ModifierFlags.MustOverride
End If
Else
If TypeOf memberNode Is TypeBlockSyntax Then
flags = flags And Not ModifierFlags.MustInherit
Else
flags = flags And Not ModifierFlags.MustOverride
End If
End If
Return member.UpdateModifiers(flags)
End Function
Public Overrides Function GetIsConstant(variableNode As SyntaxNode) As Boolean
If TypeOf variableNode Is EnumMemberDeclarationSyntax Then
Return True
End If
Dim member = TryCast(GetNodeWithModifiers(variableNode), StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Dim flags = member.GetModifierFlags()
' VB legacy code model returns True for both Const and ReadOnly fields
Return (flags And (ModifierFlags.Const Or ModifierFlags.ReadOnly)) <> 0
End Function
Public Overrides Function SetIsConstant(variableNode As SyntaxNode, value As Boolean) As SyntaxNode
Dim constKind = If(value, EnvDTE80.vsCMConstKind.vsCMConstKindConst, EnvDTE80.vsCMConstKind.vsCMConstKindNone)
Return SetConstKind(variableNode, constKind)
End Function
Public Overrides Function GetIsDefault(propertyNode As SyntaxNode) As Boolean
Debug.Assert(TypeOf propertyNode Is PropertyBlockSyntax OrElse
TypeOf propertyNode Is PropertyStatementSyntax)
If TypeOf propertyNode Is PropertyStatementSyntax Then
Return False
End If
Dim propertyBlock = TryCast(propertyNode, PropertyBlockSyntax)
If propertyBlock Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Return propertyBlock.PropertyStatement.Modifiers.Any(SyntaxKind.DefaultKeyword)
End Function
Public Overrides Function SetIsDefault(propertyNode As SyntaxNode, value As Boolean) As SyntaxNode
Debug.Assert(TypeOf propertyNode Is PropertyBlockSyntax OrElse
TypeOf propertyNode Is PropertyStatementSyntax)
Dim member = DirectCast(propertyNode, StatementSyntax)
Dim flags = member.GetModifierFlags()
flags = flags And Not ModifierFlags.Default
If value Then
flags = flags Or ModifierFlags.Default
End If
Return member.UpdateModifiers(flags)
End Function
Public Overrides Function GetIsGeneric(node As SyntaxNode) As Boolean
Debug.Assert(TypeOf node Is StatementSyntax)
Return DirectCast(node, StatementSyntax).GetArity() > 0
End Function
Public Overrides Function GetIsPropertyStyleEvent(eventNode As SyntaxNode) As Boolean
Debug.Assert(TypeOf eventNode Is EventStatementSyntax OrElse
TypeOf eventNode Is EventBlockSyntax)
Return TypeOf eventNode Is EventBlockSyntax
End Function
Public Overrides Function GetIsShared(memberNode As SyntaxNode, symbol As ISymbol) As Boolean
Return _
(symbol.Kind = SymbolKind.NamedType AndAlso DirectCast(symbol, INamedTypeSymbol).TypeKind = TypeKind.Module) OrElse
symbol.IsStatic
End Function
Public Overrides Function SetIsShared(memberNode As SyntaxNode, value As Boolean) As SyntaxNode
If TypeOf memberNode Is TypeBlockSyntax Then
Throw Exceptions.ThrowENotImpl()
End If
Dim member = TryCast(memberNode, StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Dim parentType = TryCast(member.Parent, DeclarationStatementSyntax)
If parentType Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
If TypeOf parentType Is ModuleBlockSyntax OrElse
TypeOf parentType Is InterfaceBlockSyntax OrElse
TypeOf parentType Is EnumBlockSyntax Then
Throw Exceptions.ThrowENotImpl()
End If
Dim flags = member.GetModifierFlags() And Not ModifierFlags.Dim
If value Then
flags = flags Or ModifierFlags.Shared
Else
flags = flags And Not ModifierFlags.Shared
End If
If flags = 0 AndAlso member.IsKind(SyntaxKind.FieldDeclaration) Then
flags = flags Or ModifierFlags.Dim
End If
Return member.UpdateModifiers(flags)
End Function
Public Overrides Function GetReadWrite(memberNode As SyntaxNode) As EnvDTE80.vsCMPropertyKind
Debug.Assert(TypeOf memberNode Is PropertyBlockSyntax OrElse
TypeOf memberNode Is PropertyStatementSyntax)
Dim propertyStatement = TryCast(memberNode, PropertyStatementSyntax)
If propertyStatement Is Nothing Then
Dim propertyBlock = TryCast(memberNode, PropertyBlockSyntax)
If propertyBlock IsNot Nothing Then
propertyStatement = propertyBlock.PropertyStatement
End If
End If
If propertyStatement IsNot Nothing Then
If propertyStatement.Modifiers.Any(SyntaxKind.WriteOnlyKeyword) Then
Return EnvDTE80.vsCMPropertyKind.vsCMPropertyKindWriteOnly
ElseIf propertyStatement.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)
Return EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadOnly
Else
Return EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadWrite
End If
End If
Throw Exceptions.ThrowEUnexpected()
End Function
Private Function SetDelegateType(delegateStatement As DelegateStatementSyntax, typeSymbol As ITypeSymbol) As DelegateStatementSyntax
' Remove the leading and trailing trivia and save it for reattachment later.
Dim leadingTrivia = delegateStatement.GetLeadingTrivia()
Dim trailingTrivia = delegateStatement.GetTrailingTrivia()
delegateStatement = delegateStatement _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
If typeSymbol Is Nothing Then
' If no type is specified (e.g. CodeElement.Type = Nothing), we just convert to a Sub
' it it isn't one already.
If delegateStatement.IsKind(SyntaxKind.DelegateFunctionStatement) Then
delegateStatement = SyntaxFactory.DelegateSubStatement(
attributeLists:=delegateStatement.AttributeLists,
modifiers:=delegateStatement.Modifiers,
identifier:=delegateStatement.Identifier,
typeParameterList:=delegateStatement.TypeParameterList,
parameterList:=delegateStatement.ParameterList,
asClause:=Nothing)
End If
Else
Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
Dim newType = SyntaxFactory.ParseTypeName(typeName)
' If this is a Sub, convert to a Function
If delegateStatement.IsKind(SyntaxKind.DelegateSubStatement) Then
delegateStatement = SyntaxFactory.DelegateFunctionStatement(
attributeLists:=delegateStatement.AttributeLists,
modifiers:=delegateStatement.Modifiers,
identifier:=delegateStatement.Identifier,
typeParameterList:=delegateStatement.TypeParameterList,
parameterList:=delegateStatement.ParameterList,
asClause:=delegateStatement.AsClause)
End If
If delegateStatement.AsClause IsNot Nothing Then
Debug.Assert(TypeOf delegateStatement.AsClause Is SimpleAsClauseSyntax)
Dim oldType = DirectCast(delegateStatement.AsClause, SimpleAsClauseSyntax).Type
delegateStatement = delegateStatement.ReplaceNode(oldType, newType)
Else
delegateStatement = delegateStatement.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
End If
Return delegateStatement _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia)
End Function
Private Function SetEventType(eventStatement As EventStatementSyntax, typeSymbol As ITypeSymbol) As EventStatementSyntax
If typeSymbol Is Nothing Then
Throw Exceptions.ThrowEInvalidArg()
End If
' Remove the leading and trailing trivia and save it for reattachment later.
Dim leadingTrivia = eventStatement.GetLeadingTrivia()
Dim trailingTrivia = eventStatement.GetTrailingTrivia()
eventStatement = eventStatement _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
Dim newType = SyntaxFactory.ParseTypeName(typeName)
' If the event has a parameter list, we need to remove it.
If eventStatement.ParameterList IsNot Nothing Then
eventStatement = eventStatement.WithParameterList(Nothing)
End If
If eventStatement.AsClause IsNot Nothing Then
Debug.Assert(TypeOf eventStatement.AsClause Is SimpleAsClauseSyntax)
Dim oldType = DirectCast(eventStatement.AsClause, SimpleAsClauseSyntax).Type
eventStatement = eventStatement.ReplaceNode(oldType, newType)
Else
eventStatement = eventStatement.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
Return eventStatement _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia)
End Function
Private Function SetEventType(eventBlock As EventBlockSyntax, typeSymbol As ITypeSymbol) As EventBlockSyntax
If typeSymbol Is Nothing Then
Throw Exceptions.ThrowEInvalidArg()
End If
Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
Dim newType = SyntaxFactory.ParseTypeName(typeName)
' Update the event statement
Dim eventStatement = eventBlock.EventStatement
Dim leadingTrivia = eventStatement.GetLeadingTrivia()
Dim trailingTrivia = eventStatement.GetTrailingTrivia()
eventStatement = eventStatement _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
If eventStatement.AsClause IsNot Nothing Then
Debug.Assert(TypeOf eventStatement.AsClause Is SimpleAsClauseSyntax)
Dim oldType = DirectCast(eventStatement.AsClause, SimpleAsClauseSyntax).Type
eventStatement = eventStatement.ReplaceNode(oldType, newType)
Else
eventStatement = eventStatement.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
eventStatement = eventStatement _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia)
eventBlock = eventBlock.WithEventStatement(eventStatement)
For i = 0 To eventBlock.Accessors.Count - 1
Dim accessorBlock = eventBlock.Accessors(i)
Dim newAccessorBlock = accessorBlock
If accessorBlock.Kind = SyntaxKind.AddHandlerAccessorBlock OrElse
accessorBlock.Kind = SyntaxKind.RemoveHandlerAccessorBlock Then
' Update the first parameter of the AddHandler or RemoveHandler statements
Dim firstParameter = accessorBlock.BlockStatement.ParameterList.Parameters.FirstOrDefault()
If firstParameter IsNot Nothing Then
Dim newFirstParameter As ParameterSyntax
If firstParameter.AsClause IsNot Nothing Then
Debug.Assert(TypeOf firstParameter.AsClause Is SimpleAsClauseSyntax)
Dim oldType = DirectCast(firstParameter.AsClause, SimpleAsClauseSyntax).Type
newFirstParameter = firstParameter.ReplaceNode(oldType, newType)
Else
newFirstParameter = firstParameter.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
newFirstParameter = newFirstParameter _
.WithLeadingTrivia(firstParameter.GetLeadingTrivia()) _
.WithTrailingTrivia(firstParameter.GetTrailingTrivia())
newAccessorBlock = accessorBlock.ReplaceNode(firstParameter, newFirstParameter)
End If
ElseIf accessorBlock.Kind = SyntaxKind.RaiseEventAccessorBlock Then
' For RaiseEvent, we replace the whole signature with the delegate's invoke method
Dim namedTypeSymbol = TryCast(typeSymbol, INamedTypeSymbol)
If namedTypeSymbol IsNot Nothing Then
Dim invokeMethod = namedTypeSymbol.DelegateInvokeMethod
If invokeMethod IsNot Nothing Then
Dim parameterStrings = invokeMethod.Parameters.Select(Function(p) p.ToDisplayString(s_raiseEventSignatureFormat))
Dim parameterListString = "("c & String.Join(", ", parameterStrings) & ")"c
Dim newParameterList = SyntaxFactory.ParseParameterList(parameterListString)
newParameterList = newParameterList.WithTrailingTrivia(accessorBlock.BlockStatement.ParameterList.GetTrailingTrivia())
newAccessorBlock = accessorBlock.ReplaceNode(accessorBlock.BlockStatement.ParameterList, newParameterList)
End If
End If
End If
If accessorBlock IsNot newAccessorBlock Then
eventBlock = eventBlock.ReplaceNode(accessorBlock, newAccessorBlock)
End If
Next
Return eventBlock
End Function
Private Function SetMethodType(declareStatement As DeclareStatementSyntax, typeSymbol As ITypeSymbol) As DeclareStatementSyntax
' Remove the leading and trailing trivia and save it for reattachment later.
Dim leadingTrivia = declareStatement.GetLeadingTrivia()
Dim trailingTrivia = declareStatement.GetTrailingTrivia()
declareStatement = declareStatement _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
If typeSymbol Is Nothing Then
' If no type is specified (e.g. CodeElement.Type = Nothing), we just convert to a Sub
' it it isn't one already.
If declareStatement.IsKind(SyntaxKind.DeclareFunctionStatement) Then
declareStatement = SyntaxFactory.DeclareSubStatement(
attributeLists:=declareStatement.AttributeLists,
modifiers:=declareStatement.Modifiers,
declareKeyword:=declareStatement.DeclareKeyword,
charsetKeyword:=declareStatement.CharsetKeyword,
subOrFunctionKeyword:=SyntaxFactory.Token(SyntaxKind.SubKeyword),
identifier:=declareStatement.Identifier,
libKeyword:=declareStatement.LibKeyword,
libraryName:=declareStatement.LibraryName,
aliasKeyword:=declareStatement.AliasKeyword,
aliasName:=declareStatement.AliasName,
parameterList:=declareStatement.ParameterList,
asClause:=Nothing)
End If
Else
Dim newType = SyntaxFactory.ParseTypeName(typeSymbol.ToDisplayString(s_setTypeFormat))
declareStatement = SyntaxFactory.DeclareFunctionStatement(
attributeLists:=declareStatement.AttributeLists,
modifiers:=declareStatement.Modifiers,
declareKeyword:=declareStatement.DeclareKeyword,
charsetKeyword:=declareStatement.CharsetKeyword,
subOrFunctionKeyword:=SyntaxFactory.Token(SyntaxKind.FunctionKeyword),
identifier:=declareStatement.Identifier,
libKeyword:=declareStatement.LibKeyword,
libraryName:=declareStatement.LibraryName,
aliasKeyword:=declareStatement.AliasKeyword,
aliasName:=declareStatement.AliasName,
parameterList:=declareStatement.ParameterList,
asClause:=declareStatement.AsClause)
If declareStatement.AsClause IsNot Nothing Then
Debug.Assert(TypeOf declareStatement.AsClause Is SimpleAsClauseSyntax)
Dim oldType = DirectCast(declareStatement.AsClause, SimpleAsClauseSyntax).Type
declareStatement = declareStatement.ReplaceNode(oldType, newType)
Else
declareStatement = declareStatement.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
End If
Return declareStatement.WithLeadingTrivia(leadingTrivia).WithTrailingTrivia(trailingTrivia)
End Function
Private Function SetMethodType(methodStatement As MethodStatementSyntax, typeSymbol As ITypeSymbol) As MethodStatementSyntax
' Remove the leading and trailing trivia and save it for reattachment later.
Dim leadingTrivia = methodStatement.GetLeadingTrivia()
Dim trailingTrivia = methodStatement.GetTrailingTrivia()
methodStatement = methodStatement _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
If typeSymbol Is Nothing Then
' If no type is specified (e.g. CodeElement.Type = Nothing), we just convert to a Sub
' it it isn't one already.
If methodStatement.IsKind(SyntaxKind.FunctionStatement) Then
methodStatement = SyntaxFactory.SubStatement(
attributeLists:=methodStatement.AttributeLists,
modifiers:=methodStatement.Modifiers,
identifier:=methodStatement.Identifier,
typeParameterList:=methodStatement.TypeParameterList,
parameterList:=methodStatement.ParameterList,
asClause:=Nothing,
handlesClause:=methodStatement.HandlesClause,
implementsClause:=methodStatement.ImplementsClause)
End If
Else
Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
Dim newType = SyntaxFactory.ParseTypeName(typeName)
' If this is a Sub, convert to a Function
If methodStatement.IsKind(SyntaxKind.SubStatement) Then
methodStatement = SyntaxFactory.FunctionStatement(
attributeLists:=methodStatement.AttributeLists,
modifiers:=methodStatement.Modifiers,
identifier:=methodStatement.Identifier,
typeParameterList:=methodStatement.TypeParameterList,
parameterList:=methodStatement.ParameterList,
asClause:=methodStatement.AsClause,
handlesClause:=methodStatement.HandlesClause,
implementsClause:=methodStatement.ImplementsClause)
End If
If methodStatement.AsClause IsNot Nothing Then
Debug.Assert(TypeOf methodStatement.AsClause Is SimpleAsClauseSyntax)
Dim oldType = DirectCast(methodStatement.AsClause, SimpleAsClauseSyntax).Type
methodStatement = methodStatement.ReplaceNode(oldType, newType)
Else
methodStatement = methodStatement.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
End If
Return methodStatement _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia)
End Function
Private Function SetMethodType(methodBlock As MethodBlockSyntax, typeSymbol As ITypeSymbol) As MethodBlockSyntax
' Remove the leading and trailing trivia and save it for reattachment later.
Dim leadingTrivia = methodBlock.GetLeadingTrivia()
Dim trailingTrivia = methodBlock.GetTrailingTrivia()
methodBlock = methodBlock _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
Dim methodStatement = SetMethodType(DirectCast(methodBlock.BlockStatement, MethodStatementSyntax), typeSymbol)
Dim endMethodStatement = methodBlock.EndBlockStatement
If endMethodStatement IsNot Nothing AndAlso Not endMethodStatement.IsMissing Then
' Note that we don't have to remove/replace the trailing trivia for the end block statement
' because we're already doing that for the whole block.
If endMethodStatement.IsKind(SyntaxKind.EndSubStatement) AndAlso typeSymbol IsNot Nothing Then
endMethodStatement = SyntaxFactory.EndFunctionStatement()
ElseIf endMethodStatement.IsKind(SyntaxKind.EndFunctionStatement) AndAlso typeSymbol Is Nothing Then
endMethodStatement = SyntaxFactory.EndSubStatement()
End If
End If
methodBlock = methodBlock.Update(If(methodStatement.Kind = SyntaxKind.SubStatement, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock),
methodStatement, methodBlock.Statements, endMethodStatement)
Return methodBlock _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia)
End Function
Private Function SetParameterType(parameter As ParameterSyntax, typeSymbol As ITypeSymbol) As ParameterSyntax
If typeSymbol Is Nothing Then
Return parameter
End If
' Remove the leading and trailing trivia and save it for reattachment later.\
Dim leadingTrivia = parameter.GetLeadingTrivia()
Dim trailingTrivia = parameter.GetTrailingTrivia()
parameter = parameter _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
Dim newType = SyntaxFactory.ParseTypeName(typeName)
If parameter.AsClause IsNot Nothing Then
Debug.Assert(TypeOf parameter.AsClause Is SimpleAsClauseSyntax)
Dim oldType = DirectCast(parameter.AsClause, SimpleAsClauseSyntax).Type
parameter = parameter.ReplaceNode(oldType, newType)
Else
parameter = parameter.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
Return parameter _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia)
End Function
Private Function SetPropertyType(propertyStatement As PropertyStatementSyntax, typeSymbol As ITypeSymbol) As PropertyStatementSyntax
If typeSymbol Is Nothing Then
Throw Exceptions.ThrowEInvalidArg()
End If
' Remove the leading and trailing trivia and save it for reattachment later.\
Dim leadingTrivia = propertyStatement.GetLeadingTrivia()
Dim trailingTrivia = propertyStatement.GetTrailingTrivia()
propertyStatement = propertyStatement _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
Dim newType = SyntaxFactory.ParseTypeName(typeName)
If propertyStatement.AsClause IsNot Nothing Then
Dim oldType = propertyStatement.AsClause.Type()
If oldType IsNot Nothing Then
propertyStatement = propertyStatement.ReplaceNode(oldType, newType)
End If
Else
propertyStatement = propertyStatement.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
Return propertyStatement _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia)
End Function
Private Function SetPropertyType(propertyBlock As PropertyBlockSyntax, typeSymbol As ITypeSymbol) As PropertyBlockSyntax
If typeSymbol Is Nothing Then
Throw Exceptions.ThrowEInvalidArg()
End If
' Remove the leading and trailing trivia and save it for reattachment later.\
Dim leadingTrivia = propertyBlock.GetLeadingTrivia()
Dim trailingTrivia = propertyBlock.GetTrailingTrivia()
propertyBlock = propertyBlock _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
Dim propertyStatement = SetPropertyType(propertyBlock.PropertyStatement, typeSymbol)
propertyBlock = propertyBlock.WithPropertyStatement(propertyStatement)
Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
Dim newType = SyntaxFactory.ParseTypeName(typeName)
For i = 0 To propertyBlock.Accessors.Count - 1
Dim accessorBlock = propertyBlock.Accessors(i)
Dim newAccessorBlock = accessorBlock
If accessorBlock.Kind = SyntaxKind.SetAccessorBlock Then
' Update the first parameter of the SetAccessor statement
Dim firstParameter = accessorBlock.BlockStatement.ParameterList.Parameters.FirstOrDefault()
If firstParameter IsNot Nothing Then
Dim newFirstParameter As ParameterSyntax
If firstParameter.AsClause IsNot Nothing Then
Debug.Assert(TypeOf firstParameter.AsClause Is SimpleAsClauseSyntax)
Dim oldType = DirectCast(firstParameter.AsClause, SimpleAsClauseSyntax).Type
newFirstParameter = firstParameter.ReplaceNode(oldType, newType)
Else
newFirstParameter = firstParameter.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
newFirstParameter = newFirstParameter _
.WithLeadingTrivia(firstParameter.GetLeadingTrivia()) _
.WithTrailingTrivia(firstParameter.GetTrailingTrivia())
newAccessorBlock = accessorBlock.ReplaceNode(firstParameter, newFirstParameter)
End If
End If
If accessorBlock IsNot newAccessorBlock Then
propertyBlock = propertyBlock.ReplaceNode(accessorBlock, newAccessorBlock)
End If
Next
Return propertyBlock _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia)
End Function
Private Function SetVariableType(variableDeclarator As VariableDeclaratorSyntax, typeSymbol As ITypeSymbol) As VariableDeclaratorSyntax
If typeSymbol Is Nothing Then
Throw Exceptions.ThrowEInvalidArg()
End If
' Remove the leading and trailing trivia and save it for reattachment later.\
Dim leadingTrivia = variableDeclarator.GetLeadingTrivia()
Dim trailingTrivia = variableDeclarator.GetTrailingTrivia()
variableDeclarator = variableDeclarator _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
Dim newType = SyntaxFactory.ParseTypeName(typeName)
If variableDeclarator.AsClause IsNot Nothing Then
Dim oldType = variableDeclarator.AsClause.Type()
If oldType IsNot Nothing Then
variableDeclarator = variableDeclarator.ReplaceNode(oldType, newType)
End If
Else
variableDeclarator = variableDeclarator.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
Return variableDeclarator _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia)
End Function
Public Overrides Function SetType(node As SyntaxNode, typeSymbol As ITypeSymbol) As SyntaxNode
Debug.Assert(TypeOf node Is DelegateStatementSyntax OrElse
TypeOf node Is EventStatementSyntax OrElse
TypeOf node Is EventBlockSyntax OrElse
TypeOf node Is DeclareStatementSyntax OrElse
TypeOf node Is MethodStatementSyntax OrElse
TypeOf node Is MethodBlockBaseSyntax OrElse
TypeOf node Is ParameterSyntax OrElse
TypeOf node Is PropertyStatementSyntax OrElse
TypeOf node Is PropertyBlockSyntax OrElse
TypeOf node Is VariableDeclaratorSyntax)
If TypeOf node Is DelegateStatementSyntax Then
Return SetDelegateType(DirectCast(node, DelegateStatementSyntax), typeSymbol)
End If
If TypeOf node Is EventStatementSyntax Then
Return SetEventType(DirectCast(node, EventStatementSyntax), typeSymbol)
End If
If TypeOf node Is EventBlockSyntax Then
Return SetEventType(DirectCast(node, EventBlockSyntax), typeSymbol)
End If
If TypeOf node Is DeclareStatementSyntax Then
Return SetMethodType(DirectCast(node, DeclareStatementSyntax), typeSymbol)
End If
If TypeOf node Is MethodStatementSyntax Then
Return SetMethodType(DirectCast(node, MethodStatementSyntax), typeSymbol)
End If
If TypeOf node Is MethodBlockSyntax Then
Return SetMethodType(DirectCast(node, MethodBlockSyntax), typeSymbol)
End If
If TypeOf node Is ConstructorBlockSyntax Then
Return node
End If
If TypeOf node Is OperatorBlockSyntax Then
Return node
End If
If TypeOf node Is ParameterSyntax Then
Return SetParameterType(DirectCast(node, ParameterSyntax), typeSymbol)
End If
If TypeOf node Is PropertyStatementSyntax Then
Return SetPropertyType(DirectCast(node, PropertyStatementSyntax), typeSymbol)
End If
If TypeOf node Is PropertyBlockSyntax Then
Return SetPropertyType(DirectCast(node, PropertyBlockSyntax), typeSymbol)
End If
If TypeOf node Is VariableDeclaratorSyntax Then
Return SetVariableType(DirectCast(node, VariableDeclaratorSyntax), typeSymbol)
End If
Throw New NotImplementedException()
End Function
Public Overrides Function GetFullyQualifiedName(name As String, position As Integer, semanticModel As SemanticModel) As String
Dim typeName = SyntaxFactory.ParseTypeName(name)
If TypeOf typeName Is PredefinedTypeSyntax Then
Dim predefinedType As PredefinedType
If SyntaxFactsService.TryGetPredefinedType(DirectCast(typeName, PredefinedTypeSyntax).Keyword, predefinedType) Then
Dim specialType = predefinedType.ToSpecialType()
Return semanticModel.Compilation.GetSpecialType(specialType).GetEscapedFullName()
End If
Else
Dim symbols = semanticModel.LookupNamespacesAndTypes(position, name:=name)
If symbols.Length > 0 Then
Return symbols(0).GetEscapedFullName()
End If
End If
Return name
End Function
Public Overrides Function GetInitExpression(node As SyntaxNode) As String
Dim initializer As ExpressionSyntax = Nothing
Select Case node.Kind
Case SyntaxKind.Parameter
Dim parameter = DirectCast(node, ParameterSyntax)
If parameter.Default IsNot Nothing Then
initializer = parameter.Default.Value
End If
Case SyntaxKind.ModifiedIdentifier
Dim modifiedIdentifier = DirectCast(node, ModifiedIdentifierSyntax)
Dim variableDeclarator = DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax)
initializer = variableDeclarator.GetInitializer()
Case SyntaxKind.EnumMemberDeclaration
Dim enumMemberDeclaration = DirectCast(node, EnumMemberDeclarationSyntax)
If enumMemberDeclaration.Initializer IsNot Nothing Then
initializer = enumMemberDeclaration.Initializer.Value
End If
End Select
Return If(initializer IsNot Nothing,
initializer.ToString(),
Nothing)
End Function
Public Overrides Function AddInitExpression(node As SyntaxNode, value As String) As SyntaxNode
Select Case node.Kind
Case SyntaxKind.Parameter
Dim parameter = DirectCast(node, ParameterSyntax)
Dim parameterKind = GetParameterKind(parameter)
If Not (parameterKind And EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional) <> 0 Then
Throw Exceptions.ThrowEInvalidArg
End If
If String.IsNullOrWhiteSpace(value) Then
' Remove the Optional modifier
parameterKind = parameterKind And Not EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional
parameter = DirectCast(SetParameterKind(parameter, parameterKind), ParameterSyntax)
If parameter.Default IsNot Nothing Then
parameter = parameter.RemoveNode(parameter.Default, SyntaxRemoveOptions.KeepNoTrivia)
End If
Return parameter
End If
Dim expression = SyntaxFactory.ParseExpression(value)
Dim equalsValueClause = If(parameter.Default IsNot Nothing AndAlso Not parameter.Default.IsMissing,
parameter.Default.WithValue(expression),
SyntaxFactory.EqualsValue(expression))
Return parameter.WithDefault(equalsValueClause)
Case SyntaxKind.VariableDeclarator
Dim variableDeclarator = DirectCast(node, VariableDeclaratorSyntax)
If String.IsNullOrWhiteSpace(value) Then
If variableDeclarator.Initializer IsNot Nothing Then
variableDeclarator = variableDeclarator.RemoveNode(variableDeclarator.Initializer, SyntaxRemoveOptions.KeepExteriorTrivia)
End If
Return variableDeclarator
End If
Dim trailingTrivia = variableDeclarator.GetTrailingTrivia()
variableDeclarator = variableDeclarator.WithTrailingTrivia(SyntaxTriviaList.Empty)
Dim expression = SyntaxFactory.ParseExpression(value)
Dim equalsValueClause = If(variableDeclarator.Initializer IsNot Nothing AndAlso Not variableDeclarator.Initializer.IsMissing,
variableDeclarator.Initializer.WithValue(expression),
SyntaxFactory.EqualsValue(expression)).WithTrailingTrivia(trailingTrivia)
Return variableDeclarator.WithInitializer(equalsValueClause)
Case SyntaxKind.EnumMemberDeclaration
Dim enumMemberDeclaration = DirectCast(node, EnumMemberDeclarationSyntax)
If String.IsNullOrWhiteSpace(value) Then
If enumMemberDeclaration.Initializer IsNot Nothing Then
enumMemberDeclaration = enumMemberDeclaration.RemoveNode(enumMemberDeclaration.Initializer, SyntaxRemoveOptions.KeepExteriorTrivia)
End If
Return enumMemberDeclaration
End If
Dim trailingTrivia = enumMemberDeclaration.GetTrailingTrivia()
enumMemberDeclaration = enumMemberDeclaration.WithTrailingTrivia(SyntaxTriviaList.Empty)
Dim expression = SyntaxFactory.ParseExpression(value)
Dim equalsValueClause = If(enumMemberDeclaration.Initializer IsNot Nothing AndAlso Not enumMemberDeclaration.Initializer.IsMissing,
enumMemberDeclaration.Initializer.WithValue(expression),
SyntaxFactory.EqualsValue(expression)).WithTrailingTrivia(trailingTrivia)
Return enumMemberDeclaration.WithInitializer(equalsValueClause)
Case Else
Throw Exceptions.ThrowEFail()
End Select
End Function
Public Overrides Function GetDestination(containerNode As SyntaxNode) As CodeGenerationDestination
Return VisualBasicCodeGenerationHelpers.GetDestination(containerNode)
End Function
Protected Overrides Function GetDefaultAccessibility(targetSymbolKind As SymbolKind, destination As CodeGenerationDestination) As Accessibility
If destination = CodeGenerationDestination.StructType Then
Return Accessibility.Public
End If
Select Case targetSymbolKind
Case SymbolKind.Field
Return Accessibility.Private
Case SymbolKind.Method,
SymbolKind.Property,
SymbolKind.Event,
SymbolKind.NamedType
Return Accessibility.Public
Case Else
Debug.Fail("Invalid symbol kind: " & targetSymbolKind)
Throw Exceptions.ThrowEFail()
End Select
End Function
Public Overrides Function GetTypeSymbolFromFullName(fullName As String, compilation As Compilation) As ITypeSymbol
Dim typeSymbol As ITypeSymbol = compilation.GetTypeByMetadataName(fullName)
If typeSymbol Is Nothing Then
Dim parsedTypeName = SyntaxFactory.ParseTypeName(fullName)
' If we couldn't get the name, we just grab the first tree in the compilation to
' speculatively bind at position zero. However, if there *aren't* any trees, we fork the
' compilation with an empty tree for the purposes of speculative binding.
'
' I'm a bad person.
Dim tree = compilation.SyntaxTrees.FirstOrDefault()
If tree Is Nothing Then
tree = SyntaxFactory.ParseSyntaxTree("")
compilation = compilation.AddSyntaxTrees(tree)
End If
Dim semanticModel = compilation.GetSemanticModel(tree)
typeSymbol = semanticModel.GetSpeculativeTypeInfo(0, parsedTypeName, SpeculativeBindingOption.BindAsTypeOrNamespace).Type
End If
If typeSymbol Is Nothing Then
Debug.Fail("Could not find type: " & fullName)
Throw New ArgumentException()
End If
Return typeSymbol
End Function
Protected Overrides Function GetTypeSymbolFromPartialName(partialName As String, semanticModel As SemanticModel, position As Integer) As ITypeSymbol
Dim parsedTypeName = SyntaxFactory.ParseTypeName(partialName)
Dim visualBasicSemanticModel = DirectCast(semanticModel, SemanticModel)
Return visualBasicSemanticModel.GetSpeculativeTypeInfo(position, parsedTypeName, SpeculativeBindingOption.BindAsTypeOrNamespace).Type
End Function
Public Overrides Function CreateReturnDefaultValueStatement(type As ITypeSymbol) As SyntaxNode
Return SyntaxFactory.ReturnStatement(
SyntaxFactory.NothingLiteralExpression(
SyntaxFactory.Token(SyntaxKind.NothingKeyword)))
End Function
Protected Overrides Function IsCodeModelNode(node As SyntaxNode) As Boolean
Select Case CType(node.Kind, SyntaxKind)
Case SyntaxKind.ClassBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.EnumBlock,
SyntaxKind.EnumMemberDeclaration,
SyntaxKind.EventBlock,
SyntaxKind.EventStatement,
SyntaxKind.FieldDeclaration,
SyntaxKind.FunctionBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.NamespaceBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.PropertyBlock,
SyntaxKind.StructureBlock,
SyntaxKind.SubBlock,
SyntaxKind.SimpleImportsClause
Return True
Case Else
Return False
End Select
End Function
Protected Overrides Function GetFieldFromVariableNode(variableNode As SyntaxNode) As SyntaxNode
Return If(variableNode.Kind = SyntaxKind.ModifiedIdentifier,
variableNode.FirstAncestorOrSelf(Of FieldDeclarationSyntax)(),
variableNode)
End Function
Protected Overrides Function GetVariableFromFieldNode(fieldNode As SyntaxNode) As SyntaxNode
' Work around that the fact that VB code model really deals with fields as modified identifiers
Return If(TypeOf fieldNode Is FieldDeclarationSyntax,
DirectCast(fieldNode, FieldDeclarationSyntax).Declarators.Single().Names.Single(),
fieldNode)
End Function
Protected Overrides Function GetAttributeFromAttributeDeclarationNode(node As SyntaxNode) As SyntaxNode
Return If(TypeOf node Is AttributeListSyntax,
DirectCast(node, AttributeListSyntax).Attributes.First,
node)
End Function
Protected Overrides Function GetSpanToFormat(root As SyntaxNode, span As TextSpan) As TextSpan
Dim startToken = GetTokenWithoutAnnotation(root.FindToken(span.Start).GetPreviousToken(), Function(t) t.GetPreviousToken())
Dim endToken = GetTokenWithoutAnnotation(root.FindToken(span.End), Function(t) t.GetNextToken())
Return GetEncompassingSpan(root, startToken, endToken)
End Function
Protected Overrides Function InsertMemberNodeIntoContainer(index As Integer, member As SyntaxNode, container As SyntaxNode) As SyntaxNode
Dim declarationStatement = DirectCast(member, DeclarationStatementSyntax)
If TypeOf container Is CompilationUnitSyntax Then
Dim compilationUnit = DirectCast(container, CompilationUnitSyntax)
Return compilationUnit.WithMembers(compilationUnit.Members.Insert(index, declarationStatement))
ElseIf TypeOf container Is NamespaceBlockSyntax Then
Dim namespaceBlock = DirectCast(container, NamespaceBlockSyntax)
Return namespaceBlock.WithMembers(namespaceBlock.Members.Insert(index, declarationStatement))
ElseIf TypeOf container Is ClassBlockSyntax Then
Dim classBlock = DirectCast(container, ClassBlockSyntax)
Return classBlock.WithMembers(classBlock.Members.Insert(index, declarationStatement))
ElseIf TypeOf container Is InterfaceBlockSyntax Then
Dim interfaceBlock = DirectCast(container, InterfaceBlockSyntax)
Return interfaceBlock.WithMembers(interfaceBlock.Members.Insert(index, declarationStatement))
ElseIf TypeOf container Is StructureBlockSyntax Then
Dim structureBlock = DirectCast(container, StructureBlockSyntax)
Return structureBlock.WithMembers(structureBlock.Members.Insert(index, declarationStatement))
ElseIf TypeOf container Is ModuleBlockSyntax Then
Dim moduleBlock = DirectCast(container, ModuleBlockSyntax)
Return moduleBlock.WithMembers(moduleBlock.Members.Insert(index, declarationStatement))
ElseIf TypeOf container Is EnumBlockSyntax Then
Dim enumBlock = DirectCast(container, EnumBlockSyntax)
Return enumBlock.WithMembers(enumBlock.Members.Insert(index, declarationStatement))
End If
Throw Exceptions.ThrowEFail()
End Function
Private Shared Function GetMember(container As SyntaxNode, index As Integer) As StatementSyntax
If TypeOf container Is CompilationUnitSyntax Then
Return DirectCast(container, CompilationUnitSyntax).Members(index)
ElseIf TypeOf container Is NamespaceBlockSyntax Then
Return DirectCast(container, NamespaceBlockSyntax).Members(index)
ElseIf TypeOf container Is ClassBlockSyntax Then
Return DirectCast(container, ClassBlockSyntax).Members(index)
ElseIf TypeOf container Is InterfaceBlockSyntax Then
Return DirectCast(container, InterfaceBlockSyntax).Members(index)
ElseIf TypeOf container Is StructureBlockSyntax Then
Return DirectCast(container, StructureBlockSyntax).Members(index)
ElseIf TypeOf container Is ModuleBlockSyntax Then
Return DirectCast(container, ModuleBlockSyntax).Members(index)
ElseIf TypeOf container Is EnumBlockSyntax Then
Return DirectCast(container, EnumBlockSyntax).Members(index)
End If
Throw Exceptions.ThrowEFail()
End Function
Private Shared Function GetAttribute(container As SyntaxNode, index As Integer) As AttributeListSyntax
If TypeOf container Is CompilationUnitSyntax Then
Dim compilationUnit = DirectCast(container, CompilationUnitSyntax).Attributes(index).AttributeLists(0)
ElseIf TypeOf container Is TypeBlockSyntax Then
Return DirectCast(container, TypeBlockSyntax).BlockStatement.AttributeLists(index)
ElseIf TypeOf container Is EnumMemberDeclarationSyntax Then
Return DirectCast(container, EnumMemberDeclarationSyntax).AttributeLists(index)
ElseIf TypeOf container Is MethodBlockBaseSyntax Then
Return DirectCast(container, MethodBlockBaseSyntax).BlockStatement.AttributeLists(index)
ElseIf TypeOf container Is PropertyBlockSyntax Then
Return DirectCast(container, PropertyBlockSyntax).PropertyStatement.AttributeLists(index)
ElseIf TypeOf container Is FieldDeclarationSyntax Then
Return DirectCast(container, FieldDeclarationSyntax).AttributeLists(index)
ElseIf TypeOf container Is ParameterSyntax Then
Return DirectCast(container, ParameterSyntax).AttributeLists(index)
End If
Throw Exceptions.ThrowEFail()
End Function
Protected Overrides Function InsertAttributeArgumentIntoContainer(index As Integer, attributeArgument As SyntaxNode, container As SyntaxNode) As SyntaxNode
If TypeOf container Is AttributeSyntax Then
Dim attribute = DirectCast(container, AttributeSyntax)
Dim argumentList = attribute.ArgumentList
Dim newArgumentList As ArgumentListSyntax
If argumentList Is Nothing Then
newArgumentList = SyntaxFactory.ArgumentList(
SyntaxFactory.SingletonSeparatedList(
DirectCast(attributeArgument, ArgumentSyntax)))
Else
Dim newArguments = argumentList.Arguments.Insert(index, DirectCast(attributeArgument, ArgumentSyntax))
newArgumentList = argumentList.WithArguments(newArguments)
End If
Return attribute.WithArgumentList(newArgumentList)
End If
Throw Exceptions.ThrowEFail()
End Function
Private Function InsertAttributeListInto(attributes As SyntaxList(Of AttributesStatementSyntax), index As Integer, attribute As AttributesStatementSyntax) As SyntaxList(Of AttributesStatementSyntax)
' we need to explicitly add end of line trivia here since both of them (with or without) are valid but parsed differently
If index = 0 Then
Return attributes.Insert(index, attribute)
End If
Dim previousAttribute = attributes(index - 1)
If previousAttribute.GetTrailingTrivia().Any(Function(t) t.Kind = SyntaxKind.EndOfLineTrivia) Then
Return attributes.Insert(index, attribute)
End If
attributes = attributes.Replace(previousAttribute, previousAttribute.WithAppendedTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed))
Return attributes.Insert(index, attribute)
End Function
Protected Overrides Function InsertAttributeListIntoContainer(index As Integer, list As SyntaxNode, container As SyntaxNode) As SyntaxNode
' If the attribute is being inserted at the first index and the container is not the compilation unit, copy leading trivia
' to the attribute that is being inserted.
If index = 0 AndAlso TypeOf container IsNot CompilationUnitSyntax Then
Dim firstToken = container.GetFirstToken()
If firstToken.HasLeadingTrivia Then
Dim trivia = firstToken.LeadingTrivia
container = container.ReplaceToken(firstToken, firstToken.WithLeadingTrivia(SyntaxTriviaList.Empty))
list = list.WithLeadingTrivia(trivia)
End If
End If
' If the attribute to be inserted does not have a trailing line break, add one (unless this is a parameter).
If TypeOf container IsNot ParameterSyntax AndAlso
(Not list.HasTrailingTrivia OrElse Not list.GetTrailingTrivia().Any(SyntaxKind.EndOfLineTrivia)) Then
list = list.WithAppendedTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed)
End If
Dim attributeList = DirectCast(list, AttributeListSyntax)
If TypeOf container Is CompilationUnitSyntax Then
Dim compilationUnit = DirectCast(container, CompilationUnitSyntax)
Dim attributesStatement = SyntaxFactory.AttributesStatement(SyntaxFactory.SingletonList(attributeList))
Dim attributeStatements = InsertAttributeListInto(compilationUnit.Attributes, index, attributesStatement)
Return compilationUnit.WithAttributes(attributeStatements)
ElseIf TypeOf container Is ModuleBlockSyntax Then
Dim moduleBlock = DirectCast(container, ModuleBlockSyntax)
Dim attributeLists = moduleBlock.ModuleStatement.AttributeLists.Insert(index, attributeList)
Return moduleBlock.WithBlockStatement(moduleBlock.ModuleStatement.WithAttributeLists(attributeLists))
ElseIf TypeOf container Is StructureBlockSyntax Then
Dim structureBlock = DirectCast(container, StructureBlockSyntax)
Dim attributeLists = structureBlock.StructureStatement.AttributeLists.Insert(index, attributeList)
Return structureBlock.WithStructureStatement(structureBlock.StructureStatement.WithAttributeLists(attributeLists))
ElseIf TypeOf container Is InterfaceBlockSyntax Then
Dim interfaceBlock = DirectCast(container, InterfaceBlockSyntax)
Dim attributeLists = interfaceBlock.InterfaceStatement.AttributeLists.Insert(index, attributeList)
Return interfaceBlock.WithInterfaceStatement(interfaceBlock.InterfaceStatement.WithAttributeLists(attributeLists))
ElseIf TypeOf container Is ClassBlockSyntax Then
Dim classBlock = DirectCast(container, ClassBlockSyntax)
Dim attributeLists = classBlock.ClassStatement.AttributeLists.Insert(index, attributeList)
Dim begin = classBlock.ClassStatement.WithAttributeLists(attributeLists)
Return classBlock.WithClassStatement(begin)
ElseIf TypeOf container Is EnumBlockSyntax Then
Dim enumBlock = DirectCast(container, EnumBlockSyntax)
Dim attributeLists = enumBlock.EnumStatement.AttributeLists.Insert(index, attributeList)
Return enumBlock.WithEnumStatement(enumBlock.EnumStatement.WithAttributeLists(attributeLists))
ElseIf TypeOf container Is EnumMemberDeclarationSyntax Then
Dim enumMember = DirectCast(container, EnumMemberDeclarationSyntax)
Dim attributeLists = enumMember.AttributeLists.Insert(index, attributeList)
Return enumMember.WithAttributeLists(attributeLists)
ElseIf TypeOf container Is DelegateStatementSyntax
Dim delegateStatement = DirectCast(container, DelegateStatementSyntax)
Dim attributeLists = delegateStatement.AttributeLists.Insert(index, attributeList)
Return delegateStatement.WithAttributeLists(attributeLists)
ElseIf TypeOf container Is DeclareStatementSyntax Then
Dim declareStatement = DirectCast(container, DeclareStatementSyntax)
Dim attributeLists = declareStatement.AttributeLists.Insert(index, attributeList)
Return declareStatement.WithAttributeLists(attributeLists)
ElseIf TypeOf container Is MethodStatementSyntax Then
Dim methodStatement = DirectCast(container, MethodStatementSyntax)
Dim attributeLists = methodStatement.AttributeLists.Insert(index, attributeList)
Return methodStatement.WithAttributeLists(attributeLists)
ElseIf TypeOf container Is MethodBlockBaseSyntax Then
Dim method = DirectCast(container, MethodBlockBaseSyntax)
If TypeOf method.BlockStatement Is SubNewStatementSyntax Then
Dim constructor = DirectCast(method.BlockStatement, SubNewStatementSyntax)
Dim attributeLists = constructor.AttributeLists.Insert(index, attributeList)
Return DirectCast(method, ConstructorBlockSyntax).WithBlockStatement(constructor.WithAttributeLists(attributeLists))
ElseIf TypeOf method.BlockStatement Is OperatorStatementSyntax Then
Dim operatorStatement = DirectCast(method.BlockStatement, OperatorStatementSyntax)
Dim attributeLists = operatorStatement.AttributeLists.Insert(index, attributeList)
Return DirectCast(method, OperatorBlockSyntax).WithBlockStatement(operatorStatement.WithAttributeLists(attributeLists))
ElseIf TypeOf method.BlockStatement Is MethodStatementSyntax Then
Dim methodStatement = DirectCast(method.BlockStatement, MethodStatementSyntax)
Dim attributeLists = methodStatement.AttributeLists.Insert(index, attributeList)
Return DirectCast(method, MethodBlockSyntax).WithBlockStatement(methodStatement.WithAttributeLists(attributeLists))
End If
ElseIf TypeOf container Is PropertyStatementSyntax Then
Dim propertyStatement = DirectCast(container, PropertyStatementSyntax)
Dim attributeLists = propertyStatement.AttributeLists.Insert(index, attributeList)
Return propertyStatement.WithAttributeLists(attributeLists)
ElseIf TypeOf container Is PropertyBlockSyntax Then
Dim propertyBlock = DirectCast(container, PropertyBlockSyntax)
Dim attributeLists = propertyBlock.PropertyStatement.AttributeLists.Insert(index, attributeList)
Return propertyBlock.WithPropertyStatement(propertyBlock.PropertyStatement.WithAttributeLists(attributeLists))
ElseIf TypeOf container Is EventStatementSyntax Then
Dim eventStatement = DirectCast(container, EventStatementSyntax)
Dim attributeLists = eventStatement.AttributeLists.Insert(index, attributeList)
Return eventStatement.WithAttributeLists(attributeLists)
ElseIf TypeOf container Is EventBlockSyntax
Dim eventBlock = DirectCast(container, EventBlockSyntax)
Dim attributeLists = eventBlock.EventStatement.AttributeLists.Insert(index, attributeList)
Return eventBlock.WithEventStatement(eventBlock.EventStatement.WithAttributeLists(attributeLists))
ElseIf TypeOf container Is FieldDeclarationSyntax Then
Dim field = DirectCast(container, FieldDeclarationSyntax)
Dim attributeLists = field.AttributeLists.Insert(index, attributeList)
Return field.WithAttributeLists(attributeLists)
ElseIf TypeOf container Is ParameterSyntax Then
Dim parameter = DirectCast(container, ParameterSyntax)
Dim attributeLists = parameter.AttributeLists.Insert(index, attributeList)
Return parameter.WithAttributeLists(attributeLists)
End If
Throw Exceptions.ThrowEUnexpected()
End Function
Protected Overrides Function InsertImportIntoContainer(index As Integer, importNode As SyntaxNode, container As SyntaxNode) As SyntaxNode
If TypeOf container IsNot CompilationUnitSyntax Then
Throw Exceptions.ThrowEUnexpected()
End If
Dim compilationUnit = DirectCast(container, CompilationUnitSyntax)
Dim importsStatement = DirectCast(importNode, ImportsStatementSyntax)
Dim lastToken = importsStatement.GetLastToken()
If lastToken.Kind <> SyntaxKind.EndOfLineTrivia Then
importsStatement = importsStatement.ReplaceToken(lastToken, lastToken.WithAppendedTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed))
End If
Dim importsList = compilationUnit.Imports.Insert(index, importsStatement)
Return compilationUnit.WithImports(importsList)
End Function
Private Function InsertParameterIntoParameterList(index As Integer, parameter As ParameterSyntax, list As ParameterListSyntax) As ParameterListSyntax
If list Is Nothing Then
Return SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(parameter)) _
.WithAdditionalAnnotations(Formatter.Annotation)
End If
Dim parameters = list.Parameters.Insert(index, parameter)
Return list.WithParameters(parameters)
End Function
Protected Overrides Function InsertParameterIntoContainer(index As Integer, parameter As SyntaxNode, container As SyntaxNode) As SyntaxNode
Dim parameterNode = DirectCast(parameter, ParameterSyntax)
If TypeOf container Is MethodBaseSyntax Then
Dim methodStatement = DirectCast(container, MethodBaseSyntax)
Dim parameterList = InsertParameterIntoParameterList(index, parameterNode, methodStatement.ParameterList)
Return methodStatement.WithParameterList(parameterList)
ElseIf TypeOf container Is MethodBlockBaseSyntax Then
Dim methodBlock = DirectCast(container, MethodBlockBaseSyntax)
Dim methodStatement = methodBlock.BlockStatement
Dim parameterList = InsertParameterIntoParameterList(index, parameterNode, methodStatement.ParameterList)
methodStatement = methodStatement.WithParameterList(parameterList)
Select Case methodBlock.Kind
Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock
Return DirectCast(methodBlock, MethodBlockSyntax).WithBlockStatement(DirectCast(methodStatement, MethodStatementSyntax))
Case SyntaxKind.ConstructorBlock
Return DirectCast(methodBlock, ConstructorBlockSyntax).WithBlockStatement(DirectCast(methodStatement, SubNewStatementSyntax))
Case SyntaxKind.OperatorBlock
Return DirectCast(methodBlock, OperatorBlockSyntax).WithBlockStatement(DirectCast(methodStatement, OperatorStatementSyntax))
Case Else
Return DirectCast(methodBlock, AccessorBlockSyntax).WithBlockStatement(DirectCast(methodStatement, AccessorStatementSyntax))
End Select
ElseIf TypeOf container Is PropertyBlockSyntax Then
Dim propertyBlock = DirectCast(container, PropertyBlockSyntax)
Dim propertyStatement = propertyBlock.PropertyStatement
Dim parameterList = InsertParameterIntoParameterList(index, parameterNode, propertyStatement.ParameterList)
propertyStatement = propertyStatement.WithParameterList(parameterList)
Return propertyBlock.WithPropertyStatement(propertyStatement)
End If
Throw Exceptions.ThrowEUnexpected()
End Function
Public Overrides Function IsNamespace(node As SyntaxNode) As Boolean
Return TypeOf node Is NamespaceBlockSyntax
End Function
Public Overrides Function IsType(node As SyntaxNode) As Boolean
Return TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is EnumBlockSyntax
End Function
Public Overrides Function GetMethodXml(node As SyntaxNode, semanticModel As SemanticModel) As String
Dim methodBlock = TryCast(node, MethodBlockBaseSyntax)
If methodBlock Is Nothing Then
Throw Exceptions.ThrowEUnexpected()
End If
Return MethodXmlBuilder.Generate(methodBlock, semanticModel)
End Function
Private Shared Function GetMethodStatement(method As SyntaxNode) As MethodStatementSyntax
Dim methodBlock = TryCast(method, MethodBlockBaseSyntax)
If methodBlock Is Nothing Then
Return Nothing
End If
Return TryCast(methodBlock.BlockStatement, MethodStatementSyntax)
End Function
Private Overloads Shared Function GetHandledEventNames(methodStatement As MethodStatementSyntax) As IList(Of String)
If methodStatement Is Nothing OrElse
methodStatement.HandlesClause Is Nothing OrElse
methodStatement.HandlesClause.Events.Count = 0 Then
Return SpecializedCollections.EmptyList(Of String)()
End If
Dim eventCount = methodStatement.HandlesClause.Events.Count
Dim result(eventCount - 1) As String
For i = 0 To eventCount - 1
Dim handlesItem = methodStatement.HandlesClause.Events(i)
result(i) = handlesItem.EventContainer.ToString() & "."c & handlesItem.EventMember.ToString()
Next
Return result
End Function
Private Shared Function EscapeIfNotMeMyBaseOrMyClass(identifier As String) As String
Select Case SyntaxFacts.GetKeywordKind(identifier)
Case SyntaxKind.MeKeyword,
SyntaxKind.MyBaseKeyword,
SyntaxKind.MyClassKeyword,
SyntaxKind.None
Return identifier
Case Else
Return "["c & identifier & "]"c
End Select
End Function
Private Shared Function MakeHandledEventName(parentName As String, eventName As String) As String
If eventName.Length >= parentName.Length Then
If CaseInsensitiveComparison.Equals(eventName.Substring(0, parentName.Length), parentName) Then
Return "MyBase" & eventName.Substring(parentName.Length)
End If
End If
' If eventName starts with an unescaped keyword other than Me, MyBase or MyClass, we need to escape it.
If Not eventName.StartsWith("[", StringComparison.Ordinal) Then
Dim dotIndex = eventName.IndexOf("."c)
If dotIndex >= 0 Then
Return EscapeIfNotMeMyBaseOrMyClass(eventName.Substring(0, dotIndex)) & eventName.Substring(dotIndex)
Else
EscapeIfNotMeMyBaseOrMyClass(eventName)
End If
End If
Return eventName
End Function
Public Overrides Function AddHandlesClause(document As Document, eventName As String, method As SyntaxNode, cancellationToken As CancellationToken) As Document
Dim methodStatement = GetMethodStatement(method)
Dim parentTypeBlock = TryCast(method.Parent, TypeBlockSyntax)
If parentTypeBlock Is Nothing Then
Throw Exceptions.ThrowEUnexpected()
End If
Dim parentName = parentTypeBlock.BlockStatement.Identifier.ToString()
Dim newEventName = MakeHandledEventName(parentName, eventName)
Dim position As Integer
Dim textToInsert As String
If methodStatement.HandlesClause Is Nothing Then
position = methodStatement.ParameterList.CloseParenToken.Span.End
textToInsert = " Handles " & newEventName
Else
position = methodStatement.HandlesClause.Span.End
textToInsert = ", " & newEventName
End If
Dim text = document.GetTextAsync(cancellationToken) _
.WaitAndGetResult(cancellationToken)
text = text.Replace(position, 0, textToInsert)
Return document.WithText(text)
End Function
Public Overrides Function RemoveHandlesClause(document As Document, eventName As String, method As SyntaxNode, cancellationToken As CancellationToken) As Document
Dim methodStatement = GetMethodStatement(method)
Dim parentTypeBlock = TryCast(method.Parent, TypeBlockSyntax)
If parentTypeBlock Is Nothing Then
Throw Exceptions.ThrowEUnexpected()
End If
Dim parentName = parentTypeBlock.BlockStatement.Identifier.ToString()
Dim newEventName = MakeHandledEventName(parentName, eventName)
If methodStatement.HandlesClause Is Nothing Then
Throw Exceptions.ThrowEUnexpected()
End If
Dim indexOfDot = newEventName.IndexOf("."c)
If indexOfDot = -1 Then
Throw Exceptions.ThrowEUnexpected()
End If
Dim containerName = newEventName.Substring(0, indexOfDot)
Dim memberName = newEventName.Substring(indexOfDot + 1)
Dim clauseItemToRemove As HandlesClauseItemSyntax = Nothing
For Each handlesClauseItem In methodStatement.HandlesClause.Events
If handlesClauseItem.EventContainer.ToString() = containerName AndAlso
handlesClauseItem.EventMember.ToString() = memberName Then
clauseItemToRemove = handlesClauseItem
Exit For
End If
Next
If clauseItemToRemove Is Nothing Then
Throw Exceptions.ThrowEUnexpected()
End If
Dim text = document.GetTextAsync(cancellationToken) _
.WaitAndGetResult(cancellationToken)
If methodStatement.HandlesClause.Events.Count = 1 Then
' Easy case, delete the whole clause
text = text.Replace(methodStatement.HandlesClause.Span, String.Empty)
Else
' Harder case, remove it from the list. If it's the first one, remove the following
' comma, else remove the preceding comma.
Dim index = methodStatement.HandlesClause.Events.IndexOf(clauseItemToRemove)
If index = 0 Then
text = text.Replace(TextSpan.FromBounds(clauseItemToRemove.SpanStart, methodStatement.HandlesClause.Events.GetSeparator(0).Span.End), String.Empty)
Else
text = text.Replace(TextSpan.FromBounds(methodStatement.HandlesClause.Events.GetSeparator(index - 1).SpanStart, clauseItemToRemove.Span.End), String.Empty)
End If
End If
Return document.WithText(text)
End Function
Public Overloads Overrides Function GetHandledEventNames(method As SyntaxNode, semanticModel As SemanticModel) As IList(Of String)
Dim methodStatement = GetMethodStatement(method)
Return GetHandledEventNames(methodStatement)
End Function
Public Overrides Function HandlesEvent(eventName As String, method As SyntaxNode, semanticModel As SemanticModel) As Boolean
Dim methodStatement = GetMethodStatement(method)
Dim handledEventNames = GetHandledEventNames(methodStatement)
For Each handledEventName In handledEventNames
If CaseInsensitiveComparison.Equals(eventName, handledEventName) Then
Return True
End If
Next
Return False
End Function
Public Overrides Function GetFunctionExtenderNames() As String()
Return {ExtenderNames.VBPartialMethodExtender}
End Function
Public Overrides Function GetFunctionExtender(name As String, node As SyntaxNode, symbol As ISymbol) As Object
If Not TypeOf node Is MethodBlockBaseSyntax AndAlso
Not TypeOf node Is MethodStatementSyntax AndAlso
Not TypeOf symbol Is IMethodSymbol Then
Throw Exceptions.ThrowEUnexpected()
End If
If StringComparer.OrdinalIgnoreCase.Equals(name, ExtenderNames.VBPartialMethodExtender) Then
Dim methodSymbol = DirectCast(symbol, IMethodSymbol)
Dim isPartial = methodSymbol.PartialDefinitionPart IsNot Nothing OrElse methodSymbol.PartialImplementationPart IsNot Nothing
Dim isDeclaration = If(isPartial,
methodSymbol.PartialDefinitionPart Is Nothing,
False)
Return PartialMethodExtender.Create(isDeclaration, isPartial)
End If
Throw Exceptions.ThrowEFail()
End Function
Public Overrides Function GetPropertyExtenderNames() As String()
Return {ExtenderNames.VBAutoPropertyExtender}
End Function
Public Overrides Function GetPropertyExtender(name As String, node As SyntaxNode, symbol As ISymbol) As Object
If Not TypeOf node Is PropertyBlockSyntax AndAlso
Not TypeOf node Is PropertyStatementSyntax AndAlso
Not TypeOf symbol Is IPropertySymbol Then
Throw Exceptions.ThrowEUnexpected()
End If
If StringComparer.OrdinalIgnoreCase.Equals(name, ExtenderNames.VBAutoPropertyExtender) Then
Dim isAutoImplemented = TypeOf node Is PropertyStatementSyntax AndAlso
Not TypeOf node.Parent Is InterfaceBlockSyntax
Return AutoPropertyExtender.Create(isAutoImplemented)
End If
Throw Exceptions.ThrowEFail()
End Function
Public Overrides Function GetExternalTypeExtenderNames() As String()
Return {ExtenderNames.ExternalLocation}
End Function
Public Overrides Function GetExternalTypeExtender(name As String, externalLocation As String) As Object
Debug.Assert(externalLocation IsNot Nothing)
If StringComparer.OrdinalIgnoreCase.Equals(name, ExtenderNames.ExternalLocation) Then
Return CodeTypeLocationExtender.Create(externalLocation)
End If
Throw Exceptions.ThrowEFail()
End Function
Public Overrides Function GetTypeExtenderNames() As String()
Return {ExtenderNames.VBGenericExtender}
End Function
Public Overrides Function GetTypeExtender(name As String, codeType As AbstractCodeType) As Object
If codeType Is Nothing Then
Throw Exceptions.ThrowEUnexpected()
End If
If StringComparer.OrdinalIgnoreCase.Equals(name, ExtenderNames.VBGenericExtender) Then
Return GenericExtender.Create(codeType)
End If
Throw Exceptions.ThrowEFail()
End Function
Protected Overrides Function AddBlankLineToMethodBody(node As SyntaxNode, newNode As SyntaxNode) As Boolean
Return TypeOf node Is SyntaxNode AndAlso
node.IsKind(SyntaxKind.SubStatement, SyntaxKind.FunctionStatement) AndAlso
TypeOf newNode Is SyntaxNode AndAlso
newNode.IsKind(SyntaxKind.SubBlock, SyntaxKind.FunctionBlock)
End Function
Public Overrides Function IsValidBaseType(node As SyntaxNode, typeSymbol As ITypeSymbol) As Boolean
If node.IsKind(SyntaxKind.ClassBlock) Then
Return typeSymbol.TypeKind = TypeKind.Class
ElseIf node.IsKind(SyntaxKind.InterfaceBlock) Then
Return typeSymbol.TypeKind = TypeKind.Interface
End If
Return False
End Function
Public Overrides Function AddBase(node As SyntaxNode, typeSymbol As ITypeSymbol, semanticModel As SemanticModel, position As Integer?) As SyntaxNode
If Not node.IsKind(SyntaxKind.ClassBlock, SyntaxKind.InterfaceBlock) Then
Throw Exceptions.ThrowENotImpl()
End If
Dim typeBlock = DirectCast(node, TypeBlockSyntax)
Dim baseCount = typeBlock.Inherits.Count
If typeBlock.IsKind(SyntaxKind.ClassBlock) AndAlso baseCount > 0 Then
Throw Exceptions.ThrowEFail()
End If
Dim typeBlockPosition = typeBlock.SpanStart
Dim inheritsStatement =
SyntaxFactory.InheritsStatement(
SyntaxFactory.ParseTypeName(
typeSymbol.ToMinimalDisplayString(semanticModel, typeBlockPosition)))
inheritsStatement = inheritsStatement.WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed)
Dim inheritsStatements = typeBlock.Inherits.Insert(0, inheritsStatement)
Return typeBlock.WithInherits(inheritsStatements)
End Function
Public Overrides Function RemoveBase(node As SyntaxNode, typeSymbol As ITypeSymbol, semanticModel As SemanticModel) As SyntaxNode
If Not node.IsKind(SyntaxKind.ClassBlock, SyntaxKind.InterfaceBlock) Then
Throw Exceptions.ThrowENotImpl()
End If
Dim typeBlock = DirectCast(node, TypeBlockSyntax)
If typeBlock.Inherits.Count = 0 Then
Throw Exceptions.ThrowEFail()
End If
Dim inheritsStatements = typeBlock.Inherits
Dim foundType = False
For Each inheritsStatement In inheritsStatements
For Each inheritsType In inheritsStatement.Types
Dim typeInfo = semanticModel.GetTypeInfo(inheritsType, CancellationToken.None)
If typeInfo.Type IsNot Nothing AndAlso
typeInfo.Type.Equals(typeSymbol) Then
foundType = True
If inheritsStatement.Types.Count = 1 Then
inheritsStatements = inheritsStatements.Remove(inheritsStatement)
Else
Dim newInheritsStatement = inheritsStatement.RemoveNode(inheritsType, SyntaxRemoveOptions.KeepEndOfLine)
inheritsStatements = inheritsStatements.Replace(inheritsStatement, newInheritsStatement)
End If
Exit For
End If
Next
Next
Return typeBlock.WithInherits(inheritsStatements)
End Function
Public Overrides Function IsValidInterfaceType(node As SyntaxNode, typeSymbol As ITypeSymbol) As Boolean
If node.IsKind(SyntaxKind.ClassBlock, SyntaxKind.StructureBlock) Then
Return typeSymbol.TypeKind = TypeKind.Interface
End If
Return False
End Function
Public Overrides Function AddImplementedInterface(node As SyntaxNode, typeSymbol As ITypeSymbol, semanticModel As SemanticModel, position As Integer?) As SyntaxNode
If Not node.IsKind(SyntaxKind.ClassBlock, SyntaxKind.StructureBlock) Then
Throw Exceptions.ThrowENotImpl()
End If
Dim typeBlock = DirectCast(node, TypeBlockSyntax)
Dim baseCount = typeBlock.Implements.Count
Dim insertionIndex As Integer
If position IsNot Nothing Then
insertionIndex = position.Value
If insertionIndex > baseCount Then
Throw Exceptions.ThrowEInvalidArg()
End If
Else
insertionIndex = baseCount
End If
Dim typeBlockPosition = typeBlock.SpanStart
Dim implementsStatement =
SyntaxFactory.ImplementsStatement(
SyntaxFactory.ParseTypeName(
typeSymbol.ToMinimalDisplayString(semanticModel, typeBlockPosition)))
implementsStatement = implementsStatement.WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed)
Dim implementsStatements = typeBlock.Implements.Insert(insertionIndex, implementsStatement)
Return typeBlock.WithImplements(implementsStatements)
End Function
Public Overrides Function RemoveImplementedInterface(node As SyntaxNode, typeSymbol As ITypeSymbol, semanticModel As SemanticModel) As SyntaxNode
If Not node.IsKind(SyntaxKind.ClassBlock, SyntaxKind.StructureBlock) Then
Throw Exceptions.ThrowENotImpl()
End If
Dim typeBlock = DirectCast(node, TypeBlockSyntax)
If typeBlock.Implements.Count = 0 Then
Throw Exceptions.ThrowEFail()
End If
Dim implementsStatements = typeBlock.Implements
Dim foundType = False
For Each implementsStatement In implementsStatements
For Each inheritsType In implementsStatement.Types
Dim typeInfo = semanticModel.GetTypeInfo(inheritsType, CancellationToken.None)
If typeInfo.Type IsNot Nothing AndAlso
typeInfo.Type.Equals(typeSymbol) Then
foundType = True
If implementsStatement.Types.Count = 1 Then
implementsStatements = implementsStatements.Remove(implementsStatement)
Else
Dim newImplementsStatement = implementsStatement.RemoveNode(inheritsType, SyntaxRemoveOptions.KeepEndOfLine)
implementsStatements = implementsStatements.Replace(implementsStatement, newImplementsStatement)
End If
Exit For
End If
Next
Next
Return typeBlock.WithImplements(implementsStatements)
End Function
Public Overrides Sub AttachFormatTrackingToBuffer(buffer As ITextBuffer)
_commitBufferManagerFactory.CreateForBuffer(buffer).AddReferencingView()
End Sub
Public Overrides Sub DetachFormatTrackingToBuffer(buffer As ITextBuffer)
_commitBufferManagerFactory.CreateForBuffer(buffer).RemoveReferencingView()
End Sub
Public Overrides Sub EnsureBufferFormatted(buffer As ITextBuffer)
_commitBufferManagerFactory.CreateForBuffer(buffer).CommitDirty(isExplicitFormat:=False, cancellationToken:=Nothing)
End Sub
End Class
End Namespace
|
droyad/roslyn
|
src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService.vb
|
Visual Basic
|
apache-2.0
| 213,367
|
' 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.Linq
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Debugging
Imports Roslyn.Test.Utilities
Imports Roslyn.Utilities
Imports Xunit
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.UnitTests.Debugging
Public Class NameResolverTests
Private Sub Test(text As String, searchText As String, ParamArray expectedNames() As String)
TestWithRootNamespace(Nothing, text, searchText, expectedNames)
End Sub
Private Sub TestWithRootNamespace(rootNamespace As String, text As String, searchText As String, ParamArray expectedNames() As String)
Dim compilationOptions = If(rootNamespace Is Nothing, Nothing, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace:=rootNamespace))
Using workspace = TestWorkspaceFactory.CreateWorkspaceFromLines(LanguageNames.VisualBasic, compilationOptions, Nothing, text)
Dim nameResolver = New BreakpointResolver(workspace.CurrentSolution, searchText)
Dim results = nameResolver.DoAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None)
Assert.Equal(expectedNames, results.Select(Function(r) r.LocationNameOpt))
End Using
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub TestSimpleNameInClass()
Dim text =
<text>
class C
sub Foo()
end sub
end class</text>.Value
Test(text, "Foo", "C.Foo()")
Test(text, "foo", "C.Foo()")
Test(text, "C.Foo", "C.Foo()")
Test(text, "N.C.Foo")
Test(text, "Foo(of T)")
Test(text, "C(of T).Foo")
Test(text, "Foo()", "C.Foo()")
Test(text, "Foo(i as Integer)")
Test(text, "Foo(Integer)")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub TestSimpleNameInNamespace()
Dim text =
<text>
namespace N
class C
sub Foo()
end sub
end class
end namespace</text>.Value
Test(text, "Foo", "N.C.Foo()")
Test(text, "foo", "N.C.Foo()")
Test(text, "C.Foo", "N.C.Foo()")
Test(text, "n.c.Foo", "N.C.Foo()")
Test(text, "Foo(of T)")
Test(text, "C(of T).Foo")
Test(text, "Foo()", "N.C.Foo()")
Test(text, "C.Foo()", "N.C.Foo()")
Test(text, "N.C.Foo()", "N.C.Foo()")
Test(text, "Foo(i as Integer)")
Test(text, "Foo(Integer)")
Test(text, "Foo(a)")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub TestSimpleNameInGenericClassNamespace()
Dim text =
<text>
namespace N
class C(of T)
sub Foo()
end sub
end class
end namespace</text>.Value
Test(text, "Foo", "N.C(Of T).Foo()")
Test(text, "foo", "N.C(Of T).Foo()")
Test(text, "C.Foo", "N.C(Of T).Foo()")
Test(text, "N.C.Foo", "N.C(Of T).Foo()")
Test(text, "Foo(of T)")
Test(text, "C(of T).Foo", "N.C(Of T).Foo()")
Test(text, "C(of T).Foo()", "N.C(Of T).Foo()")
Test(text, "Foo()", "N.C(Of T).Foo()")
Test(text, "C.Foo()", "N.C(Of T).Foo()")
Test(text, "N.C.Foo()", "N.C(Of T).Foo()")
Test(text, "Foo(i as Integer)")
Test(text, "Foo(Integer)")
Test(text, "Foo(a)")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub TestGenericNameInClassNamespace()
Dim text =
<text>
namespace N
class C
sub Foo(of T)()
end sub
end class
end namespace</text>.Value
Test(text, "Foo", "N.C.Foo(Of T)()")
Test(text, "foo", "N.C.Foo(Of T)()")
Test(text, "C.Foo", "N.C.Foo(Of T)()")
Test(text, "N.C.Foo", "N.C.Foo(Of T)()")
Test(text, "Foo(of T)", "N.C.Foo(Of T)()")
Test(text, "Foo(of X)", "N.C.Foo(Of T)()")
Test(text, "Foo(of T,X)")
Test(text, "C(of T).Foo")
Test(text, "C(of T).Foo()")
Test(text, "Foo()", "N.C.Foo(Of T)()")
Test(text, "C.Foo()", "N.C.Foo(Of T)()")
Test(text, "N.C.Foo()", "N.C.Foo(Of T)()")
Test(text, "Foo(i as Integer)")
Test(text, "Foo(Integer)")
Test(text, "Foo(a)")
Test(text, "Foo(of T)(i as Integer)")
Test(text, "Foo(of T)(Integer)")
Test(text, "Foo(of T)(a)")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub TestOverloadsInSingleClass()
Dim text =
<text>
class C
sub Foo()
end sub
sub Foo(i as Integer)
end sub
end class
</text>.Value
Test(text, "Foo", "C.Foo()", "C.Foo(Integer)")
Test(text, "foo", "C.Foo()", "C.Foo(Integer)")
Test(text, "C.Foo", "C.Foo()", "C.Foo(Integer)")
Test(text, "N.C.Foo")
Test(text, "Foo(of T)")
Test(text, "C(of T).Foo")
Test(text, "Foo()", "C.Foo()")
Test(text, "Foo(i as Integer)", "C.Foo(Integer)")
Test(text, "Foo(Integer)", "C.Foo(Integer)")
Test(text, "Foo(i)", "C.Foo(Integer)")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub TestMethodsInMultipleClasses()
Dim text =
<text>
namespace N
class C
sub Foo()
end sub
end class
end namespace
namespace N1
class C
sub Foo(i as Integer)
end sub
end class
end namespace</text>.Value
Test(text, "Foo", "N1.C.Foo(Integer)", "N.C.Foo()")
Test(text, "foo", "N1.C.Foo(Integer)", "N.C.Foo()")
Test(text, "C.Foo", "N1.C.Foo(Integer)", "N.C.Foo()")
Test(text, "N.C.Foo", "N.C.Foo()")
Test(text, "N1.C.Foo", "N1.C.Foo(Integer)")
Test(text, "Foo(of T)")
Test(text, "C(of T).Foo")
Test(text, "Foo()", "N.C.Foo()")
Test(text, "Foo(i as Integer)", "N1.C.Foo(Integer)")
Test(text, "Foo(Integer)", "N1.C.Foo(Integer)")
Test(text, "Foo(i)", "N1.C.Foo(Integer)")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub TestMethodsWithDifferentArityInMultipleClasses()
Dim text =
<text>
namespace N
class C
sub Foo()
end sub
end class
end namespace
namespace N1
class C
sub Foo(of T)(i as Integer)
end sub
end class
end namespace</text>.Value
Test(text, "Foo", "N1.C.Foo(Of T)(Integer)", "N.C.Foo()")
Test(text, "foo", "N1.C.Foo(Of T)(Integer)", "N.C.Foo()")
Test(text, "C.Foo", "N1.C.Foo(Of T)(Integer)", "N.C.Foo()")
Test(text, "N.C.Foo", "N.C.Foo()")
Test(text, "N1.C.Foo", "N1.C.Foo(Of T)(Integer)")
Test(text, "Foo(of T)", "N1.C.Foo(Of T)(Integer)")
Test(text, "C(of T).Foo")
Test(text, "Foo()", "N.C.Foo()")
Test(text, "Foo(of T)()")
Test(text, "Foo(i as Integer)", "N1.C.Foo(Of T)(Integer)")
Test(text, "Foo(Integer)", "N1.C.Foo(Of T)(Integer)")
Test(text, "Foo(i)", "N1.C.Foo(Of T)(Integer)")
Test(text, "Foo(of T)(i as Integer)", "N1.C.Foo(Of T)(Integer)")
Test(text, "Foo(of T)(Integer)", "N1.C.Foo(Of T)(Integer)")
Test(text, "Foo(of T)(i)", "N1.C.Foo(Of T)(Integer)")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub TestOverloadsWithMultipleParametersInSingleClass()
Dim text =
<text>
class C
sub Foo(a as Integer)
end sub
sub Foo(a as Integer, Optional b as String = "bb")
end sub
end class</text>.Value
Test(text, "Foo", "C.Foo(Integer)", "C.Foo(Integer, [String])")
Test(text, "foo", "C.Foo(Integer)", "C.Foo(Integer, [String])")
Test(text, "C.Foo", "C.Foo(Integer)", "C.Foo(Integer, [String])")
Test(text, "N.C.Foo")
Test(text, "Foo(of T)")
Test(text, "C(of T).Foo")
Test(text, "Foo()")
Test(text, "Foo(i as Integer)", "C.Foo(Integer)")
Test(text, "Foo(Integer)", "C.Foo(Integer)")
Test(text, "Foo(i)", "C.Foo(Integer)")
Test(text, "Foo(i as Integer, int b)", "C.Foo(Integer, [String])")
Test(text, "Foo(int, boolean)", "C.Foo(Integer, [String])")
Test(text, "Foo(i, s)", "C.Foo(Integer, [String])")
Test(text, "Foo(,)", "C.Foo(Integer, [String])")
Test(text, "Foo(x As Integer = 42,)", "C.Foo(Integer, [String])")
Test(text, "Foo(Optional x As Integer = 42, y = 42)", "C.Foo(Integer, [String])")
Test(text, "Foo(i as Integer, int b, char c)")
Test(text, "Foo(int, bool, char)")
Test(text, "Foo(i, s, c)")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub Properties()
Dim text =
<text>
Class C
ReadOnly Property Property1 As String
WriteOnly Property Property2 As String
Set
End Set
End Property
Property Property3 As Date
Get
Return #1/1/1970#
End Get
Set
End Set
End Property
Default ReadOnly Property Property4(i As Integer) As Integer
Get
Return i
End Get
End Property
ReadOnly Property Property5(i As Integer, j As String) As Integer
Get
Return i + j
End Get
End Property
End Class</text>.Value
Test(text, "Property1", "C.Property1")
Test(text, "property1()", "C.Property1")
Test(text, "property2", "C.Property2")
Test(text, "Property2(String)")
Test(text, "property3", "C.Property3")
Test(text, "property4", "C.Property4(Integer)")
Test(text, "property5(j, i)", "C.Property5(Integer, String)")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub NegativeTests()
Dim text =
<text>
MustInherit Class C
MustOverride Sub AbstractMethod(a As Integer)
Dim Field As Integer
Delegate Sub Delegate1()
Event Event1 As Delegate1
Sub Foo()
End Sub
Sub Foo(Optional x As Integer = 1, Optional y As Integer= 2)
End Sub
End Class</text>.Value
Test(text, "AbstractMethod")
Test(text, "Field")
Test(text, "Delegate1")
Test(text, "Event1")
Test(text, "Property1")
Test(text, "Property2")
Test(text, "New")
Test(text, "C.New")
Test(text, "Foo", "C.Foo()", "C.Foo([Integer], [Integer])") ' just making sure it would normally resolve before trying bad syntax
Test(text, "Foo Foo")
Test(text, "Foo()asdf")
Test(text, "Foo;")
Test(text, "Foo();")
Test(text, "Foo(),")
Test(text, "Foo(),f")
Test(text, "Foo().Foo")
Test(text, "Foo(")
Test(text, "(Foo")
Test(text, "Foo)")
Test(text, "(Foo)")
Test(text, "Foo(x = 42, y = 42)", "C.Foo([Integer], [Integer])") ' just making sure it would normally resolve before trying bad syntax
Test(text, "Foo[x = 42, y = 42]")
Test(text, "Dim x As Integer = 42")
Test(text, "Foo(Optional x As Integer = 42, y = 42")
Test(text, "C")
Test(text, "C.C")
Test(text, "")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub TestInstanceConstructors()
Dim text =
<text>
class C
public sub new()
end sub
end class
Class G(Of T)
Public Sub New()
End Sub
End Class</text>.Value
Test(text, "New", "G(Of T).New()", "C.New()")
Test(text, "c.new", "C.New()")
Test(text, "c.NEW()", "C.New()")
Test(text, "New()", "G(Of T).New()", "C.New()")
Test(text, "New(of T)")
Test(text, "New(of T)()")
Test(text, "New(i as Integer)")
Test(text, "New(Integer)")
Test(text, "New(i)")
Test(text, "G.New", "G(Of T).New()")
Test(text, "G.New()", "G(Of T).New()")
Test(text, "G(Of t).new", "G(Of T).New()")
Test(text, "G(of t).new()", "G(Of T).New()")
Test(text, "G(Of T)")
Test(text, "G(Of T)()")
Test(text, "G.G(Of T)")
Test(text, ".ctor")
Test(text, ".ctor()")
Test(text, "C.ctor")
Test(text, "C.ctor()")
Test(text, "G.ctor")
Test(text, "G(Of T).ctor()")
Test(text, "C")
Test(text, "C.C")
Test(text, "C.C()")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub TestStaticConstructors()
Dim text =
<text>
class C
shared sub new()
end sub
end class</text>.Value
Test(text, "New", "C.New()")
Test(text, "C.New", "C.New()")
Test(text, "C.New()", "C.New()")
Test(text, "New()", "C.New()")
Test(text, "New(of T)")
Test(text, "New(of T)()")
Test(text, "New(i as Integer)")
Test(text, "New(Integer)")
Test(text, "New(i)")
Test(text, "C")
Test(text, "C.C")
Test(text, "C.C()")
Test(text, "C.cctor")
Test(text, "C.cctor()")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub TestAllConstructors()
Dim text =
<text>
class C
shared sub new()
end sub
public sub new(i as Integer)
end sub
end class</text>.Value
Test(text, "New", "C.New(Integer)", "C.New()")
Test(text, "C.New", "C.New(Integer)", "C.New()")
Test(text, "c.New()", "C.New()")
Test(text, "new()", "C.New()")
Test(text, "New(of T)")
Test(text, "New(of T)()")
Test(text, "New(i as Integer)", "C.New(Integer)")
Test(text, "New(Integer)", "C.New(Integer)")
Test(text, "New(i)", "C.New(Integer)")
Test(text, "C")
Test(text, "C.C")
Test(text, "C.C()")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub TestPartialMethods()
Dim text =
<text>
Partial Class C
Partial Private Sub M1()
End Sub
Private Sub M2()
End Sub
Partial Private Sub M2()
End Sub
Partial Private Sub M3()
End Sub
Partial Private Sub M3(x As Integer)
End Sub
Private Sub M3(x As Integer)
End Sub
End Class</text>.Value
Test(text, "M1")
Test(text, "C.M1")
Test(text, "M2", "C.M2()")
Test(text, "M3", "C.M3(Integer)")
Test(text, "M3()")
Test(text, "M3(y)", "C.M3(Integer)")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub TestLeadingAndTrailingText()
Dim text =
<text>
Class C
Sub Foo()
End Sub
End Class</text>.Value
Test(text, " Foo", "C.Foo()")
Test(text, "Foo() ", "C.Foo()")
Test(text, " Foo ( ) ", "C.Foo()")
Test(text, "Foo() ' comment", "C.Foo()")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub TestEscapedKeywords()
Dim text =
<text>
Structure [true]
End Structure
Class [for]
Sub [where]([me] As [true])
End Sub
Sub [False]()
End Sub
End Class</text>.Value
Test(text, "where", "[for].where([true])")
Test(text, "[where]", "[for].where([true])")
Test(text, "[for].where", "[for].where([true])")
Test(text, "for.where", "[for].where([true])")
Test(text, "[for].where(true)", "[for].where([true])")
Test(text, "[for].where([if])", "[for].where([true])")
Test(text, "False", "[for].False()")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub TestGlobalQualifiedNames()
Dim text =
<text>
Class C
Sub Foo(c1 As C)
End Sub
End Class</text>.Value
Test(text, "Global.Foo")
Test(text, "Global.C.Foo")
Test(text, "Global.C.Foo(C)")
Test(text, "C.Foo(Global.C)", "C.Foo(C)")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub TestRootNamespaces()
Dim text =
<text>
Class C
Sub Foo()
End Sub
End Class
Namespace N1
Class C
Sub Foo()
End Sub
End Class
End Namespace</text>.Value
TestWithRootNamespace("Root", text, "Foo", "Root.N1.C.Foo()", "Root.C.Foo()")
TestWithRootNamespace("Root", text, "C.Foo", "Root.N1.C.Foo()", "Root.C.Foo()")
TestWithRootNamespace("Root", text, "N1.C.Foo()", "Root.N1.C.Foo()")
TestWithRootNamespace("Root", text, "Root.C.Foo()", "Root.C.Foo()")
TestWithRootNamespace("Root", text, "Root.N1.C.Foo", "Root.N1.C.Foo()")
TestWithRootNamespace("Root", text, "Root.Foo")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub TestNestedTypesAndNamespaces()
Dim text =
<text>
Namespace N1
Class C
Sub Foo()
End Sub
End Class
Namespace N2
Class C
End Class
End Namespace
Namespace N3
Class D
End Class
End Namespace
Namespace N4
Class C
Sub Foo(x As Double)
End Sub
Class D
Sub Foo()
End Sub
Class E
Sub Foo()
End Sub
End Class
End Class
End Class
End Namespace
Namespace N5
End Namespace
End Namespace</text>.Value
Test(text, "Foo", "N1.N4.C.Foo(Double)", "N1.N4.C.D.Foo()", "N1.N4.C.D.E.Foo()", "N1.C.Foo()")
Test(text, "C.Foo", "N1.N4.C.Foo(Double)", "N1.C.Foo()")
Test(text, "D.Foo", "N1.N4.C.D.Foo()")
Test(text, "N1.N4.C.D.Foo", "N1.N4.C.D.Foo()")
Test(text, "N1.Foo")
Test(text, "N3.C.Foo")
Test(text, "N5.C.Foo")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)>
Public Sub TestInterfaces()
Dim text =
<text>
Interface I1
Sub Foo()
Sub Moo()
End Interface
Class C1 : Implements I1
Sub Foo1() Implements I1.Foo
End Sub
Sub Moo() Implements I1.Moo
End Sub
End Class
</text>.Value
Test(text, "Foo")
Test(text, "I1.Foo")
Test(text, "Foo1", "C1.Foo1()")
Test(text, "Moo", "C1.Moo()")
End Sub
End Class
End Namespace
|
droyad/roslyn
|
src/VisualStudio/Core/Test/Debugging/NameResolverTests.vb
|
Visual Basic
|
apache-2.0
| 19,568
|
' 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
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements
''' <summary>
''' Recommends the "Is" keyword at the beginning of any clause in a "Case" statement
''' </summary>
Friend Class IsKeywordRecommender
Inherits AbstractKeywordRecommender
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As IEnumerable(Of RecommendedKeyword)
If context.FollowsEndOfStatement Then
Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)()
End If
Dim targetToken = context.TargetToken
' Determine whether we can offer "Is" at the beginning of a CaseClauseSyntax. Make sure
' that the token is not after a CaseElseStatement.
Dim selectBlock = targetToken.GetAncestor(Of SelectBlockSyntax)()
If selectBlock IsNot Nothing Then
Dim caseElseBlock = selectBlock.CaseBlocks.FirstOrDefault(Function(caseBlock) caseBlock.CaseStatement.Kind = SyntaxKind.CaseElseStatement)
If caseElseBlock Is Nothing OrElse targetToken.SpanStart < caseElseBlock.SpanStart Then
' Handle cases where the token is at the beginning of the first clause
' (following the Case keyword) and where the token is at the beginning of
' subsequent clauses (following the list separator token).
If targetToken.IsChildToken(Of CaseStatementSyntax)(Function(caseStatement) caseStatement.CaseKeyword) OrElse
targetToken.IsChildSeparatorToken(Of CaseStatementSyntax, CaseClauseSyntax)(Function(caseStatement) caseStatement.Cases) Then
Return SpecializedCollections.SingletonEnumerable(New RecommendedKeyword("Is", VBFeaturesResources.CaseIsKeywordToolTip))
End If
End If
End If
Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)()
End Function
End Class
End Namespace
|
KevinRansom/roslyn
|
src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Statements/IsKeywordRecommender.vb
|
Visual Basic
|
apache-2.0
| 2,468
|
' 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.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
<Flags()>
Friend Enum UnaryOperatorKind
Plus = 1
Minus = 2
[Not] = 3
IntrinsicOpMask = &H3
Lifted = &H4
UserDefined = &H8
Implicit = &H10
Explicit = &H20
IsTrue = &H30
IsFalse = &H40
OpMask = IntrinsicOpMask Or &H70
[Error] = &H80
End Enum
Friend Enum BinaryOperatorKind
Add = 1
Concatenate = 2
[Like] = 3
Equals = 4
NotEquals = 5
LessThanOrEqual = 6
GreaterThanOrEqual = 7
LessThan = 8
GreaterThan = 9
Subtract = 10
Multiply = 11
Power = 12
Divide = 13
Modulo = 14
IntegerDivide = 15
LeftShift = 16
RightShift = 17
[Xor] = 18
[Or] = 19
[OrElse] = 20
[And] = 21
[AndAlso] = 22
[Is] = 23
[IsNot] = 24
OpMask = &H1F
Lifted = &H20
CompareText = &H40
UserDefined = &H80
[Error] = &H100
End Enum
End Namespace
|
mmitche/roslyn
|
src/Compilers/VisualBasic/Portable/CodeGen/OperatorKind.vb
|
Visual Basic
|
apache-2.0
| 1,412
|
' The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227
''' <summary>
''' Provides application-specific behavior to supplement the default Application class.
''' </summary>
NotInheritable Class App
Inherits Application
''' <summary>
''' Invoked when the application is launched normally by the end user. Other entry points
''' will be used when the application is launched to open a specific file, to display
''' search results, and so forth.
''' </summary>
''' <param name="e">Details about the launch request and process.</param>
Protected Overrides Sub OnLaunched(e As Windows.ApplicationModel.Activation.LaunchActivatedEventArgs)
#If DEBUG Then
' Show graphics profiling information while debugging.
If System.Diagnostics.Debugger.IsAttached Then
' Display the current frame rate counters
Me.DebugSettings.EnableFrameRateCounter = True
End If
#End If
Dim rootFrame As Frame = TryCast(Window.Current.Content, Frame)
' Do not repeat app initialization when the Window already has content,
' just ensure that the window is active
If rootFrame Is Nothing Then
' Create a Frame to act as the navigation context and navigate to the first page
rootFrame = New Frame()
' Set the default language
rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages(0)
AddHandler rootFrame.NavigationFailed, AddressOf OnNavigationFailed
If e.PreviousExecutionState = ApplicationExecutionState.Terminated Then
' TODO: Load state from previously suspended application
End If
' Place the frame in the current Window
Window.Current.Content = rootFrame
End If
If rootFrame.Content Is Nothing Then
' When the navigation stack isn't restored navigate to the first page,
' configuring the new page by passing required information as a navigation
' parameter
rootFrame.Navigate(GetType(MainPage), e.Arguments)
End If
' Ensure the current window is active
Window.Current.Activate()
NotificationService.CreateOrUpdateNotificationsAsync()
End Sub
''' <summary>
''' Invoked when Navigation to a certain page fails
''' </summary>
''' <param name="sender">The Frame which failed navigation</param>
''' <param name="e">Details about the navigation failure</param>
Private Sub OnNavigationFailed(sender As Object, e As NavigationFailedEventArgs)
Throw New Exception("Failed to load Page " + e.SourcePageType.FullName)
End Sub
''' <summary>
''' Invoked when application execution is being suspended. Application state is saved
''' without knowing whether the application will be terminated or resumed with the contents
''' of memory still intact.
''' </summary>
''' <param name="sender">The source of the suspend request.</param>
''' <param name="e">Details about the suspend request.</param>
Private Sub OnSuspending(sender As Object, e As SuspendingEventArgs) Handles Me.Suspending
Dim deferral As SuspendingDeferral = e.SuspendingOperation.GetDeferral()
' TODO: Save application state and stop any background activity
deferral.Complete()
End Sub
End Class
|
saramgsilva/NotificationHubs
|
Using Registration Model/Case 1/NotificationHubsSample.Win81-VB/App.xaml.vb
|
Visual Basic
|
mit
| 3,429
|
Option Explicit On
Option Strict On
Imports System
Imports System.Collections.Generic
Imports ananse
' Parses expressions that are used throughout the language
Public Class ExpressionParser
Inherits AstNodeParser
'List of operators forming the operator heirachy
Private Shared operators As List(Of Token()) = New List(Of Token())
Public Overrides ReadOnly Property lookAhead As Token
Get
Throw New NotImplementedException()
End Get
End Property
'Initialize the expression parser and setup operator heirachy
Public Shared Sub setupOperations()
operators.Add(New Token() {Token.EQUALS_OPERATOR})
operators.Add(New Token() {Token.ADD_OPERATOR, Token.SUBTRACT_OPERATOR})
operators.Add(New Token() {Token.MULTIPLY_OPERATOR, Token.DIVIDE_OPERATOR, Token.MOD_OPERATOR})
End Sub
'Run the expression parser and return an expression object
Public overrides function parse() as AstNode
return parseExpression(0)
end function
private function parseExpression(level as integer) as ExpressionNode
dim expression as ExpressionNode
dim tempExpression as ExpressionNode
if level = operators.Count Then
' Return a factor if we've exhausted all operators on our heirachy
Return parseFactor()
Else
' if not, parse the next level of operators for our expression
tempExpression = parseExpression(level + 1)
expression = tempExpression
end if
'Loop through all the operators at the current heirachy and group them with their expressions
do
if Array.indexOf(operators(level), parser.lookAhead) <> -1 then
expression = new ExpressionNode
expression.left = tempExpression
expression.opr = parser.lookAhead
parser.getNextToken
expression.right = parseExpression(level + 1)
else
return expression
end if
tempExpression = expression
loop
return expression
end function
' Factors are numbers, function calls, variables or other expressions contained in parantheses
private function parseFactor as ExpressionNode
dim expression as ExpressionNode = New ExpressionNode
Select Case parser.lookAhead
Case Token.NUMBER
expression.token = Token.NUMBER
expression.value = parser.tokenString
expression.type = "integer"
parser.getNextToken()
Case Token.OPEN_PARANTHESIS
parser.getNextToken
expression = parseExpression(0)
parser.match(Token.CLOSE_PARANTHESIS)
parser.getNextToken()
End Select
return expression
end function
End Class
|
ananse/ananse
|
src/ast/parsers/ExpressionParser.vb
|
Visual Basic
|
mit
| 2,879
|
Option Infer On
Imports System
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim partDocument As SolidEdgePart.PartDocument = Nothing
Dim models As SolidEdgePart.Models = Nothing
Dim model As SolidEdgePart.Model = Nothing
Dim ribs As SolidEdgePart.Ribs = Nothing
Dim rib As SolidEdgePart.Rib = Nothing
Try
' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register()
' Attempt to connect to a running instance of Solid Edge.
application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application)
partDocument = TryCast(application.ActiveDocument, SolidEdgePart.PartDocument)
If partDocument IsNot Nothing Then
models = partDocument.Models
model = models.Item(1)
ribs = model.Ribs
For i As Integer = 1 To ribs.Count
rib = ribs.Item(i)
Dim Name = "MyAttributeSet"
Dim attributeSetPresent = rib.IsAttributeSetPresent(Name)
Next i
End If
Catch ex As System.Exception
Console.WriteLine(ex)
Finally
OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgePart.Rib.IsAttributeSetPresent.vb
|
Visual Basic
|
mit
| 1,710
|
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("VBMailMerge")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("Independentsoft")>
<Assembly: AssemblyProduct("VBMailMerge")>
<Assembly: AssemblyCopyright("Copyright © Independentsoft 2013")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("c2e40c94-77b3-47bd-beb6-419aeac11f77")>
' 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")>
|
AndreKuzubov/Easy_Report
|
packages/Independentsoft.Office.Word.2.0.400/Tutorial/VBMailMerge/My Project/AssemblyInfo.vb
|
Visual Basic
|
apache-2.0
| 1,170
|
Imports BVSoftware.Bvc5.Core
Partial Class BVAdmin_Controls_BooleanModifierField
Inherits Controls.ModificationControl(Of Boolean)
Public Enum Modes
YesNo = 0
EnabledDisabled = 1
End Enum
Public Property DisplayMode() As Modes
Get
Dim obj As Object = ViewState("mode")
If obj IsNot Nothing Then
Return DirectCast(obj, Modes)
Else
Return Modes.YesNo
End If
End Get
Set(ByVal value As Modes)
ViewState("mode") = value
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
If DisplayMode = Modes.YesNo Then
BooleanDropDownList.Items.Clear()
Dim li As New ListItem("Yes", "1", True)
li.Selected = True
BooleanDropDownList.Items.Add(li)
li = New ListItem("No", "0", True)
BooleanDropDownList.Items.Add(li)
ElseIf DisplayMode = Modes.EnabledDisabled Then
BooleanDropDownList.Items.Clear()
Dim li As New ListItem("Enabled", "1", True)
li.Selected = True
BooleanDropDownList.Items.Add(li)
li = New ListItem("Disabled", "0", True)
BooleanDropDownList.Items.Add(li)
End If
End If
End Sub
Public Overloads Overrides Function ApplyChanges(ByVal item As Boolean) As Boolean
If Me.BooleanDropDownList.SelectedValue = "0" Then
Return False
Else
Return True
End If
End Function
End Class
|
ajaydex/Scopelist_2015
|
BVAdmin/Controls/BooleanModifierField.ascx.vb
|
Visual Basic
|
apache-2.0
| 1,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.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 HandlesClauseCompletionProviderTests
Inherits AbstractVisualBasicCompletionProviderTests
Public Sub New(workspaceFixture As VisualBasicTestWorkspaceFixture)
MyBase.New(workspaceFixture)
End Sub
Friend Overrides Function CreateCompletionProvider() As CompletionListProvider
Return New HandlesClauseCompletionProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSuggestMeEvent() As Task
Dim text = <text>Public Class Class1
' Declare an event.
Public Event Ev_Event()
Sub CauseSomeEvent()
' Raise an event.
RaiseEvent Ev_Event()
End Sub
Sub Handler() Handles Me.$$
End Class </text>.Value
Await VerifyItemExistsAsync(text, "Ev_Event")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(546497)>
Public Async Function TestSuggestMeEventInDerived() As Task
Dim text = <text>Public Class Base
Public Event Click()
End Class
Public Class Derived
Inherits Base
Sub Foo() Handles Me.$$
End Class</text>.Value
Await VerifyItemExistsAsync(text, "Click")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(546497)>
Public Async Function TestSuggestMeEventInIndirectDerived() As Task
Dim text = <text>Public Class Base
Public Event Click()
End Class
Public Class Derived
Inherits Base
End Class
Public Class IndirectDerived
Inherits Base
Sub Foo() Handles MyClass.$$
End Class
</text>.Value
Await VerifyItemExistsAsync(text, "Click")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSuggestMyBaseEvent() As Task
Dim text = <text>Public Class BaseClass
Public Event Event1()
End Class
Public Class Class1
Inherits BaseClass
Sub Handler() Handles MyBase.$$
End Class</text>.Value
Await VerifyItemExistsAsync(text, "Event1")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSuggestMyClassEventEvent() As Task
Dim text = <text>Public Class Class1
' Declare an event.
Public Event Ev_Event()
Sub CauseSomeEvent()
' Raise an event.
RaiseEvent Ev_Event()
End Sub
Sub Handler() Handles MyClass.$$
End Class </text>.Value
Await VerifyItemExistsAsync(text, "Ev_Event")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSuggestField() As Task
Dim text = <text>Public Class Class1
' Declare an event.
Public Event Ev_Event()
Sub CauseSomeEvent()
' Raise an event.
RaiseEvent Ev_Event()
End Sub
End Class
Public Class Handler
WithEvents handlee as New Class1
Public Sub foo Handles $$
End Class</text>.Value
Await VerifyItemExistsAsync(text, "handlee")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSuggestFieldEvent() As Task
Dim text = <text>Public Class Class1
' Declare an event.
Public Event Ev_Event()
Sub CauseSomeEvent()
' Raise an event.
RaiseEvent Ev_Event()
End Sub
End Class
Public Class Handler
WithEvents handlee as New Class1
Public Sub foo Handles handlee.$$
End Class</text>.Value
Await VerifyItemExistsAsync(text, "Ev_Event")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(546508)>
Public Async Function TestSuggestGenericFieldEvent() As Task
Dim text = <text>Class A
Event Ev_Event()
End Class
Class test(Of T As A)
WithEvents obj As T
Sub bar() Handles obj.$$
End Class</text>.Value
Await VerifyItemExistsAsync(text, "Ev_Event")
End Function
<WorkItem(546494)>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSuggestFieldDerivedEvent() As Task
Dim text = <text>Public Class Base
Public Event Click()
End Class
Public Class Derived
Inherits Base
End Class
Class Test
WithEvents obj As Derived
Sub foo() Handles obj.$$
End Class
</text>.Value
Await VerifyItemExistsAsync(text, "Click")
End Function
<WorkItem(546513)>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInheritedFieldOfNestedType() As Task
Dim text = <text>Class container
'Delegate Sub MyDele(x As Integer)
Class inner
Event Ev As System.EventHandler
End Class
Protected WithEvents obj As inner
End Class
Class derived
Inherits container
Sub foo() Handles $$
End Class
</text>.Value
Await VerifyItemExistsAsync(text, "obj")
End Function
<WorkItem(546511)>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDoNotShowMeShadowedEvents() As Task
Dim text = <text>Public Class Base
Protected Event B()
End Class
Public Class Derived
Inherits Base
Shadows Event B()
Sub foo() Handles Me.$$
End Sub
End Class
</text>.Value
Await VerifyItemExistsAsync(text, "B", "Event Derived.B()")
Await VerifyItemIsAbsentAsync(text, "B", "Event Base.B()")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotInTrivia() As Task
Dim text = <text>Public Class Class1
' Declare an event.
Public Event Ev_Event()
Sub CauseSomeEvent()
' Raise an event.
RaiseEvent Ev_Event()
End Sub
End Class
Public Class Handler
WithEvents handlee as New Class1
Public Sub foo Handles '$$
End Class</text>.Value
Await VerifyNoItemsExistAsync(text)
End Function
End Class
End Namespace
|
HellBrick/roslyn
|
src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/HandlesClauseCompletionProviderTests.vb
|
Visual Basic
|
apache-2.0
| 6,812
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Imports Roslyn.Test.Utilities
Imports System.IO
Imports System.Reflection
Imports System.Xml.Linq
Imports Xunit
Imports System.Reflection.Metadata
Imports Microsoft.CodeAnalysis.Emit
Imports System.Collections.Immutable
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class NoPiaEmbedTypes
Inherits BasicTestBase
' See C# EmbedClass1 and EmbedClass2 tests.
<Fact()>
Public Sub BC31541ERR_CannotLinkClassWithNoPIA1()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Class A
End Class
Public Module M
End Module
Public Structure S
End Structure
Public Delegate Sub D()
Public Enum E
A
End Enum
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Imports B = A
Class C(Of T)
Sub M(o As Object)
Dim _1 As A = Nothing
Dim _2 As C(Of A) = Nothing
Dim _3 = GetType(A)
Dim _4 = GetType(A())
Dim _5 = GetType(B)
Dim _6 = GetType(M)
Dim _7 As S = Nothing
Dim _8 As D = Nothing
Dim _9 As E = Nothing
M(_1)
M(_2)
M(_3)
M(_4)
M(_5)
M(_6)
M(_7)
M(_8)
M(_9)
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Dim _1 As A = Nothing
~
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Dim _2 As C(Of A) = Nothing
~
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Dim _3 = GetType(A)
~
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Dim _4 = GetType(A())
~
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Dim _5 = GetType(B)
~
BC31541: Reference to class 'M' is not allowed when its assembly is configured to embed interop types.
Dim _6 = GetType(M)
~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=False)})
VerifyEmitDiagnostics(compilation2)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={AssemblyMetadata.CreateFromImage(compilation1.EmitToArray()).GetReference(embedInteropTypes:=False)})
VerifyEmitDiagnostics(compilation2)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={AssemblyMetadata.CreateFromImage(compilation1.EmitToArray()).GetReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
End Sub
' See C# EmbedClass3 test.
<Fact()>
Public Sub BC31541ERR_CannotLinkClassWithNoPIA1_2()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Class A
End Class
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Interface I(Of T)
End Interface
Class C(Of T)
End Class
Class B1
Inherits A
End Class
Class B2
Inherits C(Of A)
Implements I(Of A)
End Class
Class B3
Inherits C(Of I(Of A))
Implements I(Of C(Of A))
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Inherits A
~
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Inherits C(Of A)
~
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Implements I(Of A)
~
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Inherits C(Of I(Of A))
~
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Implements I(Of C(Of A))
~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation1.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
End Sub
<Fact()>
Public Sub BC31541ERR_CannotLinkClassWithNoPIA1_3()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Class A
End Class
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Imports COfA = C(Of A)
Class C(Of T)
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Imports COfA = C(Of A)
~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={AssemblyMetadata.CreateFromImage(compilation1.EmitToArray()).GetReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
End Sub
<Fact()>
Public Sub BC31558ERR_InvalidInteropType()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface IA
Interface IB
End Interface
Class C
End Class
Structure S
End Structure
Delegate Sub D()
Enum E
A
End Enum
End Interface
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Dim _1 As IA.IB
Dim _2 As IA.C
Dim _3 As IA.S
Dim _4 As IA.D
Dim _5 As IA.E
End Module
]]></file>
</compilation>
Dim errors = <errors>
BC31558: Nested type 'IA.IB' cannot be embedded.
Dim _1 As IA.IB
~~~~~
BC31541: Reference to class 'IA.C' is not allowed when its assembly is configured to embed interop types.
Dim _2 As IA.C
~~~~
BC31558: Nested type 'IA.S' cannot be embedded.
Dim _3 As IA.S
~~~~
BC31558: Nested type 'IA.D' cannot be embedded.
Dim _4 As IA.D
~~~~
BC31558: Nested type 'IA.E' cannot be embedded.
Dim _5 As IA.E
~~~~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={AssemblyMetadata.CreateFromImage(compilation1.EmitToArray()).GetReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
End Sub
<Fact()>
Public Sub EmbedNestedType1()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Function F() As S1.S2
End Interface
Public Structure S1
Structure S2
End Structure
End Structure
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Function F1(o As I) As Object
Dim x = o.F()
Return x
End Function
Function F2(o As I) As Object
Dim x As S1.S2 = o.F()
Return x
End Function
End Module
]]></file>
</compilation>
Dim errors2 = <errors>
BC31558: Nested type 'S1.S2' cannot be embedded.
Dim x = o.F()
~~~~~
BC31558: Nested type 'S1.S2' cannot be embedded.
Dim x As S1.S2 = o.F()
~~~~~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors2)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation1.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors2)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
End Sub
<Fact()>
Public Sub EmbedNestedType2()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Function F() As S1.S2
End Interface
Public Structure S1
Structure S2
End Structure
End Structure
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Function F(o As I) As Object
Return o.F()
End Function
End Module
]]></file>
</compilation>
Dim errors2 = <errors>
BC31558: Nested type 'S1.S2' cannot be embedded.
Return o.F()
~~~~~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors2)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation1.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors2)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
End Sub
<Fact()>
Public Sub EmbedNestedType3()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Structure S1
Structure S2
End Structure
End Structure
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Sub M(o As S1.S2)
End Sub
End Module
]]></file>
</compilation>
Dim errors2 = <errors>
BC31558: Nested type 'S1.S2' cannot be embedded.
Sub M(o As S1.S2)
~~~~~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors2)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors2)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation1.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors2)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors2)
End Sub
' See C# EmbedGenericType* tests.
<Fact()>
Public Sub BC36923ERR_CannotEmbedInterfaceWithGeneric()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I1(Of T)
Interface I2
End Interface
Class C2
End Class
Structure S2
End Structure
Enum E2
A
End Enum
End Interface
Public Class C1(Of T)
End Class
Public Structure S1(Of T)
End Structure
Public Delegate Sub D1(Of T)()
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Dim _1 As I1(Of Object)
Dim _2 As I1(Of Object).I2
Dim _3 As I1(Of Object).C2
Dim _4 As I1(Of Object).S2
Dim _5 As I1(Of Object).E2
Dim _6 As C1(Of Object)
Dim _7 As S1(Of Object) ' No error from Dev11
Dim _8 As D1(Of Object) ' No error from Dev11
End Module
]]></file>
</compilation>
Dim errors = <errors>
BC36923: Type 'I1(Of T)' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.
Dim _1 As I1(Of Object)
~~~~~~~~~~~~~
BC31558: Nested type 'I1(Of T).I2' cannot be embedded.
Dim _2 As I1(Of Object).I2
~~~~~~~~~~~~~~~~
BC31541: Reference to class 'I1(Of T).C2' is not allowed when its assembly is configured to embed interop types.
Dim _3 As I1(Of Object).C2
~~~~~~~~~~~~~~~~
BC31558: Nested type 'I1(Of T).S2' cannot be embedded.
Dim _4 As I1(Of Object).S2
~~~~~~~~~~~~~~~~
BC31558: Nested type 'I1(Of T).E2' cannot be embedded.
Dim _5 As I1(Of Object).E2
~~~~~~~~~~~~~~~~
BC31541: Reference to class 'C1(Of T)' is not allowed when its assembly is configured to embed interop types.
Dim _6 As C1(Of Object)
~~~~~~~~~~~~~
BC36923: Type 'S1(Of T)' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.
Dim _7 As S1(Of Object) ' No error from Dev11
~~~~~~~~~~~~~
BC36923: Type 'D1(Of T)' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.
Dim _8 As D1(Of Object) ' No error from Dev11
~~~~~~~~~~~~~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation1.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
End Sub
Private Shared Sub VerifyEmitDiagnostics(compilation As VisualBasicCompilation, Optional errors As XElement = Nothing)
If errors Is Nothing Then
errors = <errors/>
End If
Using executableStream As New MemoryStream()
Dim result = compilation.Emit(executableStream)
result.Diagnostics.AssertTheseDiagnostics(errors)
End Using
End Sub
Private Shared Sub VerifyEmitMetadataOnlyDiagnostics(compilation As VisualBasicCompilation, Optional errors As XElement = Nothing)
If errors Is Nothing Then
errors = <errors/>
End If
Using executableStream As New MemoryStream()
Dim result = compilation.Emit(executableStream, options:=New EmitOptions(metadataOnly:=True))
result.Diagnostics.AssertTheseDiagnostics(errors)
End Using
End Sub
' See C# EmbedStructWith* tests.
<Fact()>
Public Sub BC31542ERR_InvalidStructMemberNoPIA1()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
' Public field
Public Structure S0
Public F As Object
End Structure
' Private field
Public Structure S1
Friend F As Object
End Structure
' Shared field
Public Structure S2
Public Shared F As Object
End Structure
' Public method
Public Structure S3
Public Sub F()
End Sub
End Structure
' Public property
Public Structure S4
Public Property P As Object
End Structure
' Public event
Public Delegate Sub D()
Public Structure S5
Public Event E As D
End Structure
' Public type
Public Structure S6
Public Structure T
End Structure
End Structure
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Function F0() As Object
Return DirectCast(Nothing, S0)
End Function
Function F1() As Object
Return DirectCast(Nothing, S1)
End Function
Function F2() As Object
Return DirectCast(Nothing, S2)
End Function
Function F3() As Object
Return DirectCast(Nothing, S3)
End Function
Function F4() As Object
Return DirectCast(Nothing, S4)
End Function
Function F5() As Object
Return DirectCast(Nothing, S5)
End Function
Function F6() As Object
Return DirectCast(Nothing, S6)
End Function
End Module
]]></file>
</compilation>
Dim errors = <errors>
BC31542: Embedded interop structure 'S1' can contain only public instance fields.
Return DirectCast(Nothing, S1)
~~~~~~~~~~~~~~~~~~~~~~~
BC31542: Embedded interop structure 'S2' can contain only public instance fields.
Return DirectCast(Nothing, S2)
~~~~~~~~~~~~~~~~~~~~~~~
BC31542: Embedded interop structure 'S3' can contain only public instance fields.
Return DirectCast(Nothing, S3)
~~~~~~~~~~~~~~~~~~~~~~~
BC31542: Embedded interop structure 'S4' can contain only public instance fields.
Return DirectCast(Nothing, S4)
~~~~~~~~~~~~~~~~~~~~~~~
BC31542: Embedded interop structure 'S5' can contain only public instance fields.
Return DirectCast(Nothing, S5)
~~~~~~~~~~~~~~~~~~~~~~~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation1.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
End Sub
<Fact()>
Public Sub BC31561ERR_InteropMethodWithBody1()
Dim sources1 = <![CDATA[
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly A
{
.custom instance void [mscorlib]System.Runtime.InteropServices.ImportedFromTypeLibAttribute::.ctor(string) = {string('_.dll')}
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = {string('f9c2d51d-4f44-45f0-9eda-c9d599b58257')}
}
.class public sealed D extends [mscorlib]System.MulticastDelegate
{
.method public hidebysig specialname rtspecialname instance void .ctor(object o, native int m) runtime { }
.method public hidebysig instance void Invoke() runtime { }
.method public hidebysig instance class [mscorlib]System.IAsyncResult BeginInvoke(class [mscorlib]System.AsyncCallback c, object o) runtime { }
.method public hidebysig instance void EndInvoke(class [mscorlib]System.IAsyncResult r) runtime { }
.method public static void M1() { ldnull throw }
.method public static pinvokeimpl("A.dll" winapi) void M2() { }
.method public instance void M3() { ldnull throw }
}
]]>.Value
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Sub M(o As D)
D.M1()
D.M2()
o.M3()
End Sub
End Module
]]></file>
</compilation>
Dim reference1 = CompileIL(sources1, prependDefaultHeader:=False, embedInteropTypes:=True)
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources2, references:={reference1})
VerifyEmitDiagnostics(compilation2, <errors>
BC31561: Embedded interop method 'Sub D.M1()' contains a body.
D.M1()
~~~~~~
BC31561: Embedded interop method 'Sub D.M3()' contains a body.
D.M1()
~~~~~~
</errors>)
VerifyEmitMetadataOnlyDiagnostics(compilation2, <errors>
BC31561: Embedded interop method 'Sub D.M1()' contains a body.
BC31561: Embedded interop method 'Sub D.M3()' contains a body.
</errors>)
End Sub
<Fact()>
Public Sub TypeIdentifierIsMissing1()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Structure S
End Structure
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Class C
Function F() As Object
Dim x As S = Nothing
Return x
End Function
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC35000: Requested operation is not available because the runtime library function 'System.Runtime.InteropServices.TypeIdentifierAttribute..ctor' is not defined.
Dim x As S = Nothing
~~~~~~~
</errors>
Dim compilation0 = CreateEmptyCompilationWithReferences(sources0, references:={MscorlibRef_v20})
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, <errors/>)
Dim compilation1 = CreateEmptyCompilationWithReferences(
sources1,
references:={MscorlibRef_v20, New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
compilation1 = CreateEmptyCompilationWithReferences(
sources1,
references:={MscorlibRef_v20, compilation0.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
End Sub
<Fact()>
Public Sub TypeIdentifierIsMissing2()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Class C
Function F() As Object
Dim y = DirectCast(Nothing, I)
Return y
End Function
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC35000: Requested operation is not available because the runtime library function 'System.Runtime.InteropServices.TypeIdentifierAttribute..ctor' is not defined.
Dim y = DirectCast(Nothing, I)
~
</errors>
Dim compilation0 = CreateEmptyCompilationWithReferences(sources0, references:={MscorlibRef_v20})
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim compilation1 = CreateEmptyCompilationWithReferences(
sources1,
options:=TestOptions.DebugDll,
references:={MscorlibRef_v20, New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
compilation1 = CreateEmptyCompilationWithReferences(
sources1,
options:=TestOptions.DebugDll,
references:={MscorlibRef_v20, compilation0.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
End Sub
<Fact()>
Public Sub LocalTypeMetadata_Simple()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
Public Interface ITest1
End Interface
Public Structure Test2
Implements ITest1
End Structure
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58259")>
Public Interface ITest3
Inherits ITest1
End Interface
Public Interface ITest4
End Interface
<Serializable()>
<StructLayout(LayoutKind.Explicit, CharSet:=CharSet.Unicode, Pack:=16, Size:=64)>
Public Structure Test5
<FieldOffset(2)>
Public F5 As Integer
End Structure
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58260")>
Public Interface ITest6
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58261")>
Public Interface ITest7
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58262")>
Public Interface ITest8
End Interface
Public Enum Test9
F1 = 1
F2 = 2
End Enum
<Serializable()>
<StructLayout(LayoutKind.Sequential)>
Public Structure Test10
<NonSerialized()>
Public F3 As Integer
<MarshalAs(UnmanagedType.U4)>
Public F4 As Integer
End Structure
Public Delegate Sub Test11()
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58264")>
Public Interface ITest13
Sub M13(x As Integer)
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58265")>
Public Interface ITest14
Sub M14()
WriteOnly Property P6 As Integer
Event E4 As Action
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58266")>
Public Interface ITest15
Inherits ITest14
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58267")>
Public Interface ITest16
Sub M16()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58268")>
Public Interface ITest17
Sub M17()
Sub _VtblGap()
Sub M18()
Sub _VtblGap3_2()
Sub M19()
Sub _VtblGap4_2()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58269")>
Public Interface ITest18
Sub _VtblGap3_2()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58270")>
Public Interface ITest19
Function M20(ByRef x As Integer, ByRef y As Integer, <[In]()> ByRef z As Integer, <[In](), Out()> ByRef u As Integer, <[Optional]()> v As Integer, Optional w As Integer = 34) As String
Function M21(<MarshalAs(UnmanagedType.U4)> x As Integer) As <MarshalAs(UnmanagedType.LPWStr)> String
End Interface
Public Structure Test20
End Structure
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface ITest21
<SpecialName()>
Property P1 As Integer
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58272")>
Public Interface ITest22
Property P2 As Integer
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58273")>
Public Interface ITest23
ReadOnly Property P3 As Integer
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58274")>
Public Interface ITest24
WriteOnly Property P4 As Integer
Event E3 As Action
Sub M27()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58275")>
Public Interface ITest25
<SpecialName()>
Event E1 As Action
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58276")>
Public Interface ITest26
Event E2 As Action
WriteOnly Property P5 As Integer
Sub M26()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Imports System
Class UsePia
Shared Sub Main()
Dim x As New Test2()
Dim y As ITest3 = Nothing
Console.WriteLine(x)
Console.WriteLine(y)
Dim x5 As New Test5()
Console.WriteLine(x5)
End Sub
<MyAttribute(GetType(ITest7))>
Sub M2(x As ITest6)
End Sub
End Class
Class UsePia1
Implements ITest8
End Class
Class MyAttribute
Inherits Attribute
Public Sub New(type As Type)
End Sub
End Class
Class UsePia2
Sub Test(x As Test10, x11 As Test11)
Console.WriteLine(Test9.F1.ToString())
Console.WriteLine(x.F4)
Dim y As ITest17 = Nothing
y.M17()
y.M19()
End Sub
End Class
Class UsePia3
Implements ITest13
Sub M13(x As Integer) Implements ITest13.M13
End Sub
Sub M14(x As ITest13)
x.M13(1)
x.M13(1)
End Sub
End Class
Interface IUsePia4
Inherits ITest15, ITest16, ITest18, ITest19
End Interface
Class UsePia4
Public Function M1(x As ITest21) As Integer
Return x.P1
End Function
Public Sub M2(x As ITest22)
x.P2 = 1
End Sub
Public Function M3(x As ITest23) As Integer
Return x.P3
End Function
Public Sub M4(x As ITest24)
x.P4 = 1
End Sub
Public Sub M5(x As ITest25)
AddHandler x.E1, Nothing
End Sub
Public Sub M6(x As ITest26)
RemoveHandler x.E2, Nothing
End Sub
End Class
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim itest1 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest1")
Assert.Equal(TypeKind.Interface, itest1.TypeKind)
Assert.Null(itest1.BaseType)
Assert.Equal(0, itest1.Interfaces.Length)
Assert.True(itest1.IsComImport)
Assert.False(itest1.IsSerializable)
Assert.False(itest1.IsNotInheritable)
Assert.Equal(System.Runtime.InteropServices.CharSet.Ansi, itest1.MarshallingCharSet)
Assert.Equal(System.Runtime.InteropServices.LayoutKind.Auto, itest1.Layout.Kind)
Assert.Equal(0, itest1.Layout.Alignment)
Assert.Equal(0, itest1.Layout.Size)
Dim attributes = itest1.GetAttributes()
Assert.Equal(3, attributes.Length)
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes(0).ToString())
Assert.Equal("System.Runtime.InteropServices.GuidAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58258"")", attributes(1).ToString())
Assert.Equal("System.Runtime.InteropServices.TypeIdentifierAttribute", attributes(2).ToString())
' TypDefName: ITest1 (02000018)
' Flags : [Public] [AutoLayout] [Interface] [Abstract] [Import] [AnsiClass] (000010a1)
Assert.Equal(TypeAttributes.Public Or TypeAttributes.AutoLayout Or TypeAttributes.Interface Or TypeAttributes.Abstract Or TypeAttributes.Import Or TypeAttributes.AnsiClass, itest1.TypeDefFlags)
Dim test2 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("Test2")
Assert.Equal(TypeKind.Structure, test2.TypeKind)
Assert.Equal(SpecialType.System_ValueType, test2.BaseType.SpecialType)
Assert.Same(itest1, test2.Interfaces.Single())
Assert.False(test2.IsComImport)
Assert.False(test2.IsSerializable)
Assert.True(test2.IsNotInheritable)
Assert.Equal(System.Runtime.InteropServices.CharSet.Ansi, test2.MarshallingCharSet)
Assert.Equal(System.Runtime.InteropServices.LayoutKind.Sequential, test2.Layout.Kind)
Assert.Equal(0, test2.Layout.Alignment)
Assert.Equal(1, test2.Layout.Size)
' TypDefName: Test2 (02000013)
' Flags : [Public] [SequentialLayout] [Class] [Sealed] [AnsiClass] [BeforeFieldInit] (00100109)
Assert.Equal(TypeAttributes.Public Or TypeAttributes.SequentialLayout Or TypeAttributes.Class Or TypeAttributes.Sealed Or TypeAttributes.AnsiClass Or TypeAttributes.BeforeFieldInit, test2.TypeDefFlags)
attributes = test2.GetAttributes()
Assert.Equal(2, attributes.Length)
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes(0).ToString())
Assert.Equal("System.Runtime.InteropServices.TypeIdentifierAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"", ""Test2"")", attributes(1).ToString())
Dim itest3 = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("ITest3")
Assert.Equal(TypeKind.Interface, itest3.TypeKind)
Assert.Same(itest1, itest3.Interfaces.Single())
Assert.True(itest3.IsComImport)
Assert.False(itest3.IsSerializable)
Assert.False(itest3.IsNotInheritable)
Assert.Equal(System.Runtime.InteropServices.CharSet.Ansi, itest3.MarshallingCharSet)
Assert.Equal(System.Runtime.InteropServices.LayoutKind.Auto, itest3.Layout.Kind)
Assert.Equal(0, itest3.Layout.Alignment)
Assert.Equal(0, itest3.Layout.Size)
Assert.Equal(0, [module].GlobalNamespace.GetTypeMembers("ITest4").Length)
Dim test5 = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test5")
Assert.Equal(TypeKind.Structure, test5.TypeKind)
Assert.False(test5.IsComImport)
Assert.True(test5.IsSerializable)
Assert.True(test5.IsNotInheritable)
Assert.Equal(System.Runtime.InteropServices.CharSet.Unicode, test5.MarshallingCharSet)
Assert.Equal(System.Runtime.InteropServices.LayoutKind.Explicit, test5.Layout.Kind)
Assert.Equal(16, test5.Layout.Alignment)
Assert.Equal(64, test5.Layout.Size)
Dim f5 = DirectCast(test5.GetMembers()(0), PEFieldSymbol)
Assert.Equal("Test5.F5 As System.Int32", f5.ToTestDisplayString())
Assert.Equal(2, f5.TypeLayoutOffset.Value)
' Field Name: F5 (04000003)
' Flags : [Public] (00000006)
Assert.Equal(FieldAttributes.Public, f5.FieldFlags)
Dim itest6 = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("ITest6")
Assert.Equal(TypeKind.Interface, itest6.TypeKind)
Dim itest7 = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("ITest7")
Assert.Equal(TypeKind.Interface, itest7.TypeKind)
Dim itest8 = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("ITest8")
Assert.Equal(TypeKind.Interface, itest8.TypeKind)
Assert.Same(itest8, [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("UsePia1").Interfaces.Single())
Dim test9 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("Test9")
Assert.Equal(TypeKind.Enum, test9.TypeKind)
Assert.False(test9.IsComImport)
Assert.False(test9.IsSerializable)
Assert.True(test9.IsNotInheritable)
Assert.Equal(System.Runtime.InteropServices.CharSet.Ansi, test9.MarshallingCharSet)
Assert.Equal(System.Runtime.InteropServices.LayoutKind.Auto, test9.Layout.Kind)
Assert.Equal(SpecialType.System_Int32, test9.EnumUnderlyingType.SpecialType)
' TypDefName: Test9 (02000016)
' Flags : [Public] [AutoLayout] [Class] [Sealed] [AnsiClass] (00000101)
Assert.Equal(TypeAttributes.Public Or TypeAttributes.AutoLayout Or TypeAttributes.Class Or TypeAttributes.Sealed Or TypeAttributes.AnsiClass, test9.TypeDefFlags)
attributes = test9.GetAttributes()
Assert.Equal(2, attributes.Length)
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes(0).ToString())
Assert.Equal("System.Runtime.InteropServices.TypeIdentifierAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"", ""Test9"")", attributes(1).ToString())
Dim fieldToEmit = test9.GetFieldsToEmit().ToArray().AsImmutableOrNull()
Assert.Equal(3, fieldToEmit.Length)
Dim value__ = DirectCast(fieldToEmit(0), PEFieldSymbol)
Assert.Equal(Accessibility.Public, value__.DeclaredAccessibility)
Assert.Equal("Test9.value__ As System.Int32", value__.ToTestDisplayString())
Assert.False(value__.IsShared)
Assert.True(value__.HasSpecialName)
Assert.True(value__.HasRuntimeSpecialName)
Assert.Null(value__.ConstantValue)
' Field Name: value__ (04000004)
' Flags : [Public] [SpecialName] [RTSpecialName] (00000606)
Assert.Equal(FieldAttributes.Public Or FieldAttributes.SpecialName Or FieldAttributes.RTSpecialName, value__.FieldFlags)
Dim f1 = DirectCast(fieldToEmit(1), PEFieldSymbol)
Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility)
Assert.Equal("Test9.F1", f1.ToTestDisplayString())
Assert.True(f1.IsShared)
Assert.False(f1.HasSpecialName)
Assert.False(f1.HasRuntimeSpecialName)
Assert.Equal(1, f1.ConstantValue)
' Field Name: F1 (04000005)
' Flags : [Public] [Static] [Literal] [HasDefault] (00008056)
Assert.Equal(FieldAttributes.Public Or FieldAttributes.Static Or FieldAttributes.Literal Or FieldAttributes.HasDefault, f1.FieldFlags)
Dim f2 = DirectCast(fieldToEmit(2), PEFieldSymbol)
Assert.Equal("Test9.F2", f2.ToTestDisplayString())
Assert.Equal(2, f2.ConstantValue)
Assert.Equal(4, test9.GetMembers().Length)
Assert.Equal("Test9.value__ As System.Int32", test9.GetMembers()(0).ToTestDisplayString())
Assert.Same(f1, test9.GetMembers()(1))
Assert.Same(f2, test9.GetMembers()(2))
Assert.True(DirectCast(test9.GetMembers()(3), MethodSymbol).IsDefaultValueTypeConstructor())
Dim test10 = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test10")
Assert.Equal(TypeKind.Structure, test10.TypeKind)
Assert.Equal(System.Runtime.InteropServices.LayoutKind.Sequential, test10.Layout.Kind)
Assert.Equal(3, test10.GetMembers().Length)
Dim f3 = DirectCast(test10.GetMembers()(0), FieldSymbol)
Assert.Equal(Accessibility.Public, f3.DeclaredAccessibility)
Assert.Equal("Test10.F3 As System.Int32", f3.ToTestDisplayString())
Assert.False(f3.IsShared)
Assert.False(f3.HasSpecialName)
Assert.False(f3.HasRuntimeSpecialName)
Assert.Null(f3.ConstantValue)
Assert.Equal(0, f3.MarshallingType)
Assert.False(f3.TypeLayoutOffset.HasValue)
Assert.True(f3.IsNotSerialized)
Dim f4 = DirectCast(test10.GetMembers()(1), FieldSymbol)
Assert.Equal("Test10.F4 As System.Int32", f4.ToTestDisplayString())
Assert.Equal(System.Runtime.InteropServices.UnmanagedType.U4, f4.MarshallingType)
Assert.False(f4.IsNotSerialized)
Assert.True(DirectCast(test10.GetMembers()(2), MethodSymbol).IsDefaultValueTypeConstructor())
Dim test11 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("Test11")
Assert.Equal(TypeKind.Delegate, test11.TypeKind)
Assert.Equal(SpecialType.System_MulticastDelegate, test11.BaseType.SpecialType)
' TypDefName: Test11 (02000012)
' Flags : [Public] [AutoLayout] [Class] [Sealed] [AnsiClass] (00000101)
Assert.Equal(TypeAttributes.Public Or TypeAttributes.AutoLayout Or TypeAttributes.Class Or TypeAttributes.Sealed Or TypeAttributes.AnsiClass, test11.TypeDefFlags)
attributes = test11.GetAttributes()
Assert.Equal(2, attributes.Length)
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes(0).ToString())
Assert.Equal("System.Runtime.InteropServices.TypeIdentifierAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"", ""Test11"")", attributes(1).ToString())
Assert.Equal(4, test11.GetMembers().Length)
Dim ctor = DirectCast(test11.GetMethod(".ctor"), PEMethodSymbol)
' MethodName: .ctor (0600000F)
' Flags : [Public] [ReuseSlot] [SpecialName] [RTSpecialName] [.ctor] (00001886)
' ImplFlags : [Runtime] [Managed] (00000003)
' CallCnvntn: [DEFAULT]
' hasThis
' ReturnType: Void
' 2 Arguments
' Argument #1: Object
' Argument #2: I
Assert.Equal(MethodAttributes.Public Or MethodAttributes.ReuseSlot Or MethodAttributes.SpecialName Or MethodAttributes.RTSpecialName, ctor.MethodFlags)
Assert.Equal(MethodImplAttributes.Runtime, ctor.ImplementationAttributes)
Assert.Equal(Microsoft.Cci.CallingConvention.Default Or Microsoft.Cci.CallingConvention.HasThis, ctor.CallingConvention)
Assert.Equal("Sub Test11..ctor(TargetObject As System.Object, TargetMethod As System.IntPtr)", ctor.ToTestDisplayString())
Dim begin = test11.GetMember(Of PEMethodSymbol)("BeginInvoke")
' MethodName: BeginInvoke (06000011)
' Flags : [Public] [Virtual] [CheckAccessOnOverride] [NewSlot] (000001c6)
' ImplFlags : [Runtime] [Managed] (00000003)
' CallCnvntn: [DEFAULT]
' hasThis
' ReturnType: Class System.IAsyncResult
' 2 Arguments
' Argument #1: Class System.AsyncCallback
' Argument #2: Object
Assert.Equal(MethodAttributes.Public Or MethodAttributes.Virtual Or MethodAttributes.CheckAccessOnOverride Or MethodAttributes.NewSlot, begin.MethodFlags)
Assert.Equal(MethodImplAttributes.Runtime, begin.ImplementationAttributes)
Assert.Equal(Microsoft.Cci.CallingConvention.Default Or Microsoft.Cci.CallingConvention.HasThis, begin.CallingConvention)
Assert.Equal("Function Test11.BeginInvoke(DelegateCallback As System.AsyncCallback, DelegateAsyncState As System.Object) As System.IAsyncResult", begin.ToTestDisplayString())
Dim [end] = test11.GetMember(Of PEMethodSymbol)("EndInvoke")
' MethodName: EndInvoke (06000012)
' Flags : [Public] [Virtual] [CheckAccessOnOverride] [NewSlot] (000001c6)
' ImplFlags : [Runtime] [Managed] (00000003)
' CallCnvntn: [DEFAULT]
' hasThis
' ReturnType: Void
' 1 Arguments
' Argument #1: Class System.IAsyncResult
Assert.Equal(MethodAttributes.Public Or MethodAttributes.Virtual Or MethodAttributes.CheckAccessOnOverride Or MethodAttributes.NewSlot, [end].MethodFlags)
Assert.Equal(MethodImplAttributes.Runtime, [end].ImplementationAttributes)
Assert.Equal(Microsoft.Cci.CallingConvention.Default Or Microsoft.Cci.CallingConvention.HasThis, [end].CallingConvention)
Assert.Equal("Sub Test11.EndInvoke(DelegateAsyncResult As System.IAsyncResult)", [end].ToTestDisplayString())
Dim invoke = test11.GetMember(Of PEMethodSymbol)("Invoke")
' MethodName: Invoke (06000010)
' Flags : [Public] [Virtual] [CheckAccessOnOverride] [NewSlot] (000001c6)
' ImplFlags : [Runtime] [Managed] (00000003)
' CallCnvntn: [DEFAULT]
' hasThis
' ReturnType: Void
' No arguments.
Assert.Equal(MethodAttributes.Public Or MethodAttributes.Virtual Or MethodAttributes.CheckAccessOnOverride Or MethodAttributes.NewSlot, invoke.MethodFlags)
Assert.Equal(MethodImplAttributes.Runtime, invoke.ImplementationAttributes)
Assert.Equal(Microsoft.Cci.CallingConvention.Default Or Microsoft.Cci.CallingConvention.HasThis, invoke.CallingConvention)
Assert.Equal("Sub Test11.Invoke()", invoke.ToTestDisplayString())
Dim itest13 = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("ITest13")
Assert.Equal(TypeKind.Interface, itest13.TypeKind)
Dim m13 = DirectCast(itest13.GetMembers()(0), PEMethodSymbol)
' MethodName: M13 (06000001)
' Flags : [Public] [Virtual] [CheckAccessOnOverride] [NewSlot] [Abstract] (000005c6)
' ImplFlags : [IL] [Managed] (00000000)
' CallCnvntn: [DEFAULT]
' hasThis
' ReturnType: Void
' 1 Arguments
' Argument #1: I4
' 1 Parameters
' (1) ParamToken : (08000001) Name : x flags: [none] (00000000)
Assert.Equal(MethodAttributes.Public Or MethodAttributes.Virtual Or MethodAttributes.CheckAccessOnOverride Or MethodAttributes.NewSlot Or MethodAttributes.Abstract, m13.MethodFlags)
Assert.Equal(MethodImplAttributes.IL, m13.ImplementationAttributes)
Assert.Equal(Microsoft.Cci.CallingConvention.HasThis, m13.CallingConvention)
Assert.Equal("Sub ITest13.M13(x As System.Int32)", m13.ToTestDisplayString())
Dim itest14 = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("ITest14")
Assert.Equal(TypeKind.Interface, itest14.TypeKind)
Assert.Equal(6, itest14.GetMembers().Length)
Assert.Equal("Sub ITest14.M14()", itest14.GetMembers()(0).ToTestDisplayString())
Assert.Equal("Sub ITest14.set_P6(Value As System.Int32)", itest14.GetMembers()(1).ToTestDisplayString())
Assert.Equal("Sub ITest14.add_E4(obj As System.Action)", itest14.GetMembers()(2).ToTestDisplayString())
Assert.Equal("Sub ITest14.remove_E4(obj As System.Action)", itest14.GetMembers()(3).ToTestDisplayString())
Assert.Equal("WriteOnly Property ITest14.P6 As System.Int32", itest14.GetMembers()(4).ToTestDisplayString())
Assert.Equal("Event ITest14.E4 As System.Action", itest14.GetMembers()(5).ToTestDisplayString())
Dim itest16 = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("ITest16")
Assert.Equal(TypeKind.Interface, itest16.TypeKind)
Assert.Equal("Sub ITest16.M16()", itest16.GetMembers()(0).ToTestDisplayString())
Dim itest17 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest17")
Assert.Equal(TypeKind.Interface, itest17.TypeKind)
Dim metadata = DirectCast([module], PEModuleSymbol).Module
Dim methodNames = metadata.GetMethodsOfTypeOrThrow(itest17.Handle).AsEnumerable().Select(
Function(rid) metadata.GetMethodDefNameOrThrow(rid)).ToArray()
Assert.Equal(3, methodNames.Length)
Assert.Equal("M17", methodNames(0))
Assert.Equal("_VtblGap1_4", methodNames(1))
Assert.Equal("M19", methodNames(2))
Dim gapMethodDef = metadata.GetMethodsOfTypeOrThrow(itest17.Handle).AsEnumerable().ElementAt(1)
Dim name As String = Nothing
Dim implFlags As MethodImplAttributes = Nothing
Dim flags As MethodAttributes = Nothing
Dim rva As Integer = Nothing
metadata.GetMethodDefPropsOrThrow(gapMethodDef, name, implFlags, flags, rva)
Assert.Equal(MethodAttributes.Public Or MethodAttributes.RTSpecialName Or MethodAttributes.SpecialName, flags)
Assert.Equal(MethodImplAttributes.IL Or MethodImplAttributes.Runtime, implFlags)
Dim signatureHeader As SignatureHeader = Nothing
Dim mrEx As BadImageFormatException = Nothing
Dim paramInfo = New MetadataDecoder(DirectCast([module], PEModuleSymbol), itest17).GetSignatureForMethod(gapMethodDef, signatureHeader:=signatureHeader, metadataException:=mrEx)
Assert.Null(mrEx)
Assert.Equal(CByte(SignatureCallingConvention.Default) Or CByte(SignatureAttributes.Instance), signatureHeader.RawValue)
Assert.Equal(1, paramInfo.Length)
Assert.Equal(SpecialType.System_Void, paramInfo(0).Type.SpecialType)
Assert.False(paramInfo(0).IsByRef)
Assert.True(paramInfo(0).CustomModifiers.IsDefault)
Assert.Equal(2, itest17.GetMembers().Length)
Dim m17 = itest17.GetMember(Of PEMethodSymbol)("M17")
' MethodName: M17 (06000013)
' Flags : [Public] [Virtual] [CheckAccessOnOverride] [NewSlot] [Abstract] (000005c6)
' ImplFlags : [IL] [Managed] (00000000)
' CallCnvntn: [DEFAULT]
' hasThis
' ReturnType: Void
' No arguments.
Assert.Equal(MethodAttributes.Public Or MethodAttributes.Virtual Or MethodAttributes.CheckAccessOnOverride Or MethodAttributes.NewSlot Or MethodAttributes.Abstract, m17.MethodFlags)
Assert.Equal(MethodImplAttributes.IL, m17.ImplementationAttributes)
Assert.Equal(Microsoft.Cci.CallingConvention.Default Or Microsoft.Cci.CallingConvention.HasThis, m17.CallingConvention)
Assert.Equal("Sub ITest17.M17()", m17.ToTestDisplayString())
Dim itest18 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest18")
Assert.Equal(TypeKind.Interface, itest18.TypeKind)
Assert.False(metadata.GetMethodsOfTypeOrThrow(itest18.Handle).AsEnumerable().Any())
Dim itest19 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest19")
Dim m20 = itest19.GetMember(Of PEMethodSymbol)("M20")
' 6 Arguments
' Argument #1: ByRef I4
' Argument #2: ByRef I4
' Argument #3: ByRef I4
' Argument #4: ByRef I4
' Argument #5: I4
' Argument #6: I4
' 6 Parameters
' (1) ParamToken : (08000008) Name : x flags: [none] (00000000)
' (2) ParamToken : (08000009) Name : y flags: [none] (00000000)
' (3) ParamToken : (0800000a) Name : z flags: [In] (00000001)
' (4) ParamToken : (0800000b) Name : u flags: [In] [Out] (00000003)
' (5) ParamToken : (0800000c) Name : v flags: [Optional] (00000010)
' (6) ParamToken : (0800000d) Name : w flags: [Optional] [HasDefault] (00001010) Default: (I4) 34
Dim param = DirectCast(m20.Parameters(0), PEParameterSymbol)
Assert.True(param.IsByRef)
Assert.Equal(ParameterAttributes.None, param.ParamFlags)
param = DirectCast(m20.Parameters(1), PEParameterSymbol)
Assert.True(param.IsByRef)
Assert.Equal(ParameterAttributes.None, param.ParamFlags)
param = DirectCast(m20.Parameters(2), PEParameterSymbol)
Assert.True(param.IsByRef)
Assert.Equal(ParameterAttributes.In, param.ParamFlags)
param = DirectCast(m20.Parameters(3), PEParameterSymbol)
Assert.True(param.IsByRef)
Assert.Equal(ParameterAttributes.In Or ParameterAttributes.Out, param.ParamFlags)
param = DirectCast(m20.Parameters(4), PEParameterSymbol)
Assert.False(param.IsByRef)
Assert.Equal(ParameterAttributes.Optional, param.ParamFlags)
Assert.Null(param.ExplicitDefaultConstantValue)
param = DirectCast(m20.Parameters(5), PEParameterSymbol)
Assert.False(param.IsByRef)
Assert.Equal(ParameterAttributes.Optional Or ParameterAttributes.HasDefault, param.ParamFlags)
Assert.Equal(34, param.ExplicitDefaultValue)
Assert.False(m20.ReturnValueIsMarshalledExplicitly)
Dim m21 = itest19.GetMember(Of PEMethodSymbol)("M21")
' 1 Arguments
' Argument #1: I4
' 2 Parameters
' (0) ParamToken : (0800000e) Name : flags: [HasFieldMarshal] (00002000)
' NATIVE_TYPE_LPWSTR
' (1) ParamToken : (0800000f) Name : x flags: [HasFieldMarshal] (00002000)
' NATIVE_TYPE_U4
param = DirectCast(m21.Parameters(0), PEParameterSymbol)
Assert.Equal(ParameterAttributes.HasFieldMarshal, param.ParamFlags)
Assert.Equal(System.Runtime.InteropServices.UnmanagedType.U4, CType(param.MarshallingDescriptor(0), System.Runtime.InteropServices.UnmanagedType))
Assert.True(m21.ReturnValueIsMarshalledExplicitly)
Assert.Equal(System.Runtime.InteropServices.UnmanagedType.LPWStr, CType(m21.ReturnValueMarshallingDescriptor(0), System.Runtime.InteropServices.UnmanagedType))
Dim itest21 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest21")
Dim p1 = itest21.GetMember(Of PEPropertySymbol)("P1")
Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility)
Assert.True(p1.HasSpecialName)
Assert.False(p1.HasRuntimeSpecialName)
Dim get_P1 = itest21.GetMember(Of PEMethodSymbol)("get_P1")
Dim set_P1 = itest21.GetMember(Of PEMethodSymbol)("set_P1")
Assert.Same(p1.GetMethod, get_P1)
Assert.Same(p1.SetMethod, set_P1)
Dim itest22 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest22")
Dim p2 = itest22.GetMember(Of PEPropertySymbol)("P2")
Dim get_P2 = itest22.GetMember(Of PEMethodSymbol)("get_P2")
Dim set_P2 = itest22.GetMember(Of PEMethodSymbol)("set_P2")
Assert.Same(p2.GetMethod, get_P2)
Assert.Same(p2.SetMethod, set_P2)
Dim itest23 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest23")
Dim p3 = itest23.GetMember(Of PEPropertySymbol)("P3")
Dim get_P3 = itest23.GetMember(Of PEMethodSymbol)("get_P3")
Assert.Same(p3.GetMethod, get_P3)
Assert.Null(p3.SetMethod)
Dim itest24 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest24")
Dim p4 = itest24.GetMember(Of PEPropertySymbol)("P4")
Assert.Equal(2, itest24.GetMembers().Length)
Assert.False(p4.HasSpecialName)
Assert.False(p4.HasRuntimeSpecialName)
Assert.Equal(CByte(SignatureKind.Property) Or CByte(SignatureAttributes.Instance), CByte(p4.CallingConvention))
Dim set_P4 = itest24.GetMember(Of PEMethodSymbol)("set_P4")
Assert.Null(p4.GetMethod)
Assert.Same(p4.SetMethod, set_P4)
Dim itest25 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest25")
Dim e1 = itest25.GetMember(Of PEEventSymbol)("E1")
Assert.True(e1.HasSpecialName)
Assert.False(e1.HasRuntimeSpecialName)
Dim add_E1 = itest25.GetMember(Of PEMethodSymbol)("add_E1")
Dim remove_E1 = itest25.GetMember(Of PEMethodSymbol)("remove_E1")
Assert.Same(e1.AddMethod, add_E1)
Assert.Same(e1.RemoveMethod, remove_E1)
Dim itest26 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest26")
Dim e2 = itest26.GetMember(Of PEEventSymbol)("E2")
Assert.Equal(3, itest26.GetMembers().Length)
Assert.False(e2.HasSpecialName)
Assert.False(e2.HasRuntimeSpecialName)
Dim add_E2 = itest26.GetMember(Of PEMethodSymbol)("add_E2")
Dim remove_E2 = itest26.GetMember(Of PEMethodSymbol)("remove_E2")
Assert.Same(e2.AddMethod, add_E2)
Assert.Same(e2.RemoveMethod, remove_E2)
End Sub
Dim expected_M5 = <![CDATA[
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: nop
IL_0001: ldarg.1
IL_0002: ldnull
IL_0003: callvirt "Sub ITest25.add_E1(System.Action)"
IL_0008: nop
IL_0009: ret
}
]]>
Dim expected_M6 = <![CDATA[
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: nop
IL_0001: ldarg.1
IL_0002: ldnull
IL_0003: callvirt "Sub ITest26.remove_E2(System.Action)"
IL_0008: nop
IL_0009: ret
}
]]>
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
options:=TestOptions.DebugExe,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
verifier.VerifyDiagnostics()
verifier.VerifyIL("UsePia4.M5", expected_M5)
verifier.VerifyIL("UsePia4.M6", expected_M6)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
options:=TestOptions.DebugExe,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
verifier.VerifyDiagnostics()
verifier.VerifyIL("UsePia4.M5", expected_M5)
verifier.VerifyIL("UsePia4.M6", expected_M6)
End Sub
<Fact()>
Public Sub LocalTypeMetadata_GenericParameters()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58277")>
Public Interface I1
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
Public Interface I2
Sub M(Of T1, T2 As I1, T3 As New, T4 As Structure, T5 As Class, T6 As T1)
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Interface I3
Inherits I2
End Interface
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0, verify:=Verification.Fails)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type1 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I1")
Assert.Equal(TypeKind.Interface, type1.TypeKind)
Dim type2 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I2")
Assert.Equal(TypeKind.Interface, type2.TypeKind)
Dim method = type2.GetMember(Of PEMethodSymbol)("M")
Dim tp = method.TypeParameters
Assert.Equal(6, tp.Length)
Dim t1 = tp(0)
Assert.Equal("T1", t1.Name)
Assert.False(t1.HasConstructorConstraint)
Assert.False(t1.HasValueTypeConstraint)
Assert.False(t1.HasReferenceTypeConstraint)
Assert.Equal(0, t1.ConstraintTypes.Length)
Assert.Equal(VarianceKind.None, t1.Variance)
Dim t2 = tp(1)
Assert.Equal("T2", t2.Name)
Assert.False(t2.HasConstructorConstraint)
Assert.False(t2.HasValueTypeConstraint)
Assert.False(t2.HasReferenceTypeConstraint)
Assert.Equal(1, t2.ConstraintTypes.Length)
Assert.Same(type1, t2.ConstraintTypes(0))
Assert.Equal(VarianceKind.None, t2.Variance)
Dim t3 = tp(2)
Assert.Equal("T3", t3.Name)
Assert.True(t3.HasConstructorConstraint)
Assert.False(t3.HasValueTypeConstraint)
Assert.False(t3.HasReferenceTypeConstraint)
Assert.Equal(0, t3.ConstraintTypes.Length)
Assert.Equal(VarianceKind.None, t3.Variance)
Dim t4 = tp(3)
Assert.Equal("T4", t4.Name)
Assert.False(t4.HasConstructorConstraint)
Assert.True(t4.HasValueTypeConstraint)
Assert.False(t4.HasReferenceTypeConstraint)
Assert.Equal(0, t4.ConstraintTypes.Length)
Assert.Equal(VarianceKind.None, t4.Variance)
Dim t5 = tp(4)
Assert.Equal("T5", t5.Name)
Assert.False(t5.HasConstructorConstraint)
Assert.False(t5.HasValueTypeConstraint)
Assert.True(t5.HasReferenceTypeConstraint)
Assert.Equal(0, t5.ConstraintTypes.Length)
Assert.Equal(VarianceKind.None, t5.Variance)
Dim t6 = tp(5)
Assert.Equal("T6", t6.Name)
Assert.False(t6.HasConstructorConstraint)
Assert.False(t6.HasValueTypeConstraint)
Assert.False(t6.HasReferenceTypeConstraint)
Assert.Equal(1, t6.ConstraintTypes.Length)
Assert.Same(t1, t6.ConstraintTypes(0))
Assert.Equal(VarianceKind.None, t6.Variance)
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
options:=TestOptions.DebugDll,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True), SystemCoreRef})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator, verify:=Verification.Fails)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
options:=TestOptions.DebugDll,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True), SystemCoreRef})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator, verify:=Verification.Fails)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub NewWithoutCoClass()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58277")>
Public Interface I
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Structure S
Function F() As I
Return New I()
End Function
End Structure
]]></file>
</compilation>
Dim errors = <errors>
BC30375: 'New' cannot be used on an interface.
Return New I()
~~~~~~~
</errors>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
compilation0.AssertTheseDiagnostics()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, <errors/>)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, <errors/>)
End Sub
<Fact()>
Public Sub NewCoClassWithoutGiud()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58277")>
<CoClass(GetType(C))>
Public Interface I
Property P As Integer
End Interface
Public Class C
Public Sub New(o As Object)
End Sub
End Class
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Structure S
Function F() As I
Return New I() With {.P = 2}
End Function
End Structure
]]></file>
</compilation>
Dim errors = <errors>
BC31543: Interop type 'C' cannot be embedded because it is missing the required 'System.Runtime.InteropServices.GuidAttribute' attribute.
Return New I() With {.P = 2}
~~~~~~~~~~~~~~~~~~~~~
</errors>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
compilation0.AssertTheseDiagnostics()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
End Sub
<Fact()>
Public Sub NewCoClassWithGiud()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58277")>
<CoClass(GetType(C))>
Public Interface I
Property P As Integer
End Interface
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
Public MustInherit Class C
Protected Sub New(o As Object)
End Sub
End Class
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Structure S
Function F() As I
Return New I() With {.P = 2}
End Function
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Assert.Equal(1, [module].GetReferencedAssemblySymbols().Length)
Dim i = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim attr = i.GetAttributes("System.Runtime.InteropServices", "CoClassAttribute").Single()
Assert.Equal("System.Runtime.InteropServices.CoClassAttribute(GetType(Object))", attr.ToString())
End Sub
Dim compilation1 = CreateEmptyCompilationWithReferences(
sources1,
references:={MscorlibRef, SystemRef, compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
verifier.VerifyIL("S.F", <![CDATA[
{
// Code size 33 (0x21)
.maxstack 3
IL_0000: ldstr "f9c2d51d-4f44-45f0-9eda-c9d599b58278"
IL_0005: newobj "Sub System.Guid..ctor(String)"
IL_000a: call "Function System.Type.GetTypeFromCLSID(System.Guid) As System.Type"
IL_000f: call "Function System.Activator.CreateInstance(System.Type) As Object"
IL_0014: castclass "I"
IL_0019: dup
IL_001a: ldc.i4.2
IL_001b: callvirt "Sub I.set_P(Integer)"
IL_0020: ret
}
]]>)
compilation1 = CreateEmptyCompilationWithReferences(
sources1,
references:={MscorlibRef_v4_0_30316_17626, SystemRef, compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
verifier.VerifyIL("S.F", <![CDATA[
{
// Code size 33 (0x21)
.maxstack 3
IL_0000: ldstr "f9c2d51d-4f44-45f0-9eda-c9d599b58278"
IL_0005: newobj "Sub System.Guid..ctor(String)"
IL_000a: call "Function System.Runtime.InteropServices.Marshal.GetTypeFromCLSID(System.Guid) As System.Type"
IL_000f: call "Function System.Activator.CreateInstance(System.Type) As Object"
IL_0014: castclass "I"
IL_0019: dup
IL_001a: ldc.i4.2
IL_001b: callvirt "Sub I.set_P(Integer)"
IL_0020: ret
}
]]>)
End Sub
<Fact()>
Public Sub NewCoClassWithGiud_Generic()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58277")>
<CoClass(GetType(C(Of)))>
Public Interface I
End Interface
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
Public MustInherit Class C(Of T)
Protected Sub New(o As Object)
End Sub
End Class
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Function F() As I
Return New I()
End Function
End Module
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, <errors>
BC31450: Type 'C(Of )' cannot be used as an implementing class.
Return New I()
~~~~~~~
</errors>)
End Sub
''' <summary>
''' Report error attempting to instantiate NoPIA CoClass with arguments.
''' Note: Dev11 silently drops any arguments and does not report an error.
''' </summary>
<Fact()>
Public Sub NewCoClassWithArguments()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58277")>
<CoClass(GetType(C))>
Public Interface I
Property P As Integer
End Interface
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
Public Class C
Public Sub New(o As Object)
End Sub
End Class
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Structure S
Function F() As I
Return New I("")
End Function
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
compilation0.AssertTheseDiagnostics()
' No errors for /r:_.dll
Dim compilation1 = CreateEmptyCompilationWithReferences(
sources1,
references:={MscorlibRef, SystemRef, MetadataReference.CreateFromImage(compilation0.EmitToArray())})
compilation1.AssertTheseDiagnostics()
' Error for /l:_.dll
compilation1 = CreateEmptyCompilationWithReferences(
sources1,
references:={MscorlibRef, SystemRef, compilation0.EmitToImageReference(embedInteropTypes:=True)})
compilation1.AssertTheseDiagnostics(<errors>
BC30516: Overload resolution failed because no accessible 'New' accepts this number of arguments.
Return New I("")
~~~~~~~~~
</errors>)
' Verify the unused argument is available in the SemanticModel.
Dim syntaxTree = compilation1.SyntaxTrees(0)
Dim model = compilation1.GetSemanticModel(syntaxTree)
Dim node = DirectCast(syntaxTree.FindNodeOrTokenByKind(SyntaxKind.StringLiteralExpression).AsNode(), ExpressionSyntax)
Dim expr = model.GetTypeInfo(node)
Assert.Equal(expr.Type.SpecialType, SpecialType.System_String)
End Sub
<Fact()>
Public Sub NewCoClassMissingWellKnownMembers()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58277")>
<CoClass(GetType(C))>
Public Interface I
End Interface
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
Public Class C
End Class
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Namespace System
Public Class Guid
Private Sub New()
End Sub
End Class
Public Class Activator
End Class
End Namespace
]]></file>
<file name="b.vb"><![CDATA[
Structure S
Function F() As I
Dim x As New I()
Return x
End Function
End Structure
]]></file>
</compilation>
Dim errors = <errors>
BC35000: Requested operation is not available because the runtime library function 'System.Activator.CreateInstance' is not defined.
Dim x As New I()
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Guid..ctor' is not defined.
Dim x As New I()
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Type.GetTypeFromCLSID' is not defined.
Dim x As New I()
~~~~~~~
</errors>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
compilation0.AssertTheseDiagnostics()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
End Sub
' See C# AddHandler_Simple and RemoveHandler_Simple.
<Fact()>
Public Sub AddRemoveHandler()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Delegate Sub D()
<ComEventInterface(GetType(IE), GetType(Integer))>
Public Interface I1
Event E As D
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58277")>
Public Interface I2
Inherits I1
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
Public Interface IE
Sub E
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Class C
Sub Add(x As I1)
AddHandler x.E, AddressOf M
End Sub
Sub Remove(Of T As {Structure, I2})(x As T)
RemoveHandler x.E, AddressOf M
End Sub
Sub M()
End Sub
End Class
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(2, references.Length)
Assert.Equal("mscorlib", references(0).Name)
Assert.Equal("System.Core", references(1).Name)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I1")
Dim attributes = type.GetAttributes()
Assert.Equal(3, attributes.Length)
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes(0).ToString())
Assert.Equal("System.Runtime.InteropServices.ComEventInterfaceAttribute(GetType(IE), GetType(IE))", attributes(1).ToString())
Assert.Equal("System.Runtime.InteropServices.TypeIdentifierAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"", ""I1"")", attributes(2).ToString())
type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("IE")
attributes = type.GetAttributes()
Assert.Equal(3, attributes.Length)
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes(0).ToString())
Assert.Equal("System.Runtime.InteropServices.GuidAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")", attributes(1).ToString())
Assert.Equal("System.Runtime.InteropServices.TypeIdentifierAttribute", attributes(2).ToString())
Dim method = type.GetMember(Of PEMethodSymbol)("E")
Assert.NotNull(method)
End Sub
Dim expectedAdd = <![CDATA[
{
// Code size 41 (0x29)
.maxstack 4
IL_0000: nop
IL_0001: ldtoken "I1"
IL_0006: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_000b: ldstr "E"
IL_0010: newobj "Sub System.Runtime.InteropServices.ComAwareEventInfo..ctor(System.Type, String)"
IL_0015: ldarg.1
IL_0016: ldarg.0
IL_0017: ldftn "Sub C.M()"
IL_001d: newobj "Sub D..ctor(Object, System.IntPtr)"
IL_0022: callvirt "Sub System.Runtime.InteropServices.ComAwareEventInfo.AddEventHandler(Object, System.Delegate)"
IL_0027: nop
IL_0028: ret
}
]]>
Dim expectedRemove = <![CDATA[
{
// Code size 46 (0x2e)
.maxstack 4
IL_0000: nop
IL_0001: ldtoken "I1"
IL_0006: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_000b: ldstr "E"
IL_0010: newobj "Sub System.Runtime.InteropServices.ComAwareEventInfo..ctor(System.Type, String)"
IL_0015: ldarg.1
IL_0016: box "T"
IL_001b: ldarg.0
IL_001c: ldftn "Sub C.M()"
IL_0022: newobj "Sub D..ctor(Object, System.IntPtr)"
IL_0027: callvirt "Sub System.Runtime.InteropServices.ComAwareEventInfo.RemoveEventHandler(Object, System.Delegate)"
IL_002c: nop
IL_002d: ret
}
]]>
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
options:=TestOptions.DebugDll,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True), SystemCoreRef})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
verifier.VerifyIL("C.Add", expectedAdd)
verifier.VerifyIL("C.Remove(Of T)", expectedRemove)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
options:=TestOptions.DebugDll,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True), SystemCoreRef})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
verifier.VerifyIL("C.Add", expectedAdd)
verifier.VerifyIL("C.Remove(Of T)", expectedRemove)
End Sub
<Fact()>
Public Sub [RaiseEvent]()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Delegate Sub D()
<ComEventInterface(GetType(IE), GetType(Integer))>
Public Interface I
Event E As D
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
Public Interface IE
Sub E
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Class C
Implements I
Friend Event E As D Implements I.E
Sub Raise()
RaiseEvent E
End Sub
End Class
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Assert.Equal("mscorlib", references(0).Name)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim attributes = type.GetAttributes()
Assert.Equal(3, attributes.Length)
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes(0).ToString())
Assert.Equal("System.Runtime.InteropServices.ComEventInterfaceAttribute(GetType(IE), GetType(IE))", attributes(1).ToString())
Assert.Equal("System.Runtime.InteropServices.TypeIdentifierAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"", ""I"")", attributes(2).ToString())
type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("IE")
attributes = type.GetAttributes()
Assert.Equal(3, attributes.Length)
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes(0).ToString())
Assert.Equal("System.Runtime.InteropServices.GuidAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")", attributes(1).ToString())
Assert.Equal("System.Runtime.InteropServices.TypeIdentifierAttribute", attributes(2).ToString())
Dim method = type.GetMember(Of PEMethodSymbol)("E")
Assert.NotNull(method)
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
options:=TestOptions.DebugDll,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
options:=TestOptions.DebugDll,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<WorkItem(837420, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837420")>
<Fact()>
Public Sub BC31556ERR_SourceInterfaceMustBeInterface()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Delegate Sub D()
<ComEventInterface(GetType(Object()), GetType(Object))>
Public Interface I1
Event E As D
End Interface
<ComEventInterface(GetType(Object()), GetType(Object))>
Public Interface I2
Event E As D
End Interface
<ComEventInterface(Nothing, Nothing)>
Public Interface I3
Event E As D
End Interface
<ComEventInterface(Nothing, Nothing)>
Public Interface I4
Event E As D
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M1(x1 As I1)
AddHandler x1.E, AddressOf H
End Sub
Sub M2(x2 As I2)
End Sub
Sub M3(x3 As I3)
End Sub
Sub M4(x4 As I4)
AddHandler x4.E, AddressOf H
End Sub
Sub H()
End Sub
End Class
]]></file>
</compilation>
' Note: Dev12 reports errors for all four interfaces,
' even though only I1.E and I4.E are referenced.
Dim errors = <errors>
BC31556: Interface 'I1' has an invalid source interface which is required to embed event 'Event E As D'.
AddHandler x1.E, AddressOf H
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31556: Interface 'I4' has an invalid source interface which is required to embed event 'Event E As D'.
AddHandler x4.E, AddressOf H
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
compilation0.AssertTheseDiagnostics()
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True), SystemCoreRef})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, <errors/>)
compilation1 = CreateCompilationWithMscorlib40AndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True), SystemCoreRef})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, <errors/>)
End Sub
<Fact()>
Public Sub BC31557ERR_EventNoPIANoBackingMember()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Delegate Sub D()
<ComEventInterface(GetType(IE), GetType(Object))>
Public Interface I
Event E As D
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
Public Interface IE
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M1(x As I)
AddHandler x.E, AddressOf M2
End Sub
Sub M2()
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC31557: Source interface 'IE' is missing method 'E', which is required to embed event 'Event E As D'.
AddHandler x.E, AddressOf M2
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
compilation0.AssertTheseDiagnostics()
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True), SystemCoreRef})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, <errors/>)
compilation1 = CreateCompilationWithMscorlib40AndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True), SystemCoreRef})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, <errors/>)
End Sub
' See C# MissingComImport test.
<Fact()>
Public Sub BC31543ERR_NoPIAAttributeMissing2_ComImport()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Delegate Sub D()
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Event D As D
End Interface
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Sub M(o As I)
AddHandler o.D, Nothing
End Sub
End Module
]]></file>
</compilation>
Dim errors = <errors>
BC31543: Interop type 'I' cannot be embedded because it is missing the required 'System.Runtime.InteropServices.ComImportAttribute' attribute.
AddHandler o.D, Nothing
~~~~~~~~~~~~~~~~~~~~~~~
</errors>
Dim errorsMetadataOnly = <errors>
BC31543: Interop type 'I' cannot be embedded because it is missing the required 'System.Runtime.InteropServices.ComImportAttribute' attribute.
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errorsMetadataOnly)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation1.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errorsMetadataOnly)
End Sub
' See C# MissingGuid test.
<Fact()>
Public Sub BC31543ERR_NoPIAAttributeMissing2_Guid()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Delegate Sub D()
<ComImport()>
Public Interface I
Event D As D
End Interface
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Sub M(o As I)
AddHandler o.D, Nothing
End Sub
End Module
]]></file>
</compilation>
Dim errors = <errors>
BC31543: Interop type 'I' cannot be embedded because it is missing the required 'System.Runtime.InteropServices.GuidAttribute' attribute.
AddHandler o.D, Nothing
~~~~~~~~~~~~~~~~~~~~~~~
</errors>
Dim errorsMetadataOnly = <errors>
BC31543: Interop type 'I' cannot be embedded because it is missing the required 'System.Runtime.InteropServices.GuidAttribute' attribute.
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errorsMetadataOnly)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation1.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errorsMetadataOnly)
End Sub
<Fact()>
Public Sub InterfaceTypeAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
<InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface I1
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
<InterfaceType(CShort(ComInterfaceType.InterfaceIsIUnknown))>
Public Interface I2
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Implements I1, I2
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I1")
Dim attr = type.GetAttributes("System.Runtime.InteropServices", "InterfaceTypeAttribute").Single()
Assert.Equal("System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)", attr.ToString())
type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I2")
attr = type.GetAttributes("System.Runtime.InteropServices", "InterfaceTypeAttribute").Single()
Assert.Equal("System.Runtime.InteropServices.InterfaceTypeAttribute(1)", attr.ToString())
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub BestFitMappingAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
<BestFitMapping(True)>
Public Interface I1
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
<BestFitMapping(False)>
Public Interface I2
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Implements I1, I2
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I1")
Dim attr = type.GetAttributes("System.Runtime.InteropServices", "BestFitMappingAttribute").Single()
Assert.Equal("System.Runtime.InteropServices.BestFitMappingAttribute(True)", attr.ToString())
type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I2")
attr = type.GetAttributes("System.Runtime.InteropServices", "BestFitMappingAttribute").Single()
Assert.Equal("System.Runtime.InteropServices.BestFitMappingAttribute(False)", attr.ToString())
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub FlagsAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<Flags()>
Public Enum E
A = 0
End Enum
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Sub M(x As E)
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("E")
Dim attr = type.GetAttributes("System", "FlagsAttribute").Single()
Assert.Equal("System.FlagsAttribute", attr.ToString())
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub DefaultMemberAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Reflection
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
<DefaultMember("M")>
Public Interface I
Function M() As Integer()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Sub M(x As I)
x.M()
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim attr = type.GetAttributes("System.Reflection", "DefaultMemberAttribute").Single()
Assert.Equal("System.Reflection.DefaultMemberAttribute(""M"")", attr.ToString())
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub LCIDConversionAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
<LCIDConversion(123)>
Sub M()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Implements I
Private Sub M() Implements I.M
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim method = type.GetMember(Of PEMethodSymbol)("M")
Dim attr = method.GetAttributes("System.Runtime.InteropServices", "LCIDConversionAttribute").Single()
Assert.Equal("System.Runtime.InteropServices.LCIDConversionAttribute(123)", attr.ToString())
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub DispIdAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
<DispId(124)>
Sub M()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Implements I
Private Sub M() Implements I.M
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim method = type.GetMember(Of PEMethodSymbol)("M")
Dim attr = method.GetAttributes("System.Runtime.InteropServices", "DispIdAttribute").Single()
Assert.Equal("System.Runtime.InteropServices.DispIdAttribute(124)", attr.ToString())
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub ParamArrayAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Sub M(ParamArray x As Integer())
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Implements I
Private Sub M(ParamArray x As Integer()) Implements I.M
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim method = type.GetMember(Of PEMethodSymbol)("M")
Dim param = method.Parameters(0)
Assert.Equal(0, param.GetAttributes().Length)
Assert.True(param.IsParamArray)
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub DateTimeConstantAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Sub M(<[Optional](), DateTimeConstant(987654321)> x As DateTime)
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Sub M(x As I)
x.M()
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim method = type.GetMember(Of PEMethodSymbol)("M")
Assert.Equal(New Date(987654321), method.Parameters(0).ExplicitDefaultValue)
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
compilation1.AssertTheseDiagnostics(<errors>
BC30455: Argument not specified for parameter 'x' of 'Sub M(x As Date)'.
x.M()
~
</errors>)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub DecimalConstantAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Sub M1(<[Optional](), DecimalConstant(0, 0, Integer.MinValue, -2, -3)> x As Decimal)
Sub M2(<[Optional](), DecimalConstant(0, 0, UInteger.MaxValue, 2, 3)> x As Decimal)
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Sub M(x As I)
x.M1()
x.M2()
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim method = type.GetMember(Of PEMethodSymbol)("M1")
Assert.Equal(39614081275578912866186559485D, method.Parameters(0).ExplicitDefaultValue)
method = type.GetMember(Of PEMethodSymbol)("M2")
Assert.Equal(79228162495817593528424333315D, method.Parameters(0).ExplicitDefaultValue)
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
compilation1.AssertTheseDiagnostics(<errors>
BC30455: Argument not specified for parameter 'x' of 'Sub M1(x As Decimal)'.
x.M1()
~~
BC30455: Argument not specified for parameter 'x' of 'Sub M2(x As Decimal)'.
x.M2()
~~
</errors>)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub DefaultParameterValueAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Sub M(<[Optional](), DefaultParameterValue(123.456)> x As Decimal)
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Sub M(x As I)
x.M()
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40AndReferences(
sources0,
references:={SystemRef})
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(2, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim method = type.GetMember(Of PEMethodSymbol)("M")
Dim attr = method.Parameters(0).GetAttributes("System.Runtime.InteropServices", "DefaultParameterValueAttribute").Single()
Assert.Equal("System.Runtime.InteropServices.DefaultParameterValueAttribute(123.456)", attr.ToString())
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
compilation1.AssertTheseDiagnostics(<errors>
BC30455: Argument not specified for parameter 'x' of 'Sub M(x As Decimal)'.
x.M()
~
</errors>)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub UnmanagedFunctionPointerAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<UnmanagedFunctionPointerAttribute(CallingConvention.StdCall, SetLastError:=True)>
Public Delegate Sub D()
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Sub M(x As D)
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("D")
Dim attr = type.GetAttributes("System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute").Single()
Assert.Equal("System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute(System.Runtime.InteropServices.CallingConvention.StdCall, SetLastError:=True)", attr.ToString())
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub PreserveSigAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
<PreserveSig()>
Sub M()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Sub M(x As I)
x.M()
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim method = type.GetMember(Of PEMethodSymbol)("M")
Assert.Equal(MethodImplAttributes.IL Or MethodImplAttributes.PreserveSig, CType(method.ImplementationAttributes, MethodImplAttributes))
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
' See C# TypeNameConflict1 test.
<Fact()>
Public Sub BC31552ERR_DuplicateLocalTypes3()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I1
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58272")>
Public Interface I2
Inherits I1
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58256")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58273")>
Public Interface I1
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58274")>
Public Interface I3
Inherits I1
End Interface
]]></file>
</compilation>
Dim sources2 = <compilation name="2">
<file name="a.vb"><![CDATA[
Module M
Sub M(x As I2, y As I3)
End Sub
End Module
]]></file>
</compilation>
Dim errors = <errors>
BC31552: Cannot embed interop type 'I1' found in both assembly '0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and '1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Consider disabling the embedding of interop types.
</errors>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
VerifyEmitDiagnostics(compilation0)
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
VerifyEmitDiagnostics(compilation1)
' No errors for /r:0.dll /l:1.dll.
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=False), New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
' Errors for /l:0.dll /l:1.dll.
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True), New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True), compilation1.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
End Sub
' See C# TypeNameConflict2 test.
<Fact()>
Public Sub BC31560ERR_LocalTypeNameClash2()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I0
Sub M1(o As I1)
Sub M2(o As I2)
Sub M3(o As I3)
Sub M4(o As I4)
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58272")>
Public Interface I1
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58273")>
Public Interface I2
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58274")>
Public Interface I3
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58275")>
Public Interface I4
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Module M
Sub M(o As I0)
o.M1(Nothing)
o.M2(Nothing)
o.M3(Nothing)
End Sub
End Module
Class I1
End Class
Delegate Sub I2()
Structure I3
End Structure
Structure I4
End Structure
]]></file>
</compilation>
' Note: Dev11 does not report any errors although the
' generated assembly fails peverify in these cases.
Dim errors = <errors>
BC31560: Embedding the interop type 'I1' from assembly '0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' causes a name clash in the current assembly. Consider disabling the embedding of interop types.
BC31560: Embedding the interop type 'I2' from assembly '0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' causes a name clash in the current assembly. Consider disabling the embedding of interop types.
BC31560: Embedding the interop type 'I3' from assembly '0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' causes a name clash in the current assembly. Consider disabling the embedding of interop types.
</errors>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
VerifyEmitDiagnostics(compilation0)
' No errors for /r:0.dll.
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=False)})
VerifyEmitDiagnostics(compilation1)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=False)})
VerifyEmitDiagnostics(compilation1)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
' Errors for /l:0.dll.
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
End Sub
<Fact()>
Public Sub NoIndirectReference()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Sub M()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Public Class A
Public Shared F As Object
Private Shared Sub M(o As I)
End Sub
End Class
]]></file>
</compilation>
Dim sources2 = <compilation name="2">
<file name="a.vb"><![CDATA[
Class B
Private Shared Sub M(o As I)
End Sub
End Class
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation1)
AssertTheseDiagnostics(verifier, (<errors/>))
' No errors for /r:0.dll /r:1.dll.
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=False), New VisualBasicCompilationReference(compilation1, embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2)
AssertTheseDiagnostics(verifier, (<errors/>))
' Errors for /l:0.dll /r:1.dll.
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True), New VisualBasicCompilationReference(compilation1, embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True), compilation1.EmitToImageReference(embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True), New VisualBasicCompilationReference(compilation1, embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True), compilation1.EmitToImageReference(embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub IndirectReference()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Sub M()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Public Class A
Public Shared F As Object
Private Shared Sub M(o As I)
End Sub
End Class
]]></file>
</compilation>
Dim sources2 = <compilation name="2">
<file name="a.vb"><![CDATA[
Class B
Private Shared F = A.F
Private Shared Sub M(o As I)
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC40059: A reference was created to embedded interop assembly '0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' because of an indirect reference to that assembly from assembly '1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Consider changing the 'Embed Interop Types' property on either assembly.
</errors>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(2, references.Length)
Assert.Equal("1", references(1).Name)
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation1)
AssertTheseDiagnostics(verifier, (<errors/>))
' No errors for /r:0.dll /r:1.dll.
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=False), New VisualBasicCompilationReference(compilation1, embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2)
AssertTheseDiagnostics(verifier, (<errors/>))
' Errors for /l:0.dll /r:1.dll.
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True), New VisualBasicCompilationReference(compilation1, embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, errors)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True), compilation1.EmitToImageReference(embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, errors)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True), New VisualBasicCompilationReference(compilation1, embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, errors)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True), compilation1.EmitToImageReference(embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, errors)
End Sub
<Fact()>
Public Sub ImplementedInterfacesAndTheirMembers_1()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I1
Sub M1()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58272")>
Public Interface I2
Inherits I1
Sub M2()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58273")>
Public Interface I3
Inherits I2
Sub M3()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Interface I
Inherits I3
End Interface
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
CompileAndVerify(compilation0)
compilation0.AssertTheseDiagnostics()
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Assert.Equal(1, [module].GetReferencedAssemblySymbols().Length)
Dim i1 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I1")
Dim m1 = i1.GetMember(Of PEMethodSymbol)("M1")
Dim i2 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I2")
Dim m2 = i2.GetMember(Of PEMethodSymbol)("M2")
Dim i3 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I3")
Dim m3 = i3.GetMember(Of PEMethodSymbol)("M3")
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
CompileAndVerify(compilation1, symbolValidator:=validator)
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
CompileAndVerify(compilation2, symbolValidator:=validator)
End Sub
' See C# ImplementedInterfacesAndTheirMembers_2
' and ExplicitInterfaceImplementation tests.
<Fact()>
Public Sub ImplementedInterfacesAndTheirMembers_2()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I1
Sub M1()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58272")>
Public Interface I2
Inherits I1
Sub M2()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58273")>
Public Interface I3
Inherits I2
Sub M3()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Class C
Implements I3
Sub M() Implements I1.M1, I2.M2, I3.M3
End Sub
End Class
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
CompileAndVerify(compilation0)
compilation0.AssertTheseDiagnostics()
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Assert.Equal(1, [module].GetReferencedAssemblySymbols().Length)
Dim i1 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I1")
Dim m1 = i1.GetMember(Of PEMethodSymbol)("M1")
Dim i2 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I2")
Dim m2 = i2.GetMember(Of PEMethodSymbol)("M2")
Dim i3 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I3")
Dim m3 = i3.GetMember(Of PEMethodSymbol)("M3")
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
CompileAndVerify(compilation1, symbolValidator:=validator)
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
CompileAndVerify(compilation2, symbolValidator:=validator)
End Sub
<Fact()>
Public Sub ImplementedInterfacesAndTheirMembers_3()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I1
Sub M1()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58272")>
Public Interface I2
Inherits I1
Sub M2()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58273")>
Public Interface I3
Inherits I2
Sub M3()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M(o As I3)
End Sub
End Class
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
CompileAndVerify(compilation0)
compilation0.AssertTheseDiagnostics()
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Assert.Equal(1, [module].GetReferencedAssemblySymbols().Length)
Dim i1 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I1")
Assert.Equal(0, i1.GetMembers().Length)
Dim i2 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I2")
Assert.Equal(0, i2.GetMembers().Length)
Dim i3 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I3")
Assert.Equal(0, i3.GetMembers().Length)
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
CompileAndVerify(compilation1, symbolValidator:=validator)
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
CompileAndVerify(compilation2, symbolValidator:=validator)
End Sub
<Fact()>
Public Sub EmbedEnum()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Function F() As E
End Interface
Public Enum E
A
B = 3
End Enum
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Class C
Private Const F As E = E.B
End Class
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Assert.Equal(1, [module].GetReferencedAssemblySymbols().Length)
Dim e = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("E")
Dim f = e.GetMember(Of PEFieldSymbol)("A")
Assert.Equal(f.ConstantValue, 0)
f = e.GetMember(Of PEFieldSymbol)("B")
Assert.Equal(f.ConstantValue, 3)
f = e.GetMember(Of PEFieldSymbol)("value__")
Assert.False(f.HasConstantValue)
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub ErrorType1()
Dim pia1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("1.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
Public Interface I1
End Interface
]]></file>
</compilation>
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("2.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
Public Interface I2
Inherits I1
End Interface
]]></file>
</compilation>
Dim consumer = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M(o As I2)
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC31539: Cannot find the interop type that matches the embedded type 'I1'. Are you missing an assembly reference?
</errors>
Dim piaCompilation1 = CreateCompilationWithMscorlib40(pia1)
CompileAndVerify(piaCompilation1)
Dim piaCompilation2 = CreateCompilationWithMscorlib40AndReferences(
pia2,
references:={New VisualBasicCompilationReference(piaCompilation1, embedInteropTypes:=True)})
CompileAndVerify(piaCompilation2)
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, errors)
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={piaCompilation2.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
End Sub
<Fact()>
Public Sub ErrorType2()
Dim pia1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("1.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
Public Interface I1
End Interface
]]></file>
</compilation>
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("2.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
<ComEventInterface(GetType(I1), GetType(Object))>
Public Interface I2
End Interface
]]></file>
</compilation>
Dim consumer = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M(o As I2)
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC31539: Cannot find the interop type that matches the embedded type 'I1'. Are you missing an assembly reference?
</errors>
Dim piaCompilation1 = CreateCompilationWithMscorlib40(pia1)
CompileAndVerify(piaCompilation1)
Dim piaCompilation2 = CreateCompilationWithMscorlib40AndReferences(
pia2,
references:={New VisualBasicCompilationReference(piaCompilation1, embedInteropTypes:=True)})
CompileAndVerify(piaCompilation2)
Dim fullName = MetadataTypeName.FromFullName("I1")
Dim isNoPiaLocalType = False
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, errors)
Dim assembly = compilation1.SourceModule.GetReferencedAssemblySymbols()(1)
Dim [module] = assembly.Modules(0)
Assert.IsType(Of MissingMetadataTypeSymbol.TopLevel)([module].LookupTopLevelMetadataType(fullName))
Assert.Null(assembly.GetTypeByMetadataName(fullName.FullName))
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={piaCompilation2.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
assembly = compilation2.SourceModule.GetReferencedAssemblySymbols()(1)
[module] = assembly.Modules(0)
Assert.IsType(Of NoPiaMissingCanonicalTypeSymbol)(DirectCast([module], PEModuleSymbol).LookupTopLevelMetadataType(fullName, isNoPiaLocalType))
Assert.True(isNoPiaLocalType)
Assert.IsType(Of MissingMetadataTypeSymbol.TopLevel)([module].LookupTopLevelMetadataType(fullName))
Assert.Null(assembly.GetTypeByMetadataName(fullName.FullName))
Dim compilation3 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2)})
CompileAndVerify(compilation3)
assembly = compilation3.SourceModule.GetReferencedAssemblySymbols()(1)
[module] = assembly.Modules(0)
Assert.IsType(Of MissingMetadataTypeSymbol.TopLevel)([module].LookupTopLevelMetadataType(fullName))
Assert.Null(assembly.GetTypeByMetadataName(fullName.FullName))
Dim compilation4 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={MetadataReference.CreateFromImage(piaCompilation2.EmitToArray())})
CompileAndVerify(compilation4)
assembly = compilation4.SourceModule.GetReferencedAssemblySymbols()(1)
[module] = assembly.Modules(0)
Assert.IsType(Of NoPiaMissingCanonicalTypeSymbol)(DirectCast([module], PEModuleSymbol).LookupTopLevelMetadataType(fullName, isNoPiaLocalType))
Assert.True(isNoPiaLocalType)
Assert.IsType(Of MissingMetadataTypeSymbol.TopLevel)([module].LookupTopLevelMetadataType(fullName))
Assert.Null(assembly.GetTypeByMetadataName(fullName.FullName))
End Sub
<Fact()>
Public Sub ErrorType3()
Dim pia1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("1.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
Public Interface I1
End Interface
]]></file>
</compilation>
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("2.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
<ComEventInterface(GetType(I1), GetType(Object))>
Public Interface I2
Sub M2()
End Interface
]]></file>
</compilation>
Dim consumer = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M()
Dim o As I2 = Nothing
o.M2()
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC31539: Cannot find the interop type that matches the embedded type 'I1'. Are you missing an assembly reference?
o.M2()
~~~~~~
</errors>
Dim piaCompilation1 = CreateCompilationWithMscorlib40(pia1)
CompileAndVerify(piaCompilation1)
Dim piaCompilation2 = CreateCompilationWithMscorlib40AndReferences(
pia2,
references:={New VisualBasicCompilationReference(piaCompilation1, embedInteropTypes:=True)})
'CompileAndVerify(piaCompilation2, emitOptions:=EmitOptions.RefEmitBug)
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={piaCompilation2.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
Dim compilation3 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2)})
CompileAndVerify(compilation3, verify:=Verification.Fails)
Dim compilation4 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={MetadataReference.CreateFromImage(piaCompilation2.EmitToArray())})
CompileAndVerify(compilation4, verify:=Verification.Fails)
End Sub
<Fact()>
Public Sub ErrorType4()
Dim pia1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("1.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
Public Interface I1
End Interface
]]></file>
</compilation>
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("2.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
<ComEventInterface(GetType(IList(Of List(Of I1))), GetType(Object))>
Public Interface I2
End Interface
]]></file>
</compilation>
Dim consumer = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M(o As I2)
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC36924: Type 'List(Of I1)' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
</errors>
Dim piaCompilation1 = CreateCompilationWithMscorlib40(pia1)
CompileAndVerify(piaCompilation1)
Dim piaCompilation2 = CreateCompilationWithMscorlib40AndReferences(
pia2,
references:={New VisualBasicCompilationReference(piaCompilation1, embedInteropTypes:=True)})
CompileAndVerify(piaCompilation2)
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, errors)
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={piaCompilation2.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
End Sub
<Fact()>
Public Sub ErrorType5()
Dim pia1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("1.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
Public Interface I1
End Interface
]]></file>
</compilation>
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("2.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
<ComEventInterface(GetType(IList(Of List(Of I1))), GetType(Object))>
Public Interface I2
Sub M2()
End Interface
]]></file>
</compilation>
Dim consumer = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M()
Dim o As I2 = Nothing
o.M2()
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC36924: Type 'List(Of I1)' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
o.M2()
~~~~~~
</errors>
Dim piaCompilation1 = CreateCompilationWithMscorlib40(pia1)
CompileAndVerify(piaCompilation1)
Dim piaCompilation2 = CreateCompilationWithMscorlib40AndReferences(
pia2,
references:={New VisualBasicCompilationReference(piaCompilation1, embedInteropTypes:=True)})
'CompileAndVerify(piaCompilation2, emitOptions:=EmitOptions.RefEmitBug)
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={piaCompilation2.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
End Sub
<Fact()>
Public Sub ErrorType6()
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("2.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
Public Interface I2
Inherits I1
End Interface
]]></file>
</compilation>
Dim consumer = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M(o As I2)
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC30002: Type 'I1' is not defined.
</errors>
Dim piaCompilation2 = CreateCompilationWithMscorlib40(pia2)
'CompileAndVerify(piaCompilation2, emitOptions:=EmitOptions.RefEmitBug)
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, errors)
End Sub
<Fact()>
Public Sub ErrorType7()
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("2.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
Public Interface I2
Sub M2(o As I1)
End Interface
]]></file>
</compilation>
Dim consumer = <compilation name="Consumer">
<file name="a.vb"><![CDATA[
Class C
Sub M(o As I2)
o.M2(Nothing)
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC30002: Type 'I1' is not defined.
o.M2(Nothing)
~~~~~~~~~~~~~
</errors>
Dim piaCompilation2 = CreateCompilationWithMscorlib40(pia2)
'CompileAndVerify(piaCompilation2, emitOptions:=EmitOptions.RefEmitBug)
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
End Sub
<Fact()>
Public Sub ErrorType8()
Dim pia1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("1.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
Public Interface I1
End Interface
]]></file>
</compilation>
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("2.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
<ComEventInterface(GetType(List(Of I1)), GetType(Object))>
Public Interface I2
End Interface
]]></file>
</compilation>
Dim consumer = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M(o As I2)
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC36924: Type 'List(Of I1)' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
</errors>
Dim piaCompilation1 = CreateCompilationWithMscorlib40(pia1)
CompileAndVerify(piaCompilation1)
Dim piaCompilation2 = CreateCompilationWithMscorlib40AndReferences(
pia2,
references:={New VisualBasicCompilationReference(piaCompilation1, embedInteropTypes:=True)})
CompileAndVerify(piaCompilation2)
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, errors)
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={piaCompilation2.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
Dim compilation3 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2)})
CompileAndVerify(compilation3)
Dim compilation4 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={MetadataReference.CreateFromImage(piaCompilation2.EmitToArray())})
CompileAndVerify(compilation4)
End Sub
<Fact>
Public Sub ErrorType_Tuple()
Dim pia1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
<Assembly: ImportedFromTypeLib("GeneralPIA1.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
Public Interface ITest33
End Interface
]]></file>
</compilation>
Dim piaCompilation1 = CreateCompilationWithMscorlib40(pia1, options:=TestOptions.ReleaseDll)
CompileAndVerify(piaCompilation1)
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
Imports System.Collections.Generic
<assembly: ImportedFromTypeLib("GeneralPIA2.dll")>
<assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58290")>
<ComImport>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
Public Interface ITest34
Function M() As List(Of (ITest33, ITest33))
End Interface
]]></file>
</compilation>
Dim piaCompilation2 = CreateCompilationWithMscorlib40(
pia2, options:=TestOptions.ReleaseDll,
references:={piaCompilation1.EmitToImageReference(embedInteropTypes:=True), ValueTupleRef, SystemRuntimeFacadeRef})
CompileAndVerify(piaCompilation2)
Dim consumer = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Public MustInherit Class UsePia5
Implements ITest34
End Class
]]></file>
</compilation>
Dim expected = <errors>
BC36924: Type 'List(Of ValueTuple(Of ITest33, ITest33))' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
Implements ITest34
~~~~~~~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer, options:=TestOptions.ReleaseDll,
references:={piaCompilation2.ToMetadataReference(embedInteropTypes:=True), piaCompilation1.ToMetadataReference(), ValueTupleRef, SystemRuntimeFacadeRef})
VerifyEmitDiagnostics(compilation1, expected)
VerifyEmitMetadataOnlyDiagnostics(compilation1, expected)
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
consumer, options:=TestOptions.ReleaseDll,
references:={piaCompilation2.EmitToImageReference(embedInteropTypes:=True), piaCompilation1.ToMetadataReference(), ValueTupleRef, SystemRuntimeFacadeRef})
VerifyEmitDiagnostics(compilation2, expected)
VerifyEmitMetadataOnlyDiagnostics(compilation2, expected)
Dim compilation3 = CreateCompilationWithMscorlib40AndReferences(
consumer, options:=TestOptions.ReleaseDll,
references:={piaCompilation2.ToMetadataReference(), piaCompilation1.ToMetadataReference(), ValueTupleRef, SystemRuntimeFacadeRef})
VerifyEmitDiagnostics(compilation3, expected)
VerifyEmitMetadataOnlyDiagnostics(compilation3, expected)
Dim compilation4 = CreateCompilationWithMscorlib40AndReferences(
consumer, options:=TestOptions.ReleaseDll,
references:={piaCompilation2.EmitToImageReference(), piaCompilation1.ToMetadataReference(), ValueTupleRef, SystemRuntimeFacadeRef})
VerifyEmitDiagnostics(compilation4, expected)
VerifyEmitMetadataOnlyDiagnostics(compilation4, expected)
End Sub
<Fact()>
Public Sub ErrorType9()
Dim pia1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("1.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
Public Interface I1
End Interface
]]></file>
</compilation>
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("2.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
<ComEventInterface(GetType(List(Of I1)), GetType(Object))>
Public Interface I2
Sub M2()
End Interface
]]></file>
</compilation>
Dim consumer = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M()
Dim o As I2 = Nothing
o.M2()
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC36924: Type 'List(Of I1)' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
o.M2()
~~~~~~
</errors>
Dim piaCompilation1 = CreateCompilationWithMscorlib40(pia1)
CompileAndVerify(piaCompilation1)
Dim piaCompilation2 = CreateCompilationWithMscorlib40AndReferences(
pia2,
references:={New VisualBasicCompilationReference(piaCompilation1, embedInteropTypes:=True)})
'CompileAndVerify(piaCompilation2, emitOptions:=EmitOptions.RefEmitBug)
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={piaCompilation2.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
Dim compilation3 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2)})
CompileAndVerify(compilation3, verify:=Verification.Fails)
Dim compilation4 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={MetadataReference.CreateFromImage(piaCompilation2.EmitToArray())})
CompileAndVerify(compilation4, verify:=Verification.Fails)
End Sub
<Fact(), WorkItem(673546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673546")>
Public Sub MissingComAwareEventInfo()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Delegate Sub D()
<ComEventInterface(GetType(IE), GetType(Integer))>
Public Interface I1
Event E As D
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58277")>
Public Interface I2
Inherits I1
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
Public Interface IE
Sub E
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Class C
Sub Add(x As I1)
AddHandler x.E, Sub() System.Console.WriteLine()
End Sub
End Class
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
options:=TestOptions.DebugDll,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
AssertTheseEmitDiagnostics(compilation1,
<expected>
BC35000: Requested operation is not available because the runtime library function 'System.Runtime.InteropServices.ComAwareEventInfo..ctor' is not defined.
AddHandler x.E, Sub() System.Console.WriteLine()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
Private Shared Sub AssertTheseDiagnostics(verifier As CompilationVerifier, diagnostics As XElement)
verifier.Diagnostics.AssertTheseDiagnostics(diagnostics)
End Sub
<Fact()>
Public Sub DefaultValueWithoutOptional_01()
Dim sources1 = <![CDATA[
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.ver 4:0:0:0
}
.assembly extern System
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.ver 4:0:0:0
}
.assembly pia
{
.custom instance void [mscorlib]System.Runtime.InteropServices.ImportedFromTypeLibAttribute::.ctor(string) = ( 01 00 0E 47 65 6E 65 72 61 6C 50 49 41 2E 64 6C // ...GeneralPIA.dl
6C 00 00 ) // l..
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 66 39 63 32 64 35 31 64 2D 34 66 34 34 // ..$f9c2d51d-4f44
2D 34 35 66 30 2D 39 65 64 61 2D 63 39 64 35 39 // -45f0-9eda-c9d59
39 62 35 38 32 35 37 00 00 ) // 9b58257..
}
.module pia.dll
// MVID: {FDF1B1F7-A867-40B9-83CD-3F75B2D2B3C2}
.imagebase 0x10000000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003 // WINDOWS_CUI
.corflags 0x00000001 // ILONLY
.class interface public abstract auto ansi import IA
{
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 44 45 41 44 42 45 45 46 2D 43 41 46 45 // ..$DEADBEEF-CAFE
2D 42 41 42 45 2D 42 41 41 44 2D 44 45 41 44 43 // -BABE-BAAD-DEADC
30 44 45 30 30 30 30 00 00 ) // 0DE0000..
.method public newslot abstract strict virtual
instance void M(int32 x) cil managed
{
.param [1] = int32(0x0000000C)
} // end of method IA::M
} // end of class IA
]]>.Value
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Public Class B
Implements IA
Sub M(x As Integer) Implements IA.M
End Sub
End Class
]]></file>
</compilation>
Dim reference1 = CompileIL(sources1, prependDefaultHeader:=False, embedInteropTypes:=True)
CompileAndVerify(sources2, references:={reference1}, symbolValidator:=
Sub([module] As ModuleSymbol)
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim ia = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("IA")
Dim m = CType(ia.GetMember("M"), MethodSymbol)
Dim p = DirectCast(m.Parameters(0), PEParameterSymbol)
Assert.False(p.IsMetadataOptional)
Assert.Equal(ParameterAttributes.HasDefault, p.ParamFlags)
Assert.Equal(CObj(&H0000000C), p.ExplicitDefaultConstantValue.Value)
Assert.False(p.HasExplicitDefaultValue)
Assert.Throws(GetType(InvalidOperationException), Sub()
Dim tmp = p.ExplicitDefaultValue
End Sub)
End Sub).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub DefaultValueWithoutOptional_02()
Dim sources1 = <![CDATA[
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.ver 4:0:0:0
}
.assembly extern System
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.ver 4:0:0:0
}
.assembly pia
{
.custom instance void [mscorlib]System.Runtime.InteropServices.ImportedFromTypeLibAttribute::.ctor(string) = ( 01 00 0E 47 65 6E 65 72 61 6C 50 49 41 2E 64 6C // ...GeneralPIA.dl
6C 00 00 ) // l..
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 66 39 63 32 64 35 31 64 2D 34 66 34 34 // ..$f9c2d51d-4f44
2D 34 35 66 30 2D 39 65 64 61 2D 63 39 64 35 39 // -45f0-9eda-c9d59
39 62 35 38 32 35 37 00 00 ) // 9b58257..
}
.module pia.dll
// MVID: {FDF1B1F7-A867-40B9-83CD-3F75B2D2B3C2}
.imagebase 0x10000000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003 // WINDOWS_CUI
.corflags 0x00000001 // ILONLY
.class interface public abstract auto ansi import IA
{
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 44 45 41 44 42 45 45 46 2D 43 41 46 45 // ..$DEADBEEF-CAFE
2D 42 41 42 45 2D 42 41 41 44 2D 44 45 41 44 43 // -BABE-BAAD-DEADC
30 44 45 30 30 30 30 00 00 ) // 0DE0000..
.method public newslot abstract strict virtual
instance void M(valuetype [mscorlib]System.DateTime x) cil managed
{
.param [1]
.custom instance void [mscorlib]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 B1 68 DE 3A 00 00 00 00 00 00 ) // ...h.:......
} // end of method IA::M
} // end of class IA
]]>.Value
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Public Class B
Implements IA
Sub M(x As System.DateTime) Implements IA.M
End Sub
End Class
]]></file>
</compilation>
Dim reference1 = CompileIL(sources1, prependDefaultHeader:=False, embedInteropTypes:=True)
CompileAndVerify(sources2, references:={reference1}, symbolValidator:=
Sub([module] As ModuleSymbol)
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim ia = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("IA")
Dim m = CType(ia.GetMember("M"), MethodSymbol)
Dim p = DirectCast(m.Parameters(0), PEParameterSymbol)
Assert.False(p.IsMetadataOptional)
Assert.Equal(ParameterAttributes.None, p.ParamFlags)
Assert.Equal("System.Runtime.CompilerServices.DateTimeConstantAttribute(987654321)", p.GetAttributes().Single().ToString())
Assert.Null(p.ExplicitDefaultConstantValue)
Assert.False(p.HasExplicitDefaultValue)
Assert.Throws(GetType(InvalidOperationException), Sub()
Dim tmp = p.ExplicitDefaultValue
End Sub)
End Sub).VerifyDiagnostics()
End Sub
<Fact, WorkItem(8088, "https://github.com/dotnet/roslyn/issues/8088")>
Public Sub ParametersWithoutNames()
Dim sources =
<compilation>
<file name="a.vb">
Public Class Program
Sub M(x As I1)
x.M1(1, 2, 3)
End Sub
Sub M1(value As Integer)
End Sub
Sub M2(Param As Integer)
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources,
{
AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.ParametersWithoutNames).
GetReference(display:="ParametersWithoutNames.dll", embedInteropTypes:=True)
},
options:=TestOptions.ReleaseDll)
AssertParametersWithoutNames(compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("I1").GetMember(Of MethodSymbol)("M1").Parameters, False)
CompileAndVerify(compilation,
symbolValidator:=
Sub([module] As ModuleSymbol)
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
AssertParametersWithoutNames([module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("I1").GetMember(Of MethodSymbol)("M1").Parameters, True)
Dim p As PEParameterSymbol
p = DirectCast([module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("Program").GetMember(Of MethodSymbol)("M").Parameters(0), PEParameterSymbol)
Assert.Equal("x", DirectCast([module], PEModuleSymbol).Module.GetParamNameOrThrow(p.Handle))
Assert.Equal("x", p.Name)
Assert.Equal("x", p.MetadataName)
p = DirectCast([module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("Program").GetMember(Of MethodSymbol)("M1").Parameters(0), PEParameterSymbol)
Assert.Equal("value", DirectCast([module], PEModuleSymbol).Module.GetParamNameOrThrow(p.Handle))
Assert.Equal("value", p.Name)
Assert.Equal("value", p.MetadataName)
p = DirectCast([module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("Program").GetMember(Of MethodSymbol)("M2").Parameters(0), PEParameterSymbol)
Assert.Equal("Param", DirectCast([module], PEModuleSymbol).Module.GetParamNameOrThrow(p.Handle))
Assert.Equal("Param", p.Name)
Assert.Equal("Param", p.MetadataName)
End Sub).VerifyDiagnostics()
End Sub
Private Shared Sub AssertParametersWithoutNames(parameters As ImmutableArray(Of ParameterSymbol), isEmbedded As Boolean)
Assert.True(DirectCast(parameters(0), PEParameterSymbol).Handle.IsNil)
Dim p1 = DirectCast(parameters(1), PEParameterSymbol)
Assert.True(p1.IsMetadataOptional)
Assert.False(p1.Handle.IsNil)
Assert.True(DirectCast(p1.ContainingModule, PEModuleSymbol).Module.MetadataReader.GetParameter(p1.Handle).Name.IsNil)
Dim p2 = DirectCast(parameters(2), PEParameterSymbol)
If isEmbedded Then
Assert.True(p2.Handle.IsNil)
Else
Assert.True(DirectCast(p2.ContainingModule, PEModuleSymbol).Module.MetadataReader.GetParameter(p2.Handle).Name.IsNil)
End If
For Each p In parameters
Assert.Equal("Param", p.Name)
Assert.Equal("", p.MetadataName)
Next
End Sub
End Class
End Namespace
|
abock/roslyn
|
src/Compilers/VisualBasic/Test/Emit/Emit/NoPiaEmbedTypes.vb
|
Visual Basic
|
mit
| 221,803
|
' Licensed to the .NET Foundation under one or more 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.Collections
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Retargeting
#If Not Retargeting Then
Public Class RetargetCustomModifiers
Inherits BasicTestBase
<Fact>
Public Sub Test1()
Dim oldMsCorLib = TestReferences.NetFx.v4_0_21006.mscorlib
Dim c1 = VisualBasicCompilation.Create("C1", references:={oldMsCorLib, TestReferences.SymbolsTests.CustomModifiers.Modifiers.netmodule})
Dim c1Assembly = c1.Assembly
Dim newMsCorLib = TestReferences.NetFx.v4_0_30319.mscorlib
Dim c2 = VisualBasicCompilation.Create("C2", references:=New MetadataReference() {newMsCorLib, New VisualBasicCompilationReference(c1)})
Dim mscorlibAssembly = c2.GetReferencedAssemblySymbol(newMsCorLib)
Assert.NotSame(mscorlibAssembly, c1.GetReferencedAssemblySymbol(oldMsCorLib))
Dim modifiers = c2.GlobalNamespace.GetTypeMembers("Modifiers").Single()
Assert.IsType(Of PENamedTypeSymbol)(modifiers)
Dim f0 As FieldSymbol = modifiers.GetMembers("F0").OfType(Of FieldSymbol)().Single()
Assert.Equal(1, f0.CustomModifiers.Length)
Dim f0Mod = f0.CustomModifiers(0)
Assert.[True](f0Mod.IsOptional)
Assert.Equal("System.Runtime.CompilerServices.IsConst", f0Mod.Modifier.ToTestDisplayString())
Assert.Same(mscorlibAssembly, f0Mod.Modifier.ContainingAssembly)
Dim m1 As MethodSymbol = modifiers.GetMembers("F1").OfType(Of MethodSymbol)().Single()
Dim p1 As ParameterSymbol = m1.Parameters(0)
Dim p2 As ParameterSymbol = modifiers.GetMembers("F2").OfType(Of MethodSymbol)().Single().Parameters(0)
Dim m5 As MethodSymbol = modifiers.GetMembers("F5").OfType(Of MethodSymbol)().Single()
Dim p5 As ParameterSymbol = m5.Parameters(0)
Dim p6 As ParameterSymbol = modifiers.GetMembers("F6").OfType(Of MethodSymbol)().Single().Parameters(0)
Dim m7 As MethodSymbol = modifiers.GetMembers("F7").OfType(Of MethodSymbol)().Single()
Assert.Equal(0, m1.ReturnTypeCustomModifiers.Length)
Assert.Equal(1, p1.CustomModifiers.Length)
Dim p1Mod = p1.CustomModifiers(0)
Assert.[True](p1Mod.IsOptional)
Assert.Equal("System.Runtime.CompilerServices.IsConst", p1Mod.Modifier.ToTestDisplayString())
Assert.Same(mscorlibAssembly, p1Mod.Modifier.ContainingAssembly)
Assert.Equal(2, p2.CustomModifiers.Length)
For Each p2Mod In p2.CustomModifiers
Assert.[True](p2Mod.IsOptional)
Assert.Equal("System.Runtime.CompilerServices.IsConst", p2Mod.Modifier.ToTestDisplayString())
Assert.Same(mscorlibAssembly, p2Mod.Modifier.ContainingAssembly)
Next
Assert.[True](m5.IsSub)
Assert.Equal(1, m5.ReturnTypeCustomModifiers.Length)
Dim m5Mod = m5.ReturnTypeCustomModifiers(0)
Assert.[True](m5Mod.IsOptional)
Assert.Equal("System.Runtime.CompilerServices.IsConst", m5Mod.Modifier.ToTestDisplayString())
Assert.Same(mscorlibAssembly, m5Mod.Modifier.ContainingAssembly)
Assert.Equal(0, p5.CustomModifiers.Length)
Dim p5Type As ArrayTypeSymbol = DirectCast(p5.[Type], ArrayTypeSymbol)
Assert.Equal("System.Int32", p5Type.ElementType.ToTestDisplayString())
Assert.Equal(1, p5Type.CustomModifiers.Length)
Dim p5TypeMod = p5Type.CustomModifiers(0)
Assert.[True](p5TypeMod.IsOptional)
Assert.Equal("System.Runtime.CompilerServices.IsConst", p5TypeMod.Modifier.ToTestDisplayString())
Assert.Same(mscorlibAssembly, p5TypeMod.Modifier.ContainingAssembly)
Assert.Equal(0, p6.CustomModifiers.Length)
Assert.True(p6.[Type].IsErrorType())
Assert.IsType(Of PointerTypeSymbol)(p6.Type)
Assert.False(DirectCast(p6.Type, INamedTypeSymbol).IsSerializable)
Assert.[False](m7.IsSub)
Assert.Equal(1, m7.ReturnTypeCustomModifiers.Length)
Dim m7Mod = m7.ReturnTypeCustomModifiers(0)
Assert.[True](m7Mod.IsOptional)
Assert.Equal("System.Runtime.CompilerServices.IsConst", m7Mod.Modifier.ToTestDisplayString())
Assert.Same(mscorlibAssembly, m7Mod.Modifier.ContainingAssembly)
End Sub
<Fact>
Public Sub Test2()
Dim oldMsCorLib = TestReferences.NetFx.v4_0_21006.mscorlib
Dim source = "
public class Modifiers
public volatileFld As Integer
Overloads Sub F1(p As System.DateTime)
End Sub
End Class"
Dim c1 = VisualBasicCompilation.Create("C1", {Parse(source)}, {oldMsCorLib})
Dim c1Assembly = c1.Assembly
Dim newMsCorLib = TestReferences.NetFx.v4_0_30319.mscorlib
Dim r1 = New VisualBasicCompilationReference(c1)
Dim c2 As VisualBasicCompilation = VisualBasicCompilation.Create("C2", references:={newMsCorLib, r1})
Dim c1AsmRef = c2.GetReferencedAssemblySymbol(r1)
Assert.NotSame(c1Assembly, c1AsmRef)
Dim mscorlibAssembly = c2.GetReferencedAssemblySymbol(newMsCorLib)
Assert.NotSame(mscorlibAssembly, c1.GetReferencedAssemblySymbol(oldMsCorLib))
Dim modifiers = c2.GlobalNamespace.GetTypeMembers("Modifiers").Single()
Assert.IsType(Of RetargetingNamedTypeSymbol)(modifiers)
Dim volatileFld As FieldSymbol = modifiers.GetMembers("volatileFld").OfType(Of FieldSymbol)().Single()
Assert.Equal(0, volatileFld.CustomModifiers.Length)
Assert.Equal(SpecialType.System_Int32, volatileFld.[Type].SpecialType)
Assert.Equal("volatileFld", volatileFld.Name)
Assert.Same(volatileFld, volatileFld.OriginalDefinition)
Assert.Null(volatileFld.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty))
Assert.Null(volatileFld.ConstantValue)
Assert.Null(volatileFld.AssociatedSymbol)
Assert.Same(c1AsmRef, volatileFld.ContainingAssembly)
Assert.Same(c1AsmRef.Modules(0), volatileFld.ContainingModule)
Assert.Same(modifiers, volatileFld.ContainingSymbol)
Assert.Equal(Accessibility.[Public], volatileFld.DeclaredAccessibility)
Assert.[False](volatileFld.IsConst)
Assert.[False](volatileFld.IsReadOnly)
Assert.[False](volatileFld.IsShared)
Assert.Same(volatileFld.ContainingModule, (DirectCast(volatileFld, RetargetingFieldSymbol)).RetargetingModule)
Assert.Same(c1Assembly, (DirectCast(volatileFld, RetargetingFieldSymbol)).UnderlyingField.ContainingAssembly)
Dim m1 As MethodSymbol = modifiers.GetMembers("F1").OfType(Of MethodSymbol)().Single()
Assert.Equal(0, m1.ReturnTypeCustomModifiers.Length)
Assert.Equal(0, m1.ExplicitInterfaceImplementations.Length)
Assert.True(m1.IsOverloads)
Assert.False(m1.IsExtensionMethod)
Assert.Equal((DirectCast(m1, RetargetingMethodSymbol)).UnderlyingMethod.CallingConvention, m1.CallingConvention)
Assert.Null(m1.AssociatedSymbol)
Assert.Same(c1AsmRef.Modules(0), m1.ContainingModule)
Dim p1 As ParameterSymbol = m1.Parameters(0)
Assert.Equal(0, p1.CustomModifiers.Length)
Assert.Same(c1AsmRef.Modules(0), p1.ContainingModule)
Assert.False(p1.HasExplicitDefaultValue)
Assert.Equal(0, p1.Ordinal)
End Sub
End Class
#End If
End Namespace
|
abock/roslyn
|
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Retargeting/RetargetCustomModifiers.vb
|
Visual Basic
|
mit
| 8,419
|
' 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.Recommendations.Expressions
Public Class WithKeywordRecommenderTests
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function NoneInClassDeclarationTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>|</ClassDeclaration>, "With")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function NoneAfterFromTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Dim x = New Goo From |</ClassDeclaration>, "With")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function NoneAfterWith1Test() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Dim x = New With |</ClassDeclaration>, "With")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function NoneAfterWith2Test() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Dim x = New Goo With |</ClassDeclaration>, "With")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function WithAfterDimEqualsNewTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = New |</MethodBody>, "With")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function WithAfterDimEqualsNewTypeNameTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = New Goo |</MethodBody>, "With")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function WithAfterDimEqualsNewTypeNameAndParensTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = New Goo() |</MethodBody>, "With")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function WithAfterDimAsNewTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim x As New |</MethodBody>, "With")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function WithAfterDimAsNewTypeNameTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim x As New Goo |</MethodBody>, "With")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function WithAfterDimAsNewTypeNameAndParensTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim x As New Goo() |</MethodBody>, "With")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function WithAfterAssignmentNewTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>x = New |</MethodBody>, "With")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function WithAfterAssignmentNewTypeNameTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>x = New Goo |</MethodBody>, "With")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function WithAfterAssignmentNewTypeNameAndParensTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>x = New Goo() |</MethodBody>, "With")
End Function
<WorkItem(543291, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543291")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function NoWithAfterDotTest() As Task
Dim code = <File>
Class C
Sub M()
Dim c As New C.|
End Sub
End Class
</File>
Await VerifyRecommendationsMissingAsync(code, "With")
End Function
<WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function NotAfterEolTest() As Task
Await VerifyRecommendationsMissingAsync(
<ClassDeclaration>Dim x = New Goo
|</ClassDeclaration>, "With")
End Function
<WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AfterExplicitLineContinuationTest() As Task
Await VerifyRecommendationsContainAsync(
<ClassDeclaration>Dim x = New Goo _
|</ClassDeclaration>, "With")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AfterExplicitLineContinuationTestCommentsAfterLineContinuation() As Task
Await VerifyRecommendationsContainAsync(
<ClassDeclaration>Dim x = New Goo _ ' Test
|</ClassDeclaration>, "With")
End Function
End Class
End Namespace
|
aelij/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/Expressions/WithKeywordRecommenderTests.vb
|
Visual Basic
|
apache-2.0
| 5,381
|
' Licensed to the .NET Foundation under one or more 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.IO
Imports System.Reflection
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
Imports Microsoft.VisualStudio.LanguageServices.Implementation.TaskList
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim
<UseExportProvider>
Public Class VisualStudioAnalyzerTests
Private Shared ReadOnly s_compositionWithMockDiagnosticUpdateSourceRegistrationService As TestComposition = EditorTestCompositions.EditorFeatures _
.AddExcludedPartTypes(GetType(IDiagnosticUpdateSourceRegistrationService)) _
.AddParts(GetType(MockDiagnosticUpdateSourceRegistrationService))
<WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub GetReferenceCalledMultipleTimes()
Dim composition = s_compositionWithMockDiagnosticUpdateSourceRegistrationService
Dim exportProvider = composition.ExportProviderFactory.CreateExportProvider()
Using workspace = New TestWorkspace(composition:=composition)
Dim lazyWorkspace = New Lazy(Of VisualStudioWorkspace)(
Function()
Return Nothing
End Function)
Dim registrationService = Assert.IsType(Of MockDiagnosticUpdateSourceRegistrationService)(exportProvider.GetExportedValue(Of IDiagnosticUpdateSourceRegistrationService)())
Dim hostDiagnosticUpdateSource = New HostDiagnosticUpdateSource(lazyWorkspace, registrationService)
Using tempRoot = New TempRoot(), analyzer = New VisualStudioAnalyzer(tempRoot.CreateFile().Path, hostDiagnosticUpdateSource, ProjectId.CreateNewId(), LanguageNames.VisualBasic)
Dim reference1 = analyzer.GetReference()
Dim reference2 = analyzer.GetReference()
Assert.True(Object.ReferenceEquals(reference1, reference2))
End Using
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub AnalyzerErrorsAreUpdated()
Dim composition = s_compositionWithMockDiagnosticUpdateSourceRegistrationService
Dim exportProvider = composition.ExportProviderFactory.CreateExportProvider()
Dim lazyWorkspace = New Lazy(Of VisualStudioWorkspace)(
Function()
Return Nothing
End Function)
Dim registrationService = Assert.IsType(Of MockDiagnosticUpdateSourceRegistrationService)(exportProvider.GetExportedValue(Of IDiagnosticUpdateSourceRegistrationService)())
Dim hostDiagnosticUpdateSource = New HostDiagnosticUpdateSource(lazyWorkspace, registrationService)
Dim file = Path.GetTempFileName()
Using workspace = New TestWorkspace(composition:=composition)
Dim globalOptions = workspace.GetService(Of IGlobalOptionService)
Dim eventHandler = New EventHandlers(file, globalOptions)
AddHandler hostDiagnosticUpdateSource.DiagnosticsUpdated, AddressOf eventHandler.DiagnosticAddedTest
Using analyzer = New VisualStudioAnalyzer(file, hostDiagnosticUpdateSource, ProjectId.CreateNewId(), LanguageNames.VisualBasic)
Dim reference = analyzer.GetReference()
reference.GetAnalyzers(LanguageNames.VisualBasic)
RemoveHandler hostDiagnosticUpdateSource.DiagnosticsUpdated, AddressOf eventHandler.DiagnosticAddedTest
AddHandler hostDiagnosticUpdateSource.DiagnosticsUpdated, AddressOf eventHandler.DiagnosticRemovedTest
End Using
IO.File.Delete(file)
End Using
End Sub
Private Class EventHandlers
Public File As String
Private ReadOnly _globalOptions As IGlobalOptionService
Public Sub New(file As String, globalOptions As IGlobalOptionService)
Me.File = file
_globalOptions = globalOptions
End Sub
Public Sub DiagnosticAddedTest(o As Object, e As DiagnosticsUpdatedArgs)
Dim diagnostics = e.GetPushDiagnostics(_globalOptions, InternalDiagnosticsOptions.NormalDiagnosticMode)
Assert.Equal(1, diagnostics.Length)
Dim diagnostic As DiagnosticData = diagnostics.First()
Assert.Equal("BC42378", diagnostic.Id)
Assert.Contains(File, diagnostic.Message, StringComparison.Ordinal)
End Sub
Public Sub DiagnosticRemovedTest(o As Object, e As DiagnosticsUpdatedArgs)
Dim diagnostics = e.GetPushDiagnostics(_globalOptions, InternalDiagnosticsOptions.NormalDiagnosticMode)
Assert.Equal(0, diagnostics.Length)
End Sub
End Class
Private Class MockAnalyzerAssemblyLoader
Implements IAnalyzerAssemblyLoader
Public Sub AddDependencyLocation(fullPath As String) Implements IAnalyzerAssemblyLoader.AddDependencyLocation
Throw New NotImplementedException()
End Sub
Public Function LoadFromPath(fullPath As String) As Assembly Implements IAnalyzerAssemblyLoader.LoadFromPath
Throw New NotImplementedException()
End Function
End Class
End Class
End Namespace
|
CyrusNajmabadi/roslyn
|
src/VisualStudio/Core/Test/ProjectSystemShim/VisualStudioAnalyzerTests.vb
|
Visual Basic
|
mit
| 6,075
|
' 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 Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.VisualStudio.Debugger
Imports Microsoft.VisualStudio.Debugger.Clr
Imports Microsoft.VisualStudio.Debugger.Evaluation
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
<DkmReportNonFatalWatsonException(ExcludeExceptionType:=GetType(NotImplementedException)), DkmContinueCorruptingException>
Friend NotInheritable Class VisualBasicExpressionCompiler
Inherits ExpressionCompiler
Private Shared ReadOnly s_compilerId As New DkmCompilerId(DkmVendorId.Microsoft, DkmLanguageId.VB)
Friend Overrides ReadOnly Property DiagnosticFormatter As DiagnosticFormatter
Get
Return DebuggerDiagnosticFormatter.Instance
End Get
End Property
Friend Overrides ReadOnly Property CompilerId As DkmCompilerId
Get
Return s_compilerId
End Get
End Property
Friend Overrides Function CreateTypeContext(
appDomain As DkmClrAppDomain,
metadataBlocks As ImmutableArray(Of MetadataBlock),
moduleVersionId As Guid,
typeToken As Integer,
useReferencedModulesOnly As Boolean) As EvaluationContextBase
If useReferencedModulesOnly Then
' Avoid using the cache for referenced assemblies only
' since this should be the exceptional case.
Dim compilation = metadataBlocks.ToCompilationReferencedModulesOnly(moduleVersionId)
Return EvaluationContext.CreateTypeContext(
compilation,
moduleVersionId,
typeToken)
End If
Dim previous = appDomain.GetMetadataContext(Of VisualBasicMetadataContext)()
Dim context = EvaluationContext.CreateTypeContext(
previous,
metadataBlocks,
moduleVersionId,
typeToken)
' New type context is not attached to the AppDomain since it is less
' re-usable than the previous attached method context. (We could hold
' on to it if we don't have a previous method context but it's unlikely
' that we evaluated a type-level expression before a method-level.)
Debug.Assert(context IsNot previous.EvaluationContext)
Return context
End Function
Friend Overrides Function CreateMethodContext(
appDomain As DkmClrAppDomain,
metadataBlocks As ImmutableArray(Of MetadataBlock),
lazyAssemblyReaders As Lazy(Of ImmutableArray(Of AssemblyReaders)),
symReader As Object,
moduleVersionId As Guid,
methodToken As Integer,
methodVersion As Integer,
ilOffset As UInteger,
localSignatureToken As Integer,
useReferencedModulesOnly As Boolean) As EvaluationContextBase
If useReferencedModulesOnly Then
' Avoid using the cache for referenced assemblies only
' since this should be the exceptional case.
Dim compilation = metadataBlocks.ToCompilationReferencedModulesOnly(moduleVersionId)
Return EvaluationContext.CreateMethodContext(
compilation,
lazyAssemblyReaders,
symReader,
moduleVersionId,
methodToken,
methodVersion,
ilOffset,
localSignatureToken)
End If
Dim previous = appDomain.GetMetadataContext(Of VisualBasicMetadataContext)()
Dim context = EvaluationContext.CreateMethodContext(
previous,
metadataBlocks,
lazyAssemblyReaders,
symReader,
moduleVersionId,
methodToken,
methodVersion,
ilOffset,
localSignatureToken)
If context IsNot previous.EvaluationContext Then
appDomain.SetMetadataContext(New VisualBasicMetadataContext(metadataBlocks, context))
End If
Return context
End Function
Friend Overrides Sub RemoveDataItem(appDomain As DkmClrAppDomain)
appDomain.RemoveMetadataContext(Of VisualBasicMetadataContext)()
End Sub
Friend Overrides Function GetMetadataBlocks(appDomain As DkmClrAppDomain, runtimeInstance As DkmClrRuntimeInstance) As ImmutableArray(Of MetadataBlock)
Dim previous = appDomain.GetMetadataContext(Of VisualBasicMetadataContext)()
Return runtimeInstance.GetMetadataBlocks(appDomain, previous.MetadataBlocks)
End Function
End Class
End Namespace
|
jkotas/roslyn
|
src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicExpressionCompiler.vb
|
Visual Basic
|
apache-2.0
| 5,037
|
' 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
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations
Public Class DimKeywordRecommenderTests
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimInMethodDeclarationTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>|</MethodBody>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotAfterStaticInMethodBodyTest() As Task
Await VerifyRecommendationsMissingAsync(<MethodBody>Static |</MethodBody>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimInMultiLineLambdaTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>
Dim x = Sub()
|
End Sub</MethodBody>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotInSingleLineLambdaTest() As Task
Await VerifyRecommendationsMissingAsync(<MethodBody>Dim x = Sub() |</MethodBody>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimInClassDeclarationTest() As Task
Await VerifyRecommendationsContainAsync(<ClassDeclaration>|</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotInNamespaceTest() As Task
Await VerifyRecommendationsMissingAsync(<NamespaceDeclaration>|</NamespaceDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotInInterfaceTest() As Task
Await VerifyRecommendationsMissingAsync(<InterfaceDeclaration>|</InterfaceDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotInEnumTest() As Task
Await VerifyRecommendationsMissingAsync(<EnumDeclaration>|</EnumDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimInStructureTest() As Task
Await VerifyRecommendationsContainAsync(<StructureDeclaration>|</StructureDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimInModuleTest() As Task
Await VerifyRecommendationsContainAsync(<ModuleDeclaration>|</ModuleDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotAfterPartialTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Partial |</ClassDeclaration>, "Dim")
End Function
<WorkItem(545036, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545036")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotAfterDimTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Dim |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimAfterPublicTest() As Task
Await VerifyRecommendationsContainAsync(<ClassDeclaration>Public |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimAfterProtectedTest() As Task
Await VerifyRecommendationsContainAsync(<ClassDeclaration>Protected |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimAfterFriendTest() As Task
Await VerifyRecommendationsContainAsync(<ClassDeclaration>Friend |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimAfterPrivateTest() As Task
Await VerifyRecommendationsContainAsync(<ClassDeclaration>Private |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimAfterProtectedFriendTest() As Task
Await VerifyRecommendationsContainAsync(<ClassDeclaration>Protected Friend |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotAfterOverloadsTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Overloads |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotAfterOverridesTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Overrides |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotAfterOverridableTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Overridable |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotAfterNotOverridableTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotAfterMustOverrideTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotAfterMustOverrideOverridesTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>MustOverride Overrides |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotAfterNotOverridableOverridesTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>NotOverridable Overrides |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotAfterConstTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Const |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotAfterDefaultTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Default |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotAfterMustInheritTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>MustInherit |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotAfterNotInheritableTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>NotInheritable |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotAfterNarrowingTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Narrowing |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotAfterWideningTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Widening |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimAfterReadOnlyTest() As Task
Await VerifyRecommendationsContainAsync(<ClassDeclaration>ReadOnly |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotAfterWriteOnlyTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>WriteOnly |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimNotAfterCustomTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>Custom |</ClassDeclaration>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimAfterSharedTest() As Task
Await VerifyRecommendationsContainAsync(<ClassDeclaration>Shared |</ClassDeclaration>, "Dim")
End Function
<WorkItem(542720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542720")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimInSingleLineIfTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>If True Then Di|</MethodBody>, "Dim")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function DimAfterSingleLineLambdaTest() As Task
Dim code =
<MethodBody>
Dim X = Function() True
|
</MethodBody>
Await VerifyRecommendationsContainAsync(code, "Dim")
End Function
<WorkItem(674791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674791")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function NotAfterHashTest() As Task
Await VerifyRecommendationsMissingAsync(<File>
Imports System
#|
Module Module1
End Module
</File>, "Dim")
End Function
End Class
End Namespace
|
ericfe-ms/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/DimKeywordRecommenderTests.vb
|
Visual Basic
|
apache-2.0
| 10,618
|
' 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 Microsoft.VisualStudio.GraphModel
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression
<[UseExportProvider]>
Public Class VisualBasicSymbolLabelTests
<Fact, Trait(Traits.Feature, Traits.Features.Progression), WorkItem(545008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545008")>
Public Async Function TestMethodWithOptionalParameter() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj">
<Document FilePath="Z:\Project.vb">
Class C
Sub $$S(Optional i As Integer = 42)
End Sub
End Class
</Document>
</Project>
</Workspace>)
Await testState.AssertMarkedSymbolLabelIsAsync(GraphCommandDefinition.Contains.Id, "S([Integer])", "C.S([Integer])")
End Using
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression), WorkItem(545009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545009")>
Public Async Function TestMethodWithByRefParameter() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj">
<Document FilePath="Z:\Project.vb">
Class C
Sub $$S(ByRef i As Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>)
Await testState.AssertMarkedSymbolLabelIsAsync(GraphCommandDefinition.Contains.Id, "S(ByRef Integer)", "C.S(ByRef Integer)")
End Using
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression), WorkItem(545017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545017")>
Public Async Function TestEnumMember() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj">
<Document FilePath="Z:\Project.vb">
Enum E
$$M
End Enum
</Document>
</Project>
</Workspace>)
Await testState.AssertMarkedSymbolLabelIsAsync(GraphCommandDefinition.Contains.Id, "M", "E.M")
End Using
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression), WorkItem(608256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608256")>
Public Async Function TestGenericType() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj">
<Document FilePath="Z:\Project.vb">
Class $$C(Of T)
End Class
</Document>
</Project>
</Workspace>)
Await testState.AssertMarkedSymbolLabelIsAsync(GraphCommandDefinition.Contains.Id, "C(Of T)", "C(Of T)")
End Using
End Function
End Class
End Namespace
|
tmeschter/roslyn
|
src/VisualStudio/Core/Test/Progression/VisualBasicSymbolLabelTests.vb
|
Visual Basic
|
apache-2.0
| 4,116
|
' 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.Reflection.Metadata
Imports Microsoft.Cci
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Emit
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend Partial Class TypeParameterSymbol
Implements IGenericParameterReference
Implements IGenericMethodParameterReference
Implements IGenericTypeParameterReference
Implements IGenericParameter
Implements IGenericMethodParameter
Implements IGenericTypeParameter
Private ReadOnly Property ITypeReferenceIsEnum As Boolean Implements ITypeReference.IsEnum
Get
Return False
End Get
End Property
Private ReadOnly Property ITypeReferenceIsValueType As Boolean Implements ITypeReference.IsValueType
Get
Return False
End Get
End Property
Private Function ITypeReferenceGetResolvedType(context As EmitContext) As ITypeDefinition Implements ITypeReference.GetResolvedType
Return Nothing
End Function
Private Function ITypeReferenceTypeCode(context As EmitContext) As Cci.PrimitiveTypeCode Implements ITypeReference.TypeCode
Return Cci.PrimitiveTypeCode.NotPrimitive
End Function
Private ReadOnly Property ITypeReferenceTypeDef As TypeDefinitionHandle Implements ITypeReference.TypeDef
Get
Return Nothing
End Get
End Property
Private ReadOnly Property IGenericParameterAsGenericMethodParameter As IGenericMethodParameter Implements IGenericParameter.AsGenericMethodParameter
Get
CheckDefinitionInvariant()
If Me.ContainingSymbol.Kind = SymbolKind.Method Then
Return Me
End If
Return Nothing
End Get
End Property
Private ReadOnly Property ITypeReferenceAsGenericMethodParameterReference As IGenericMethodParameterReference Implements ITypeReference.AsGenericMethodParameterReference
Get
Debug.Assert(Me.IsDefinition)
If Me.ContainingSymbol.Kind = SymbolKind.Method Then
Return Me
End If
Return Nothing
End Get
End Property
Private ReadOnly Property ITypeReferenceAsGenericTypeInstanceReference As IGenericTypeInstanceReference Implements ITypeReference.AsGenericTypeInstanceReference
Get
Return Nothing
End Get
End Property
Private ReadOnly Property IGenericParameterAsGenericTypeParameter As IGenericTypeParameter Implements IGenericParameter.AsGenericTypeParameter
Get
CheckDefinitionInvariant()
If Me.ContainingSymbol.Kind = SymbolKind.NamedType Then
Return Me
End If
Return Nothing
End Get
End Property
Private ReadOnly Property ITypeReferenceAsGenericTypeParameterReference As IGenericTypeParameterReference Implements ITypeReference.AsGenericTypeParameterReference
Get
Debug.Assert(Me.IsDefinition)
If Me.ContainingSymbol.Kind = SymbolKind.NamedType Then
Return Me
End If
Return Nothing
End Get
End Property
Private Function ITypeReferenceAsNamespaceTypeDefinition(context As EmitContext) As INamespaceTypeDefinition Implements ITypeReference.AsNamespaceTypeDefinition
Return Nothing
End Function
Private ReadOnly Property ITypeReferenceAsNamespaceTypeReference As INamespaceTypeReference Implements ITypeReference.AsNamespaceTypeReference
Get
Return Nothing
End Get
End Property
Private Function ITypeReferenceAsNestedTypeDefinition(context As EmitContext) As INestedTypeDefinition Implements ITypeReference.AsNestedTypeDefinition
Return Nothing
End Function
Private ReadOnly Property ITypeReferenceAsNestedTypeReference As INestedTypeReference Implements ITypeReference.AsNestedTypeReference
Get
Return Nothing
End Get
End Property
Private ReadOnly Property ITypeReferenceAsSpecializedNestedTypeReference As ISpecializedNestedTypeReference Implements ITypeReference.AsSpecializedNestedTypeReference
Get
Return Nothing
End Get
End Property
Private Function ITypeReferenceAsTypeDefinition(context As EmitContext) As ITypeDefinition Implements ITypeReference.AsTypeDefinition
Return Nothing
End Function
Friend NotOverridable Overrides Sub IReferenceDispatch(visitor As MetadataVisitor) ' Implements IReference.Dispatch
Debug.Assert(Me.IsDefinition)
Dim kind As SymbolKind = Me.ContainingSymbol.Kind
If (DirectCast(visitor.Context.Module, PEModuleBuilder)).SourceModule = Me.ContainingModule Then
If kind = SymbolKind.NamedType Then
visitor.Visit(DirectCast(Me, IGenericTypeParameter))
Else
If kind = SymbolKind.Method Then
visitor.Visit(DirectCast(Me, IGenericMethodParameter))
Else
Throw ExceptionUtilities.UnexpectedValue(kind)
End If
End If
Else
If kind = SymbolKind.NamedType Then
visitor.Visit(DirectCast(Me, IGenericTypeParameterReference))
Else
If kind = SymbolKind.Method Then
visitor.Visit(DirectCast(Me, IGenericMethodParameterReference))
Else
Throw ExceptionUtilities.UnexpectedValue(kind)
End If
End If
End If
End Sub
Friend NotOverridable Overrides Function IReferenceAsDefinition(context As EmitContext) As IDefinition ' Implements IReference.AsDefinition
Debug.Assert(Me.IsDefinition)
Return Nothing
End Function
Private ReadOnly Property INamedEntityName As String Implements INamedEntity.Name
Get
Return Me.MetadataName
End Get
End Property
Private ReadOnly Property IParameterListEntryIndex As UShort Implements IParameterListEntry.Index
Get
Return CType(Me.Ordinal, UShort)
End Get
End Property
Private ReadOnly Property IGenericMethodParameterReferenceDefiningMethod As IMethodReference Implements IGenericMethodParameterReference.DefiningMethod
Get
Debug.Assert(Me.IsDefinition)
Return DirectCast(Me.ContainingSymbol, MethodSymbol)
End Get
End Property
Private ReadOnly Property IGenericTypeParameterReferenceDefiningType As ITypeReference Implements IGenericTypeParameterReference.DefiningType
Get
Debug.Assert(Me.IsDefinition)
Return DirectCast(Me.ContainingSymbol, NamedTypeSymbol)
End Get
End Property
Private Iterator Function IGenericParameterGetConstraints(context As EmitContext) As IEnumerable(Of ITypeReference) Implements IGenericParameter.GetConstraints
Dim _module = DirectCast(context.Module, PEModuleBuilder)
Dim seenValueType = False
For Each t In Me.ConstraintTypesNoUseSiteDiagnostics
If t.SpecialType = SpecialType.System_ValueType Then
seenValueType = True
End If
Yield _module.Translate(t, syntaxNodeOpt:=DirectCast(context.SyntaxNodeOpt, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics)
Next
If Me.HasValueTypeConstraint AndAlso Not seenValueType Then
' Add System.ValueType constraint to comply with Dev11 C# output
Yield _module.GetSpecialType(CodeAnalysis.SpecialType.System_ValueType,
DirectCast(context.SyntaxNodeOpt, VisualBasicSyntaxNode), context.Diagnostics)
End If
End Function
Private ReadOnly Property IGenericParameterMustBeReferenceType As Boolean Implements IGenericParameter.MustBeReferenceType
Get
Return Me.HasReferenceTypeConstraint
End Get
End Property
Private ReadOnly Property IGenericParameterMustBeValueType As Boolean Implements IGenericParameter.MustBeValueType
Get
Return Me.HasValueTypeConstraint
End Get
End Property
Private ReadOnly Property IGenericParameterMustHaveDefaultConstructor As Boolean Implements IGenericParameter.MustHaveDefaultConstructor
Get
' add constructor constraint for value type constrained
' type parameters to comply with Dev11 output
Return Me.HasConstructorConstraint OrElse Me.HasValueTypeConstraint
End Get
End Property
Private ReadOnly Property IGenericParameterVariance As TypeParameterVariance Implements IGenericParameter.Variance
Get
Select Case Me.Variance
Case VarianceKind.None
Return TypeParameterVariance.NonVariant
Case VarianceKind.In
Return TypeParameterVariance.Contravariant
Case VarianceKind.Out
Return TypeParameterVariance.Covariant
Case Else
Throw ExceptionUtilities.UnexpectedValue(Me.Variance)
End Select
End Get
End Property
Private ReadOnly Property IGenericMethodParameterDefiningMethod As IMethodDefinition Implements IGenericMethodParameter.DefiningMethod
Get
CheckDefinitionInvariant()
Return DirectCast(Me.ContainingSymbol, MethodSymbol)
End Get
End Property
Private ReadOnly Property IGenericTypeParameterDefiningType As ITypeDefinition Implements IGenericTypeParameter.DefiningType
Get
CheckDefinitionInvariant()
Return DirectCast(Me.ContainingSymbol, NamedTypeSymbol)
End Get
End Property
Friend Overrides Function GetUnificationUseSiteDiagnosticRecursive(owner As Symbol, ByRef checkedTypes As HashSet(Of TypeSymbol)) As DiagnosticInfo
Return Nothing
End Function
End Class
End Namespace
|
AlexisArce/roslyn
|
src/Compilers/VisualBasic/Portable/Emit/TypeParameterSymbolAdapter.vb
|
Visual Basic
|
apache-2.0
| 10,988
|
Namespace Security.View_Layout
Public Class Save
Inherits SecurityItemBase
Public Sub New()
_ConceptItemName = "Save"
_ConceptName = "View_Layout"
_Description = "Enable Layout 'Save' button"
_IsEnterprise = True
_IsSmallBusiness = True
_IsViewer = True
_IsWeb = True
_IsWebPlus = True
End Sub
End Class
End Namespace
|
nublet/DMS
|
DMS.Forms.Shared/Security/Items/View/Layout/Save.vb
|
Visual Basic
|
mit
| 455
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rSaldos_DGarantias_CCMV"
'-------------------------------------------------------------------------------------------'
Partial Class rSaldos_DGarantias_CCMV
Inherits vis2formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0))
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0))
Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1))
Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1))
Dim lcParametro2Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2))
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim loComandoSeleccionar As New StringBuilder()
loComandoSeleccionar.AppendLine(" SELECT Clientes.Cod_Cli,")
loComandoSeleccionar.AppendLine(" Clientes.Nom_Cli,")
loComandoSeleccionar.AppendLine(" CASE")
loComandoSeleccionar.AppendLine(" WHEN Clientes.Status = 'A' THEN 'Activo'")
loComandoSeleccionar.AppendLine(" WHEN Clientes.Status = 'I' THEN 'Inactivo'")
loComandoSeleccionar.AppendLine(" WHEN Clientes.Status = 'S' THEN 'Suspendido'")
loComandoSeleccionar.AppendLine(" END AS Status,")
loComandoSeleccionar.AppendLine(" Clientes.Rif,")
loComandoSeleccionar.AppendLine(" Movimientos_Cuentas.Mon_Deb,")
loComandoSeleccionar.AppendLine(" Movimientos_Cuentas.Mon_Hab")
loComandoSeleccionar.AppendLine(" INTO #tmpTemporal")
loComandoSeleccionar.AppendLine(" FROM Clientes JOIN Movimientos_Cuentas")
loComandoSeleccionar.AppendLine(" ON Movimientos_Cuentas.Cod_Reg = Clientes.Cod_Cli")
loComandoSeleccionar.AppendLine(" WHERE Movimientos_Cuentas.Status = 'Confirmado'")
loComandoSeleccionar.AppendLine(" AND Movimientos_Cuentas.Cla_Doc = 'Cliente'")
loComandoSeleccionar.AppendLine(" AND Clientes.Cod_Cli BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Movimientos_Cuentas.Cod_Cue BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Clientes.Status IN (" & lcParametro2Desde & ")")
loComandoSeleccionar.AppendLine(" ORDER BY " & lcOrdenamiento)
loComandoSeleccionar.AppendLine(" SELECT Cod_Cli,")
loComandoSeleccionar.AppendLine(" Nom_Cli,")
loComandoSeleccionar.AppendLine(" Status,")
loComandoSeleccionar.AppendLine(" Rif,")
loComandoSeleccionar.AppendLine(" SUM(Mon_Deb) AS Mon_Deb,")
loComandoSeleccionar.AppendLine(" SUM(Mon_Hab) AS Mon_Hab,")
loComandoSeleccionar.AppendLine(" SUM(Mon_Deb - Mon_Hab) AS Saldo")
loComandoSeleccionar.AppendLine(" FROM #tmpTemporal")
loComandoSeleccionar.AppendLine(" GROUP BY Cod_Cli,")
loComandoSeleccionar.AppendLine(" Nom_Cli,")
loComandoSeleccionar.AppendLine(" Status,")
loComandoSeleccionar.AppendLine(" Rif")
loComandoSeleccionar.AppendLine(" ORDER BY Cod_Cli,")
loComandoSeleccionar.AppendLine(" Nom_Cli,")
loComandoSeleccionar.AppendLine(" Status,")
loComandoSeleccionar.AppendLine(" Rif")
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes")
'--------------------------------------------------'
' Carga la imagen del logo en cusReportes '
'--------------------------------------------------'
Me.mCargarLogoEmpresa(laDatosReporte.Tables(0), "LogoEmpresa")
'-------------------------------------------------------------------------------------------------------
' Verificando si el select (tabla nº0) trae registros
'-------------------------------------------------------------------------------------------------------
If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
"No se Encontraron Registros para los Parámetros Especificados. ", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
"350px", _
"200px")
End If
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rSaldos_DGarantias_CCMV", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrSaldos_DGarantias_CCMV.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo
'-------------------------------------------------------------------------------------------'
' JJD: 09/06/10: Codigo inicial
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
rSaldos_DGarantias_CCMV.aspx.vb
|
Visual Basic
|
mit
| 7,392
|
''' <summary></summary>
''' <autogenerated>Generated from a T4 template. Modifications will be lost, if applicable use a partial class instead.</autogenerated>
''' <generator-date>17/02/2014 16:02:02</generator-date>
''' <generator-functions>1</generator-functions>
''' <generator-source>Deimos\General\Enums\OfficePageState.tt</generator-source>
''' <generator-version>1</generator-version>
<System.CodeDom.Compiler.GeneratedCode("Deimos\General\Enums\OfficePageState.tt", "1")> _
Public Enum OfficePageState As System.Int32
''' <summary>Indicates no State, e.g. no Page</summary>
None = 0
''' <summary>Indicates Page was already Open</summary>
Existing = 1
''' <summary>Indicates Page was Created</summary>
Created = 2
End Enum
|
thiscouldbejd/Deimos
|
General/Enums/OfficePageState.vb
|
Visual Basic
|
mit
| 739
|
Option Infer On
Imports System
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim partDocument As SolidEdgePart.PartDocument = Nothing
Dim models As SolidEdgePart.Models = Nothing
Dim model As SolidEdgePart.Model = Nothing
Dim attributeSets As SolidEdgeFramework.AttributeSets = Nothing
Dim attributeSet As SolidEdgeFramework.AttributeSet = Nothing
Dim attribute As SolidEdgeFramework.Attribute = Nothing
Try
' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register()
' Attempt to connect to a running instance of Solid Edge.
application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application)
partDocument = TryCast(application.ActiveDocument, SolidEdgePart.PartDocument)
If partDocument IsNot Nothing Then
models = partDocument.Models
model = models.Item(1)
attributeSets = CType(model.AttributeSets, SolidEdgeFramework.AttributeSets)
attributeSet = attributeSets.Add("My attribute set")
attribute = attributeSet.Add("Attribute1", SolidEdgeFramework.AttributeTypeConstants.seInteger)
Dim attributeType = attribute.Type
End If
Catch ex As System.Exception
Console.WriteLine(ex)
Finally
OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgeFramework.Attribute.Type.vb
|
Visual Basic
|
mit
| 1,833
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.34014
'
' 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("JLStrongPass.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
|
joeylane/JLStrongPass
|
JLStrongPass/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,718
|
Imports System
Imports System.Drawing
Imports System.Drawing.Printing
Imports System.IO
Imports System.Windows.Forms
Imports GemBox.Document
Partial Public Class Form1
Inherits Form
Dim document As DocumentModel
Public Sub New()
ComponentInfo.SetLicense("FREE-LIMITED-KEY")
InitializeComponent()
End Sub
Private Sub LoadFileMenuItem_Click(sender As Object, e As EventArgs) Handles LoadFileMenuItem.Click
Dim openFileDialog As New OpenFileDialog()
openFileDialog.Filter =
"DOCX files (*.docx, *.dotx, *.docm, *.dotm)|*.docx;*.dotx;*.docm;*.dotm" &
"|DOC files (*.doc, *.dot)|*.doc;*.dot" &
"|RTF files (*.rtf)|*.rtf" &
"|HTML files (*.html, *.htm)|*.html;*.htm" &
"|PDF files (*.pdf)|*.pdf" &
"|TXT files (*.txt)|*.txt"
If (openFileDialog.ShowDialog() = DialogResult.OK) Then
Me.document = DocumentModel.Load(openFileDialog.FileName)
Me.ShowPrintPreview()
End If
End Sub
Private Sub PrintFileMenuItem_Click(sender As Object, e As EventArgs) Handles PrintFileMenuItem.Click
If document Is Nothing Then Return
Dim printDialog As New PrintDialog() With {.AllowSomePages = True}
If (printDialog.ShowDialog() = DialogResult.OK) Then
Dim printerSettings As PrinterSettings = printDialog.PrinterSettings
Dim printOptions As New PrintOptions()
' Set PrintOptions properties based on PrinterSettings properties.
printOptions.CopyCount = printerSettings.Copies
printOptions.FromPage = printerSettings.FromPage - 1
printOptions.ToPage = If(printerSettings.ToPage = 0, Integer.MaxValue, printerSettings.ToPage - 1)
Me.document.Print(printerSettings.PrinterName, printOptions)
End If
End Sub
Private Sub ShowPrintPreview()
' Create image for each Word document's page.
Dim images As Image() = Me.CreatePrintPreviewImages()
Dim imageIndex As Integer = 0
' Draw each page's image on PrintDocument for print preview.
Dim printDocument = New PrintDocument()
AddHandler printDocument.PrintPage,
Sub(sender, e)
Using image As Image = images(imageIndex)
Dim graphics = e.Graphics
Dim region = graphics.VisibleClipBounds
' Rotate image if it has landscape orientation.
If image.Width > image.Height Then image.RotateFlip(RotateFlipType.Rotate270FlipNone)
graphics.DrawImage(image, 0, 0, region.Width, region.Height)
End Using
imageIndex += 1
e.HasMorePages = imageIndex < images.Length
End Sub
Me.PageUpDown.Value = 1
Me.PageUpDown.Maximum = images.Length
Me.printPreviewControl.Document = printDocument
End Sub
Private Function CreatePrintPreviewImages() As Image()
Dim pageCount As Integer = Me.document.GetPaginator().Pages.Count
Dim images = New Image(pageCount - 1) {}
For pageIndex As Integer = 0 To pageCount - 1
Dim imageStream = New MemoryStream()
Dim imageOptions = New ImageSaveOptions() With {.PageNumber = pageIndex}
Me.document.Save(imageStream, imageOptions)
images(pageIndex) = Image.FromStream(imageStream)
Next
Return images
End Function
Private Sub PageUpDown_ValueChanged(sender As Object, e As EventArgs) Handles PageUpDown.ValueChanged
Me.printPreviewControl.StartPage = Me.PageUpDown.Value - 1
End Sub
End Class
|
gemboxsoftware-dev-team/GemBox.Document.Examples
|
VB.NET/Common Uses/Print/PrintInWinForms/Form1.vb
|
Visual Basic
|
mit
| 3,717
|
Namespace UI
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class CriteriaItemControl
Inherits UserControl
'UserControl overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()>
Protected Overrides Sub dispose(disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
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.
<System.Diagnostics.DebuggerStepThrough()>
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(CriteriaItemControl))
Me.LayoutPanel = New System.Windows.Forms.TableLayoutPanel()
Me.mbProperties = New StaxRip.UI.MenuButton()
Me.bnRemove = New System.Windows.Forms.Button()
Me.te = New StaxRip.UI.TextEdit()
Me.mbCondition = New StaxRip.UI.MenuButton()
Me.LayoutPanel.SuspendLayout()
Me.SuspendLayout()
'
'LayoutPanel
'
Me.LayoutPanel.AutoSize = True
Me.LayoutPanel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.LayoutPanel.ColumnCount = 4
Me.LayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 40.0!))
Me.LayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 30.0!))
Me.LayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 30.0!))
Me.LayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle())
Me.LayoutPanel.Controls.Add(Me.mbProperties, 0, 0)
Me.LayoutPanel.Controls.Add(Me.bnRemove, 3, 0)
Me.LayoutPanel.Controls.Add(Me.mbCondition, 1, 0)
Me.LayoutPanel.Controls.Add(Me.te, 2, 0)
Me.LayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill
Me.LayoutPanel.Location = New System.Drawing.Point(0, 0)
Me.LayoutPanel.Name = "LayoutPanel"
Me.LayoutPanel.RowCount = 1
Me.LayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle())
Me.LayoutPanel.Size = New System.Drawing.Size(911, 175)
Me.LayoutPanel.TabIndex = 0
'
'mbProperties
'
Me.mbProperties.Anchor = CType((System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.mbProperties.Location = New System.Drawing.Point(3, 70)
Me.mbProperties.ShowMenuSymbol = True
Me.mbProperties.Size = New System.Drawing.Size(292, 35)
'
'bnRemove
'
Me.bnRemove.Anchor = System.Windows.Forms.AnchorStyles.None
Me.bnRemove.AutoSize = True
Me.bnRemove.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.bnRemove.Location = New System.Drawing.Point(749, 58)
Me.bnRemove.Name = "bnRemove"
Me.bnRemove.Size = New System.Drawing.Size(158, 58)
Me.bnRemove.TabIndex = 3
Me.bnRemove.Text = "Remove"
Me.bnRemove.UseVisualStyleBackColor = True
'
'te
'
Me.te.Anchor = CType((System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.te.Location = New System.Drawing.Point(525, 70)
Me.te.Name = "te"
Me.te.Size = New System.Drawing.Size(218, 35)
Me.te.TabIndex = 4
'
'mbCondition
'
Me.mbCondition.Anchor = CType((System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.mbCondition.Location = New System.Drawing.Point(301, 70)
Me.mbCondition.ShowMenuSymbol = True
Me.mbCondition.Size = New System.Drawing.Size(218, 35)
'
'CriteriaItemControl
'
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None
Me.BackColor = System.Drawing.SystemColors.Window
Me.Controls.Add(Me.LayoutPanel)
Me.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Margin = New System.Windows.Forms.Padding(0)
Me.Name = "CriteriaItemControl"
Me.Size = New System.Drawing.Size(911, 175)
Me.LayoutPanel.ResumeLayout(False)
Me.LayoutPanel.PerformLayout()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents LayoutPanel As System.Windows.Forms.TableLayoutPanel
Public WithEvents bnRemove As System.Windows.Forms.Button
Friend WithEvents te As StaxRip.UI.TextEdit
Friend WithEvents mbCondition As MenuButton
Friend WithEvents mbProperties As MenuButton
End Class
End Namespace
|
stax76/staxrip
|
UI/Criteria/CriteriaItemControl.Designer.vb
|
Visual Basic
|
mit
| 5,642
|
Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Diagnostics
Imports System.IO
Imports System.Xml
Imports AnimatGuiCtrls.Controls
Imports AnimatGUI.Framework
Namespace DataObjects.Behavior
Public Class LinkedSynapse
Inherits AnimatGUI.Framework.DataObject
#Region " Attributes "
Protected m_bnNode As AnimatGUI.DataObjects.Behavior.Node
Protected m_blLink As AnimatGUI.DataObjects.Behavior.Link
#End Region
#Region " Properties "
<Browsable(False)> _
Public Property Node() As AnimatGUI.DataObjects.Behavior.Node
Get
Return m_bnNode
End Get
Set(ByVal Value As AnimatGUI.DataObjects.Behavior.Node)
m_bnNode = Value
End Set
End Property
<Browsable(False)> _
Public Property Link() As AnimatGUI.DataObjects.Behavior.Link
Get
Return m_blLink
End Get
Set(ByVal Value As AnimatGUI.DataObjects.Behavior.Link)
m_blLink = Value
End Set
End Property
<Browsable(False)> _
Public Overrides Property ViewSubProperties() As Boolean
Get
Return False
End Get
Set(ByVal Value As Boolean)
End Set
End Property
#End Region
#Region " Methods "
Public Sub New(ByVal doParent As AnimatGUI.Framework.DataObject)
MyBase.New(doParent)
End Sub
Public Sub New(ByRef bnNode As AnimatGUI.DataObjects.Behavior.Node, ByRef blLink As AnimatGUI.DataObjects.Behavior.Link)
MyBase.New(blLink)
m_bnNode = bnNode
m_blLink = blLink
End Sub
Public Overrides Function Clone(ByVal doParent As AnimatGUI.Framework.DataObject, ByVal bCutData As Boolean, _
ByVal doRoot As AnimatGUI.Framework.DataObject) As AnimatGUI.Framework.DataObject
Dim oNew As New LinkedSynapse(doParent)
oNew.Node = Me.Node
oNew.Link = Me.Link
Return oNew
End Function
Public Overrides Sub BuildProperties(ByRef propTable As AnimatGuiCtrls.Controls.PropertyTable)
End Sub
Public Overrides Sub BuildPropertyDropDown(ByRef ctrlDropDown As System.Windows.Forms.Control)
If m_bnNode Is Nothing Then Return
If TypeOf m_bnNode Is AnimatGUI.DataObjects.Behavior.Nodes.OffPage Then
Dim doNode As AnimatGUI.DataObjects.Behavior.Nodes.OffPage = DirectCast(m_bnNode, AnimatGUI.DataObjects.Behavior.Nodes.OffPage)
If doNode.LinkedNode Is Nothing OrElse doNode.LinkedNode.Node Is Nothing Then Return
m_bnNode = doNode.LinkedNode.Node
End If
If Not TypeOf (ctrlDropDown) Is ListBox Then
Throw New System.Exception("The control passed into LinkedSynapse.BuildPropertyDropDown is not a listbox type")
End If
Dim lbList As ListBox = DirectCast(ctrlDropDown, ListBox)
lbList.BeginUpdate()
lbList.Items.Clear()
Dim lbSelectedItem As AnimatGUI.TypeHelpers.DropDownEntry = Nothing
For Each oLink As DictionaryEntry In m_bnNode.InLinks
Dim blLink As AnimatGUI.DataObjects.Behavior.Link = DirectCast(oLink.Value, AnimatGUI.DataObjects.Behavior.Link)
If TypeOf (blLink) Is Synapses.Normal Then
Dim lsSynapse As AnimatGUI.Framework.DataObject = New LinkedSynapse(m_bnNode, blLink)
Dim leItem As New AnimatGUI.TypeHelpers.DropDownEntry((blLink.Origin.Text & " (" & Replace(blLink.Text, vbCrLf, " ") & ")"), lsSynapse)
lbList.Items.Add(leItem)
If Not m_blLink Is Nothing AndAlso m_blLink.ID = blLink.ID Then
lbSelectedItem = leItem
End If
End If
Next
If Not lbSelectedItem Is Nothing Then lbList.SelectedItem = lbSelectedItem
lbList.DisplayMember = "Display"
lbList.ValueMember = "Value"
MyBase.FormatDropDownList(lbList)
lbList.EndUpdate()
lbList.Invalidate()
End Sub
#End Region
End Class
End Namespace
|
NeuroRoboticTech/AnimatLabPublicSource
|
Libraries/FiringRateGUI/DataObjects/Behavior/LinkedSynapse.vb
|
Visual Basic
|
bsd-3-clause
| 4,547
|
' 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.v201309
Imports System
Imports System.Collections.Generic
Imports System.IO
Namespace Google.Api.Ads.AdWords.Examples.VB.v201309
''' <summary>
''' This code example deletes a keyword using the 'REMOVE' operator. To get
''' keywords, run GetKeywords.vb.
'''
''' Tags: AdGroupCriterionService.mutate
''' </summary>
Public Class DeleteKeyword
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 DeleteKeyword
Console.WriteLine(codeExample.Description)
Try
Dim adGroupId As Long = Long.Parse("INSERT_ADGROUP_ID_HERE")
Dim keywordId As Long = Long.Parse("INSERT_KEYWORD_ID_HERE")
codeExample.Run(New AdWordsUser, adGroupId, keywordId)
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 a keyword using the 'REMOVE' operator. To get " & _
"keywords, run GetKeywords.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 that contains the keyword.
''' </param>
''' <param name="keywordId">Id of the keyword to be deleted.</param>
Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId As Long, ByVal keywordId As Long)
' Get the AdGroupCriterionService.
Dim adGroupCriterionService As AdGroupCriterionService = user.GetService( _
AdWordsService.v201309.AdGroupCriterionService)
' Create base class criterion to avoid setting keyword-specific
' fields.
Dim criterion As New Criterion
criterion.id = keywordId
' Create the ad group criterion.
Dim adGroupCriterion As New BiddableAdGroupCriterion
adGroupCriterion.adGroupId = adGroupId
adGroupCriterion.criterion = criterion
' Create the operation.
Dim operation As New AdGroupCriterionOperation
operation.operand = adGroupCriterion
operation.operator = [Operator].REMOVE
Try
' Delete the keyword.
Dim retVal As AdGroupCriterionReturnValue = adGroupCriterionService.mutate( _
New AdGroupCriterionOperation() {operation})
' Display the results.
If ((Not retVal Is Nothing) AndAlso (Not retVal.value Is Nothing) AndAlso _
(retVal.value.Length > 0)) Then
Dim deletedKeyword As AdGroupCriterion = retVal.value(0)
Console.WriteLine("Keyword with ad group id = ""{0}"" and id = ""{1}"" was " & _
"deleted.", deletedKeyword.adGroupId, deletedKeyword.criterion.id)
Else
Console.WriteLine("No keywords were deleted.")
End If
Catch ex As Exception
Throw New System.ApplicationException("Failed to delete keywords.", ex)
End Try
End Sub
End Class
End Namespace
|
akilb/googleads-adwords-dotnet-lib
|
examples/adwords/VB/v201309/BasicOperations/DeleteKeyword.vb
|
Visual Basic
|
apache-2.0
| 4,064
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.18444
'
' 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("ucGridcoinProgressBar.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
|
Lederstrumpf/Gridcoin-Research
|
contrib/Installer/ucGridcoinProgressBar/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,730
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Expressions
Public Class GlobalKeywordRecommenderTests
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NoneInClassDeclarationTest()
VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalInStatementTest()
VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterReturnTest()
VerifyRecommendationsContain(<MethodBody>Return |</MethodBody>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterArgument1Test()
VerifyRecommendationsContain(<MethodBody>Goo(|</MethodBody>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterArgument2Test()
VerifyRecommendationsContain(<MethodBody>Goo(bar, |</MethodBody>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterBinaryExpressionTest()
VerifyRecommendationsContain(<MethodBody>Goo(bar + |</MethodBody>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterNotTest()
VerifyRecommendationsContain(<MethodBody>Goo(Not |</MethodBody>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterTypeOfTest()
VerifyRecommendationsContain(<MethodBody>If TypeOf |</MethodBody>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterDoWhileTest()
VerifyRecommendationsContain(<MethodBody>Do While |</MethodBody>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterDoUntilTest()
VerifyRecommendationsContain(<MethodBody>Do Until |</MethodBody>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterLoopWhileTest()
VerifyRecommendationsContain(<MethodBody>
Do
Loop While |</MethodBody>, "Global")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterLoopUntilTest()
VerifyRecommendationsContain(<MethodBody>
Do
Loop Until |</MethodBody>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterIfTest()
VerifyRecommendationsContain(<MethodBody>If |</MethodBody>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterElseIfTest()
VerifyRecommendationsContain(<MethodBody>ElseIf |</MethodBody>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterElseSpaceIfTest()
VerifyRecommendationsContain(<MethodBody>Else If |</MethodBody>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterErrorTest()
VerifyRecommendationsContain(<MethodBody>Error |</MethodBody>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterThrowTest()
VerifyRecommendationsContain(<MethodBody>Throw |</MethodBody>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterInitializerTest()
VerifyRecommendationsContain(<MethodBody>Dim x = |</MethodBody>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterArrayInitializerSquiggleTest()
VerifyRecommendationsContain(<MethodBody>Dim x = {|</MethodBody>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterArrayInitializerCommaTest()
VerifyRecommendationsContain(<MethodBody>Dim x = {0, |</MethodBody>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalNotAfterItselfTest()
VerifyRecommendationsMissing(<MethodBody>Global.|</MethodBody>, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalNotAfterImportsTest()
VerifyRecommendationsMissing(<File>Imports |</File>, "Global")
End Sub
<WorkItem(543270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543270")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInDelegateCreationTest()
Dim code =
<File>
Module Program
Sub Main(args As String())
Dim f1 As New Goo2( |
End Sub
Delegate Sub Goo2()
Function Bar2() As Object
Return Nothing
End Function
End Module
</File>
VerifyRecommendationsMissing(code, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterInheritsTest()
Dim code =
<File>
Class C
Inherits |
End Class
</File>
VerifyRecommendationsContain(code, "Global")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub GlobalAfterImplementsTest()
Dim code =
<File>
Class C
Implements |
End Class
</File>
VerifyRecommendationsContain(code, "Global")
End Sub
End Class
End Namespace
|
physhi/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/Expressions/GlobalKeywordRecommenderTests.vb
|
Visual Basic
|
apache-2.0
| 6,383
|
' Licensed to the .NET Foundation under one or more 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.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.Shared.Extensions
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Utilities
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Extenders
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.MethodXml
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel
Partial Friend Class VisualBasicCodeModelService
Inherits AbstractCodeModelService
Private ReadOnly _commitBufferManagerFactory As CommitBufferManagerFactory
Friend Sub New(provider As HostLanguageServices, editorOptionsFactoryService As IEditorOptionsFactoryService, refactorNotifyServices As IEnumerable(Of IRefactorNotifyService), commitBufferManagerFactory As CommitBufferManagerFactory, threadingContext As IThreadingContext)
MyBase.New(
provider,
editorOptionsFactoryService,
refactorNotifyServices,
LineAdjustmentFormattingRule.Instance,
EndRegionFormattingRule.Instance,
threadingContext)
Me._commitBufferManagerFactory = commitBufferManagerFactory
End Sub
Private Shared ReadOnly s_codeTypeRefAsFullNameFormat As SymbolDisplayFormat =
New SymbolDisplayFormat(
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.ExpandNullable)
Private Shared ReadOnly s_codeTypeRefAsStringFormat As SymbolDisplayFormat =
New SymbolDisplayFormat(
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes)
Private Shared ReadOnly s_externalNameFormat As SymbolDisplayFormat =
New SymbolDisplayFormat(
genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.ExpandNullable,
parameterOptions:=SymbolDisplayParameterOptions.IncludeName)
Private Shared ReadOnly s_externalfullNameFormat As SymbolDisplayFormat =
New SymbolDisplayFormat(
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:=SymbolDisplayMemberOptions.IncludeContainingType,
miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.ExpandNullable,
parameterOptions:=SymbolDisplayParameterOptions.IncludeName)
Private Shared ReadOnly s_setTypeFormat As SymbolDisplayFormat =
New SymbolDisplayFormat(
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.ExpandNullable Or SymbolDisplayMiscellaneousOptions.UseSpecialTypes)
Private Shared ReadOnly s_raiseEventSignatureFormat As SymbolDisplayFormat =
New SymbolDisplayFormat(
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
parameterOptions:=SymbolDisplayParameterOptions.IncludeName Or SymbolDisplayParameterOptions.IncludeParamsRefOut Or SymbolDisplayParameterOptions.IncludeType,
miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes)
Private Shared Function IsNameableNode(node As SyntaxNode) As Boolean
Select Case node.Kind
Case SyntaxKind.Attribute,
SyntaxKind.ClassBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.EnumBlock,
SyntaxKind.EnumMemberDeclaration,
SyntaxKind.EventBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.NamespaceBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.Parameter,
SyntaxKind.PropertyBlock,
SyntaxKind.StructureBlock,
SyntaxKind.SubBlock,
SyntaxKind.OptionStatement,
SyntaxKind.SimpleImportsClause,
SyntaxKind.InheritsStatement,
SyntaxKind.ImplementsStatement
Return True
Case SyntaxKind.NameColonEquals
Return True
Case SyntaxKind.SimpleArgument,
SyntaxKind.OmittedArgument
' Only arguments in attributes are valid
Return node.FirstAncestorOrSelf(Of AttributeSyntax) IsNot Nothing
Case SyntaxKind.ModifiedIdentifier
Return node.FirstAncestorOrSelf(Of FieldDeclarationSyntax)() IsNot Nothing
Case SyntaxKind.EventStatement
' Only top-level event statements that aren't included in an event block are valid (e.g. single line events)
Return node.FirstAncestorOrSelf(Of EventBlockSyntax)() Is Nothing
Case SyntaxKind.PropertyStatement
' Only top-level property statements that aren't included in an property block are valid (e.g. auto-properties)
Return node.FirstAncestorOrSelf(Of PropertyBlockSyntax)() Is Nothing
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
Return node.FirstAncestorOrSelf(Of MethodBlockSyntax)() Is Nothing
Case Else
Return False
End Select
End Function
Public Overrides Function GetElementKind(node As SyntaxNode) As EnvDTE.vsCMElement
Select Case node.Kind
Case SyntaxKind.ModuleBlock
Return EnvDTE.vsCMElement.vsCMElementModule
Case SyntaxKind.ClassBlock
Return EnvDTE.vsCMElement.vsCMElementClass
Case Else
Debug.Fail("Unsupported element kind" & CType(node.Kind, SyntaxKind))
Throw Exceptions.ThrowEInvalidArg()
End Select
End Function
Public Overrides Function MatchesScope(node As SyntaxNode, scope As EnvDTE.vsCMElement) As Boolean
'TODO: This has been copied from CSharpCodeModelService. Tweak to implement VB semantics.
Select Case node.Kind
Case SyntaxKind.NamespaceBlock
If scope = EnvDTE.vsCMElement.vsCMElementNamespace AndAlso
node.Parent IsNot Nothing Then
Return True
End If
Case SyntaxKind.ModuleBlock
If scope = EnvDTE.vsCMElement.vsCMElementModule Then
Return True
End If
Case SyntaxKind.ClassBlock
If scope = EnvDTE.vsCMElement.vsCMElementClass Then
Return True
End If
Case SyntaxKind.StructureBlock
If scope = EnvDTE.vsCMElement.vsCMElementStruct Then
Return True
End If
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
If scope = EnvDTE.vsCMElement.vsCMElementFunction AndAlso
node.FirstAncestorOrSelf(Of MethodBlockSyntax)() Is Nothing Then
Return True
End If
Case SyntaxKind.ConstructorBlock,
SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
If scope = EnvDTE.vsCMElement.vsCMElementFunction Then
Return True
End If
Case SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement
If scope = EnvDTE.vsCMElement.vsCMElementDeclareDecl Then
Return True
End If
Case SyntaxKind.EnumMemberDeclaration
If scope = EnvDTE.vsCMElement.vsCMElementVariable Then
Return True
End If
Case SyntaxKind.FieldDeclaration
If scope = EnvDTE.vsCMElement.vsCMElementVariable Then
Return True
End If
Case SyntaxKind.EventBlock
If scope = EnvDTE.vsCMElement.vsCMElementEvent Then
Return True
End If
Case SyntaxKind.EventStatement
If Not TypeOf node.Parent Is EventBlockSyntax Then
If scope = EnvDTE.vsCMElement.vsCMElementEvent Then
Return True
End If
End If
Case SyntaxKind.PropertyBlock
If scope = EnvDTE.vsCMElement.vsCMElementProperty Then
Return True
End If
Case SyntaxKind.PropertyStatement
If Not TypeOf node.Parent Is PropertyBlockSyntax Then
If scope = EnvDTE.vsCMElement.vsCMElementProperty Then
Return True
End If
End If
Case SyntaxKind.Attribute
If scope = EnvDTE.vsCMElement.vsCMElementAttribute Then
Return True
End If
Case SyntaxKind.InterfaceBlock
If scope = EnvDTE.vsCMElement.vsCMElementInterface Then
Return True
End If
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
If scope = EnvDTE.vsCMElement.vsCMElementDelegate Then
Return True
End If
Case SyntaxKind.EnumBlock
If scope = EnvDTE.vsCMElement.vsCMElementEnum Then
Return True
End If
Case SyntaxKind.StructureBlock
If scope = EnvDTE.vsCMElement.vsCMElementStruct Then
Return True
End If
Case SyntaxKind.SimpleImportsClause
If scope = EnvDTE.vsCMElement.vsCMElementImportStmt Then
Return True
End If
Case SyntaxKind.ModifiedIdentifier,
SyntaxKind.VariableDeclarator
If node.Parent.Kind <> SyntaxKind.Parameter Then
' The parent of an identifier/variable declarator may be a
' field. If the parent matches the desired scope, then this
' node matches as well.
Return MatchesScope(node.Parent, scope)
End If
Case SyntaxKind.Parameter
If scope = EnvDTE.vsCMElement.vsCMElementParameter Then
Return True
End If
Case SyntaxKind.OptionStatement
If scope = EnvDTE.vsCMElement.vsCMElementOptionStmt Then
Return True
End If
Case SyntaxKind.InheritsStatement
If scope = EnvDTE.vsCMElement.vsCMElementInheritsStmt Then
Return True
End If
Case SyntaxKind.ImplementsStatement
If scope = EnvDTE.vsCMElement.vsCMElementImplementsStmt Then
Return True
End If
Case Else
Return False
End Select
Return False
End Function
Public Overrides Function GetOptionNodes(parent As SyntaxNode) As IEnumerable(Of SyntaxNode)
If TypeOf parent Is CompilationUnitSyntax Then
Return DirectCast(parent, CompilationUnitSyntax).Options.AsEnumerable()
End If
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End Function
Private Overloads Shared Function GetImportNodes(parent As CompilationUnitSyntax) As IEnumerable(Of SyntaxNode)
Dim result = New List(Of SyntaxNode)
For Each importStatement In parent.Imports
For Each importClause In importStatement.ImportsClauses
' NOTE: XmlNamespaceImportsClause is not support by VB Code Model
If importClause.IsKind(SyntaxKind.SimpleImportsClause) Then
result.Add(importClause)
End If
Next
Next
Return result
End Function
Public Overrides Function GetImportNodes(parent As SyntaxNode) As IEnumerable(Of SyntaxNode)
If TypeOf parent Is CompilationUnitSyntax Then
Return GetImportNodes(DirectCast(parent, CompilationUnitSyntax))
End If
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End Function
Private Overloads Shared Function GetAttributeNodes(attributesBlockList As SyntaxList(Of AttributeListSyntax)) As IEnumerable(Of SyntaxNode)
Dim result = New List(Of SyntaxNode)
For Each attributeBlock In attributesBlockList
For Each attribute In attributeBlock.Attributes
result.Add(attribute)
Next
Next
Return result
End Function
Private Overloads Shared Function GetAttributeNodes(attributesStatementList As SyntaxList(Of AttributesStatementSyntax)) As IEnumerable(Of SyntaxNode)
Dim result = New List(Of SyntaxNode)
For Each attributesStatement In attributesStatementList
For Each attributeBlock In attributesStatement.AttributeLists
For Each attribute In attributeBlock.Attributes
result.Add(attribute)
Next
Next
Next
Return result
End Function
Public Overrides Function GetAttributeNodes(node As SyntaxNode) As IEnumerable(Of SyntaxNode)
If TypeOf node Is CompilationUnitSyntax Then
Return GetAttributeNodes(DirectCast(node, CompilationUnitSyntax).Attributes)
ElseIf TypeOf node Is TypeBlockSyntax Then
Return GetAttributeNodes(DirectCast(node, TypeBlockSyntax).BlockStatement.AttributeLists)
ElseIf TypeOf node Is EnumBlockSyntax Then
Return GetAttributeNodes(DirectCast(node, EnumBlockSyntax).EnumStatement.AttributeLists)
ElseIf TypeOf node Is DelegateStatementSyntax Then
Return GetAttributeNodes(DirectCast(node, DelegateStatementSyntax).AttributeLists)
ElseIf TypeOf node Is DeclareStatementSyntax Then
Return GetAttributeNodes(DirectCast(node, DeclareStatementSyntax).AttributeLists)
ElseIf TypeOf node Is MethodStatementSyntax Then
Return GetAttributeNodes(DirectCast(node, MethodStatementSyntax).AttributeLists)
ElseIf TypeOf node Is MethodBlockBaseSyntax Then
Return GetAttributeNodes(DirectCast(node, MethodBlockBaseSyntax).BlockStatement.AttributeLists)
ElseIf TypeOf node Is PropertyBlockSyntax Then
Return GetAttributeNodes(DirectCast(node, PropertyBlockSyntax).PropertyStatement.AttributeLists)
ElseIf TypeOf node Is PropertyStatementSyntax Then
Return GetAttributeNodes(DirectCast(node, PropertyStatementSyntax).AttributeLists)
ElseIf TypeOf node Is EventBlockSyntax Then
Return GetAttributeNodes(DirectCast(node, EventBlockSyntax).EventStatement.AttributeLists)
ElseIf TypeOf node Is EventStatementSyntax Then
Return GetAttributeNodes(DirectCast(node, EventStatementSyntax).AttributeLists)
ElseIf TypeOf node Is FieldDeclarationSyntax Then
Return GetAttributeNodes(DirectCast(node, FieldDeclarationSyntax).AttributeLists)
ElseIf TypeOf node Is ParameterSyntax Then
Return GetAttributeNodes(DirectCast(node, ParameterSyntax).AttributeLists)
ElseIf TypeOf node Is EnumMemberDeclarationSyntax Then
Return GetAttributeNodes(DirectCast(node, EnumMemberDeclarationSyntax).AttributeLists)
ElseIf TypeOf node Is ModifiedIdentifierSyntax OrElse
TypeOf node Is VariableDeclaratorSyntax Then
Return GetAttributeNodes(node.Parent)
End If
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End Function
Public Overrides Function GetAttributeArgumentNodes(parent As SyntaxNode) As IEnumerable(Of SyntaxNode)
If TypeOf parent Is AttributeSyntax Then
Dim attribute = DirectCast(parent, AttributeSyntax)
If attribute.ArgumentList Is Nothing Then
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End If
Return attribute.ArgumentList.Arguments
End If
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End Function
Public Overrides Function GetInheritsNodes(parent As SyntaxNode) As IEnumerable(Of SyntaxNode)
If TypeOf parent Is TypeBlockSyntax Then
Dim typeBlock = DirectCast(parent, TypeBlockSyntax)
Return typeBlock.Inherits.AsEnumerable()
End If
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End Function
Public Overrides Function GetImplementsNodes(parent As SyntaxNode) As IEnumerable(Of SyntaxNode)
If TypeOf parent Is TypeBlockSyntax Then
Dim typeBlock = DirectCast(parent, TypeBlockSyntax)
Return typeBlock.Implements.AsEnumerable()
End If
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End Function
Private Shared Function IsContainerNode(container As SyntaxNode) As Boolean
Return TypeOf container Is CompilationUnitSyntax OrElse
TypeOf container Is NamespaceBlockSyntax OrElse
TypeOf container Is TypeBlockSyntax OrElse
TypeOf container Is EnumBlockSyntax
End Function
Private Shared Function IsNamespaceOrTypeDeclaration(node As SyntaxNode) As Boolean
Return node.Kind() = SyntaxKind.NamespaceBlock OrElse
TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is EnumBlockSyntax OrElse
TypeOf node Is DelegateStatementSyntax
End Function
Private Shared Iterator Function GetChildMemberNodes(container As SyntaxNode) As IEnumerable(Of DeclarationStatementSyntax)
If TypeOf container Is CompilationUnitSyntax Then
For Each member In DirectCast(container, CompilationUnitSyntax).Members
If IsNamespaceOrTypeDeclaration(member) Then
Yield DirectCast(member, DeclarationStatementSyntax)
End If
Next
ElseIf TypeOf container Is NamespaceBlockSyntax Then
For Each member In DirectCast(container, NamespaceBlockSyntax).Members
If IsNamespaceOrTypeDeclaration(member) Then
Yield DirectCast(member, DeclarationStatementSyntax)
End If
Next
ElseIf TypeOf container Is TypeBlockSyntax Then
For Each member In DirectCast(container, TypeBlockSyntax).Members
If member.Kind() <> SyntaxKind.NamespaceBlock AndAlso TypeOf member Is DeclarationStatementSyntax Then
Yield DirectCast(member, DeclarationStatementSyntax)
End If
Next
ElseIf TypeOf container Is EnumBlockSyntax Then
For Each member In DirectCast(container, EnumBlockSyntax).Members
If member.Kind() = SyntaxKind.EnumMemberDeclaration Then
Yield DirectCast(member, DeclarationStatementSyntax)
End If
Next
End If
End Function
Private Shared Function NodeIsSupported(test As Boolean, node As SyntaxNode) As Boolean
Return Not test OrElse IsNameableNode(node)
End Function
''' <summary>
''' Retrieves the members of a specified <paramref name="container"/> node. The members that are
''' returned can be controlled by passing various parameters.
''' </summary>
''' <param name="container">The <see cref="SyntaxNode"/> from which to retrieve members.</param>
''' <param name="includeSelf">If true, the container Is returned as well.</param>
''' <param name="recursive">If true, members are recursed to return descendant members as well
''' as immediate children. For example, a namespace would return the namespaces And types within.
''' However, if <paramref name="recursive"/> Is true, members with the namespaces And types would
''' also be returned.</param>
''' <param name="logicalFields">If true, field declarations are broken into their respective declarators.
''' For example, the field "Dim x, y As Integer" would return two nodes, one for x And one for y in place
''' of the field.</param>
''' <param name="onlySupportedNodes">If true, only members supported by Code Model are returned.</param>
Public Overrides Iterator Function GetMemberNodes(container As SyntaxNode, includeSelf As Boolean, recursive As Boolean, logicalFields As Boolean, onlySupportedNodes As Boolean) As IEnumerable(Of SyntaxNode)
If Not IsContainerNode(container) Then
Exit Function
End If
If includeSelf AndAlso NodeIsSupported(onlySupportedNodes, container) Then
Yield container
End If
For Each member In GetChildMemberNodes(container)
If member.Kind = SyntaxKind.FieldDeclaration Then
' For fields, the 'logical' and 'supported' flags are intrinsically tied.
' * If 'logical' is true, only declarators should be returned, regardless of the value of 'supported'.
' * If 'logical' is false, the field should only be returned if 'supported' is also false.
If logicalFields Then
For Each declarator In DirectCast(member, FieldDeclarationSyntax).Declarators
' We know that declarators are supported, so there's no need to check them here.
For Each identifier In declarator.Names
Yield identifier
Next
Next
ElseIf Not onlySupportedNodes Then
' Only return fields if the supported flag Is false.
Yield member
End If
ElseIf NodeIsSupported(onlySupportedNodes, member) Then
Yield member
End If
If recursive AndAlso IsContainerNode(member) Then
For Each innerMember In GetMemberNodes(member, includeSelf:=False, recursive:=True, logicalFields:=logicalFields, onlySupportedNodes:=onlySupportedNodes)
Yield innerMember
Next
End If
Next
End Function
Public Overrides ReadOnly Property Language As String
Get
Return EnvDTE.CodeModelLanguageConstants.vsCMLanguageVB
End Get
End Property
Public Overrides ReadOnly Property AssemblyAttributeString As String
Get
Return "Assembly"
End Get
End Property
''' <summary>
''' Do not use this method directly! Instead, go through <see cref="FileCodeModel.GetOrCreateCodeElement(Of T)(SyntaxNode)"/>
''' </summary>
Public Overloads Overrides Function CreateInternalCodeElement(
state As CodeModelState,
fileCodeModel As FileCodeModel,
node As SyntaxNode
) As EnvDTE.CodeElement
Select Case node.Kind
Case SyntaxKind.Attribute
Return CType(CreateInternalCodeAttribute(state, fileCodeModel, node), EnvDTE.CodeElement)
Case SyntaxKind.NameColonEquals
Return Nothing
Case SyntaxKind.SimpleArgument
Return CType(CreateInternalCodeAttributeArgument(state, fileCodeModel, node), EnvDTE.CodeElement)
Case SyntaxKind.SimpleImportsClause
Return CType(CreateInternalCodeImport(state, fileCodeModel, node), EnvDTE.CodeElement)
Case SyntaxKind.ImportsStatement
Dim importsStatement = DirectCast(node, ImportsStatementSyntax)
Return CreateInternalCodeElement(state, fileCodeModel, importsStatement.ImportsClauses(0))
Case SyntaxKind.Parameter
Return CType(CreateInternalCodeParameter(state, fileCodeModel, node), EnvDTE.CodeElement)
Case SyntaxKind.OptionStatement
Return CType(CreateInternalCodeOptionStatement(state, fileCodeModel, node), EnvDTE.CodeElement)
Case SyntaxKind.InheritsStatement
Return CType(CreateInternalCodeInheritsStatement(state, fileCodeModel, node), EnvDTE.CodeElement)
Case SyntaxKind.ImplementsStatement
Return CType(CreateInternalCodeImplementsStatement(state, fileCodeModel, node), EnvDTE.CodeElement)
End Select
If IsAccessorNode(node) Then
Return CType(CreateInternalCodeAccessorFunction(state, fileCodeModel, node), EnvDTE.CodeElement)
End If
Dim nodeKey = GetNodeKey(node)
Select Case node.Kind
Case SyntaxKind.ClassBlock,
SyntaxKind.ModuleBlock
Return CType(CodeClass.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.StructureBlock
Return CType(CodeStruct.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.InterfaceBlock
Return CType(CodeInterface.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.EnumBlock
Return CType(CodeEnum.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return CType(CodeDelegate.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.ConstructorBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.SubBlock,
SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
Return CType(CodeFunctionWithEventHandler.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement
Return CType(CodeFunctionDeclareDecl.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.PropertyBlock,
SyntaxKind.PropertyStatement
Return CType(CodeProperty.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.EventBlock,
SyntaxKind.EventStatement
Return CType(CodeEvent.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.NamespaceBlock
Return CType(CodeNamespace.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case SyntaxKind.ModifiedIdentifier,
SyntaxKind.EnumMemberDeclaration
Return CType(CodeVariable.Create(state, fileCodeModel, nodeKey, node.Kind), EnvDTE.CodeElement)
Case Else
Throw New NotImplementedException()
End Select
End Function
Public Overrides Function CreateUnknownCodeElement(state As CodeModelState, fileCodeModel As FileCodeModel, node As SyntaxNode) As EnvDTE.CodeElement
Select Case node.Kind
Case SyntaxKind.ClassBlock,
SyntaxKind.ModuleBlock
Return CType(CodeClass.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.StructureBlock
Return CType(CodeStruct.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.InterfaceBlock
Return CType(CodeInterface.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.EnumBlock
Return CType(CodeEnum.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return CType(CodeDelegate.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.ConstructorBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.SubBlock,
SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
Return CType(CodeFunctionWithEventHandler.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement
Return CType(CodeFunctionDeclareDecl.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.PropertyBlock,
SyntaxKind.PropertyStatement
Return CType(CodeProperty.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.EventBlock,
SyntaxKind.EventStatement
Return CType(CodeEvent.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.NamespaceBlock
Return CType(CodeNamespace.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.ModifiedIdentifier,
SyntaxKind.EnumMemberDeclaration
Return CType(CodeVariable.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.SimpleImportsClause
Return CType(CodeImport.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.OptionStatement
Return CType(CodeOptionsStatement.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.InheritsStatement
Return CType(CodeInheritsStatement.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case SyntaxKind.ImplementsStatement
Return CType(CodeImplementsStatement.CreateUnknown(state, fileCodeModel, node.Kind, GetName(node)), EnvDTE.CodeElement)
Case Else
Throw New NotImplementedException()
End Select
End Function
Public Overrides Function CreateUnknownRootNamespaceCodeElement(state As CodeModelState, fileCodeModel As FileCodeModel) As EnvDTE.CodeElement
Dim compilation = CType(fileCodeModel.GetCompilation(), Compilation)
Dim rootNamespace = DirectCast(compilation.Options, VisualBasicCompilationOptions).RootNamespace
Return CType(CodeNamespace.CreateUnknown(state, fileCodeModel, SyntaxKind.NamespaceBlock, rootNamespace), EnvDTE.CodeElement)
End Function
Private Shared Function IsValidTypeRefKind(kind As EnvDTE.vsCMTypeRef) As Boolean
Return kind = EnvDTE.vsCMTypeRef.vsCMTypeRefVoid OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefObject OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefBool OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefByte OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefShort OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefInt OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefLong OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefDecimal OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefFloat OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefDouble OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefChar OrElse
kind = EnvDTE.vsCMTypeRef.vsCMTypeRefString OrElse
kind = EnvDTE80.vsCMTypeRef2.vsCMTypeRefSByte OrElse
kind = EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedInt OrElse
kind = EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedLong OrElse
kind = EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedShort
End Function
Public Overrides Function CreateCodeTypeRef(state As CodeModelState, projectId As ProjectId, type As Object) As EnvDTE.CodeTypeRef
Dim project = state.Workspace.CurrentSolution.GetProject(projectId)
If project Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Dim compilation = project.GetCompilationAsync().Result
If TypeOf type Is Byte OrElse
TypeOf type Is Short OrElse
TypeOf type Is Integer Then
Dim typeRefKind = CType(type, EnvDTE.vsCMTypeRef)
If Not IsValidTypeRefKind(typeRefKind) Then
Throw Exceptions.ThrowEInvalidArg()
End If
Dim specialType = GetSpecialType(typeRefKind)
Return CodeTypeRef.Create(state, Nothing, projectId, compilation.GetSpecialType(specialType))
End If
Dim typeName As String
Dim parent As Object = Nothing
If TypeOf type Is String Then
typeName = CStr(type)
ElseIf TypeOf type Is EnvDTE.CodeType Then
typeName = CType(type, EnvDTE.CodeType).FullName
parent = type
Else
Throw Exceptions.ThrowEInvalidArg()
End If
Dim typeSymbol = GetTypeSymbolFromFullName(typeName, compilation)
If typeSymbol Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Return CodeTypeRef.Create(state, parent, projectId, typeSymbol)
End Function
Public Overrides Function GetTypeKindForCodeTypeRef(typeSymbol As ITypeSymbol) As EnvDTE.vsCMTypeRef
' Rough translation of CodeModelSymbol::GetTypeKind from vb\Language\VsPackage\CodeModelHelpers.cpp
If typeSymbol.SpecialType = SpecialType.System_Void Then
Return EnvDTE.vsCMTypeRef.vsCMTypeRefVoid
End If
If typeSymbol.TypeKind = TypeKind.Array Then
Return EnvDTE.vsCMTypeRef.vsCMTypeRefArray
End If
If typeSymbol.TypeKind = TypeKind.Pointer Then
typeSymbol = DirectCast(typeSymbol, IPointerTypeSymbol).PointedAtType
End If
If typeSymbol IsNot Nothing AndAlso Not typeSymbol.TypeKind = TypeKind.Error Then
If typeSymbol.SpecialType = SpecialType.System_Object Then
Return EnvDTE.vsCMTypeRef.vsCMTypeRefObject
End If
If typeSymbol.TypeKind = TypeKind.Enum Then
Return EnvDTE.vsCMTypeRef.vsCMTypeRefCodeType
End If
Select Case typeSymbol.SpecialType
Case SpecialType.System_Boolean
Return EnvDTE.vsCMTypeRef.vsCMTypeRefBool
Case SpecialType.System_SByte
Return CType(EnvDTE80.vsCMTypeRef2.vsCMTypeRefSByte, EnvDTE.vsCMTypeRef)
Case SpecialType.System_Byte
Return EnvDTE.vsCMTypeRef.vsCMTypeRefByte
Case SpecialType.System_Int16
Return EnvDTE.vsCMTypeRef.vsCMTypeRefShort
Case SpecialType.System_UInt16
Return CType(EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedShort, EnvDTE.vsCMTypeRef)
Case SpecialType.System_Int32
Return EnvDTE.vsCMTypeRef.vsCMTypeRefInt
Case SpecialType.System_UInt32
Return CType(EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedInt, EnvDTE.vsCMTypeRef)
Case SpecialType.System_Int64
Return EnvDTE.vsCMTypeRef.vsCMTypeRefLong
Case SpecialType.System_UInt64
Return CType(EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedLong, EnvDTE.vsCMTypeRef)
Case SpecialType.System_Decimal
Return EnvDTE.vsCMTypeRef.vsCMTypeRefDecimal
Case SpecialType.System_Single
Return EnvDTE.vsCMTypeRef.vsCMTypeRefFloat
Case SpecialType.System_Double
Return EnvDTE.vsCMTypeRef.vsCMTypeRefDouble
Case SpecialType.System_Char
Return EnvDTE.vsCMTypeRef.vsCMTypeRefChar
Case SpecialType.System_String
Return EnvDTE.vsCMTypeRef.vsCMTypeRefString
End Select
If typeSymbol.TypeKind = TypeKind.Pointer Then
Return EnvDTE.vsCMTypeRef.vsCMTypeRefPointer
End If
If typeSymbol.TypeKind = TypeKind.TypeParameter Then
Return EnvDTE.vsCMTypeRef.vsCMTypeRefOther
End If
Return EnvDTE.vsCMTypeRef.vsCMTypeRefCodeType
End If
Return EnvDTE.vsCMTypeRef.vsCMTypeRefOther
End Function
Public Overrides Function GetAsFullNameForCodeTypeRef(typeSymbol As ITypeSymbol) As String
Return typeSymbol.ToDisplayString(s_codeTypeRefAsFullNameFormat)
End Function
Public Overrides Function GetAsStringForCodeTypeRef(typeSymbol As ITypeSymbol) As String
Return typeSymbol.ToDisplayString(s_codeTypeRefAsStringFormat)
End Function
Public Overrides Function IsParameterNode(node As SyntaxNode) As Boolean
Return TypeOf node Is ParameterSyntax
End Function
Public Overrides Function IsAttributeNode(node As SyntaxNode) As Boolean
Return TypeOf node Is AttributeSyntax
End Function
Public Overrides Function IsAttributeArgumentNode(node As SyntaxNode) As Boolean
Return TypeOf node Is SimpleArgumentSyntax OrElse
TypeOf node Is OmittedArgumentSyntax
End Function
Public Overrides Function IsOptionNode(node As SyntaxNode) As Boolean
Return TypeOf node Is OptionStatementSyntax
End Function
Public Overrides Function IsImportNode(node As SyntaxNode) As Boolean
Return TypeOf node Is SimpleImportsClauseSyntax
End Function
Public Overrides Function GetUnescapedName(name As String) As String
Return If(name IsNot Nothing AndAlso name.Length > 2 AndAlso name.StartsWith("[", StringComparison.Ordinal) AndAlso name.EndsWith("]", StringComparison.Ordinal),
name.Substring(1, name.Length - 2),
name)
End Function
Private Function GetNormalizedName(node As SyntaxNode) As String
Dim nameBuilder = New StringBuilder()
Dim token = node.GetFirstToken(includeSkipped:=True)
While True
nameBuilder.Append(token.ToString())
Dim nextToken = token.GetNextToken(includeSkipped:=True)
If Not nextToken.IsDescendantOf(node) Then
Exit While
End If
If (token.IsKeyword() OrElse token.Kind = SyntaxKind.IdentifierToken) AndAlso
(nextToken.IsKeyword() OrElse nextToken.Kind = SyntaxKind.IdentifierToken) Then
nameBuilder.Append(" "c)
End If
token = nextToken
End While
Return nameBuilder.ToString().Trim()
End Function
Public Overrides Function GetName(node As SyntaxNode) As String
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
Debug.Assert(TypeOf node Is SyntaxNode)
Debug.Assert(IsNameableNode(node))
Select Case node.Kind
Case SyntaxKind.Attribute
Return GetNormalizedName(DirectCast(node, AttributeSyntax).Name)
Case SyntaxKind.ClassBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.StructureBlock
Return DirectCast(node, TypeBlockSyntax).BlockStatement.Identifier.ToString()
Case SyntaxKind.EnumBlock
Return DirectCast(node, EnumBlockSyntax).EnumStatement.Identifier.ToString()
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return DirectCast(node, DelegateStatementSyntax).Identifier.ToString()
Case SyntaxKind.NamespaceBlock
Return DirectCast(node, NamespaceBlockSyntax).NamespaceStatement.Name.ToString()
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock
Dim methodBlock = DirectCast(node, MethodBlockSyntax)
Return methodBlock.SubOrFunctionStatement.Identifier.ToString()
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
Return DirectCast(node, MethodStatementSyntax).Identifier.ToString()
Case SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement
Return DirectCast(node, DeclareStatementSyntax).Identifier.ToString()
Case SyntaxKind.ConstructorBlock
Dim methodBlock = DirectCast(node, ConstructorBlockSyntax)
Return methodBlock.SubNewStatement.NewKeyword.ToString()
Case SyntaxKind.OperatorBlock
Dim operatorBlock = DirectCast(node, OperatorBlockSyntax)
Return operatorBlock.OperatorStatement.OperatorToken.ToString()
Case SyntaxKind.PropertyBlock
Dim propertyBlock = DirectCast(node, PropertyBlockSyntax)
Return propertyBlock.PropertyStatement.Identifier.ToString()
Case SyntaxKind.PropertyStatement
Return DirectCast(node, PropertyStatementSyntax).Identifier.ToString()
Case SyntaxKind.EventBlock
Return DirectCast(node, EventBlockSyntax).EventStatement.Identifier.ToString()
Case SyntaxKind.EventStatement
Return DirectCast(node, EventStatementSyntax).Identifier.ToString()
Case SyntaxKind.ModifiedIdentifier
Return DirectCast(node, ModifiedIdentifierSyntax).Identifier.ToString()
Case SyntaxKind.EnumMemberDeclaration
Return DirectCast(node, EnumMemberDeclarationSyntax).Identifier.ToString()
Case SyntaxKind.SimpleArgument
Dim simpleArgument = DirectCast(node, SimpleArgumentSyntax)
Return If(simpleArgument.IsNamed,
simpleArgument.NameColonEquals.Name.ToString(),
String.Empty)
Case SyntaxKind.OmittedArgument
Return String.Empty
Case SyntaxKind.Parameter
Return GetParameterName(node)
Case SyntaxKind.OptionStatement
Return GetNormalizedName(node)
Case SyntaxKind.SimpleImportsClause
Return GetNormalizedName(DirectCast(node, ImportsClauseSyntax).GetName())
Case SyntaxKind.InheritsStatement
Return DirectCast(node, InheritsStatementSyntax).InheritsKeyword.ToString()
Case SyntaxKind.ImplementsStatement
Return DirectCast(node, ImplementsStatementSyntax).ImplementsKeyword.ToString()
Case Else
Debug.Fail(String.Format("Invalid node kind: {0}", node.Kind))
Throw New ArgumentException()
End Select
End Function
Public Overrides Function SetName(node As SyntaxNode, name As String) As SyntaxNode
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
' In all cases, the resulting syntax for the new name has elastic trivia attached,
' whether via this call to SyntaxFactory.Identifier or via explicitly added elastic
' markers.
Dim identifier As SyntaxToken = SyntaxFactory.Identifier(name)
Select Case node.Kind
Case SyntaxKind.Attribute
Return DirectCast(node, AttributeSyntax).WithName(
SyntaxFactory.ParseTypeName(name) _
.WithLeadingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker)) _
.WithTrailingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker)))
Case SyntaxKind.ClassStatement
Return DirectCast(node, ClassStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.InterfaceStatement
Return DirectCast(node, InterfaceStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.ModuleStatement
Return DirectCast(node, ModuleStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.StructureStatement
Return DirectCast(node, StructureStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.EnumStatement
Return DirectCast(node, EnumStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return DirectCast(node, DelegateStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.NamespaceStatement
Return DirectCast(node, NamespaceStatementSyntax).WithName(
SyntaxFactory.ParseName(name) _
.WithLeadingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker)) _
.WithTrailingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker)))
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.SubNewStatement
Return DirectCast(node, MethodStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareFunctionStatement
Return DirectCast(node, DeclareStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.PropertyStatement
Return DirectCast(node, PropertyStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.EventStatement
Return DirectCast(node, EventStatementSyntax).WithIdentifier(identifier)
Case SyntaxKind.ModifiedIdentifier
Return DirectCast(node, ModifiedIdentifierSyntax).WithIdentifier(identifier)
Case SyntaxKind.SimpleArgument
Return DirectCast(node, SimpleArgumentSyntax).WithNameColonEquals(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName(name)))
Case Else
Debug.Fail("Invalid node kind: " & CType(node.Kind, SyntaxKind))
Throw Exceptions.ThrowEFail()
End Select
End Function
Public Overrides Function GetNodeWithName(node As SyntaxNode) As SyntaxNode
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
If node.Kind = SyntaxKind.OperatorBlock Then
Throw Exceptions.ThrowEFail
End If
Debug.Assert(IsNameableNode(node))
Select Case node.Kind
Case SyntaxKind.Attribute
Return node
Case SyntaxKind.ClassBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.StructureBlock
Return DirectCast(node, TypeBlockSyntax).BlockStatement
Case SyntaxKind.EnumBlock
Return DirectCast(node, EnumBlockSyntax).EnumStatement
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return node
Case SyntaxKind.NamespaceBlock
Return DirectCast(node, NamespaceBlockSyntax).NamespaceStatement
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.ConstructorBlock
Return DirectCast(node, MethodBlockBaseSyntax).BlockStatement
Case SyntaxKind.PropertyBlock
Return DirectCast(node, PropertyBlockSyntax).PropertyStatement
Case SyntaxKind.EventBlock
Return DirectCast(node, EventBlockSyntax).EventStatement
Case SyntaxKind.ModifiedIdentifier
Return node
Case SyntaxKind.SimpleArgument
Dim simpleArgument = DirectCast(node, SimpleArgumentSyntax)
Return If(simpleArgument.IsNamed, simpleArgument.NameColonEquals.Name, node)
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement
Return node
Case SyntaxKind.EventStatement
Return node
Case Else
Debug.Fail("Invalid node kind: " & CType(node.Kind, SyntaxKind))
Throw New ArgumentException()
End Select
End Function
Public Overrides Function GetFullName(node As SyntaxNode, semanticModel As SemanticModel) As String
If node.Kind = SyntaxKind.SimpleImportsClause Then
Throw Exceptions.ThrowENotImpl()
End If
Dim symbol = If(TypeOf node Is AttributeSyntax,
semanticModel.GetTypeInfo(node).Type,
semanticModel.GetDeclaredSymbol(node))
Return GetExternalSymbolFullName(symbol)
End Function
Public Overrides Function IsExpressionBodiedProperty(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function TryGetAutoPropertyExpressionBody(parentNode As SyntaxNode, ByRef accessorNode As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function IsAccessorNode(node As SyntaxNode) As Boolean
Select Case node.Kind
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return True
End Select
Return False
End Function
Public Overrides Function GetAccessorKind(node As SyntaxNode) As MethodKind
Select Case node.Kind
Case SyntaxKind.GetAccessorBlock
Return MethodKind.PropertyGet
Case SyntaxKind.SetAccessorBlock
Return MethodKind.PropertySet
Case SyntaxKind.AddHandlerAccessorBlock
Return MethodKind.EventAdd
Case SyntaxKind.RemoveHandlerAccessorBlock
Return MethodKind.EventRemove
Case SyntaxKind.RaiseEventAccessorBlock
Return MethodKind.EventRaise
Case Else
Throw Exceptions.ThrowEUnexpected()
End Select
End Function
Private Overloads Shared Function GetAccessorKind(methodKind As MethodKind) As SyntaxKind
Select Case methodKind
Case MethodKind.PropertyGet
Return SyntaxKind.GetAccessorBlock
Case MethodKind.PropertySet
Return SyntaxKind.SetAccessorBlock
Case MethodKind.EventAdd
Return SyntaxKind.AddHandlerAccessorBlock
Case MethodKind.EventRemove
Return SyntaxKind.RemoveHandlerAccessorBlock
Case MethodKind.EventRaise
Return SyntaxKind.RaiseEventAccessorBlock
Case Else
Throw Exceptions.ThrowEUnexpected()
End Select
End Function
Private Shared Function GetAccessors(node As SyntaxNode) As SyntaxList(Of AccessorBlockSyntax)
Select Case node.Kind()
Case SyntaxKind.PropertyBlock
Return DirectCast(node, PropertyBlockSyntax).Accessors
Case SyntaxKind.EventBlock
Return DirectCast(node, EventBlockSyntax).Accessors
Case Else
Return Nothing
End Select
End Function
Public Overrides Function TryGetAccessorNode(parentNode As SyntaxNode, kind As MethodKind, ByRef accessorNode As SyntaxNode) As Boolean
Dim accessorKind = GetAccessorKind(kind)
For Each accessor In GetAccessors(parentNode)
If accessor.Kind = accessorKind Then
accessorNode = accessor
Return True
End If
Next
accessorNode = Nothing
Return False
End Function
Public Overrides Function TryGetParameterNode(parentNode As SyntaxNode, name As String, ByRef parameterNode As SyntaxNode) As Boolean
For Each parameter As ParameterSyntax In GetParameterNodes(parentNode)
Dim parameterName = GetNameFromParameter(parameter)
If String.Equals(parameterName, name, StringComparison.OrdinalIgnoreCase) Then
parameterNode = parameter
Return True
End If
Next
parameterNode = Nothing
Return False
End Function
Private Overloads Function GetParameterNodes(methodStatement As MethodBaseSyntax) As IEnumerable(Of ParameterSyntax)
Return If(methodStatement.ParameterList IsNot Nothing,
methodStatement.ParameterList.Parameters,
SpecializedCollections.EmptyEnumerable(Of ParameterSyntax))
End Function
Public Overloads Overrides Function GetParameterNodes(parent As SyntaxNode) As IEnumerable(Of SyntaxNode)
If TypeOf parent Is MethodBaseSyntax Then
Return GetParameterNodes(DirectCast(parent, MethodBaseSyntax))
ElseIf TypeOf parent Is MethodBlockBaseSyntax Then
Return GetParameterNodes(DirectCast(parent, MethodBlockBaseSyntax).BlockStatement)
ElseIf TypeOf parent Is PropertyBlockSyntax Then
Return GetParameterNodes(DirectCast(parent, PropertyBlockSyntax).PropertyStatement)
End If
Return SpecializedCollections.EmptyEnumerable(Of ParameterSyntax)()
End Function
Public Overrides Function TryGetImportNode(parentNode As SyntaxNode, dottedName As String, ByRef importNode As SyntaxNode) As Boolean
For Each node In GetImportNodes(parentNode)
If GetImportNamespaceOrType(node) = dottedName Then
importNode = node
Return True
End If
Next
importNode = Nothing
Return False
End Function
Public Overrides Function TryGetOptionNode(parentNode As SyntaxNode, name As String, ordinal As Integer, ByRef optionNode As SyntaxNode) As Boolean
Dim count = -1
For Each [option] As OptionStatementSyntax In GetOptionNodes(parentNode)
If [option].ToString() = name Then
count += 1
If count = ordinal Then
optionNode = [option]
Return True
End If
End If
Next
optionNode = Nothing
Return False
End Function
Public Overrides Function TryGetInheritsNode(parentNode As SyntaxNode, name As String, ordinal As Integer, ByRef inheritsNode As SyntaxNode) As Boolean
Dim count = -1
For Each [inherits] As InheritsStatementSyntax In GetInheritsNodes(parentNode)
If [inherits].Types.ToString() = name Then
count += 1
If count = ordinal Then
inheritsNode = [inherits]
Return True
End If
End If
Next
inheritsNode = Nothing
Return False
End Function
Public Overrides Function TryGetImplementsNode(parentNode As SyntaxNode, name As String, ordinal As Integer, ByRef implementsNode As SyntaxNode) As Boolean
Dim count = -1
For Each [implements] As ImplementsStatementSyntax In GetImplementsNodes(parentNode)
If [implements].Types.ToString() = name Then
count += 1
If count = ordinal Then
implementsNode = [implements]
Return True
End If
End If
Next
implementsNode = Nothing
Return False
End Function
Public Overrides Function TryGetAttributeNode(parentNode As SyntaxNode, name As String, ordinal As Integer, ByRef attributeNode As SyntaxNode) As Boolean
Dim count = -1
For Each attribute As AttributeSyntax In GetAttributeNodes(parentNode)
If attribute.Name.ToString() = name Then
count += 1
If count = ordinal Then
attributeNode = attribute
Return True
End If
End If
Next
attributeNode = Nothing
Return False
End Function
Public Overrides Function TryGetAttributeArgumentNode(attributeNode As SyntaxNode, index As Integer, ByRef attributeArgumentNode As SyntaxNode) As Boolean
Debug.Assert(TypeOf attributeNode Is AttributeSyntax)
Dim attribute = DirectCast(attributeNode, AttributeSyntax)
If attribute.ArgumentList IsNot Nothing AndAlso
attribute.ArgumentList.Arguments.Count > index Then
attributeArgumentNode = attribute.ArgumentList.Arguments(index)
Return True
End If
attributeArgumentNode = Nothing
Return False
End Function
Private Function DeleteMember(document As Document, node As SyntaxNode) As Document
Dim text = document.GetTextSynchronously(CancellationToken.None)
Dim deletionEnd = node.FullSpan.End
Dim deletionStart = node.SpanStart
Dim contiguousEndOfLines = 0
For Each trivia In node.GetLeadingTrivia().Reverse()
If trivia.IsDirective Then
Exit For
End If
If trivia.Kind = SyntaxKind.EndOfLineTrivia Then
If contiguousEndOfLines > 0 Then
Exit For
Else
contiguousEndOfLines += 1
End If
ElseIf trivia.Kind <> SyntaxKind.WhitespaceTrivia Then
contiguousEndOfLines = 0
End If
deletionStart = trivia.FullSpan.Start
Next
text = text.Replace(TextSpan.FromBounds(deletionStart, deletionEnd), String.Empty)
Return document.WithText(text)
End Function
Public Overrides Function Delete(document As Document, node As SyntaxNode) As Document
Select Case node.Kind
Case SyntaxKind.Attribute
Return Delete(document, DirectCast(node, AttributeSyntax))
Case SyntaxKind.SimpleArgument
Return Delete(document, DirectCast(node, ArgumentSyntax))
Case SyntaxKind.Parameter
Return Delete(document, DirectCast(node, ParameterSyntax))
Case SyntaxKind.ModifiedIdentifier
Return Delete(document, DirectCast(node, ModifiedIdentifierSyntax))
Case SyntaxKind.VariableDeclarator
Return Delete(document, DirectCast(node, VariableDeclaratorSyntax))
Case Else
Return DeleteMember(document, node)
End Select
End Function
Private Overloads Function Delete(document As Document, node As ModifiedIdentifierSyntax) As Document
Dim declarator = node.FirstAncestorOrSelf(Of VariableDeclaratorSyntax)()
' If this is the only name in declarator, then delete the entire
' declarator.
If declarator.Names.Count = 1 Then
Return Delete(document, declarator)
Else
Dim newDeclarator = declarator.RemoveNode(node, SyntaxRemoveOptions.KeepEndOfLine).WithAdditionalAnnotations(Formatter.Annotation)
Return document.ReplaceNodeSynchronously(declarator, newDeclarator, CancellationToken.None)
End If
End Function
Private Overloads Function Delete(document As Document, node As VariableDeclaratorSyntax) As Document
Dim declaration = node.FirstAncestorOrSelf(Of FieldDeclarationSyntax)()
' If this is the only declarator in the declaration, then delete
' the entire declarator.
If declaration.Declarators.Count = 1 Then
Return Delete(document, declaration)
Else
Dim newDeclaration = declaration.RemoveNode(node, SyntaxRemoveOptions.KeepEndOfLine).WithAdditionalAnnotations(Formatter.Annotation)
Return document.ReplaceNodeSynchronously(declaration, newDeclaration, CancellationToken.None)
End If
End Function
Private Overloads Function Delete(document As Document, node As AttributeSyntax) As Document
Dim attributeList = node.FirstAncestorOrSelf(Of AttributeListSyntax)()
' If we don't have anything left, then just delete the whole attribute list.
' Keep all leading trivia, but delete all trailing trivia.
If attributeList.Attributes.Count = 1 Then
Dim spanStart = attributeList.SpanStart
Dim spanEnd = attributeList.FullSpan.End
Dim text = document.GetTextSynchronously(CancellationToken.None)
text = text.Replace(TextSpan.FromBounds(spanStart, spanEnd), String.Empty)
Return document.WithText(text)
Else
Dim newAttributeList = attributeList.RemoveNode(node, SyntaxRemoveOptions.KeepEndOfLine)
Return document.ReplaceNodeSynchronously(attributeList, newAttributeList, CancellationToken.None)
End If
End Function
Private Overloads Function Delete(document As Document, node As ArgumentSyntax) As Document
Dim argumentList = node.FirstAncestorOrSelf(Of ArgumentListSyntax)()
Dim newArgumentList = argumentList.RemoveNode(node, SyntaxRemoveOptions.KeepEndOfLine).WithAdditionalAnnotations(Formatter.Annotation)
Return document.ReplaceNodeSynchronously(argumentList, newArgumentList, CancellationToken.None)
End Function
Private Overloads Function Delete(document As Document, node As ParameterSyntax) As Document
Dim parameterList = node.FirstAncestorOrSelf(Of ParameterListSyntax)()
Dim newParameterList = parameterList.RemoveNode(node, SyntaxRemoveOptions.KeepEndOfLine).WithAdditionalAnnotations(Formatter.Annotation)
Return document.ReplaceNodeSynchronously(parameterList, newParameterList, CancellationToken.None)
End Function
Public Overrides Function IsValidExternalSymbol(symbol As ISymbol) As Boolean
Dim methodSymbol = TryCast(symbol, IMethodSymbol)
If methodSymbol IsNot Nothing Then
If methodSymbol.MethodKind = MethodKind.PropertyGet OrElse
methodSymbol.MethodKind = MethodKind.PropertySet OrElse
methodSymbol.MethodKind = MethodKind.EventAdd OrElse
methodSymbol.MethodKind = MethodKind.EventRemove OrElse
methodSymbol.MethodKind = MethodKind.EventRaise Then
Return False
End If
End If
Dim fieldSymbol = TryCast(symbol, IFieldSymbol)
If fieldSymbol IsNot Nothing Then
Dim propertySymbol = TryCast(fieldSymbol.AssociatedSymbol, IPropertySymbol)
If propertySymbol?.IsWithEvents Then
Return True
End If
End If
Return symbol.DeclaredAccessibility = Accessibility.Public OrElse
symbol.DeclaredAccessibility = Accessibility.Protected OrElse
symbol.DeclaredAccessibility = Accessibility.ProtectedOrFriend OrElse
symbol.DeclaredAccessibility = Accessibility.ProtectedAndFriend OrElse
symbol.DeclaredAccessibility = Accessibility.Friend
End Function
Public Overrides Function GetExternalSymbolName(symbol As ISymbol) As String
If symbol Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Return symbol.ToDisplayString(s_externalNameFormat)
End Function
Public Overrides Function GetExternalSymbolFullName(symbol As ISymbol) As String
If symbol Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Return symbol.ToDisplayString(s_externalfullNameFormat)
End Function
Public Overrides Function GetAccess(symbol As ISymbol) As EnvDTE.vsCMAccess
Debug.Assert(symbol IsNot Nothing)
Dim access As EnvDTE.vsCMAccess = 0
Select Case symbol.DeclaredAccessibility
Case Accessibility.Private
access = access Or EnvDTE.vsCMAccess.vsCMAccessPrivate
Case Accessibility.Protected
access = access Or EnvDTE.vsCMAccess.vsCMAccessProtected
Case Accessibility.Internal, Accessibility.Friend
access = access Or EnvDTE.vsCMAccess.vsCMAccessProject
Case Accessibility.ProtectedOrInternal, Accessibility.ProtectedOrFriend
access = access Or EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected
Case Accessibility.ProtectedAndInternal, Accessibility.ProtectedAndFriend
' there is no appropriate mapping for private protected in EnvDTE.vsCMAccess
' See https://github.com/dotnet/roslyn/issues/22406
access = access Or EnvDTE.vsCMAccess.vsCMAccessProject
Case Accessibility.Public
access = access Or EnvDTE.vsCMAccess.vsCMAccessPublic
Case Else
Throw Exceptions.ThrowEFail()
End Select
If TryCast(symbol, IPropertySymbol)?.IsWithEvents Then
access = access Or EnvDTE.vsCMAccess.vsCMAccessWithEvents
End If
Return access
End Function
Public Overrides Function GetAccess(node As SyntaxNode) As EnvDTE.vsCMAccess
Dim member = TryCast(Me.GetNodeWithModifiers(node), StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Dim flags = member.GetModifierFlags()
Dim access As EnvDTE.vsCMAccess
If (flags And ModifierFlags.Public) <> 0 Then
access = EnvDTE.vsCMAccess.vsCMAccessPublic
ElseIf (flags And ModifierFlags.Protected) <> 0 AndAlso
(flags And ModifierFlags.Friend) <> 0 Then
access = EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected
ElseIf (flags And ModifierFlags.Friend) <> 0 Then
access = EnvDTE.vsCMAccess.vsCMAccessProject
ElseIf (flags And ModifierFlags.Protected) <> 0 Then
access = EnvDTE.vsCMAccess.vsCMAccessProtected
ElseIf (flags And ModifierFlags.Private) <> 0 Then
access = EnvDTE.vsCMAccess.vsCMAccessPrivate
Else
' The code does not specify the accessibility, so we need to
' determine the default accessibility
access = GetDefaultAccessibility(member)
End If
If (flags And ModifierFlags.WithEvents) <> 0 Then
access = access Or EnvDTE.vsCMAccess.vsCMAccessWithEvents
End If
Return access
End Function
Public Overrides Function GetNodeWithModifiers(node As SyntaxNode) As SyntaxNode
Return If(TypeOf node Is ModifiedIdentifierSyntax,
node.GetAncestor(Of DeclarationStatementSyntax)(),
node)
End Function
Public Overrides Function GetNodeWithType(node As SyntaxNode) As SyntaxNode
Return If(TypeOf node Is ModifiedIdentifierSyntax,
node.GetAncestor(Of VariableDeclaratorSyntax)(),
node)
End Function
Public Overrides Function GetNodeWithInitializer(node As SyntaxNode) As SyntaxNode
Return If(TypeOf node Is ModifiedIdentifierSyntax,
node.GetAncestor(Of VariableDeclaratorSyntax)(),
node)
End Function
Public Overrides Function SetAccess(node As SyntaxNode, newAccess As EnvDTE.vsCMAccess) As SyntaxNode
Dim member = TryCast(node, StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
If member.Parent.Kind = SyntaxKind.InterfaceBlock OrElse
member.Parent.Kind = SyntaxKind.EnumBlock Then
If newAccess = EnvDTE.vsCMAccess.vsCMAccessDefault OrElse
newAccess = EnvDTE.vsCMAccess.vsCMAccessPublic Then
Return node
Else
Throw Exceptions.ThrowEInvalidArg()
End If
End If
If TypeOf member Is TypeBlockSyntax OrElse
TypeOf member Is EnumBlockSyntax Then
If Not TypeOf member.Parent Is TypeBlockSyntax AndAlso
(newAccess = EnvDTE.vsCMAccess.vsCMAccessPrivate OrElse
newAccess = EnvDTE.vsCMAccess.vsCMAccessProtected OrElse
newAccess = EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) Then
Throw Exceptions.ThrowEInvalidArg()
End If
End If
Dim flags = member.GetModifierFlags() And Not (ModifierFlags.AccessModifierMask Or ModifierFlags.Dim Or ModifierFlags.WithEvents)
If (newAccess And EnvDTE.vsCMAccess.vsCMAccessPrivate) <> 0 Then
flags = flags Or ModifierFlags.Private
ElseIf (newAccess And EnvDTE.vsCMAccess.vsCMAccessProtected) <> 0 Then
flags = flags Or ModifierFlags.Protected
If (newAccess And EnvDTE.vsCMAccess.vsCMAccessProject) <> 0 Then
flags = flags Or ModifierFlags.Friend
End If
ElseIf (newAccess And EnvDTE.vsCMAccess.vsCMAccessPublic) <> 0 Then
flags = flags Or ModifierFlags.Public
ElseIf (newAccess And EnvDTE.vsCMAccess.vsCMAccessProject) <> 0 Then
flags = flags Or ModifierFlags.Friend
ElseIf (newAccess And EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) <> 0 Then
flags = flags Or ModifierFlags.Protected Or ModifierFlags.Friend
ElseIf (newAccess And EnvDTE.vsCMAccess.vsCMAccessDefault) <> 0 Then
' No change
End If
If (newAccess And EnvDTE.vsCMAccess.vsCMAccessWithEvents) <> 0 Then
flags = flags Or ModifierFlags.WithEvents
End If
If flags = 0 AndAlso member.IsKind(SyntaxKind.FieldDeclaration) Then
flags = flags Or ModifierFlags.Dim
End If
Return member.UpdateModifiers(flags)
End Function
Private Overloads Function GetDefaultAccessibility(node As SyntaxNode) As EnvDTE.vsCMAccess
If node.HasAncestor(Of StructureBlockSyntax)() Then
Return EnvDTE.vsCMAccess.vsCMAccessPublic
End If
If TypeOf node Is FieldDeclarationSyntax Then
Return EnvDTE.vsCMAccess.vsCMAccessPrivate
ElseIf (TypeOf node Is MethodBlockBaseSyntax OrElse
TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is EnumBlockSyntax OrElse
TypeOf node Is MethodBaseSyntax OrElse
TypeOf node Is EnumMemberDeclarationSyntax) Then
Return EnvDTE.vsCMAccess.vsCMAccessPublic
End If
Throw Exceptions.ThrowEFail()
End Function
Protected Overrides Function GetAttributeIndexInContainer(containerNode As SyntaxNode, predicate As Func(Of SyntaxNode, Boolean)) As Integer
Dim attributes = GetAttributeNodes(containerNode).ToArray()
Dim index = 0
While index < attributes.Length
Dim attribute = DirectCast(attributes(index), AttributeSyntax)
If predicate(attribute) Then
Dim attributeBlock = DirectCast(attribute.Parent, AttributeListSyntax)
' If this attribute is part of a block with multiple attributes,
' make sure to return the index of the last attribute in the block.
If attributeBlock.Attributes.Count > 1 Then
Dim indexOfAttributeInBlock = attributeBlock.Attributes.IndexOf(attribute)
Return index + (attributeBlock.Attributes.Count - indexOfAttributeInBlock)
End If
Return index + 1
End If
index += 1
End While
Return -1
End Function
Protected Overrides Function GetAttributeArgumentIndexInContainer(containerNode As SyntaxNode, predicate As Func(Of SyntaxNode, Boolean)) As Integer
Dim attributeArguments = GetAttributeArgumentNodes(containerNode).ToArray()
Dim index = 0
While index < attributeArguments.Length
If predicate(attributeArguments(index)) Then
Return index + 1
End If
index += 1
End While
Return -1
End Function
Protected Overrides Function GetImportIndexInContainer(containerNode As SyntaxNode, predicate As Func(Of SyntaxNode, Boolean)) As Integer
Dim importsClauses = GetImportNodes(containerNode).ToArray()
Dim index = 0
While index < importsClauses.Length
Dim importsClause = DirectCast(importsClauses(index), ImportsClauseSyntax)
If predicate(importsClause) Then
Dim importsStatement = DirectCast(importsClause.Parent, ImportsStatementSyntax)
' If this attribute is part of a block with multiple attributes,
' make sure to return the index of the last attribute in the block.
If importsStatement.ImportsClauses.Count > 1 Then
Dim indexOfImportClauseInStatement = importsStatement.ImportsClauses.IndexOf(importsClause)
Return index + (importsStatement.ImportsClauses.Count - indexOfImportClauseInStatement)
End If
Return index + 1
End If
index += 1
End While
Return -1
End Function
Protected Overrides Function GetParameterIndexInContainer(containerNode As SyntaxNode, predicate As Func(Of SyntaxNode, Boolean)) As Integer
Dim parameters = GetParameterNodes(containerNode).ToArray()
For index = 0 To parameters.Length - 1
If predicate(parameters(index)) Then
Return index + 1
End If
Next
Return -1
End Function
Protected Overrides Function GetMemberIndexInContainer(containerNode As SyntaxNode, predicate As Func(Of SyntaxNode, Boolean)) As Integer
Dim members = GetLogicalMemberNodes(containerNode).ToArray()
Dim index = 0
While index < members.Length
Dim member = members(index)
If predicate(member) Then
' Special case: if a modified identifier was specified, make sure we return the index
' of the last modified identifier of the last variable declarator in the parenting field
' declaration.
If member.Kind = SyntaxKind.ModifiedIdentifier Then
Dim modifiedIdentifier = DirectCast(member, ModifiedIdentifierSyntax)
Dim variableDeclarator = DirectCast(member.Parent, VariableDeclaratorSyntax)
Dim fieldDeclaration = DirectCast(variableDeclarator.Parent, FieldDeclarationSyntax)
Dim indexOfNameInDeclarator = variableDeclarator.Names.IndexOf(modifiedIdentifier)
Dim indexOfDeclaratorInField = fieldDeclaration.Declarators.IndexOf(variableDeclarator)
Dim indexOfNameInField = indexOfNameInDeclarator
If indexOfDeclaratorInField > 0 Then
For i = 0 To indexOfDeclaratorInField - 1
indexOfNameInField += fieldDeclaration.Declarators(i).Names.Count
Next
End If
Dim namesInFieldCount = fieldDeclaration.Declarators.SelectMany(Function(v) v.Names).Count()
Return index + (namesInFieldCount - indexOfNameInField)
End If
Return index + 1
End If
index += 1
End While
Return -1
End Function
Public Overrides Sub GetOptionNameAndOrdinal(parentNode As SyntaxNode, optionNode As SyntaxNode, ByRef name As String, ByRef ordinal As Integer)
Debug.Assert(TypeOf optionNode Is OptionStatementSyntax)
name = GetNormalizedName(DirectCast(optionNode, OptionStatementSyntax))
ordinal = -1
For Each [option] As OptionStatementSyntax In GetOptionNodes(parentNode)
If GetNormalizedName([option]) = name Then
ordinal += 1
End If
If [option].Equals(optionNode) Then
Exit For
End If
Next
End Sub
Public Overrides Sub GetInheritsNamespaceAndOrdinal(parentNode As SyntaxNode, inheritsNode As SyntaxNode, ByRef namespaceName As String, ByRef ordinal As Integer)
Debug.Assert(TypeOf inheritsNode Is InheritsStatementSyntax)
namespaceName = DirectCast(inheritsNode, InheritsStatementSyntax).Types.ToString()
ordinal = -1
For Each [inherits] As InheritsStatementSyntax In GetInheritsNodes(parentNode)
If [inherits].Types.ToString() = namespaceName Then
ordinal += 1
End If
If [inherits].Equals(inheritsNode) Then
Exit For
End If
Next
End Sub
Public Overrides Sub GetImplementsNamespaceAndOrdinal(parentNode As SyntaxNode, implementsNode As SyntaxNode, ByRef namespaceName As String, ByRef ordinal As Integer)
Debug.Assert(TypeOf implementsNode Is ImplementsStatementSyntax)
namespaceName = DirectCast(implementsNode, ImplementsStatementSyntax).Types.ToString()
ordinal = -1
For Each [implements] As ImplementsStatementSyntax In GetImplementsNodes(parentNode)
If [implements].Types.ToString() = namespaceName Then
ordinal += 1
End If
If [implements].Equals(implementsNode) Then
Exit For
End If
Next
End Sub
Public Overrides Sub GetAttributeNameAndOrdinal(parentNode As SyntaxNode, attributeNode As SyntaxNode, ByRef name As String, ByRef ordinal As Integer)
Debug.Assert(TypeOf attributeNode Is AttributeSyntax)
name = DirectCast(attributeNode, AttributeSyntax).Name.ToString()
ordinal = -1
For Each attribute As AttributeSyntax In GetAttributeNodes(parentNode)
If attribute.Name.ToString() = name Then
ordinal += 1
End If
If attribute.Equals(attributeNode) Then
Exit For
End If
Next
End Sub
Public Overrides Function GetAttributeTargetNode(attributeNode As SyntaxNode) As SyntaxNode
If TypeOf attributeNode Is AttributeSyntax Then
Return attributeNode
End If
Throw Exceptions.ThrowEUnexpected()
End Function
Public Overrides Function GetAttributeTarget(attributeNode As SyntaxNode) As String
Debug.Assert(TypeOf attributeNode Is AttributeSyntax)
Dim attribute = DirectCast(attributeNode, AttributeSyntax)
Return If(attribute.Target IsNot Nothing,
attribute.Target.AttributeModifier.ToString(),
String.Empty)
End Function
Public Overrides Function SetAttributeTarget(attributeNode As SyntaxNode, value As String) As SyntaxNode
Debug.Assert(TypeOf attributeNode Is AttributeSyntax)
Dim attribute = DirectCast(attributeNode, AttributeSyntax)
Dim target = attribute.Target
If Not String.IsNullOrEmpty(value) Then
' VB only supports Assembly and Module as attribute modifiers.
Dim newModifier As SyntaxToken
If String.Equals(value, "Assembly", StringComparison.OrdinalIgnoreCase) Then
newModifier = SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)
ElseIf String.Equals(value, "Module", StringComparison.OrdinalIgnoreCase) Then
newModifier = SyntaxFactory.Token(SyntaxKind.ModuleKeyword)
Else
Throw Exceptions.ThrowEInvalidArg()
End If
Dim newTarget = If(target IsNot Nothing,
target.WithAttributeModifier(newModifier),
SyntaxFactory.AttributeTarget(newModifier))
Return attribute.WithTarget(newTarget)
Else
Return attribute.WithTarget(Nothing)
End If
End Function
Public Overrides Function GetAttributeValue(attributeNode As SyntaxNode) As String
Debug.Assert(TypeOf attributeNode Is AttributeSyntax)
Dim attribute = DirectCast(attributeNode, AttributeSyntax)
Dim argumentList = attribute.ArgumentList
If argumentList IsNot Nothing Then
Return argumentList.Arguments.ToString()
End If
Return String.Empty
End Function
Public Overrides Function SetAttributeValue(attributeNode As SyntaxNode, value As String) As SyntaxNode
Debug.Assert(TypeOf attributeNode Is AttributeSyntax)
Dim attribute = DirectCast(attributeNode, AttributeSyntax)
Dim argumentList = attribute.ArgumentList
Dim parsedArgumentList = SyntaxFactory.ParseArgumentList("(" & value & ")")
Dim newArgumentList = If(argumentList IsNot Nothing,
argumentList.WithArguments(parsedArgumentList.Arguments),
parsedArgumentList)
Return attribute.WithArgumentList(newArgumentList)
End Function
Public Overrides Function GetNodeWithAttributes(node As SyntaxNode) As SyntaxNode
Return If(TypeOf node Is ModifiedIdentifierSyntax,
node.GetAncestor(Of FieldDeclarationSyntax),
node)
End Function
Public Overrides Function GetEffectiveParentForAttribute(node As SyntaxNode) As SyntaxNode
If node.HasAncestor(Of FieldDeclarationSyntax)() Then
Return node.GetAncestor(Of FieldDeclarationSyntax).Declarators.First().Names.First()
ElseIf node.HasAncestor(Of ParameterSyntax)() Then
Return node.GetAncestor(Of ParameterSyntax)()
Else
Return node.Parent
End If
End Function
Public Overrides Sub GetAttributeArgumentParentAndIndex(attributeArgumentNode As SyntaxNode, ByRef attributeNode As SyntaxNode, ByRef index As Integer)
Debug.Assert(TypeOf attributeArgumentNode Is ArgumentSyntax)
Dim argument = DirectCast(attributeArgumentNode, ArgumentSyntax)
Dim attribute = DirectCast(argument.Ancestors.FirstOrDefault(Function(n) n.Kind = SyntaxKind.Attribute), AttributeSyntax)
attributeNode = attribute
index = attribute.ArgumentList.Arguments.IndexOf(DirectCast(attributeArgumentNode, ArgumentSyntax))
End Sub
Public Overrides Function CreateAttributeNode(name As String, value As String, Optional target As String = Nothing) As SyntaxNode
Dim specifier As AttributeTargetSyntax = Nothing
If target IsNot Nothing Then
Dim contextualKeywordKind = SyntaxFacts.GetContextualKeywordKind(target)
If contextualKeywordKind = SyntaxKind.AssemblyKeyword OrElse
contextualKeywordKind = SyntaxKind.ModuleKeyword Then
specifier = SyntaxFactory.AttributeTarget(SyntaxFactory.Token(contextualKeywordKind, text:=target))
Else
specifier = SyntaxFactory.AttributeTarget(SyntaxFactory.ParseToken(target))
End If
End If
Return SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Attribute(
target:=specifier,
name:=SyntaxFactory.ParseName(name),
argumentList:=SyntaxFactory.ParseArgumentList("(" & value & ")"))))
End Function
Public Overrides Function CreateAttributeArgumentNode(name As String, value As String) As SyntaxNode
If Not String.IsNullOrEmpty(name) Then
Return SyntaxFactory.SimpleArgument(
SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName(name)),
SyntaxFactory.ParseExpression(value))
Else
Return SyntaxFactory.SimpleArgument(SyntaxFactory.ParseExpression(value))
End If
End Function
Public Overrides Function CreateImportNode(name As String, Optional [alias] As String = Nothing) As SyntaxNode
Dim nameSyntax = SyntaxFactory.ParseName(name)
Dim importsClause As ImportsClauseSyntax
If Not String.IsNullOrEmpty([alias]) Then
importsClause = SyntaxFactory.SimpleImportsClause(SyntaxFactory.ImportAliasClause([alias]), nameSyntax)
Else
importsClause = SyntaxFactory.SimpleImportsClause(nameSyntax)
End If
Return SyntaxFactory.ImportsStatement(SyntaxFactory.SingletonSeparatedList(importsClause))
End Function
Public Overrides Function CreateParameterNode(name As String, type As String) As SyntaxNode
Return SyntaxFactory.Parameter(SyntaxFactory.ModifiedIdentifier(name)).WithAsClause(SyntaxFactory.SimpleAsClause(SyntaxFactory.ParseTypeName(type)))
End Function
Public Overrides Function GetAttributeArgumentValue(attributeArgumentNode As SyntaxNode) As String
Select Case attributeArgumentNode.Kind
Case SyntaxKind.SimpleArgument
Return DirectCast(attributeArgumentNode, SimpleArgumentSyntax).Expression.ToString()
End Select
Throw New InvalidOperationException()
End Function
Public Overrides Function GetImportAlias(node As SyntaxNode) As String
Select Case node.Kind
Case SyntaxKind.SimpleImportsClause
Dim simpleImportsClause = DirectCast(node, SimpleImportsClauseSyntax)
Return If(simpleImportsClause.Alias IsNot Nothing,
simpleImportsClause.Alias.Identifier.ToString(),
String.Empty)
Case Else
Throw New InvalidOperationException()
End Select
End Function
Public Overrides Function GetImportNamespaceOrType(node As SyntaxNode) As String
Select Case node.Kind
Case SyntaxKind.SimpleImportsClause
Return GetNormalizedName(DirectCast(node, SimpleImportsClauseSyntax).Name)
Case Else
Throw New InvalidOperationException()
End Select
End Function
Public Overrides Sub GetImportParentAndName(node As SyntaxNode, ByRef parentNode As SyntaxNode, ByRef name As String)
parentNode = Nothing
Select Case node.Kind
Case SyntaxKind.SimpleImportsClause
name = GetNormalizedName(DirectCast(node, SimpleImportsClauseSyntax).Name)
Case Else
Throw New InvalidOperationException()
End Select
End Sub
Public Overrides Function GetParameterName(node As SyntaxNode) As String
Dim parameter = TryCast(node, ParameterSyntax)
If parameter IsNot Nothing Then
Return GetNameFromParameter(parameter)
End If
Throw New InvalidOperationException()
End Function
Private Function GetNameFromParameter(parameter As ParameterSyntax) As String
Dim parameterName As String = parameter.Identifier.Identifier.ToString()
Return If(Not String.IsNullOrEmpty(parameterName) AndAlso SyntaxFactsService.IsTypeCharacter(parameterName.Last()),
parameterName.Substring(0, parameterName.Length - 1),
parameterName)
End Function
Public Overrides Function GetParameterFullName(node As SyntaxNode) As String
Dim parameter = TryCast(node, ParameterSyntax)
If parameter IsNot Nothing Then
Return parameter.Identifier.ToString()
End If
Throw New InvalidOperationException()
End Function
Public Overrides Function GetParameterKind(node As SyntaxNode) As EnvDTE80.vsCMParameterKind
Dim parameter = TryCast(node, ParameterSyntax)
If parameter IsNot Nothing Then
Dim kind = EnvDTE80.vsCMParameterKind.vsCMParameterKindNone
Dim modifiers = parameter.Modifiers
If modifiers.Any(SyntaxKind.OptionalKeyword) Then
kind = kind Or EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional
End If
If modifiers.Any(SyntaxKind.ParamArrayKeyword) Then
kind = kind Or EnvDTE80.vsCMParameterKind.vsCMParameterKindParamArray
End If
If modifiers.Any(SyntaxKind.ByRefKeyword) Then
kind = kind Or EnvDTE80.vsCMParameterKind.vsCMParameterKindRef
Else
kind = kind Or EnvDTE80.vsCMParameterKind.vsCMParameterKindIn
End If
Return kind
End If
Throw New InvalidOperationException()
End Function
Public Overrides Function SetParameterKind(node As SyntaxNode, kind As EnvDTE80.vsCMParameterKind) As SyntaxNode
Dim parameter = TryCast(node, ParameterSyntax)
If parameter Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
If Not IsValidParameterKind(kind) Then
Throw Exceptions.ThrowEInvalidArg()
End If
Dim newModifierList = New List(Of SyntaxToken)
' TODO (tomescht): The Dev11 code allowed different sets of modifiers to be
' set when in batch mode vs non-batch mode.
If (kind And EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional) <> 0 Then
newModifierList.Add(SyntaxFactory.Token(SyntaxKind.OptionalKeyword))
End If
If (kind And EnvDTE80.vsCMParameterKind.vsCMParameterKindIn) <> 0 AndAlso parameter.Modifiers.Any(SyntaxKind.ByValKeyword) Then
' Ensure that we keep ByVal if it was already present.
newModifierList.Add(SyntaxFactory.Token(SyntaxKind.ByValKeyword))
ElseIf (kind And EnvDTE80.vsCMParameterKind.vsCMParameterKindRef) <> 0 Then
newModifierList.Add(SyntaxFactory.Token(SyntaxKind.ByRefKeyword))
End If
If (kind And EnvDTE80.vsCMParameterKind.vsCMParameterKindParamArray) <> 0 Then
newModifierList.Add(SyntaxFactory.Token(SyntaxKind.ParamArrayKeyword))
End If
Return parameter.WithModifiers(SyntaxFactory.TokenList(newModifierList))
End Function
Private Function IsValidParameterKind(kind As EnvDTE80.vsCMParameterKind) As Boolean
Select Case kind
Case EnvDTE80.vsCMParameterKind.vsCMParameterKindNone,
EnvDTE80.vsCMParameterKind.vsCMParameterKindIn,
EnvDTE80.vsCMParameterKind.vsCMParameterKindRef,
EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional,
EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional Or EnvDTE80.vsCMParameterKind.vsCMParameterKindIn,
EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional Or EnvDTE80.vsCMParameterKind.vsCMParameterKindRef,
EnvDTE80.vsCMParameterKind.vsCMParameterKindParamArray,
EnvDTE80.vsCMParameterKind.vsCMParameterKindParamArray Or EnvDTE80.vsCMParameterKind.vsCMParameterKindIn
Return True
End Select
Return False
End Function
Public Overrides Function UpdateParameterKind(parameterKind As EnvDTE80.vsCMParameterKind, passingMode As PARAMETER_PASSING_MODE) As EnvDTE80.vsCMParameterKind
Dim updatedParameterKind = parameterKind
Select Case passingMode
Case PARAMETER_PASSING_MODE.cmParameterTypeIn
updatedParameterKind = updatedParameterKind Or EnvDTE80.vsCMParameterKind.vsCMParameterKindIn
updatedParameterKind = updatedParameterKind And Not EnvDTE80.vsCMParameterKind.vsCMParameterKindRef
updatedParameterKind = updatedParameterKind And Not EnvDTE80.vsCMParameterKind.vsCMParameterKindOut
Case PARAMETER_PASSING_MODE.cmParameterTypeInOut
updatedParameterKind = updatedParameterKind And Not EnvDTE80.vsCMParameterKind.vsCMParameterKindIn
updatedParameterKind = updatedParameterKind Or EnvDTE80.vsCMParameterKind.vsCMParameterKindRef
updatedParameterKind = updatedParameterKind And Not EnvDTE80.vsCMParameterKind.vsCMParameterKindOut
Case PARAMETER_PASSING_MODE.cmParameterTypeOut
Throw Exceptions.ThrowEInvalidArg()
End Select
Return updatedParameterKind
End Function
Public Overrides Function ValidateFunctionKind(containerNode As SyntaxNode, kind As EnvDTE.vsCMFunction, name As String) As EnvDTE.vsCMFunction
If kind = EnvDTE.vsCMFunction.vsCMFunctionSub Then
Return If(name = "New" AndAlso Not TypeOf containerNode Is InterfaceBlockSyntax,
EnvDTE.vsCMFunction.vsCMFunctionConstructor,
kind)
End If
If kind = EnvDTE.vsCMFunction.vsCMFunctionFunction Then
Return kind
End If
Throw Exceptions.ThrowEInvalidArg()
End Function
Public Overrides ReadOnly Property SupportsEventThrower As Boolean
Get
Return True
End Get
End Property
Public Overrides Function GetCanOverride(memberNode As SyntaxNode) As Boolean
Debug.Assert(TypeOf memberNode Is StatementSyntax)
Dim member = TryCast(memberNode, StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
If member.Parent.Kind = SyntaxKind.InterfaceBlock Then
Return True
End If
Dim flags = member.GetModifierFlags()
If (flags And ModifierFlags.NotOverridable) <> 0 Then
Return False
End If
If (flags And ModifierFlags.MustOverride) <> 0 Then
Return True
End If
If (flags And ModifierFlags.Overridable) <> 0 Then
Return True
End If
If (flags And ModifierFlags.Overrides) <> 0 Then
Return True
End If
Return False
End Function
Public Overrides Function SetCanOverride(memberNode As SyntaxNode, value As Boolean) As SyntaxNode
Dim overrideKind = If(value, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone)
Return SetOverrideKind(memberNode, overrideKind)
End Function
Public Overrides Function GetClassKind(typeNode As SyntaxNode, typeSymbol As INamedTypeSymbol) As EnvDTE80.vsCMClassKind
Debug.Assert(TypeOf typeNode Is ClassBlockSyntax OrElse
TypeOf typeNode Is ModuleBlockSyntax)
Dim typeBlock = DirectCast(typeNode, TypeBlockSyntax)
If TypeOf typeBlock Is ModuleBlockSyntax Then
Return EnvDTE80.vsCMClassKind.vsCMClassKindModule
End If
Dim flags = typeBlock.GetModifierFlags()
If (flags And ModifierFlags.Partial) <> 0 Then
Return EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass
End If
If typeSymbol.DeclaringSyntaxReferences.Length > 1 Then
Return EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass
End If
Return EnvDTE80.vsCMClassKind.vsCMClassKindMainClass
End Function
Private Function IsValidClassKind(kind As EnvDTE80.vsCMClassKind) As Boolean
Return kind = EnvDTE80.vsCMClassKind.vsCMClassKindMainClass OrElse
kind = EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass
End Function
Public Overrides Function SetClassKind(typeNode As SyntaxNode, kind As EnvDTE80.vsCMClassKind) As SyntaxNode
Debug.Assert(TypeOf typeNode Is ClassBlockSyntax OrElse
TypeOf typeNode Is ModuleBlockSyntax)
Dim typeBlock = DirectCast(typeNode, StatementSyntax)
If TypeOf typeBlock Is ModuleBlockSyntax Then
If kind = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone Then
Return typeBlock
End If
Throw Exceptions.ThrowENotImpl()
End If
If Not IsValidClassKind(kind) Then
Throw Exceptions.ThrowEInvalidArg()
End If
Dim flags = typeBlock.GetModifierFlags()
flags = flags And Not ModifierFlags.Partial
If kind = EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass Then
flags = flags Or ModifierFlags.Partial
End If
Return typeBlock.UpdateModifiers(flags)
End Function
Private Shared Function CollectComments(triviaList As IList(Of SyntaxTrivia)) As IList(Of SyntaxTrivia)
Dim commentList = New List(Of SyntaxTrivia)
Dim firstCommentFound = False
For i = triviaList.Count - 1 To 0 Step -1
Dim trivia = triviaList(i)
Dim nextTrivia = If(i > 0, triviaList(i - 1), Nothing)
If trivia.Kind = SyntaxKind.CommentTrivia Then
firstCommentFound = True
commentList.Add(trivia)
ElseIf Not firstCommentFound AndAlso trivia.IsWhitespaceOrEndOfLine() Then
Continue For
ElseIf firstCommentFound AndAlso trivia.Kind = SyntaxKind.EndOfLineTrivia AndAlso nextTrivia.Kind = SyntaxKind.CommentTrivia Then
Continue For
Else
Exit For
End If
Next
commentList.Reverse()
Return commentList
End Function
Public Overrides Function GetComment(node As SyntaxNode) As String
Debug.Assert(TypeOf node Is StatementSyntax)
Dim member = DirectCast(node, StatementSyntax)
Dim firstToken = member.GetFirstToken()
Dim triviaList = firstToken.LeadingTrivia
Dim commentList = CollectComments(firstToken.LeadingTrivia.ToArray())
If commentList.Count = 0 Then
Return String.Empty
End If
Dim textBuilder = New StringBuilder()
For Each trivia In commentList
Debug.Assert(trivia.ToString().StartsWith("'", StringComparison.Ordinal))
Dim commentText = trivia.ToString().Substring(1)
textBuilder.AppendLine(commentText)
Next
Return textBuilder.ToString().TrimEnd()
End Function
Public Overrides Function SetComment(node As SyntaxNode, value As String) As SyntaxNode
Debug.Assert(TypeOf node Is StatementSyntax)
Dim member = DirectCast(node, StatementSyntax)
Dim text = member.SyntaxTree.GetText(CancellationToken.None)
Dim newLine = GetNewLineCharacter(text)
Dim commentText = String.Empty
If value IsNot Nothing Then
Dim builder = New StringBuilder()
For Each line In value.Split({vbCr, vbLf}, StringSplitOptions.RemoveEmptyEntries)
builder.Append("' ")
builder.Append(line)
builder.Append(newLine)
Next
commentText = builder.ToString()
End If
Dim newTriviaList = SyntaxFactory.ParseLeadingTrivia(commentText)
Dim leadingTriviaList = member.GetLeadingTrivia().ToList()
Dim commentList = CollectComments(leadingTriviaList)
If commentList.Count > 0 Then
' In this case, we're going to replace the existing comment.
Dim firstIndex = leadingTriviaList.FindIndex(Function(t) t = commentList(0))
Dim lastIndex = leadingTriviaList.FindIndex(Function(t) t = commentList(commentList.Count - 1))
Dim count = lastIndex - firstIndex + 1
leadingTriviaList.RemoveRange(firstIndex, count)
' Note: single line comments have a trailing new-line but that won't be
' returned by CollectComments. So, we may need to remove an additional new line below.
If firstIndex < leadingTriviaList.Count AndAlso
leadingTriviaList(firstIndex).Kind = SyntaxKind.EndOfLineTrivia Then
leadingTriviaList.RemoveAt(firstIndex)
End If
For Each triviaElement In newTriviaList.Reverse()
leadingTriviaList.Insert(firstIndex, triviaElement)
Next
Else
' Otherwise, just add the comment to the end of the leading trivia.
leadingTriviaList.AddRange(newTriviaList)
End If
Return member.WithLeadingTrivia(leadingTriviaList)
End Function
Public Overrides Function GetConstKind(variableNode As SyntaxNode) As EnvDTE80.vsCMConstKind
If TypeOf variableNode Is EnumMemberDeclarationSyntax Then
Return EnvDTE80.vsCMConstKind.vsCMConstKindConst
End If
Dim member = TryCast(GetNodeWithModifiers(variableNode), StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Dim flags = member.GetModifierFlags()
If (flags And ModifierFlags.Const) <> 0 Then
Return EnvDTE80.vsCMConstKind.vsCMConstKindConst
End If
If (flags And ModifierFlags.ReadOnly) <> 0 Then
Return EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly
End If
Return EnvDTE80.vsCMConstKind.vsCMConstKindNone
End Function
Private Function IsValidConstKind(kind As EnvDTE80.vsCMConstKind) As Boolean
Return kind = EnvDTE80.vsCMConstKind.vsCMConstKindConst OrElse
kind = EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly OrElse
kind = EnvDTE80.vsCMConstKind.vsCMConstKindNone
End Function
Public Overrides Function SetConstKind(variableNode As SyntaxNode, kind As EnvDTE80.vsCMConstKind) As SyntaxNode
If TypeOf variableNode Is EnumMemberDeclarationSyntax Then
Throw Exceptions.ThrowENotImpl()
End If
If Not IsValidConstKind(kind) Then
Throw Exceptions.ThrowEInvalidArg()
End If
Dim member = TryCast(GetNodeWithModifiers(variableNode), StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Dim flags = member.GetModifierFlags()
flags = flags And Not (ModifierFlags.Const Or ModifierFlags.ReadOnly Or ModifierFlags.Dim)
If kind = EnvDTE80.vsCMConstKind.vsCMConstKindConst Then
flags = flags Or ModifierFlags.Const
ElseIf kind = EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly Then
flags = flags Or ModifierFlags.ReadOnly
End If
If flags = 0 Then
flags = flags Or ModifierFlags.Dim
End If
Return member.UpdateModifiers(flags)
End Function
Public Overrides Function GetDataTypeKind(typeNode As SyntaxNode, symbol As INamedTypeSymbol) As EnvDTE80.vsCMDataTypeKind
Debug.Assert(TypeOf typeNode Is ClassBlockSyntax OrElse
TypeOf typeNode Is InterfaceBlockSyntax OrElse
TypeOf typeNode Is ModuleBlockSyntax OrElse
TypeOf typeNode Is StructureBlockSyntax)
Dim typeBlock = DirectCast(typeNode, TypeBlockSyntax)
If TypeOf typeBlock Is ModuleBlockSyntax Then
Return EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindModule
End If
Dim flags = typeBlock.GetModifierFlags()
If (flags And ModifierFlags.Partial) <> 0 Then
Return EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindPartial
End If
If symbol.DeclaringSyntaxReferences.Length > 1 Then
Return EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindPartial
End If
Return EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindMain
End Function
Private Function IsValidDataTypeKind(kind As EnvDTE80.vsCMDataTypeKind, allowModule As Boolean) As Boolean
Return kind = EnvDTE80.vsCMClassKind.vsCMClassKindMainClass OrElse
kind = EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass OrElse
(allowModule AndAlso kind = EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindModule)
End Function
Public Overrides Function SetDataTypeKind(typeNode As SyntaxNode, kind As EnvDTE80.vsCMDataTypeKind) As SyntaxNode
Debug.Assert(TypeOf typeNode Is ClassBlockSyntax OrElse
TypeOf typeNode Is InterfaceBlockSyntax OrElse
TypeOf typeNode Is ModuleBlockSyntax OrElse
TypeOf typeNode Is StructureBlockSyntax)
Dim typeBlock = DirectCast(typeNode, TypeBlockSyntax)
If TypeOf typeBlock Is InterfaceBlockSyntax Then
Throw Exceptions.ThrowENotImpl()
End If
Dim allowModule = TypeOf typeBlock Is ClassBlockSyntax OrElse
TypeOf typeBlock Is ModuleBlockSyntax
If Not IsValidDataTypeKind(kind, allowModule) Then
Throw Exceptions.ThrowEFail()
End If
Dim flags = typeBlock.GetModifierFlags()
flags = flags And Not ModifierFlags.Partial
If kind = EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindPartial Then
flags = flags Or ModifierFlags.Partial
End If
' VB supports changing a Module to a Class and vice versa.
If TypeOf typeBlock Is ModuleBlockSyntax Then
If kind = EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindMain OrElse
kind = EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindPartial Then
Dim moduleBlock = DirectCast(typeBlock, ModuleBlockSyntax)
typeBlock = SyntaxFactory.ClassBlock(
classStatement:=SyntaxFactory.ClassStatement(
attributeLists:=moduleBlock.ModuleStatement.AttributeLists,
modifiers:=moduleBlock.ModuleStatement.Modifiers,
classKeyword:=SyntaxFactory.Token(moduleBlock.ModuleStatement.ModuleKeyword.LeadingTrivia, SyntaxKind.ClassKeyword, moduleBlock.ModuleStatement.ModuleKeyword.TrailingTrivia),
identifier:=moduleBlock.ModuleStatement.Identifier,
typeParameterList:=moduleBlock.ModuleStatement.TypeParameterList),
[inherits]:=moduleBlock.Inherits,
[implements]:=moduleBlock.Implements,
members:=moduleBlock.Members,
endClassStatement:=SyntaxFactory.EndClassStatement(
endKeyword:=moduleBlock.EndModuleStatement.EndKeyword,
blockKeyword:=SyntaxFactory.Token(moduleBlock.EndModuleStatement.BlockKeyword.LeadingTrivia, SyntaxKind.ClassKeyword, moduleBlock.EndModuleStatement.BlockKeyword.TrailingTrivia)))
End If
ElseIf TypeOf typeBlock Is ClassBlockSyntax Then
If kind = EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindModule Then
flags = flags And Not ModifierFlags.Shared
Dim classBlock = DirectCast(typeBlock, ClassBlockSyntax)
typeBlock = SyntaxFactory.ModuleBlock(
moduleStatement:=SyntaxFactory.ModuleStatement(
attributeLists:=classBlock.ClassStatement.AttributeLists,
modifiers:=classBlock.ClassStatement.Modifiers,
moduleKeyword:=SyntaxFactory.Token(classBlock.ClassStatement.ClassKeyword.LeadingTrivia, SyntaxKind.ModuleKeyword, classBlock.ClassStatement.ClassKeyword.TrailingTrivia),
identifier:=classBlock.ClassStatement.Identifier,
typeParameterList:=classBlock.ClassStatement.TypeParameterList),
[inherits]:=Nothing,
[implements]:=Nothing,
members:=classBlock.Members,
endModuleStatement:=SyntaxFactory.EndModuleStatement(
endKeyword:=classBlock.EndClassStatement.EndKeyword,
blockKeyword:=SyntaxFactory.Token(classBlock.EndClassStatement.BlockKeyword.LeadingTrivia, SyntaxKind.ModuleKeyword, classBlock.EndClassStatement.BlockKeyword.TrailingTrivia)))
End If
End If
Return typeBlock.UpdateModifiers(flags)
End Function
Private Shared Function GetDocCommentNode(memberDeclaration As StatementSyntax) As DocumentationCommentTriviaSyntax
Dim docCommentTrivia = memberDeclaration _
.GetLeadingTrivia() _
.Reverse() _
.FirstOrDefault(Function(t) t.Kind = SyntaxKind.DocumentationCommentTrivia)
If docCommentTrivia.Kind <> SyntaxKind.DocumentationCommentTrivia Then
Return Nothing
End If
Return DirectCast(docCommentTrivia.GetStructure(), DocumentationCommentTriviaSyntax)
End Function
Public Overrides Function GetDocComment(node As SyntaxNode) As String
Debug.Assert(TypeOf node Is StatementSyntax)
Dim member = DirectCast(node, StatementSyntax)
Dim documentationComment = GetDocCommentNode(member)
If documentationComment Is Nothing Then
Return String.Empty
End If
Dim text = member.SyntaxTree.GetText(CancellationToken.None)
Dim newLine = GetNewLineCharacter(text)
Dim lines = documentationComment.ToString().Split({newLine}, StringSplitOptions.None)
' trim off leading whitespace and exterior trivia.
Dim lengthToStrip = lines(0).GetLeadingWhitespace().Length
Dim linesCount = lines.Length
For i = 1 To lines.Length - 1
Dim line = lines(i).TrimStart()
If line.StartsWith("'''", StringComparison.Ordinal) Then
lines(i) = line.Substring(3)
End If
Next
Return lines.Join(newLine).TrimEnd()
End Function
Public Overrides Function SetDocComment(node As SyntaxNode, value As String) As SyntaxNode
Debug.Assert(TypeOf node Is StatementSyntax)
Dim member = DirectCast(node, StatementSyntax)
Dim triviaList = CType(Nothing, SyntaxTriviaList)
If value IsNot Nothing Then
Dim text = member.SyntaxTree.GetText(CancellationToken.None)
Dim newLine = GetNewLineCharacter(text)
Dim builder = New StringBuilder()
For Each line In value.Split({vbCr, vbLf}, StringSplitOptions.RemoveEmptyEntries)
builder.Append("''' ")
builder.Append(line)
builder.Append(newLine)
Next
triviaList = SyntaxFactory.ParseLeadingTrivia(builder.ToString())
End If
Dim leadingTriviaList = member.GetLeadingTrivia().ToList()
Dim documentationComment = GetDocCommentNode(member)
If documentationComment IsNot Nothing Then
' In this case, we're going to replace the existing XML doc comment.
Dim index = leadingTriviaList.FindIndex(Function(t) t = documentationComment.ParentTrivia)
leadingTriviaList.RemoveAt(index)
For Each triviaElement In triviaList.Reverse()
leadingTriviaList.Insert(index, triviaElement)
Next
Else
' Otherwise, just add the XML doc comment to the end of the leading trivia.
leadingTriviaList.AddRange(triviaList)
End If
Return member.WithLeadingTrivia(leadingTriviaList)
End Function
Public Overrides Function GetFunctionKind(symbol As IMethodSymbol) As EnvDTE.vsCMFunction
If symbol.IsOverride AndAlso symbol.Name = "Finalize" Then
Return EnvDTE.vsCMFunction.vsCMFunctionDestructor
End If
Select Case symbol.MethodKind
Case MethodKind.Ordinary,
MethodKind.DeclareMethod
Return If(symbol.ReturnsVoid, EnvDTE.vsCMFunction.vsCMFunctionSub, EnvDTE.vsCMFunction.vsCMFunctionFunction)
Case MethodKind.Constructor,
MethodKind.StaticConstructor
Return EnvDTE.vsCMFunction.vsCMFunctionConstructor
Case MethodKind.UserDefinedOperator
Return EnvDTE.vsCMFunction.vsCMFunctionOperator
Case MethodKind.PropertyGet
Return EnvDTE.vsCMFunction.vsCMFunctionPropertyGet
Case MethodKind.PropertySet
Return EnvDTE.vsCMFunction.vsCMFunctionPropertySet
Case MethodKind.EventAdd
Return CType(EnvDTE80.vsCMFunction2.vsCMFunctionAddHandler, EnvDTE.vsCMFunction)
Case MethodKind.EventRemove
Return CType(EnvDTE80.vsCMFunction2.vsCMFunctionRemoveHandler, EnvDTE.vsCMFunction)
Case MethodKind.EventRaise
Return CType(EnvDTE80.vsCMFunction2.vsCMFunctionRaiseEvent, EnvDTE.vsCMFunction)
End Select
Throw Exceptions.ThrowEUnexpected()
End Function
Public Overrides Function GetInheritanceKind(typeNode As SyntaxNode, typeSymbol As INamedTypeSymbol) As EnvDTE80.vsCMInheritanceKind
Dim result As EnvDTE80.vsCMInheritanceKind = 0
If typeSymbol.IsSealed Then
result = result Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed
ElseIf typeSymbol.IsAbstract Then
result = result Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract
End If
' Old VB code model had a special case to check other parts for Shadows, so we'll do that here..
Dim statements = typeSymbol.DeclaringSyntaxReferences _
.Select(Function(r) TryCast(r.GetSyntax(), StatementSyntax)) _
.Where(Function(s) s IsNot Nothing)
For Each statement In statements
Dim modifiers = SyntaxFactory.TokenList(statement.GetModifiers())
If modifiers.Any(SyntaxKind.ShadowsKeyword) Then
result = result Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew
Exit For
End If
Next
Return result
End Function
Private Function IsValidInheritanceKind(kind As EnvDTE80.vsCMInheritanceKind) As Boolean
Return kind = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract OrElse
kind = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone OrElse
kind = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed OrElse
kind = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew OrElse
kind = (EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract) OrElse
kind = (EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed)
End Function
Public Overrides Function SetInheritanceKind(typeNode As SyntaxNode, kind As EnvDTE80.vsCMInheritanceKind) As SyntaxNode
Debug.Assert(TypeOf typeNode Is ClassBlockSyntax OrElse
TypeOf typeNode Is ModuleBlockSyntax)
If TypeOf typeNode Is ModuleBlockSyntax Then
If kind = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone Then
Return typeNode
End If
Throw Exceptions.ThrowENotImpl()
End If
If Not IsValidInheritanceKind(kind) Then
Throw Exceptions.ThrowEInvalidArg()
End If
Dim member = TryCast(typeNode, StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Dim flags = member.GetModifierFlags()
flags = flags And Not (ModifierFlags.MustInherit Or ModifierFlags.NotInheritable Or ModifierFlags.Shadows)
If kind <> EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone Then
If (kind And EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract) <> 0 Then
flags = flags Or ModifierFlags.MustInherit
ElseIf (kind And EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed) <> 0 Then
flags = flags Or ModifierFlags.NotInheritable
End If
If (kind And EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew) <> 0 Then
flags = flags Or ModifierFlags.Shadows
End If
End If
Return member.UpdateModifiers(flags)
End Function
Public Overrides Function GetMustImplement(memberNode As SyntaxNode) As Boolean
Debug.Assert(TypeOf memberNode Is StatementSyntax)
Dim member = TryCast(memberNode, StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
If member.Parent.Kind = SyntaxKind.InterfaceBlock Then
Return True
End If
Dim flags = member.GetModifierFlags()
Return (flags And ModifierFlags.MustOverride) <> 0
End Function
Public Overrides Function SetMustImplement(memberNode As SyntaxNode, value As Boolean) As SyntaxNode
Dim overrideKind = If(value, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone)
Return SetOverrideKind(memberNode, overrideKind)
End Function
Public Overrides Function GetOverrideKind(memberNode As SyntaxNode) As EnvDTE80.vsCMOverrideKind
Debug.Assert(TypeOf memberNode Is DeclarationStatementSyntax)
Dim member = TryCast(memberNode, DeclarationStatementSyntax)
If member IsNot Nothing Then
Dim modifiers = SyntaxFactory.TokenList(member.GetModifiers())
Dim result As EnvDTE80.vsCMOverrideKind = 0
If modifiers.Any(SyntaxKind.ShadowsKeyword) Then
result = result Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew
End If
If modifiers.Any(SyntaxKind.OverridesKeyword) Then
result = result Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride
End If
If modifiers.Any(SyntaxKind.MustOverrideKeyword) Or member.IsParentKind(SyntaxKind.InterfaceBlock) Then
result = result Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract
End If
If modifiers.Any(SyntaxKind.OverridableKeyword) Then
result = result Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual
ElseIf modifiers.Any(SyntaxKind.NotOverridableKeyword) Then
result = result Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed
End If
Return result
End If
Throw New InvalidOperationException
End Function
Private Function IsValidOverrideKind(kind As EnvDTE80.vsCMOverrideKind) As Boolean
Return kind = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed OrElse
kind = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew OrElse
kind = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride OrElse
kind = (EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed) OrElse
kind = (EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual Or EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew) OrElse
kind = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract OrElse
kind = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual OrElse
kind = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone
End Function
Public Overrides Function SetOverrideKind(memberNode As SyntaxNode, kind As EnvDTE80.vsCMOverrideKind) As SyntaxNode
Dim member = TryCast(memberNode, StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
If TypeOf memberNode.Parent Is ModuleBlockSyntax OrElse
TypeOf memberNode.Parent Is InterfaceBlockSyntax OrElse
TypeOf memberNode.Parent Is PropertyBlockSyntax OrElse
TypeOf memberNode.Parent Is PropertyStatementSyntax Then
Throw Exceptions.ThrowENotImpl()
End If
If Not IsValidOverrideKind(kind) Then
Throw Exceptions.ThrowEInvalidArg()
End If
Dim flags = member.GetModifierFlags()
flags = flags And Not (ModifierFlags.NotOverridable Or ModifierFlags.Shadows Or ModifierFlags.Overrides Or ModifierFlags.MustOverride Or ModifierFlags.Overridable)
Select Case kind
Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed
flags = flags Or ModifierFlags.NotOverridable
Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew
flags = flags Or ModifierFlags.Shadows
Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride
flags = flags Or ModifierFlags.Overrides
Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract
flags = flags Or ModifierFlags.MustOverride
Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual
flags = flags Or ModifierFlags.Overridable
Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed
flags = flags Or ModifierFlags.NotOverridable Or ModifierFlags.Overrides
Case EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew
flags = flags Or ModifierFlags.Overridable Or ModifierFlags.Shadows
End Select
Dim resultMember = member.UpdateModifiers(flags)
If (flags And ModifierFlags.MustOverride) <> 0 Then
If TypeOf resultMember Is MethodBlockBaseSyntax Then
resultMember = DirectCast(resultMember, MethodBlockBaseSyntax).BlockStatement
ElseIf TypeOf resultMember Is PropertyBlockSyntax Then
resultMember = DirectCast(resultMember, PropertyBlockSyntax).PropertyStatement
End If
Else
If TypeOf resultMember Is MethodStatementSyntax Then
If resultMember.Kind = SyntaxKind.FunctionStatement Then
resultMember = SyntaxFactory.FunctionBlock(
subOrFunctionStatement:=DirectCast(resultMember, MethodStatementSyntax),
statements:=Nothing,
endSubOrFunctionStatement:=SyntaxFactory.EndFunctionStatement())
ElseIf resultMember.Kind = SyntaxKind.SubStatement Then
resultMember = SyntaxFactory.SubBlock(
subOrFunctionStatement:=DirectCast(resultMember, MethodStatementSyntax),
statements:=Nothing,
endSubOrFunctionStatement:=SyntaxFactory.EndSubStatement())
End If
ElseIf TypeOf resultMember Is PropertyStatementSyntax Then
Dim propertyStatement = DirectCast(resultMember, PropertyStatementSyntax)
Dim parameterName = "value"
If propertyStatement.Identifier.GetTypeCharacter() <> TypeCharacter.None Then
parameterName &= propertyStatement.Identifier.GetTypeCharacter().GetTypeCharacterString()
End If
Dim returnType = propertyStatement.GetReturnType()
Dim asClauseText = If(returnType IsNot Nothing,
" As " & returnType.ToString(),
String.Empty)
resultMember = SyntaxFactory.PropertyBlock(
propertyStatement:=propertyStatement,
accessors:=SyntaxFactory.List(Of AccessorBlockSyntax)({
SyntaxFactory.GetAccessorBlock(
accessorStatement:=SyntaxFactory.GetAccessorStatement(),
statements:=Nothing,
endAccessorStatement:=SyntaxFactory.EndGetStatement()),
SyntaxFactory.SetAccessorBlock(
accessorStatement:=SyntaxFactory.SetAccessorStatement(
attributeLists:=Nothing,
modifiers:=Nothing,
parameterList:=SyntaxFactory.ParseParameterList("(" & parameterName & asClauseText & ")")),
statements:=Nothing,
endAccessorStatement:=SyntaxFactory.EndSetStatement())
}))
End If
End If
Return resultMember
End Function
Public Overrides Function GetIsAbstract(memberNode As SyntaxNode, symbol As ISymbol) As Boolean
Return symbol.IsAbstract
End Function
Public Overrides Function SetIsAbstract(memberNode As SyntaxNode, value As Boolean) As SyntaxNode
If TypeOf memberNode Is StructureBlockSyntax OrElse
TypeOf memberNode Is ModuleBlockSyntax Then
Throw Exceptions.ThrowENotImpl()
End If
Dim member = TryCast(memberNode, StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Dim flags = member.GetModifierFlags()
If value Then
If TypeOf memberNode Is TypeBlockSyntax Then
flags = flags Or ModifierFlags.MustInherit
Else
flags = flags Or ModifierFlags.MustOverride
End If
Else
If TypeOf memberNode Is TypeBlockSyntax Then
flags = flags And Not ModifierFlags.MustInherit
Else
flags = flags And Not ModifierFlags.MustOverride
End If
End If
Return member.UpdateModifiers(flags)
End Function
Public Overrides Function GetIsConstant(variableNode As SyntaxNode) As Boolean
If TypeOf variableNode Is EnumMemberDeclarationSyntax Then
Return True
End If
Dim member = TryCast(GetNodeWithModifiers(variableNode), StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Dim flags = member.GetModifierFlags()
' VB legacy code model returns True for both Const and ReadOnly fields
Return (flags And (ModifierFlags.Const Or ModifierFlags.ReadOnly)) <> 0
End Function
Public Overrides Function SetIsConstant(variableNode As SyntaxNode, value As Boolean) As SyntaxNode
Dim constKind = If(value, EnvDTE80.vsCMConstKind.vsCMConstKindConst, EnvDTE80.vsCMConstKind.vsCMConstKindNone)
Return SetConstKind(variableNode, constKind)
End Function
Public Overrides Function GetIsDefault(propertyNode As SyntaxNode) As Boolean
Debug.Assert(TypeOf propertyNode Is PropertyBlockSyntax OrElse
TypeOf propertyNode Is PropertyStatementSyntax)
If TypeOf propertyNode Is PropertyStatementSyntax Then
Return False
End If
Dim propertyBlock = TryCast(propertyNode, PropertyBlockSyntax)
If propertyBlock Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Return propertyBlock.PropertyStatement.Modifiers.Any(SyntaxKind.DefaultKeyword)
End Function
Public Overrides Function SetIsDefault(propertyNode As SyntaxNode, value As Boolean) As SyntaxNode
Debug.Assert(TypeOf propertyNode Is PropertyBlockSyntax OrElse
TypeOf propertyNode Is PropertyStatementSyntax)
Dim member = DirectCast(propertyNode, StatementSyntax)
Dim flags = member.GetModifierFlags()
flags = flags And Not ModifierFlags.Default
If value Then
flags = flags Or ModifierFlags.Default
End If
Return member.UpdateModifiers(flags)
End Function
Public Overrides Function GetIsGeneric(node As SyntaxNode) As Boolean
Debug.Assert(TypeOf node Is StatementSyntax)
Return DirectCast(node, StatementSyntax).GetArity() > 0
End Function
Public Overrides Function GetIsPropertyStyleEvent(eventNode As SyntaxNode) As Boolean
Debug.Assert(TypeOf eventNode Is EventStatementSyntax OrElse
TypeOf eventNode Is EventBlockSyntax)
Return TypeOf eventNode Is EventBlockSyntax
End Function
Public Overrides Function GetIsShared(memberNode As SyntaxNode, symbol As ISymbol) As Boolean
Return _
(symbol.Kind = SymbolKind.NamedType AndAlso DirectCast(symbol, INamedTypeSymbol).TypeKind = TypeKind.Module) OrElse
symbol.IsStatic
End Function
Public Overrides Function SetIsShared(memberNode As SyntaxNode, value As Boolean) As SyntaxNode
If TypeOf memberNode Is TypeBlockSyntax Then
Throw Exceptions.ThrowENotImpl()
End If
Dim member = TryCast(memberNode, StatementSyntax)
If member Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Dim parentType = TryCast(member.Parent, DeclarationStatementSyntax)
If parentType Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
If TypeOf parentType Is ModuleBlockSyntax OrElse
TypeOf parentType Is InterfaceBlockSyntax OrElse
TypeOf parentType Is EnumBlockSyntax Then
Throw Exceptions.ThrowENotImpl()
End If
Dim flags = member.GetModifierFlags() And Not ModifierFlags.Dim
If value Then
flags = flags Or ModifierFlags.Shared
Else
flags = flags And Not ModifierFlags.Shared
End If
If flags = 0 AndAlso member.IsKind(SyntaxKind.FieldDeclaration) Then
flags = flags Or ModifierFlags.Dim
End If
Return member.UpdateModifiers(flags)
End Function
Public Overrides Function GetReadWrite(memberNode As SyntaxNode) As EnvDTE80.vsCMPropertyKind
Debug.Assert(TypeOf memberNode Is PropertyBlockSyntax OrElse
TypeOf memberNode Is PropertyStatementSyntax)
Dim propertyStatement = TryCast(memberNode, PropertyStatementSyntax)
If propertyStatement Is Nothing Then
Dim propertyBlock = TryCast(memberNode, PropertyBlockSyntax)
If propertyBlock IsNot Nothing Then
propertyStatement = propertyBlock.PropertyStatement
End If
End If
If propertyStatement IsNot Nothing Then
If propertyStatement.Modifiers.Any(SyntaxKind.WriteOnlyKeyword) Then
Return EnvDTE80.vsCMPropertyKind.vsCMPropertyKindWriteOnly
ElseIf propertyStatement.Modifiers.Any(SyntaxKind.ReadOnlyKeyword) Then
Return EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadOnly
Else
Return EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadWrite
End If
End If
Throw Exceptions.ThrowEUnexpected()
End Function
Private Function SetDelegateType(delegateStatement As DelegateStatementSyntax, typeSymbol As ITypeSymbol) As DelegateStatementSyntax
' Remove the leading and trailing trivia and save it for reattachment later.
Dim leadingTrivia = delegateStatement.GetLeadingTrivia()
Dim trailingTrivia = delegateStatement.GetTrailingTrivia()
delegateStatement = delegateStatement _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
If typeSymbol Is Nothing Then
' If no type is specified (e.g. CodeElement.Type = Nothing), we just convert to a Sub
' if it isn't one already.
If delegateStatement.IsKind(SyntaxKind.DelegateFunctionStatement) Then
delegateStatement = SyntaxFactory.DelegateSubStatement(
attributeLists:=delegateStatement.AttributeLists,
modifiers:=delegateStatement.Modifiers,
identifier:=delegateStatement.Identifier,
typeParameterList:=delegateStatement.TypeParameterList,
parameterList:=delegateStatement.ParameterList,
asClause:=Nothing)
End If
Else
Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
Dim newType = SyntaxFactory.ParseTypeName(typeName)
' If this is a Sub, convert to a Function
If delegateStatement.IsKind(SyntaxKind.DelegateSubStatement) Then
delegateStatement = SyntaxFactory.DelegateFunctionStatement(
attributeLists:=delegateStatement.AttributeLists,
modifiers:=delegateStatement.Modifiers,
identifier:=delegateStatement.Identifier,
typeParameterList:=delegateStatement.TypeParameterList,
parameterList:=delegateStatement.ParameterList,
asClause:=delegateStatement.AsClause)
End If
If delegateStatement.AsClause IsNot Nothing Then
Debug.Assert(TypeOf delegateStatement.AsClause Is SimpleAsClauseSyntax)
Dim oldType = DirectCast(delegateStatement.AsClause, SimpleAsClauseSyntax).Type
delegateStatement = delegateStatement.ReplaceNode(oldType, newType)
Else
delegateStatement = delegateStatement.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
End If
Return delegateStatement _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia)
End Function
Private Function SetEventType(eventStatement As EventStatementSyntax, typeSymbol As ITypeSymbol) As EventStatementSyntax
If typeSymbol Is Nothing Then
Throw Exceptions.ThrowEInvalidArg()
End If
' Remove the leading and trailing trivia and save it for reattachment later.
Dim leadingTrivia = eventStatement.GetLeadingTrivia()
Dim trailingTrivia = eventStatement.GetTrailingTrivia()
eventStatement = eventStatement _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
Dim newType = SyntaxFactory.ParseTypeName(typeName)
' If the event has a parameter list, we need to remove it.
If eventStatement.ParameterList IsNot Nothing Then
eventStatement = eventStatement.WithParameterList(Nothing)
End If
If eventStatement.AsClause IsNot Nothing Then
Debug.Assert(TypeOf eventStatement.AsClause Is SimpleAsClauseSyntax)
Dim oldType = DirectCast(eventStatement.AsClause, SimpleAsClauseSyntax).Type
eventStatement = eventStatement.ReplaceNode(oldType, newType)
Else
eventStatement = eventStatement.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
Return eventStatement _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia)
End Function
Private Function SetEventType(eventBlock As EventBlockSyntax, typeSymbol As ITypeSymbol) As EventBlockSyntax
If typeSymbol Is Nothing Then
Throw Exceptions.ThrowEInvalidArg()
End If
Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
Dim newType = SyntaxFactory.ParseTypeName(typeName)
' Update the event statement
Dim eventStatement = eventBlock.EventStatement
Dim leadingTrivia = eventStatement.GetLeadingTrivia()
Dim trailingTrivia = eventStatement.GetTrailingTrivia()
eventStatement = eventStatement _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
If eventStatement.AsClause IsNot Nothing Then
Debug.Assert(TypeOf eventStatement.AsClause Is SimpleAsClauseSyntax)
Dim oldType = DirectCast(eventStatement.AsClause, SimpleAsClauseSyntax).Type
eventStatement = eventStatement.ReplaceNode(oldType, newType)
Else
eventStatement = eventStatement.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
eventStatement = eventStatement _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia)
eventBlock = eventBlock.WithEventStatement(eventStatement)
For i = 0 To eventBlock.Accessors.Count - 1
Dim accessorBlock = eventBlock.Accessors(i)
Dim newAccessorBlock = accessorBlock
If accessorBlock.Kind = SyntaxKind.AddHandlerAccessorBlock OrElse
accessorBlock.Kind = SyntaxKind.RemoveHandlerAccessorBlock Then
' Update the first parameter of the AddHandler or RemoveHandler statements
Dim firstParameter = accessorBlock.BlockStatement.ParameterList.Parameters.FirstOrDefault()
If firstParameter IsNot Nothing Then
Dim newFirstParameter As ParameterSyntax
If firstParameter.AsClause IsNot Nothing Then
Debug.Assert(TypeOf firstParameter.AsClause Is SimpleAsClauseSyntax)
Dim oldType = DirectCast(firstParameter.AsClause, SimpleAsClauseSyntax).Type
newFirstParameter = firstParameter.ReplaceNode(oldType, newType)
Else
newFirstParameter = firstParameter.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
newFirstParameter = newFirstParameter _
.WithLeadingTrivia(firstParameter.GetLeadingTrivia()) _
.WithTrailingTrivia(firstParameter.GetTrailingTrivia())
newAccessorBlock = accessorBlock.ReplaceNode(firstParameter, newFirstParameter)
End If
ElseIf accessorBlock.Kind = SyntaxKind.RaiseEventAccessorBlock Then
' For RaiseEvent, we replace the whole signature with the delegate's invoke method
Dim namedTypeSymbol = TryCast(typeSymbol, INamedTypeSymbol)
If namedTypeSymbol IsNot Nothing Then
Dim invokeMethod = namedTypeSymbol.DelegateInvokeMethod
If invokeMethod IsNot Nothing Then
Dim parameterStrings = invokeMethod.Parameters.Select(Function(p) p.ToDisplayString(s_raiseEventSignatureFormat))
Dim parameterListString = "("c & String.Join(", ", parameterStrings) & ")"c
Dim newParameterList = SyntaxFactory.ParseParameterList(parameterListString)
newParameterList = newParameterList.WithTrailingTrivia(accessorBlock.BlockStatement.ParameterList.GetTrailingTrivia())
newAccessorBlock = accessorBlock.ReplaceNode(accessorBlock.BlockStatement.ParameterList, newParameterList)
End If
End If
End If
If accessorBlock IsNot newAccessorBlock Then
eventBlock = eventBlock.ReplaceNode(accessorBlock, newAccessorBlock)
End If
Next
Return eventBlock
End Function
Private Function SetMethodType(declareStatement As DeclareStatementSyntax, typeSymbol As ITypeSymbol) As DeclareStatementSyntax
' Remove the leading and trailing trivia and save it for reattachment later.
Dim leadingTrivia = declareStatement.GetLeadingTrivia()
Dim trailingTrivia = declareStatement.GetTrailingTrivia()
declareStatement = declareStatement _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
If typeSymbol Is Nothing Then
' If no type is specified (e.g. CodeElement.Type = Nothing), we just convert to a Sub
' if it isn't one already.
If declareStatement.IsKind(SyntaxKind.DeclareFunctionStatement) Then
declareStatement = SyntaxFactory.DeclareSubStatement(
attributeLists:=declareStatement.AttributeLists,
modifiers:=declareStatement.Modifiers,
declareKeyword:=declareStatement.DeclareKeyword,
charsetKeyword:=declareStatement.CharsetKeyword,
subOrFunctionKeyword:=SyntaxFactory.Token(SyntaxKind.SubKeyword),
identifier:=declareStatement.Identifier,
libKeyword:=declareStatement.LibKeyword,
libraryName:=declareStatement.LibraryName,
aliasKeyword:=declareStatement.AliasKeyword,
aliasName:=declareStatement.AliasName,
parameterList:=declareStatement.ParameterList,
asClause:=Nothing)
End If
Else
Dim newType = SyntaxFactory.ParseTypeName(typeSymbol.ToDisplayString(s_setTypeFormat))
declareStatement = SyntaxFactory.DeclareFunctionStatement(
attributeLists:=declareStatement.AttributeLists,
modifiers:=declareStatement.Modifiers,
declareKeyword:=declareStatement.DeclareKeyword,
charsetKeyword:=declareStatement.CharsetKeyword,
subOrFunctionKeyword:=SyntaxFactory.Token(SyntaxKind.FunctionKeyword),
identifier:=declareStatement.Identifier,
libKeyword:=declareStatement.LibKeyword,
libraryName:=declareStatement.LibraryName,
aliasKeyword:=declareStatement.AliasKeyword,
aliasName:=declareStatement.AliasName,
parameterList:=declareStatement.ParameterList,
asClause:=declareStatement.AsClause)
If declareStatement.AsClause IsNot Nothing Then
Debug.Assert(TypeOf declareStatement.AsClause Is SimpleAsClauseSyntax)
Dim oldType = DirectCast(declareStatement.AsClause, SimpleAsClauseSyntax).Type
declareStatement = declareStatement.ReplaceNode(oldType, newType)
Else
declareStatement = declareStatement.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
End If
Return declareStatement.WithLeadingTrivia(leadingTrivia).WithTrailingTrivia(trailingTrivia)
End Function
Private Function SetMethodType(methodStatement As MethodStatementSyntax, typeSymbol As ITypeSymbol) As MethodStatementSyntax
' Remove the leading and trailing trivia and save it for reattachment later.
Dim leadingTrivia = methodStatement.GetLeadingTrivia()
Dim trailingTrivia = methodStatement.GetTrailingTrivia()
methodStatement = methodStatement _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
If typeSymbol Is Nothing Then
' If no type is specified (e.g. CodeElement.Type = Nothing), we just convert to a Sub
' if it isn't one already.
If methodStatement.IsKind(SyntaxKind.FunctionStatement) Then
methodStatement = SyntaxFactory.SubStatement(
attributeLists:=methodStatement.AttributeLists,
modifiers:=methodStatement.Modifiers,
identifier:=methodStatement.Identifier,
typeParameterList:=methodStatement.TypeParameterList,
parameterList:=methodStatement.ParameterList,
asClause:=Nothing,
handlesClause:=methodStatement.HandlesClause,
implementsClause:=methodStatement.ImplementsClause)
End If
Else
Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
Dim newType = SyntaxFactory.ParseTypeName(typeName)
' If this is a Sub, convert to a Function
If methodStatement.IsKind(SyntaxKind.SubStatement) Then
methodStatement = SyntaxFactory.FunctionStatement(
attributeLists:=methodStatement.AttributeLists,
modifiers:=methodStatement.Modifiers,
identifier:=methodStatement.Identifier,
typeParameterList:=methodStatement.TypeParameterList,
parameterList:=methodStatement.ParameterList,
asClause:=methodStatement.AsClause,
handlesClause:=methodStatement.HandlesClause,
implementsClause:=methodStatement.ImplementsClause)
End If
If methodStatement.AsClause IsNot Nothing Then
Debug.Assert(TypeOf methodStatement.AsClause Is SimpleAsClauseSyntax)
Dim oldType = DirectCast(methodStatement.AsClause, SimpleAsClauseSyntax).Type
methodStatement = methodStatement.ReplaceNode(oldType, newType)
Else
methodStatement = methodStatement.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
End If
Return methodStatement _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia)
End Function
Private Function SetMethodType(methodBlock As MethodBlockSyntax, typeSymbol As ITypeSymbol) As MethodBlockSyntax
' Remove the leading and trailing trivia and save it for reattachment later.
Dim leadingTrivia = methodBlock.GetLeadingTrivia()
Dim trailingTrivia = methodBlock.GetTrailingTrivia()
methodBlock = methodBlock _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
Dim methodStatement = SetMethodType(DirectCast(methodBlock.BlockStatement, MethodStatementSyntax), typeSymbol)
Dim endMethodStatement = methodBlock.EndBlockStatement
If endMethodStatement IsNot Nothing AndAlso Not endMethodStatement.IsMissing Then
' Note that we don't have to remove/replace the trailing trivia for the end block statement
' because we're already doing that for the whole block.
If endMethodStatement.IsKind(SyntaxKind.EndSubStatement) AndAlso typeSymbol IsNot Nothing Then
endMethodStatement = SyntaxFactory.EndFunctionStatement()
ElseIf endMethodStatement.IsKind(SyntaxKind.EndFunctionStatement) AndAlso typeSymbol Is Nothing Then
endMethodStatement = SyntaxFactory.EndSubStatement()
End If
End If
methodBlock = methodBlock.Update(If(methodStatement.Kind = SyntaxKind.SubStatement, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock),
methodStatement, methodBlock.Statements, endMethodStatement)
Return methodBlock _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia)
End Function
Private Function SetParameterType(parameter As ParameterSyntax, typeSymbol As ITypeSymbol) As ParameterSyntax
If typeSymbol Is Nothing Then
Return parameter
End If
' Remove the leading and trailing trivia and save it for reattachment later.\
Dim leadingTrivia = parameter.GetLeadingTrivia()
Dim trailingTrivia = parameter.GetTrailingTrivia()
parameter = parameter _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
Dim newType = SyntaxFactory.ParseTypeName(typeName)
If parameter.AsClause IsNot Nothing Then
Debug.Assert(TypeOf parameter.AsClause Is SimpleAsClauseSyntax)
Dim oldType = DirectCast(parameter.AsClause, SimpleAsClauseSyntax).Type
parameter = parameter.ReplaceNode(oldType, newType)
Else
parameter = parameter.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
Return parameter _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia)
End Function
Private Function SetPropertyType(propertyStatement As PropertyStatementSyntax, typeSymbol As ITypeSymbol) As PropertyStatementSyntax
If typeSymbol Is Nothing Then
Throw Exceptions.ThrowEInvalidArg()
End If
' Remove the leading and trailing trivia and save it for reattachment later.\
Dim leadingTrivia = propertyStatement.GetLeadingTrivia()
Dim trailingTrivia = propertyStatement.GetTrailingTrivia()
propertyStatement = propertyStatement _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
Dim newType = SyntaxFactory.ParseTypeName(typeName)
If propertyStatement.AsClause IsNot Nothing Then
Dim oldType = propertyStatement.AsClause.Type()
If oldType IsNot Nothing Then
propertyStatement = propertyStatement.ReplaceNode(oldType, newType)
End If
Else
propertyStatement = propertyStatement.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
Return propertyStatement _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia)
End Function
Private Function SetPropertyType(propertyBlock As PropertyBlockSyntax, typeSymbol As ITypeSymbol) As PropertyBlockSyntax
If typeSymbol Is Nothing Then
Throw Exceptions.ThrowEInvalidArg()
End If
' Remove the leading and trailing trivia and save it for reattachment later.\
Dim leadingTrivia = propertyBlock.GetLeadingTrivia()
Dim trailingTrivia = propertyBlock.GetTrailingTrivia()
propertyBlock = propertyBlock _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
Dim propertyStatement = SetPropertyType(propertyBlock.PropertyStatement, typeSymbol)
propertyBlock = propertyBlock.WithPropertyStatement(propertyStatement)
Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
Dim newType = SyntaxFactory.ParseTypeName(typeName)
For i = 0 To propertyBlock.Accessors.Count - 1
Dim accessorBlock = propertyBlock.Accessors(i)
Dim newAccessorBlock = accessorBlock
If accessorBlock.Kind = SyntaxKind.SetAccessorBlock Then
' Update the first parameter of the SetAccessor statement
Dim firstParameter = accessorBlock.BlockStatement.ParameterList.Parameters.FirstOrDefault()
If firstParameter IsNot Nothing Then
Dim newFirstParameter As ParameterSyntax
If firstParameter.AsClause IsNot Nothing Then
Debug.Assert(TypeOf firstParameter.AsClause Is SimpleAsClauseSyntax)
Dim oldType = DirectCast(firstParameter.AsClause, SimpleAsClauseSyntax).Type
newFirstParameter = firstParameter.ReplaceNode(oldType, newType)
Else
newFirstParameter = firstParameter.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
newFirstParameter = newFirstParameter _
.WithLeadingTrivia(firstParameter.GetLeadingTrivia()) _
.WithTrailingTrivia(firstParameter.GetTrailingTrivia())
newAccessorBlock = accessorBlock.ReplaceNode(firstParameter, newFirstParameter)
End If
End If
If accessorBlock IsNot newAccessorBlock Then
propertyBlock = propertyBlock.ReplaceNode(accessorBlock, newAccessorBlock)
End If
Next
Return propertyBlock _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia)
End Function
Private Function SetVariableType(variableDeclarator As VariableDeclaratorSyntax, typeSymbol As ITypeSymbol) As VariableDeclaratorSyntax
If typeSymbol Is Nothing Then
Throw Exceptions.ThrowEInvalidArg()
End If
' Remove the leading and trailing trivia and save it for reattachment later.\
Dim leadingTrivia = variableDeclarator.GetLeadingTrivia()
Dim trailingTrivia = variableDeclarator.GetTrailingTrivia()
variableDeclarator = variableDeclarator _
.WithLeadingTrivia(SyntaxTriviaList.Empty) _
.WithTrailingTrivia(SyntaxTriviaList.Empty)
Dim typeName = typeSymbol.ToDisplayString(s_setTypeFormat)
Dim newType = SyntaxFactory.ParseTypeName(typeName)
If variableDeclarator.AsClause IsNot Nothing Then
Dim oldType = variableDeclarator.AsClause.Type()
If oldType IsNot Nothing Then
variableDeclarator = variableDeclarator.ReplaceNode(oldType, newType)
End If
Else
variableDeclarator = variableDeclarator.WithAsClause(SyntaxFactory.SimpleAsClause(newType))
End If
Return variableDeclarator _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia)
End Function
Public Overrides Function SetType(node As SyntaxNode, typeSymbol As ITypeSymbol) As SyntaxNode
Debug.Assert(TypeOf node Is DelegateStatementSyntax OrElse
TypeOf node Is EventStatementSyntax OrElse
TypeOf node Is EventBlockSyntax OrElse
TypeOf node Is DeclareStatementSyntax OrElse
TypeOf node Is MethodStatementSyntax OrElse
TypeOf node Is MethodBlockBaseSyntax OrElse
TypeOf node Is ParameterSyntax OrElse
TypeOf node Is PropertyStatementSyntax OrElse
TypeOf node Is PropertyBlockSyntax OrElse
TypeOf node Is VariableDeclaratorSyntax)
If TypeOf node Is DelegateStatementSyntax Then
Return SetDelegateType(DirectCast(node, DelegateStatementSyntax), typeSymbol)
End If
If TypeOf node Is EventStatementSyntax Then
Return SetEventType(DirectCast(node, EventStatementSyntax), typeSymbol)
End If
If TypeOf node Is EventBlockSyntax Then
Return SetEventType(DirectCast(node, EventBlockSyntax), typeSymbol)
End If
If TypeOf node Is DeclareStatementSyntax Then
Return SetMethodType(DirectCast(node, DeclareStatementSyntax), typeSymbol)
End If
If TypeOf node Is MethodStatementSyntax Then
Return SetMethodType(DirectCast(node, MethodStatementSyntax), typeSymbol)
End If
If TypeOf node Is MethodBlockSyntax Then
Return SetMethodType(DirectCast(node, MethodBlockSyntax), typeSymbol)
End If
If TypeOf node Is ConstructorBlockSyntax Then
Return node
End If
If TypeOf node Is OperatorBlockSyntax Then
Return node
End If
If TypeOf node Is ParameterSyntax Then
Return SetParameterType(DirectCast(node, ParameterSyntax), typeSymbol)
End If
If TypeOf node Is PropertyStatementSyntax Then
Return SetPropertyType(DirectCast(node, PropertyStatementSyntax), typeSymbol)
End If
If TypeOf node Is PropertyBlockSyntax Then
Return SetPropertyType(DirectCast(node, PropertyBlockSyntax), typeSymbol)
End If
If TypeOf node Is VariableDeclaratorSyntax Then
Return SetVariableType(DirectCast(node, VariableDeclaratorSyntax), typeSymbol)
End If
Throw New NotImplementedException()
End Function
Public Overrides Function GetFullyQualifiedName(name As String, position As Integer, semanticModel As SemanticModel) As String
Dim typeName = SyntaxFactory.ParseTypeName(name)
If TypeOf typeName Is PredefinedTypeSyntax Then
Dim predefinedType As PredefinedType
If SyntaxFactsService.TryGetPredefinedType(DirectCast(typeName, PredefinedTypeSyntax).Keyword, predefinedType) Then
Dim specialType = predefinedType.ToSpecialType()
Return semanticModel.Compilation.GetSpecialType(specialType).GetEscapedFullName()
End If
Else
Dim symbols = semanticModel.LookupNamespacesAndTypes(position, name:=name)
If symbols.Length > 0 Then
Return symbols(0).GetEscapedFullName()
End If
End If
Return name
End Function
Public Overrides Function GetInitExpression(node As SyntaxNode) As String
Dim initializer As ExpressionSyntax = Nothing
Select Case node.Kind
Case SyntaxKind.Parameter
Dim parameter = DirectCast(node, ParameterSyntax)
If parameter.Default IsNot Nothing Then
initializer = parameter.Default.Value
End If
Case SyntaxKind.ModifiedIdentifier
Dim modifiedIdentifier = DirectCast(node, ModifiedIdentifierSyntax)
Dim variableDeclarator = DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax)
initializer = variableDeclarator.GetInitializer()
Case SyntaxKind.EnumMemberDeclaration
Dim enumMemberDeclaration = DirectCast(node, EnumMemberDeclarationSyntax)
If enumMemberDeclaration.Initializer IsNot Nothing Then
initializer = enumMemberDeclaration.Initializer.Value
End If
End Select
Return If(initializer IsNot Nothing,
initializer.ToString(),
Nothing)
End Function
Public Overrides Function AddInitExpression(node As SyntaxNode, value As String) As SyntaxNode
Select Case node.Kind
Case SyntaxKind.Parameter
Dim parameter = DirectCast(node, ParameterSyntax)
Dim parameterKind = GetParameterKind(parameter)
If Not (parameterKind And EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional) <> 0 Then
Throw Exceptions.ThrowEInvalidArg
End If
If String.IsNullOrWhiteSpace(value) Then
' Remove the Optional modifier
parameterKind = parameterKind And Not EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional
parameter = DirectCast(SetParameterKind(parameter, parameterKind), ParameterSyntax)
If parameter.Default IsNot Nothing Then
parameter = parameter.RemoveNode(parameter.Default, SyntaxRemoveOptions.KeepNoTrivia)
End If
Return parameter
End If
Dim expression = SyntaxFactory.ParseExpression(value)
Dim equalsValueClause = If(parameter.Default IsNot Nothing AndAlso Not parameter.Default.IsMissing,
parameter.Default.WithValue(expression),
SyntaxFactory.EqualsValue(expression))
Return parameter.WithDefault(equalsValueClause)
Case SyntaxKind.VariableDeclarator
Dim variableDeclarator = DirectCast(node, VariableDeclaratorSyntax)
If String.IsNullOrWhiteSpace(value) Then
If variableDeclarator.Initializer IsNot Nothing Then
variableDeclarator = variableDeclarator.RemoveNode(variableDeclarator.Initializer, SyntaxRemoveOptions.KeepExteriorTrivia)
End If
Return variableDeclarator
End If
Dim trailingTrivia = variableDeclarator.GetTrailingTrivia()
variableDeclarator = variableDeclarator.WithTrailingTrivia(SyntaxTriviaList.Empty)
Dim expression = SyntaxFactory.ParseExpression(value)
Dim equalsValueClause = If(variableDeclarator.Initializer IsNot Nothing AndAlso Not variableDeclarator.Initializer.IsMissing,
variableDeclarator.Initializer.WithValue(expression),
SyntaxFactory.EqualsValue(expression)).WithTrailingTrivia(trailingTrivia)
Return variableDeclarator.WithInitializer(equalsValueClause)
Case SyntaxKind.EnumMemberDeclaration
Dim enumMemberDeclaration = DirectCast(node, EnumMemberDeclarationSyntax)
If String.IsNullOrWhiteSpace(value) Then
If enumMemberDeclaration.Initializer IsNot Nothing Then
enumMemberDeclaration = enumMemberDeclaration.RemoveNode(enumMemberDeclaration.Initializer, SyntaxRemoveOptions.KeepExteriorTrivia)
End If
Return enumMemberDeclaration
End If
Dim trailingTrivia = enumMemberDeclaration.GetTrailingTrivia()
enumMemberDeclaration = enumMemberDeclaration.WithTrailingTrivia(SyntaxTriviaList.Empty)
Dim expression = SyntaxFactory.ParseExpression(value)
Dim equalsValueClause = If(enumMemberDeclaration.Initializer IsNot Nothing AndAlso Not enumMemberDeclaration.Initializer.IsMissing,
enumMemberDeclaration.Initializer.WithValue(expression),
SyntaxFactory.EqualsValue(expression)).WithTrailingTrivia(trailingTrivia)
Return enumMemberDeclaration.WithInitializer(equalsValueClause)
Case Else
Throw Exceptions.ThrowEFail()
End Select
End Function
Public Overrides Function GetDestination(containerNode As SyntaxNode) As CodeGenerationDestination
Return VisualBasicCodeGenerationHelpers.GetDestination(containerNode)
End Function
Protected Overrides Function GetDefaultAccessibility(targetSymbolKind As SymbolKind, destination As CodeGenerationDestination) As Accessibility
If destination = CodeGenerationDestination.StructType Then
Return Accessibility.Public
End If
Select Case targetSymbolKind
Case SymbolKind.Field
Return Accessibility.Private
Case SymbolKind.Method,
SymbolKind.Property,
SymbolKind.Event,
SymbolKind.NamedType
Return Accessibility.Public
Case Else
Debug.Fail("Invalid symbol kind: " & targetSymbolKind)
Throw Exceptions.ThrowEFail()
End Select
End Function
Public Overrides Function GetTypeSymbolFromFullName(fullName As String, compilation As Compilation) As ITypeSymbol
Dim typeSymbol As ITypeSymbol = compilation.GetTypeByMetadataName(fullName)
If typeSymbol Is Nothing Then
Dim parsedTypeName = SyntaxFactory.ParseTypeName(fullName)
' Check to see if the name we parsed has any skipped text. If it does, don't bother trying to
' speculatively bind it because we'll likely just get the wrong thing since we found a bunch
' of non-sensical tokens.
' NOTE: There appears to be a VB parser issue where "ContainsSkippedText" does not return true
' even when there is clearly skipped token trivia present. We work around this by for a particularly
' common case by checking whether the trailing trivia contains any skipped token trivia.
' https://github.com/dotnet/roslyn/issues/7182 has been filed for the parser issue.
If parsedTypeName.ContainsSkippedText OrElse
parsedTypeName.GetTrailingTrivia().Any(SyntaxKind.SkippedTokensTrivia) Then
Return Nothing
End If
' If we couldn't get the name, we just grab the first tree in the compilation to
' speculatively bind at position zero. However, if there *aren't* any trees, we fork the
' compilation with an empty tree for the purposes of speculative binding.
'
' I'm a bad person.
Dim tree = compilation.SyntaxTrees.FirstOrDefault()
If tree Is Nothing Then
tree = SyntaxFactory.ParseSyntaxTree("")
compilation = compilation.AddSyntaxTrees(tree)
End If
Dim semanticModel = compilation.GetSemanticModel(tree)
typeSymbol = semanticModel.GetSpeculativeTypeInfo(0, parsedTypeName, SpeculativeBindingOption.BindAsTypeOrNamespace).Type
End If
If typeSymbol Is Nothing Then
Debug.Fail("Could not find type: " & fullName)
Throw New ArgumentException()
End If
Return typeSymbol
End Function
Protected Overrides Function GetTypeSymbolFromPartialName(partialName As String, semanticModel As SemanticModel, position As Integer) As ITypeSymbol
Dim parsedTypeName = SyntaxFactory.ParseTypeName(partialName)
Return semanticModel.GetSpeculativeTypeInfo(position, parsedTypeName, SpeculativeBindingOption.BindAsTypeOrNamespace).Type
End Function
Public Overrides Function CreateReturnDefaultValueStatement(type As ITypeSymbol) As SyntaxNode
Return SyntaxFactory.ReturnStatement(
SyntaxFactory.NothingLiteralExpression(
SyntaxFactory.Token(SyntaxKind.NothingKeyword)))
End Function
Protected Overrides Function IsCodeModelNode(node As SyntaxNode) As Boolean
Select Case CType(node.Kind, SyntaxKind)
Case SyntaxKind.ClassBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.EnumBlock,
SyntaxKind.EnumMemberDeclaration,
SyntaxKind.EventBlock,
SyntaxKind.EventStatement,
SyntaxKind.FieldDeclaration,
SyntaxKind.FunctionBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.NamespaceBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.PropertyBlock,
SyntaxKind.StructureBlock,
SyntaxKind.SubBlock,
SyntaxKind.SimpleImportsClause
Return True
Case Else
Return False
End Select
End Function
Protected Overrides Function GetFieldFromVariableNode(variableNode As SyntaxNode) As SyntaxNode
Return If(variableNode.Kind = SyntaxKind.ModifiedIdentifier,
variableNode.FirstAncestorOrSelf(Of FieldDeclarationSyntax)(),
variableNode)
End Function
Protected Overrides Function GetVariableFromFieldNode(fieldNode As SyntaxNode) As SyntaxNode
' Work around that the fact that VB code model really deals with fields as modified identifiers
Return If(TypeOf fieldNode Is FieldDeclarationSyntax,
DirectCast(fieldNode, FieldDeclarationSyntax).Declarators.Single().Names.Single(),
fieldNode)
End Function
Protected Overrides Function GetAttributeFromAttributeDeclarationNode(node As SyntaxNode) As SyntaxNode
Return If(TypeOf node Is AttributeListSyntax,
DirectCast(node, AttributeListSyntax).Attributes.First,
node)
End Function
Protected Overrides Function GetSpanToFormat(root As SyntaxNode, span As TextSpan) As TextSpan
Dim startToken = GetTokenWithoutAnnotation(root.FindToken(span.Start).GetPreviousToken(), Function(t) t.GetPreviousToken())
Dim endToken = GetTokenWithoutAnnotation(root.FindToken(span.End), Function(t) t.GetNextToken())
Return GetEncompassingSpan(root, startToken, endToken)
End Function
Protected Overrides Function InsertMemberNodeIntoContainer(index As Integer, member As SyntaxNode, container As SyntaxNode) As SyntaxNode
Dim declarationStatement = DirectCast(member, DeclarationStatementSyntax)
If TypeOf container Is CompilationUnitSyntax Then
Dim compilationUnit = DirectCast(container, CompilationUnitSyntax)
Return compilationUnit.WithMembers(compilationUnit.Members.Insert(index, declarationStatement))
ElseIf TypeOf container Is NamespaceBlockSyntax Then
Dim namespaceBlock = DirectCast(container, NamespaceBlockSyntax)
Return namespaceBlock.WithMembers(namespaceBlock.Members.Insert(index, declarationStatement))
ElseIf TypeOf container Is ClassBlockSyntax Then
Dim classBlock = DirectCast(container, ClassBlockSyntax)
Return classBlock.WithMembers(classBlock.Members.Insert(index, declarationStatement))
ElseIf TypeOf container Is InterfaceBlockSyntax Then
Dim interfaceBlock = DirectCast(container, InterfaceBlockSyntax)
Return interfaceBlock.WithMembers(interfaceBlock.Members.Insert(index, declarationStatement))
ElseIf TypeOf container Is StructureBlockSyntax Then
Dim structureBlock = DirectCast(container, StructureBlockSyntax)
Return structureBlock.WithMembers(structureBlock.Members.Insert(index, declarationStatement))
ElseIf TypeOf container Is ModuleBlockSyntax Then
Dim moduleBlock = DirectCast(container, ModuleBlockSyntax)
Return moduleBlock.WithMembers(moduleBlock.Members.Insert(index, declarationStatement))
ElseIf TypeOf container Is EnumBlockSyntax Then
Dim enumBlock = DirectCast(container, EnumBlockSyntax)
Return enumBlock.WithMembers(enumBlock.Members.Insert(index, declarationStatement))
End If
Throw Exceptions.ThrowEFail()
End Function
Protected Overrides Function InsertAttributeArgumentIntoContainer(index As Integer, attributeArgument As SyntaxNode, container As SyntaxNode) As SyntaxNode
If TypeOf container Is AttributeSyntax Then
Dim attribute = DirectCast(container, AttributeSyntax)
Dim argumentList = attribute.ArgumentList
Dim newArgumentList As ArgumentListSyntax
If argumentList Is Nothing Then
newArgumentList = SyntaxFactory.ArgumentList(
SyntaxFactory.SingletonSeparatedList(
DirectCast(attributeArgument, ArgumentSyntax)))
Else
Dim newArguments = argumentList.Arguments.Insert(index, DirectCast(attributeArgument, ArgumentSyntax))
newArgumentList = argumentList.WithArguments(newArguments)
End If
Return attribute.WithArgumentList(newArgumentList)
End If
Throw Exceptions.ThrowEFail()
End Function
Private Function InsertAttributeListInto(attributes As SyntaxList(Of AttributesStatementSyntax), index As Integer, attribute As AttributesStatementSyntax) As SyntaxList(Of AttributesStatementSyntax)
' we need to explicitly add end of line trivia here since both of them (with or without) are valid but parsed differently
If index = 0 Then
Return attributes.Insert(index, attribute)
End If
Dim previousAttribute = attributes(index - 1)
If previousAttribute.GetTrailingTrivia().Any(Function(t) t.Kind = SyntaxKind.EndOfLineTrivia) Then
Return attributes.Insert(index, attribute)
End If
attributes = attributes.Replace(previousAttribute, previousAttribute.WithAppendedTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed))
Return attributes.Insert(index, attribute)
End Function
Protected Overrides Function InsertAttributeListIntoContainer(index As Integer, list As SyntaxNode, container As SyntaxNode) As SyntaxNode
' If the attribute is being inserted at the first index and the container is not the compilation unit, copy leading trivia
' to the attribute that is being inserted.
If index = 0 AndAlso TypeOf container IsNot CompilationUnitSyntax Then
Dim firstToken = container.GetFirstToken()
If firstToken.HasLeadingTrivia Then
Dim trivia = firstToken.LeadingTrivia
container = container.ReplaceToken(firstToken, firstToken.WithLeadingTrivia(SyntaxTriviaList.Empty))
list = list.WithLeadingTrivia(trivia)
End If
End If
' If the attribute to be inserted does not have a trailing line break, add one (unless this is a parameter).
If TypeOf container IsNot ParameterSyntax AndAlso
(Not list.HasTrailingTrivia OrElse Not list.GetTrailingTrivia().Any(SyntaxKind.EndOfLineTrivia)) Then
list = list.WithAppendedTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed)
End If
Dim attributeList = DirectCast(list, AttributeListSyntax)
If TypeOf container Is CompilationUnitSyntax Then
Dim compilationUnit = DirectCast(container, CompilationUnitSyntax)
Dim attributesStatement = SyntaxFactory.AttributesStatement(SyntaxFactory.SingletonList(attributeList))
Dim attributeStatements = InsertAttributeListInto(compilationUnit.Attributes, index, attributesStatement)
Return compilationUnit.WithAttributes(attributeStatements)
ElseIf TypeOf container Is ModuleBlockSyntax Then
Dim moduleBlock = DirectCast(container, ModuleBlockSyntax)
Dim attributeLists = moduleBlock.ModuleStatement.AttributeLists.Insert(index, attributeList)
Return moduleBlock.WithBlockStatement(moduleBlock.ModuleStatement.WithAttributeLists(attributeLists))
ElseIf TypeOf container Is StructureBlockSyntax Then
Dim structureBlock = DirectCast(container, StructureBlockSyntax)
Dim attributeLists = structureBlock.StructureStatement.AttributeLists.Insert(index, attributeList)
Return structureBlock.WithStructureStatement(structureBlock.StructureStatement.WithAttributeLists(attributeLists))
ElseIf TypeOf container Is InterfaceBlockSyntax Then
Dim interfaceBlock = DirectCast(container, InterfaceBlockSyntax)
Dim attributeLists = interfaceBlock.InterfaceStatement.AttributeLists.Insert(index, attributeList)
Return interfaceBlock.WithInterfaceStatement(interfaceBlock.InterfaceStatement.WithAttributeLists(attributeLists))
ElseIf TypeOf container Is ClassBlockSyntax Then
Dim classBlock = DirectCast(container, ClassBlockSyntax)
Dim attributeLists = classBlock.ClassStatement.AttributeLists.Insert(index, attributeList)
Dim begin = classBlock.ClassStatement.WithAttributeLists(attributeLists)
Return classBlock.WithClassStatement(begin)
ElseIf TypeOf container Is EnumBlockSyntax Then
Dim enumBlock = DirectCast(container, EnumBlockSyntax)
Dim attributeLists = enumBlock.EnumStatement.AttributeLists.Insert(index, attributeList)
Return enumBlock.WithEnumStatement(enumBlock.EnumStatement.WithAttributeLists(attributeLists))
ElseIf TypeOf container Is EnumMemberDeclarationSyntax Then
Dim enumMember = DirectCast(container, EnumMemberDeclarationSyntax)
Dim attributeLists = enumMember.AttributeLists.Insert(index, attributeList)
Return enumMember.WithAttributeLists(attributeLists)
ElseIf TypeOf container Is DelegateStatementSyntax Then
Dim delegateStatement = DirectCast(container, DelegateStatementSyntax)
Dim attributeLists = delegateStatement.AttributeLists.Insert(index, attributeList)
Return delegateStatement.WithAttributeLists(attributeLists)
ElseIf TypeOf container Is DeclareStatementSyntax Then
Dim declareStatement = DirectCast(container, DeclareStatementSyntax)
Dim attributeLists = declareStatement.AttributeLists.Insert(index, attributeList)
Return declareStatement.WithAttributeLists(attributeLists)
ElseIf TypeOf container Is MethodStatementSyntax Then
Dim methodStatement = DirectCast(container, MethodStatementSyntax)
Dim attributeLists = methodStatement.AttributeLists.Insert(index, attributeList)
Return methodStatement.WithAttributeLists(attributeLists)
ElseIf TypeOf container Is MethodBlockBaseSyntax Then
Dim method = DirectCast(container, MethodBlockBaseSyntax)
If TypeOf method.BlockStatement Is SubNewStatementSyntax Then
Dim constructor = DirectCast(method.BlockStatement, SubNewStatementSyntax)
Dim attributeLists = constructor.AttributeLists.Insert(index, attributeList)
Return DirectCast(method, ConstructorBlockSyntax).WithBlockStatement(constructor.WithAttributeLists(attributeLists))
ElseIf TypeOf method.BlockStatement Is OperatorStatementSyntax Then
Dim operatorStatement = DirectCast(method.BlockStatement, OperatorStatementSyntax)
Dim attributeLists = operatorStatement.AttributeLists.Insert(index, attributeList)
Return DirectCast(method, OperatorBlockSyntax).WithBlockStatement(operatorStatement.WithAttributeLists(attributeLists))
ElseIf TypeOf method.BlockStatement Is MethodStatementSyntax Then
Dim methodStatement = DirectCast(method.BlockStatement, MethodStatementSyntax)
Dim attributeLists = methodStatement.AttributeLists.Insert(index, attributeList)
Return DirectCast(method, MethodBlockSyntax).WithBlockStatement(methodStatement.WithAttributeLists(attributeLists))
End If
ElseIf TypeOf container Is PropertyStatementSyntax Then
Dim propertyStatement = DirectCast(container, PropertyStatementSyntax)
Dim attributeLists = propertyStatement.AttributeLists.Insert(index, attributeList)
Return propertyStatement.WithAttributeLists(attributeLists)
ElseIf TypeOf container Is PropertyBlockSyntax Then
Dim propertyBlock = DirectCast(container, PropertyBlockSyntax)
Dim attributeLists = propertyBlock.PropertyStatement.AttributeLists.Insert(index, attributeList)
Return propertyBlock.WithPropertyStatement(propertyBlock.PropertyStatement.WithAttributeLists(attributeLists))
ElseIf TypeOf container Is EventStatementSyntax Then
Dim eventStatement = DirectCast(container, EventStatementSyntax)
Dim attributeLists = eventStatement.AttributeLists.Insert(index, attributeList)
Return eventStatement.WithAttributeLists(attributeLists)
ElseIf TypeOf container Is EventBlockSyntax Then
Dim eventBlock = DirectCast(container, EventBlockSyntax)
Dim attributeLists = eventBlock.EventStatement.AttributeLists.Insert(index, attributeList)
Return eventBlock.WithEventStatement(eventBlock.EventStatement.WithAttributeLists(attributeLists))
ElseIf TypeOf container Is FieldDeclarationSyntax Then
Dim field = DirectCast(container, FieldDeclarationSyntax)
Dim attributeLists = field.AttributeLists.Insert(index, attributeList)
Return field.WithAttributeLists(attributeLists)
ElseIf TypeOf container Is ParameterSyntax Then
Dim parameter = DirectCast(container, ParameterSyntax)
Dim attributeLists = parameter.AttributeLists.Insert(index, attributeList)
Return parameter.WithAttributeLists(attributeLists)
End If
Throw Exceptions.ThrowEUnexpected()
End Function
Protected Overrides Function InsertImportIntoContainer(index As Integer, importNode As SyntaxNode, container As SyntaxNode) As SyntaxNode
If TypeOf container IsNot CompilationUnitSyntax Then
Throw Exceptions.ThrowEUnexpected()
End If
Dim compilationUnit = DirectCast(container, CompilationUnitSyntax)
Dim importsStatement = DirectCast(importNode, ImportsStatementSyntax)
Dim lastToken = importsStatement.GetLastToken()
If lastToken.Kind <> SyntaxKind.EndOfLineTrivia Then
importsStatement = importsStatement.ReplaceToken(lastToken, lastToken.WithAppendedTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed))
End If
Dim importsList = compilationUnit.Imports.Insert(index, importsStatement)
Return compilationUnit.WithImports(importsList)
End Function
Private Function InsertParameterIntoParameterList(index As Integer, parameter As ParameterSyntax, list As ParameterListSyntax) As ParameterListSyntax
If list Is Nothing Then
Return SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(parameter)) _
.WithAdditionalAnnotations(Formatter.Annotation)
End If
Dim parameters = list.Parameters.Insert(index, parameter)
Return list.WithParameters(parameters)
End Function
Protected Overrides Function InsertParameterIntoContainer(index As Integer, parameter As SyntaxNode, container As SyntaxNode) As SyntaxNode
Dim parameterNode = DirectCast(parameter, ParameterSyntax)
If TypeOf container Is MethodBaseSyntax Then
Dim methodStatement = DirectCast(container, MethodBaseSyntax)
Dim parameterList = InsertParameterIntoParameterList(index, parameterNode, methodStatement.ParameterList)
Return methodStatement.WithParameterList(parameterList)
ElseIf TypeOf container Is MethodBlockBaseSyntax Then
Dim methodBlock = DirectCast(container, MethodBlockBaseSyntax)
Dim methodStatement = methodBlock.BlockStatement
Dim parameterList = InsertParameterIntoParameterList(index, parameterNode, methodStatement.ParameterList)
methodStatement = methodStatement.WithParameterList(parameterList)
Select Case methodBlock.Kind
Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock
Return DirectCast(methodBlock, MethodBlockSyntax).WithBlockStatement(DirectCast(methodStatement, MethodStatementSyntax))
Case SyntaxKind.ConstructorBlock
Return DirectCast(methodBlock, ConstructorBlockSyntax).WithBlockStatement(DirectCast(methodStatement, SubNewStatementSyntax))
Case SyntaxKind.OperatorBlock
Return DirectCast(methodBlock, OperatorBlockSyntax).WithBlockStatement(DirectCast(methodStatement, OperatorStatementSyntax))
Case Else
Return DirectCast(methodBlock, AccessorBlockSyntax).WithBlockStatement(DirectCast(methodStatement, AccessorStatementSyntax))
End Select
ElseIf TypeOf container Is PropertyBlockSyntax Then
Dim propertyBlock = DirectCast(container, PropertyBlockSyntax)
Dim propertyStatement = propertyBlock.PropertyStatement
Dim parameterList = InsertParameterIntoParameterList(index, parameterNode, propertyStatement.ParameterList)
propertyStatement = propertyStatement.WithParameterList(parameterList)
Return propertyBlock.WithPropertyStatement(propertyStatement)
End If
Throw Exceptions.ThrowEUnexpected()
End Function
Public Overrides Function IsNamespace(node As SyntaxNode) As Boolean
Return TypeOf node Is NamespaceBlockSyntax
End Function
Public Overrides Function IsType(node As SyntaxNode) As Boolean
Return TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is EnumBlockSyntax
End Function
Public Overrides Function GetMethodXml(node As SyntaxNode, semanticModel As SemanticModel) As String
Dim methodBlock = TryCast(node, MethodBlockBaseSyntax)
If methodBlock Is Nothing Then
Throw Exceptions.ThrowEUnexpected()
End If
Return MethodXmlBuilder.Generate(methodBlock, semanticModel)
End Function
Private Shared Function GetMethodStatement(method As SyntaxNode) As MethodStatementSyntax
Dim methodBlock = TryCast(method, MethodBlockBaseSyntax)
If methodBlock Is Nothing Then
Return Nothing
End If
Return TryCast(methodBlock.BlockStatement, MethodStatementSyntax)
End Function
Private Overloads Shared Function GetHandledEventNames(methodStatement As MethodStatementSyntax) As IList(Of String)
If methodStatement Is Nothing OrElse
methodStatement.HandlesClause Is Nothing OrElse
methodStatement.HandlesClause.Events.Count = 0 Then
Return SpecializedCollections.EmptyList(Of String)()
End If
Dim eventCount = methodStatement.HandlesClause.Events.Count
Dim result(eventCount - 1) As String
For i = 0 To eventCount - 1
Dim handlesItem = methodStatement.HandlesClause.Events(i)
result(i) = handlesItem.EventContainer.ToString() & "."c & handlesItem.EventMember.ToString()
Next
Return result
End Function
Private Shared Function EscapeIfNotMeMyBaseOrMyClass(identifier As String) As String
Select Case SyntaxFacts.GetKeywordKind(identifier)
Case SyntaxKind.MeKeyword,
SyntaxKind.MyBaseKeyword,
SyntaxKind.MyClassKeyword,
SyntaxKind.None
Return identifier
Case Else
Return "["c & identifier & "]"c
End Select
End Function
Private Shared Function MakeHandledEventName(parentName As String, eventName As String) As String
If eventName.Length >= parentName.Length Then
If CaseInsensitiveComparison.Equals(eventName.Substring(0, parentName.Length), parentName) Then
Return "MyBase" & eventName.Substring(parentName.Length)
End If
End If
' If eventName starts with an unescaped keyword other than Me, MyBase or MyClass, we need to escape it.
If Not eventName.StartsWith("[", StringComparison.Ordinal) Then
Dim dotIndex = eventName.IndexOf("."c)
If dotIndex >= 0 Then
Return EscapeIfNotMeMyBaseOrMyClass(eventName.Substring(0, dotIndex)) & eventName.Substring(dotIndex)
Else
EscapeIfNotMeMyBaseOrMyClass(eventName)
End If
End If
Return eventName
End Function
Public Overrides Function AddHandlesClause(document As Document, eventName As String, method As SyntaxNode, cancellationToken As CancellationToken) As Document
Dim methodStatement = GetMethodStatement(method)
Dim parentTypeBlock = TryCast(method.Parent, TypeBlockSyntax)
If parentTypeBlock Is Nothing Then
Throw Exceptions.ThrowEUnexpected()
End If
Dim parentName = parentTypeBlock.BlockStatement.Identifier.ToString()
Dim newEventName = MakeHandledEventName(parentName, eventName)
Dim position As Integer
Dim textToInsert As String
If methodStatement.HandlesClause Is Nothing Then
position = methodStatement.ParameterList.CloseParenToken.Span.End
textToInsert = " Handles " & newEventName
Else
position = methodStatement.HandlesClause.Span.End
textToInsert = ", " & newEventName
End If
Dim text = document.GetTextSynchronously(cancellationToken)
text = text.Replace(position, 0, textToInsert)
Return document.WithText(text)
End Function
Public Overrides Function RemoveHandlesClause(document As Document, eventName As String, method As SyntaxNode, cancellationToken As CancellationToken) As Document
Dim methodStatement = GetMethodStatement(method)
Dim parentTypeBlock = TryCast(method.Parent, TypeBlockSyntax)
If parentTypeBlock Is Nothing Then
Throw Exceptions.ThrowEUnexpected()
End If
Dim parentName = parentTypeBlock.BlockStatement.Identifier.ToString()
Dim newEventName = MakeHandledEventName(parentName, eventName)
If methodStatement.HandlesClause Is Nothing Then
Throw Exceptions.ThrowEUnexpected()
End If
Dim indexOfDot = newEventName.IndexOf("."c)
If indexOfDot = -1 Then
Throw Exceptions.ThrowEUnexpected()
End If
Dim containerName = newEventName.Substring(0, indexOfDot)
Dim memberName = newEventName.Substring(indexOfDot + 1)
Dim clauseItemToRemove As HandlesClauseItemSyntax = Nothing
For Each handlesClauseItem In methodStatement.HandlesClause.Events
If handlesClauseItem.EventContainer.ToString() = containerName AndAlso
handlesClauseItem.EventMember.ToString() = memberName Then
clauseItemToRemove = handlesClauseItem
Exit For
End If
Next
If clauseItemToRemove Is Nothing Then
Throw Exceptions.ThrowEUnexpected()
End If
Dim text = document.GetTextSynchronously(cancellationToken)
If methodStatement.HandlesClause.Events.Count = 1 Then
' Easy case, delete the whole clause
text = text.Replace(methodStatement.HandlesClause.Span, String.Empty)
Else
' Harder case, remove it from the list. If it's the first one, remove the following
' comma, else remove the preceding comma.
Dim index = methodStatement.HandlesClause.Events.IndexOf(clauseItemToRemove)
If index = 0 Then
text = text.Replace(TextSpan.FromBounds(clauseItemToRemove.SpanStart, methodStatement.HandlesClause.Events.GetSeparator(0).Span.End), String.Empty)
Else
text = text.Replace(TextSpan.FromBounds(methodStatement.HandlesClause.Events.GetSeparator(index - 1).SpanStart, clauseItemToRemove.Span.End), String.Empty)
End If
End If
Return document.WithText(text)
End Function
Public Overloads Overrides Function GetHandledEventNames(method As SyntaxNode, semanticModel As SemanticModel) As IList(Of String)
Dim methodStatement = GetMethodStatement(method)
Return GetHandledEventNames(methodStatement)
End Function
Public Overrides Function HandlesEvent(eventName As String, method As SyntaxNode, semanticModel As SemanticModel) As Boolean
Dim methodStatement = GetMethodStatement(method)
Dim handledEventNames = GetHandledEventNames(methodStatement)
For Each handledEventName In handledEventNames
If CaseInsensitiveComparison.Equals(eventName, handledEventName) Then
Return True
End If
Next
Return False
End Function
Public Overrides Function GetFunctionExtenderNames() As String()
Return {ExtenderNames.VBPartialMethodExtender}
End Function
Public Overrides Function GetFunctionExtender(name As String, node As SyntaxNode, symbol As ISymbol) As Object
If Not TypeOf node Is MethodBlockBaseSyntax AndAlso
Not TypeOf node Is MethodStatementSyntax AndAlso
Not TypeOf symbol Is IMethodSymbol Then
Throw Exceptions.ThrowEUnexpected()
End If
If StringComparer.OrdinalIgnoreCase.Equals(name, ExtenderNames.VBPartialMethodExtender) Then
Dim methodSymbol = DirectCast(symbol, IMethodSymbol)
Dim isPartial = methodSymbol.PartialDefinitionPart IsNot Nothing OrElse methodSymbol.PartialImplementationPart IsNot Nothing
Dim isDeclaration = If(isPartial,
methodSymbol.PartialDefinitionPart Is Nothing,
False)
Return PartialMethodExtender.Create(isDeclaration, isPartial)
End If
Throw Exceptions.ThrowEFail()
End Function
Public Overrides Function GetPropertyExtenderNames() As String()
Return {ExtenderNames.VBAutoPropertyExtender}
End Function
Public Overrides Function GetPropertyExtender(name As String, node As SyntaxNode, symbol As ISymbol) As Object
If Not TypeOf node Is PropertyBlockSyntax AndAlso
Not TypeOf node Is PropertyStatementSyntax AndAlso
Not TypeOf symbol Is IPropertySymbol Then
Throw Exceptions.ThrowEUnexpected()
End If
If StringComparer.OrdinalIgnoreCase.Equals(name, ExtenderNames.VBAutoPropertyExtender) Then
Dim isAutoImplemented = TypeOf node Is PropertyStatementSyntax AndAlso
Not TypeOf node.Parent Is InterfaceBlockSyntax
Return AutoPropertyExtender.Create(isAutoImplemented)
End If
Throw Exceptions.ThrowEFail()
End Function
Public Overrides Function GetExternalTypeExtenderNames() As String()
Return {ExtenderNames.ExternalLocation}
End Function
Public Overrides Function GetExternalTypeExtender(name As String, externalLocation As String) As Object
Debug.Assert(externalLocation IsNot Nothing)
If StringComparer.OrdinalIgnoreCase.Equals(name, ExtenderNames.ExternalLocation) Then
Return CodeTypeLocationExtender.Create(externalLocation)
End If
Throw Exceptions.ThrowEFail()
End Function
Public Overrides Function GetTypeExtenderNames() As String()
Return {ExtenderNames.VBGenericExtender}
End Function
Public Overrides Function GetTypeExtender(name As String, codeType As AbstractCodeType) As Object
If codeType Is Nothing Then
Throw Exceptions.ThrowEUnexpected()
End If
If StringComparer.OrdinalIgnoreCase.Equals(name, ExtenderNames.VBGenericExtender) Then
Return GenericExtender.Create(codeType)
End If
Throw Exceptions.ThrowEFail()
End Function
Protected Overrides Function AddBlankLineToMethodBody(node As SyntaxNode, newNode As SyntaxNode) As Boolean
Return TypeOf node Is SyntaxNode AndAlso
node.IsKind(SyntaxKind.SubStatement, SyntaxKind.FunctionStatement) AndAlso
TypeOf newNode Is SyntaxNode AndAlso
newNode.IsKind(SyntaxKind.SubBlock, SyntaxKind.FunctionBlock)
End Function
Public Overrides Function IsValidBaseType(node As SyntaxNode, typeSymbol As ITypeSymbol) As Boolean
If node.IsKind(SyntaxKind.ClassBlock) Then
Return typeSymbol.TypeKind = TypeKind.Class
ElseIf node.IsKind(SyntaxKind.InterfaceBlock) Then
Return typeSymbol.TypeKind = TypeKind.Interface
End If
Return False
End Function
Public Overrides Function AddBase(node As SyntaxNode, typeSymbol As ITypeSymbol, semanticModel As SemanticModel, position As Integer?) As SyntaxNode
If Not node.IsKind(SyntaxKind.ClassBlock, SyntaxKind.InterfaceBlock) Then
Throw Exceptions.ThrowENotImpl()
End If
Dim typeBlock = DirectCast(node, TypeBlockSyntax)
Dim baseCount = typeBlock.Inherits.Count
If typeBlock.IsKind(SyntaxKind.ClassBlock) AndAlso baseCount > 0 Then
Throw Exceptions.ThrowEFail()
End If
Dim typeBlockPosition = typeBlock.SpanStart
Dim inheritsStatement =
SyntaxFactory.InheritsStatement(
SyntaxFactory.ParseTypeName(
typeSymbol.ToMinimalDisplayString(semanticModel, typeBlockPosition)))
inheritsStatement = inheritsStatement.WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed)
Dim inheritsStatements = typeBlock.Inherits.Insert(0, inheritsStatement)
Return typeBlock.WithInherits(inheritsStatements)
End Function
Public Overrides Function RemoveBase(node As SyntaxNode, typeSymbol As ITypeSymbol, semanticModel As SemanticModel) As SyntaxNode
If Not node.IsKind(SyntaxKind.ClassBlock, SyntaxKind.InterfaceBlock) Then
Throw Exceptions.ThrowENotImpl()
End If
Dim typeBlock = DirectCast(node, TypeBlockSyntax)
If typeBlock.Inherits.Count = 0 Then
Throw Exceptions.ThrowEFail()
End If
Dim inheritsStatements = typeBlock.Inherits
For Each inheritsStatement In inheritsStatements
For Each inheritsType In inheritsStatement.Types
Dim typeInfo = semanticModel.GetTypeInfo(inheritsType, CancellationToken.None)
If typeInfo.Type IsNot Nothing AndAlso
typeInfo.Type.Equals(typeSymbol) Then
If inheritsStatement.Types.Count = 1 Then
inheritsStatements = inheritsStatements.Remove(inheritsStatement)
Else
Dim newInheritsStatement = inheritsStatement.RemoveNode(inheritsType, SyntaxRemoveOptions.KeepEndOfLine)
inheritsStatements = inheritsStatements.Replace(inheritsStatement, newInheritsStatement)
End If
Exit For
End If
Next
Next
Return typeBlock.WithInherits(inheritsStatements)
End Function
Public Overrides Function IsValidInterfaceType(node As SyntaxNode, typeSymbol As ITypeSymbol) As Boolean
If node.IsKind(SyntaxKind.ClassBlock, SyntaxKind.StructureBlock) Then
Return typeSymbol.TypeKind = TypeKind.Interface
End If
Return False
End Function
Public Overrides Function AddImplementedInterface(node As SyntaxNode, typeSymbol As ITypeSymbol, semanticModel As SemanticModel, position As Integer?) As SyntaxNode
If Not node.IsKind(SyntaxKind.ClassBlock, SyntaxKind.StructureBlock) Then
Throw Exceptions.ThrowENotImpl()
End If
Dim typeBlock = DirectCast(node, TypeBlockSyntax)
Dim baseCount = typeBlock.Implements.Count
Dim insertionIndex As Integer
If position IsNot Nothing Then
insertionIndex = position.Value
If insertionIndex > baseCount Then
Throw Exceptions.ThrowEInvalidArg()
End If
Else
insertionIndex = baseCount
End If
Dim typeBlockPosition = typeBlock.SpanStart
Dim implementsStatement =
SyntaxFactory.ImplementsStatement(
SyntaxFactory.ParseTypeName(
typeSymbol.ToMinimalDisplayString(semanticModel, typeBlockPosition)))
implementsStatement = implementsStatement.WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed)
Dim implementsStatements = typeBlock.Implements.Insert(insertionIndex, implementsStatement)
Return typeBlock.WithImplements(implementsStatements)
End Function
Public Overrides Function RemoveImplementedInterface(node As SyntaxNode, typeSymbol As ITypeSymbol, semanticModel As SemanticModel) As SyntaxNode
If Not node.IsKind(SyntaxKind.ClassBlock, SyntaxKind.StructureBlock) Then
Throw Exceptions.ThrowENotImpl()
End If
Dim typeBlock = DirectCast(node, TypeBlockSyntax)
If typeBlock.Implements.Count = 0 Then
Throw Exceptions.ThrowEFail()
End If
Dim implementsStatements = typeBlock.Implements
For Each implementsStatement In implementsStatements
For Each inheritsType In implementsStatement.Types
Dim typeInfo = semanticModel.GetTypeInfo(inheritsType, CancellationToken.None)
If typeInfo.Type IsNot Nothing AndAlso
typeInfo.Type.Equals(typeSymbol) Then
If implementsStatement.Types.Count = 1 Then
implementsStatements = implementsStatements.Remove(implementsStatement)
Else
Dim newImplementsStatement = implementsStatement.RemoveNode(inheritsType, SyntaxRemoveOptions.KeepEndOfLine)
implementsStatements = implementsStatements.Replace(implementsStatement, newImplementsStatement)
End If
Exit For
End If
Next
Next
Return typeBlock.WithImplements(implementsStatements)
End Function
Public Overrides Sub AttachFormatTrackingToBuffer(buffer As ITextBuffer)
_commitBufferManagerFactory.CreateForBuffer(buffer).AddReferencingView()
End Sub
Public Overrides Sub DetachFormatTrackingToBuffer(buffer As ITextBuffer)
_commitBufferManagerFactory.CreateForBuffer(buffer).RemoveReferencingView()
End Sub
Public Overrides Sub EnsureBufferFormatted(buffer As ITextBuffer)
_commitBufferManagerFactory.CreateForBuffer(buffer).CommitDirty(isExplicitFormat:=False, cancellationToken:=Nothing)
End Sub
End Class
End Namespace
|
AlekseyTs/roslyn
|
src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService.vb
|
Visual Basic
|
mit
| 217,340
|
' 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.VisualBasic
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigationBar
<[UseExportProvider]>
Partial Public Class VisualBasicNavigationBarTests
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545000")>
Public Async Function TestEventsInInterfaces() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface I
Event Goo As EventHandler
End Interface
</Document>
</Project>
</Workspace>,
Item("I", Glyph.InterfaceInternal, bolded:=True, children:={
Item("Goo", Glyph.EventPublic, bolded:=True)}))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544996")>
Public Async Function TestEmptyStructure() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Structure S
End Structure
</Document>
</Project>
</Workspace>,
Item("S", Glyph.StructureInternal, bolded:=True, children:={}))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544996")>
Public Async Function TestEmptyInterface() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface I
End Interface
</Document>
</Project>
</Workspace>,
Item("I", Glyph.InterfaceInternal, bolded:=True, children:={}))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")>
Public Async Function TestUserDefinedOperators() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Shared Operator -(x As C, y As C) As C
End Operator
Shared Operator +(x As C, y As C) As C
End Operator
Shared Operator +(x As C, y As Integer) As C
End Operator
End Class
</Document>
</Project>
</Workspace>,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("Operator +(C, C) As C", Glyph.Operator, bolded:=True),
Item("Operator +(C, Integer) As C", Glyph.Operator, bolded:=True),
Item("Operator -", Glyph.Operator, bolded:=True)}))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")>
Public Async Function TestSingleConversion() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Shared Narrowing Operator CType(x As C) As Integer
End Operator
End Class
</Document>
</Project>
</Workspace>,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("Narrowing Operator CType", Glyph.Operator, bolded:=True)}))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")>
Public Async Function TestMultipleConversions() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Shared Narrowing Operator CType(x As C) As Integer
End Operator
Shared Narrowing Operator CType(x As C) As String
End Operator
End Class
</Document>
</Project>
</Workspace>,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("Narrowing Operator CType(C) As Integer", Glyph.Operator, bolded:=True),
Item("Narrowing Operator CType(C) As String", Glyph.Operator, bolded:=True)}))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544993")>
Public Async Function TestNestedClass() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Namespace N
Class C
Class Nested
End Class
End Class
End Namespace
</Document>
</Project>
</Workspace>,
Item("C", Glyph.ClassInternal, bolded:=True),
Item("Nested (N.C)", Glyph.ClassPublic, bolded:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544997")>
Public Async Function TestDelegate() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Delegate Sub Goo()
</Document>
</Project>
</Workspace>,
Item("Goo", Glyph.DelegateInternal, children:={}, bolded:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544995"), WorkItem(545283, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545283")>
Public Async Function TestGenericType() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface C(Of In T)
End Interface
</Document>
</Project>
</Workspace>,
Item("C(Of In T)", Glyph.InterfaceInternal, bolded:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545113")>
Public Async Function TestMethodGroupWithGenericMethod() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub S()
End Sub
Sub S(Of T)()
End Sub
End Class
</Document>
</Project>
</Workspace>,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("S()", Glyph.MethodPublic, bolded:=True),
Item("S(Of T)()", Glyph.MethodPublic, bolded:=True)}))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545113")>
Public Async Function TestSingleGenericMethod() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub S(Of T)()
End Sub
End Class
</Document>
</Project>
</Workspace>,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("S(Of T)()", Glyph.MethodPublic, bolded:=True)}))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545285, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545285")>
Public Async Function TestSingleGenericFunction() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Function S(Of T)() As Integer
End Sub
End Class
</Document>
</Project>
</Workspace>,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("S(Of T)() As Integer", Glyph.MethodPublic, bolded:=True)}))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestSingleNonGenericMethod() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub S(arg As Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("S", Glyph.MethodPublic, bolded:=True)}))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544994, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544994")>
Public Async Function TestSelectedItemForNestedClass() As Task
Await AssertSelectedItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Class Nested
$$
End Class
End Class
</Document>
</Project>
</Workspace>,
Item("Nested (C)", Glyph.ClassPublic, bolded:=True), False, Nothing, False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(899330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899330")>
Public Async Function TestSelectedItemForNestedClassAlphabeticallyBeforeContainingClass() As Task
Await AssertSelectedItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Z
Class Nested
$$
End Class
End Class
</Document>
</Project>
</Workspace>,
Item("Nested (Z)", Glyph.ClassPublic, bolded:=True), False, Nothing, False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544990")>
Public Async Function TestFinalizer() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Protected Overrides Sub Finalize()
End Class
End Class
</Document>
</Project>
</Workspace>,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=True)}))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(556, "https://github.com/dotnet/roslyn/issues/556")>
Public Async Function TestFieldsAndConstants() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Private Const Co = 1
Private F As Integer
End Class
</Document>
</Project>
</Workspace>,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("Co", Glyph.ConstantPrivate, bolded:=True),
Item("F", Glyph.FieldPrivate, bolded:=True)}))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544988")>
Public Async Function TestGenerateFinalizer() As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
End Class
</Document>
</Project>
</Workspace>,
"C", "Finalize",
<Result>
Class C
Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub
End Class
</Result>)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestGenerateConstructor() As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
End Class
</Document>
</Project>
</Workspace>,
"C", VBEditorResources.New_,
<Result>
Class C
Public Sub New()
End Sub
End Class
</Result>)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestGenerateConstructorInDesignerGeneratedFile() As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute>
Class C
Sub InitializeComponent()
End Sub
End Class
</Document>
</Project>
</Workspace>,
"C", VBEditorResources.New_,
<Result>
<Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute>
Class C
Public Sub New()
' <%= VBEditorResources.This_call_is_required_by_the_designer %>
InitializeComponent()
' <%= VBEditorResources.Add_any_initialization_after_the_InitializeComponent_call %>
End Sub
Sub InitializeComponent()
End Sub
End Class
</Result>)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestGeneratePartialMethod() As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Partial Class C
End Class
</Document>
<Document>
Partial Class C
Private Partial Sub Goo()
End Sub
End Class
</Document>
</Project>
</Workspace>,
"C", "Goo",
<Result>
Partial Class C
Private Sub Goo()
End Sub
End Class
</Result>)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestPartialMethodInDifferentFile() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Partial Class C
End Class
</Document>
<Document>
Partial Class C
Sub Goo()
End Sub
End Class
</Document>
</Project>
</Workspace>,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("Goo", Glyph.MethodPublic, grayed:=True)}))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544991")>
Public Async Function TestWithEventsField() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Private WithEvents goo As System.Console
End Class
</Document>
</Project>
</Workspace>,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item("goo", Glyph.FieldPrivate, bolded:=False, hasNavigationSymbolId:=False, indent:=1, children:={
Item("CancelKeyPress", Glyph.EventPublic, hasNavigationSymbolId:=False)}))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589")>
Public Async Function TestWithEventsField_EventsFromInheritedInterfaces() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface I1
Event I1Event(sender As Object, e As EventArgs)
End Interface
Interface I2
Event I2Event(sender As Object, e As EventArgs)
End Interface
Interface I3
Inherits I1, I2
Event I3Event(sender As Object, e As EventArgs)
End Interface
Class Test
WithEvents i3 As I3
End Class
</Document>
</Project>
</Workspace>,
Item("I1", Glyph.InterfaceInternal, bolded:=True, children:={
Item("I1Event", Glyph.EventPublic, bolded:=True)}),
Item("I2", Glyph.InterfaceInternal, bolded:=True, children:={
Item("I2Event", Glyph.EventPublic, bolded:=True)}),
Item("I3", Glyph.InterfaceInternal, bolded:=True, children:={
Item("I3Event", Glyph.EventPublic, bolded:=True)}),
Item("Test", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item("i3", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={
Item("I1Event", Glyph.EventPublic, hasNavigationSymbolId:=False),
Item("I2Event", Glyph.EventPublic, hasNavigationSymbolId:=False),
Item("I3Event", Glyph.EventPublic, hasNavigationSymbolId:=False)}))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")>
Public Async Function TestDoNotIncludeShadowedEvents() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class B
Event E(sender As Object, e As EventArgs)
End Class
Class C
Inherits B
Shadows Event E(sender As Object, e As EventArgs)
End Class
Class Test
WithEvents c As C
End Class
</Document>
</Project>
</Workspace>,
Item("B", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("E", Glyph.EventPublic, bolded:=True)}),
Item(String.Format(VBEditorResources._0_Events, "B"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}),
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("E", Glyph.EventPublic, bolded:=True)}),
Item(String.Format(VBEditorResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}), ' Only one E under the "(C Events)" node
Item("Test", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item("c", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)})) ' Only one E for WithEvents handling
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")>
Public Async Function TestEventList_EnsureInternalEventsInEventListAndInInheritedEventList() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Event E()
End Class
Class D
Inherits C
End Class
</Document>
</Project>
</Workspace>,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("E", Glyph.EventPublic, bolded:=True)}),
Item(String.Format(VBEditorResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}),
Item("D", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item(String.Format(VBEditorResources._0_Events, "D"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")>
Public Async Function TestEventList_EnsurePrivateEventsInEventListButNotInInheritedEventList() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Private Event E()
End Class
Class D
Inherits C
End Class
</Document>
</Project>
</Workspace>,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("E", Glyph.EventPrivate, bolded:=True)}),
Item(String.Format(VBEditorResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E", Glyph.EventPrivate, hasNavigationSymbolId:=False)}),
Item("D", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")>
Public Async Function TestEventList_TestAccessibilityThroughNestedAndDerivedTypes() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Public Event E0()
Protected Event E1()
Private Event E2()
Class N1
Class N2
Inherits C
End Class
End Class
End Class
Class D2
Inherits C
End Class
Class T
WithEvents c As C
End Class
</Document>
</Project>
</Workspace>,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("E0", Glyph.EventPublic, bolded:=True),
Item("E1", Glyph.EventProtected, bolded:=True),
Item("E2", Glyph.EventPrivate, bolded:=True)}),
Item(String.Format(VBEditorResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False),
Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False),
Item("E2", Glyph.EventPrivate, hasNavigationSymbolId:=False)}),
Item("D2", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item(String.Format(VBEditorResources._0_Events, "D2"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False),
Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False)}),
Item("N1 (C)", Glyph.ClassPublic, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item("N2 (C.N1)", Glyph.ClassPublic, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item(String.Format(VBEditorResources._0_Events, "N2"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False),
Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False),
Item("E2", Glyph.EventPrivate, hasNavigationSymbolId:=False)}),
Item("T", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item("c", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False)}))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestGenerateEventHandler() As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Private WithEvents goo As System.Console
End Class
</Document>
</Project>
</Workspace>,
"goo", "CancelKeyPress",
<Result>
Class C
Private WithEvents goo As System.Console
Private Sub goo_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs) Handles goo.CancelKeyPress
End Sub
End Class
</Result>)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(529946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529946")>
Public Async Function TestGenerateEventHandlerWithEscapedName() As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Event [Rem] As System.Action
End Class
</Document>
</Project>
</Workspace>,
String.Format(VBEditorResources._0_Events, "C"), "Rem",
<Result>
Class C
Event [Rem] As System.Action
Private Sub C_Rem() Handles Me.[Rem]
End Sub
End Class
</Result>)
End Function
<WorkItem(546152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546152")>
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestGenerateEventHandlerWithRemName() As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class C
Event E As Action
WithEvents [Rem] As C
End Class
</Document>
</Project>
</Workspace>,
"Rem", "E",
<Result>
Imports System
Class C
Event E As Action
WithEvents [Rem] As C
Private Sub Rem_E() Handles [Rem].E
End Sub
End Class
</Result>)
End Function
<ConditionalWpfFact(GetType(IsEnglishLocal))>
<WorkItem(25763, "https://github.com/dotnet/roslyn/issues/25763")>
<WorkItem(18792, "https://github.com/dotnet/roslyn/issues/18792")>
<Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestGenerateEventHandlerWithDuplicate() As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class ExampleClass
Public Event ExampleEvent()
Public Event ExampleEvent()
End Class
</Document>
</Project>
</Workspace>,
$"(ExampleClass { FeaturesResources.Events })",
Function(items) items.First(Function(i) i.Text = "ExampleEvent"),
<Result>
Public Class ExampleClass
Public Event ExampleEvent()
Public Event ExampleEvent()
Private Sub ExampleClass_ExampleEvent() Handles Me.ExampleEvent
End Sub
End Class
</Result>)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestNoListedEventToGenerateWithInvalidTypeName() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Event BindingError As System.FogBar
End Class
</Document>
</Project>
</Workspace>,
Item("C", Glyph.ClassInternal, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("BindingError", Glyph.EventPublic, hasNavigationSymbolId:=True, bolded:=True)},
bolded:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(530657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530657")>
Public Async Function TestCodeGenerationItemsShouldNotAppearWhenWorkspaceDoesNotSupportDocumentChanges() As Task
Dim workspaceSupportsChangeDocument = False
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Partial Class C
Private WithEvents M As System.Console
End Class
Partial Class C
Partial Private Sub S()
End Sub
End Class
</Document>
</Project>
</Workspace>,
workspaceSupportsChangeDocument,
Item("C", Glyph.ClassInternal, bolded:=True),
Item("M", Glyph.FieldPrivate, indent:=1, hasNavigationSymbolId:=False))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545220")>
Public Async Function TestEnum() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Enum MyEnum
A
B
C
End Enum
</Document>
</Project>
</Workspace>,
Item("MyEnum", Glyph.EnumInternal, children:={
Item("A", Glyph.EnumMemberPublic),
Item("B", Glyph.EnumMemberPublic),
Item("C", Glyph.EnumMemberPublic)},
bolded:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestEvents() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Base
Public WithEvents o1 As New Class1
Public WithEvents o2 As New Class1
Public Class Class1
' Declare an event.
Public Event Ev_Event()
End Class
$$
Sub EventHandler() Handles o1.Ev_Event
End Sub
End Class
</Document>
</Project>
</Workspace>,
Item("Base", Glyph.ClassPublic, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)},
bolded:=True),
Item("o1", Glyph.FieldPublic, children:={
Item("Ev_Event", Glyph.EventPublic, bolded:=True)},
bolded:=False,
hasNavigationSymbolId:=False,
indent:=1),
Item("o2", Glyph.FieldPublic, children:={
Item("Ev_Event", Glyph.EventPublic, hasNavigationSymbolId:=False)},
bolded:=False,
hasNavigationSymbolId:=False,
indent:=1),
Item("Class1 (Base)", Glyph.ClassPublic, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("Ev_Event", Glyph.EventPublic, bolded:=True)},
bolded:=True),
Item(String.Format(VBEditorResources._0_Events, "Class1"), Glyph.EventPublic, children:={
Item("Ev_Event", Glyph.EventPublic, hasNavigationSymbolId:=False)},
bolded:=False,
indent:=1,
hasNavigationSymbolId:=False))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestNavigationBetweenFiles() As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Source.vb">
Partial Class Program
Sub StartingFile()
End Sub
End Class
</Document>
<Document FilePath="Sink.vb">
Partial Class Program
Sub MethodThatWastesTwoLines()
End Sub
Sub TargetMethod()
$$End Sub
End Class
</Document>
</Project>
</Workspace>,
startingDocumentFilePath:="Source.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="TargetMethod")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(566752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/566752")>
Public Async Function TestNavigationWithMethodWithLineContinuation() As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
Private Iterator Function SomeNumbers() _
As System.Collections.IEnumerable
$$Yield 3
Yield 5
Yield 8
End Function
End Class
</Document>
</Project>
</Workspace>,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="SomeNumbers")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(531586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531586")>
Public Async Function TestNavigationWithMethodWithNoTerminator() As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
$$Private Sub S()
End Class
</Document>
</Project>
</Workspace>,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(531586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531586")>
Public Async Function TestNavigationWithMethodWithDocumentationComment() As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb"><![CDATA[
Partial Class Program
''' <summary></summary>
$$Private Sub S()
End Class
]]></Document>
</Project>
</Workspace>,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(567914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/567914")>
Public Async Function TestNavigationWithMethodWithMultipleLineDeclaration() As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
Private Sub S(
value As Integer
)
$$Exit Sub
End Sub
End Class
</Document>
</Project>
</Workspace>,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")>
Public Async Function TestNavigationWithMethodContainingComment() As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
Private Sub S(value As Integer)
$$' Goo
End Sub
End Class
</Document>
</Project>
</Workspace>,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")>
Public Async Function TestNavigationWithMethodContainingBlankLineWithSpaces() As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
Private Sub S(value As Integer)
$$
End Sub
End Class
</Document>
</Project>
</Workspace>,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")>
Public Async Function TestNavigationWithMethodContainingBlankLineWithNoSpaces() As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
Private Sub S(value As Integer)
$$
End Sub
End Class
</Document>
</Project>
</Workspace>,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S",
expectedVirtualSpace:=8)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")>
Public Async Function TestNavigationWithMethodContainingBlankLineWithSomeSpaces() As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
Private Sub S(value As Integer)
$$
End Sub
End Class
</Document>
</Project>
</Workspace>,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S",
expectedVirtualSpace:=4)
End Function
<WorkItem(187865, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/187865")>
<Fact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function DifferentMembersMetadataName() As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Function Get_P(o As Object) As Object
Return o
End Function
ReadOnly Property P As Object
Get
Return Nothing
End Get
End Property
End Class
</Document>
</Project>
</Workspace>,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item(VBEditorResources.New_, Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("Get_P", Glyph.MethodPublic, bolded:=True),
Item("P", Glyph.PropertyPublic, bolded:=True)}))
End Function
End Class
End Namespace
|
DustinCampbell/roslyn
|
src/EditorFeatures/Test2/NavigationBar/VisualBasicNavigationBarTests.vb
|
Visual Basic
|
apache-2.0
| 50,265
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.