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
|
|---|---|---|---|---|---|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Debugging
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.IntroduceVariable
Imports Microsoft.CodeAnalysis.Notification
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Remote.Testing
Imports Microsoft.CodeAnalysis.Rename
Imports Microsoft.CodeAnalysis.Shared.Utilities
Imports Microsoft.VisualStudio.Text
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename
<[UseExportProvider]>
Public Class InlineRenameTests
Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper
Public Sub New(outputHelper As Abstractions.ITestOutputHelper)
_outputHelper = outputHelper
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function SimpleEditAndCommit(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$Test1|]
{
void Blah()
{
[|Test1|] f = new [|Test1|]();
}
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
' Type a bit in the file
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
textBuffer.Insert(caretPosition, "Bar")
session.Commit()
Await VerifyTagsAreCorrect(workspace, "BarTest1")
VerifyFileName(workspace, "BarTest1")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function RenameLocalVariableInTopLevelStatement(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
object [|$$test|] = new object();
var other = [|test|];
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
' Type a bit in the file
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
textBuffer.Insert(caretPosition, "renamed")
session.Commit()
Await VerifyTagsAreCorrect(workspace, "renamedtest")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function RenameLambdaDiscard(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void M()
{
C _ = null;
System.Func<int, string, int> f = (int _, string [|$$_|]) => { _ = null; return 1; };
}
}
]]></Document>
</Project>
</Workspace>, host)
Await VerifyRenameOptionChangedSessionCommit(workspace, originalTextToRename:="_", renameTextPrefix:="change", renameOverloads:=True)
VerifyFileName(workspace, "Test1")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(22495, "https://github.com/dotnet/roslyn/issues/22495")>
Public Async Function RenameDeconstructionForeachCollection(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System.Collections.Generic;
class Deconstructable
{
void M(IEnumerable<Deconstructable> [|$$x|])
{
foreach (var (y1, y2) in [|x|])
{
}
}
void Deconstruct(out int i, out int j) { i = 0; j = 0; }
}
]]></Document>
</Project>
</Workspace>, host)
Await VerifyRenameOptionChangedSessionCommit(workspace, "x", "change", renameOverloads:=True)
VerifyFileName(workspace, "Test1")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function RenameDeconstructMethodInDeconstructionForeach(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><;
}
void [|$$Deconstruct|](out int i, out int j) { i = 0; j = 0; }
}
]]></Document>
</Project>
</Workspace>, host)
Await VerifyRenameOptionChangedSessionCommit(workspace, "Deconstruct", "Changed", renameOverloads:=True)
VerifyFileName(workspace, "Test1")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(540120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540120")>
Public Async Function SimpleEditAndVerifyTagsPropagatedAndCommit(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$Test1|]
{
void Blah()
{
[|Test1|] f = new [|Test1|]();
}
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
' Type a bit in the file
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
textBuffer.Insert(caretPosition, "Bar")
Await WaitForRename(workspace)
Await VerifyTagsAreCorrect(workspace, "BarTest1")
session.Commit()
Await VerifyTagsAreCorrect(workspace, "BarTest1")
VerifyFileName(workspace, "BarTest1")
End Using
End Function
Private Shared Async Function VerifyRenameOptionChangedSessionCommit(workspace As TestWorkspace,
originalTextToRename As String,
renameTextPrefix As String,
Optional renameOverloads As Boolean = False,
Optional renameInStrings As Boolean = False,
Optional renameInComments As Boolean = False,
Optional renameFile As Boolean = False,
Optional fileToRename As DocumentId = Nothing) As Task
Dim optionSet = workspace.Options
optionSet = optionSet.WithChangedOption(RenameOptions.RenameOverloads, renameOverloads)
optionSet = optionSet.WithChangedOption(RenameOptions.RenameInStrings, renameInStrings)
optionSet = optionSet.WithChangedOption(RenameOptions.RenameInComments, renameInComments)
optionSet = optionSet.WithChangedOption(RenameOptions.RenameFile, renameFile)
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(optionSet))
Dim session = StartSession(workspace)
' Type a bit in the file
Dim renameDocument As TestHostDocument = workspace.DocumentWithCursor
renameDocument.GetTextBuffer().Insert(renameDocument.CursorPosition.Value, renameTextPrefix)
Dim replacementText = renameTextPrefix + originalTextToRename
Await WaitForRename(workspace)
Await VerifyTagsAreCorrect(workspace, replacementText)
session.Commit()
Await VerifyTagsAreCorrect(workspace, replacementText)
If renameFile Then
If fileToRename Is Nothing Then
VerifyFileName(workspace, replacementText)
Else
VerifyFileName(workspace.CurrentSolution.GetDocument(fileToRename), replacementText)
End If
End If
End Function
<WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/13186")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(700921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700921")>
Public Async Function RenameOverloadsCSharp(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
public void [|$$goo|]()
{
[|goo|]();
}
public void [|goo|]<T>()
{
[|goo|]<T>();
}
public void [|goo|](int i)
{
[|goo|](i);
}
}
</Document>
</Project>
</Workspace>, host)
Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True)
VerifyFileName(workspace, "Test1")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(700921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700921")>
Public Async Function RenameOverloadsVisualBasic(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System.Collections.Generic
Imports System.Linq
Imports System
Public Class Program
Sub Main(args As String())
End Sub
Public Sub [|$$goo|]()
[|goo|]()
End Sub
Public Sub [|goo|](of T)()
[|goo|](of T)()
End Sub
Public Sub [|goo|](s As String)
[|goo|](s)
End Sub
Public Shared Sub [|goo|](d As Double)
[|goo|](d)
End Sub
End Class
</Document>
</Project>
</Workspace>, host)
Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True)
VerifyFileName(workspace, "Test1")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(960955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960955")>
Public Async Function RenameParameterShouldNotAffectCommentsInOtherDocuments(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Program
Sub Main([|$$args|] As String())
End Sub
End Class
</Document>
<Document>
' args
</Document>
</Project>
</Workspace>, host)
Await VerifyRenameOptionChangedSessionCommit(workspace, "args", "bar", renameInComments:=True)
Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "Test1.vb"))
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")>
Public Async Function RenameInLinkedFilesDoesNotCrash(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1">
<Document FilePath="C.cs"><![CDATA[public class [|$$C|] { } // [|C|]]]></Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
</Project>
</Workspace>, host)
Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB", renameInComments:=True)
Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs"))
' https://github.com/dotnet/roslyn/issues/36075
' VerifyFileRename(workspace, "ABC")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")>
Public Async Function RenameInLinkedFilesHandlesBothProjects(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1">
<Document FilePath="C.cs"><![CDATA[
public partial class [|$$C|] { }
// [|C|]
]]></Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
<Document FilePath="C2.cs"><![CDATA[
public partial class C { }
// [|C|]
]]></Document>
</Project>
</Workspace>, host)
Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB", renameInComments:=True)
Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs"))
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")>
Public Async Function RenameInLinkedFilesWithPrivateAccessibility(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1">
<Document FilePath="C.cs"><![CDATA[
public partial class C { private void [|$$F|](){} }
]]></Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2" AssemblyName="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
<Document FilePath="C2.cs"><![CDATA[
public partial class C { }
// [|F|]
]]></Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj3">
<ProjectReference>Proj2</ProjectReference>
<Document FilePath="C3.cs"><![CDATA[
// F
]]></Document>
</Project>
</Workspace>, host)
Await VerifyRenameOptionChangedSessionCommit(workspace, "F", "AB", renameInComments:=True)
Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs"))
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")>
Public Async Function RenameInLinkedFilesWithPublicAccessibility(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1">
<Document FilePath="C.cs"><![CDATA[
public partial class C { public void [|$$F|](){} }
]]></Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2" AssemblyName="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
<Document FilePath="C2.cs"><![CDATA[
public partial class C { }
// [|F|]
]]></Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj3">
<ProjectReference>Proj2</ProjectReference>
<Document FilePath="C3.cs"><![CDATA[
// [|F|]
]]></Document>
</Project>
</Workspace>, host)
Await VerifyRenameOptionChangedSessionCommit(workspace, "F", "AB", renameInComments:=True)
Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs"))
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(3623, "https://github.com/dotnet/roslyn/issues/3623")>
Public Async Function RenameTypeInLinkedFiles(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj">
<Document FilePath="C.cs"><![CDATA[
public class [|$$C|] { }
]]></Document>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
</Project>
</Workspace>, host)
Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB")
Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs"))
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925"), WorkItem(1486, "https://github.com/dotnet/roslyn/issues/1486")>
<WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")>
Public Async Function RenameInCommentsAndStringsCSharp(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.goo(System.Int32)")]
class Program
{
/// <[|goo|]> [|goo|]! </[|goo|]>
public void [|$$goo|]()
{
// [|goo|] GOO
/* [|goo|] */
[|goo|]();
var a = "goo";
var b = $"{1}goo{2}";
}
public void goo(int i)
{
goo(i);
}
}]]>
</Document>
</Project>
</Workspace>, host)
Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True)
VerifyFileName(workspace, "Test1")
End Using
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|](System.Int32)")]
class Program
{
/// <[|goo|]> [|goo|]! </[|goo|]>
public void [|$$goo|]()
{
// [|goo|] GOO
/* [|goo|] */
[|goo|]();
var a = "goo";
var b = $"{1}goo{2}";
}
public void [|goo|](int i)
{
[|goo|](i);
}
}]]>
</Document>
</Project>
</Workspace>, host)
Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True, renameInComments:=True)
VerifyFileName(workspace, "Test1")
End Using
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|](System.Int32)")]
class Program
{
/// <[|goo|]> [|goo|]! </[|goo|]>
public void [|$$goo|]()
{
// [|goo|] GOO
/* [|goo|] */
[|goo|]();
var a = "[|goo|]";
var b = $"{1}[|goo|]{2}";
}
public void goo(int i)
{
goo(i);
}
}]]>
</Document>
</Project>
</Workspace>, host)
Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True, renameInStrings:=True)
VerifyFileName(workspace, "Test1")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925"), WorkItem(1486, "https://github.com/dotnet/roslyn/issues/1486")>
<WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")>
Public Async Function RenameInCommentsAndStringsVisualBasic(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")>
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.goo(System.Int32)")>
Class Program
''' <[|goo|]> [|goo|]! </[|goo|]>
Public Sub [|$$goo|]()
' [|goo|] GOO
' [|goo|]
[|goo|]()
Dim a = "goo"
Dim b = $"{1}goo{2}"
End Sub
Public Sub goo(i As Integer)
goo(i)
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>, host)
Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True)
VerifyFileName(workspace, "Test1")
End Using
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")>
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|](System.Int32)")>
Class Program
''' <[|goo|]> [|goo|]! </[|goo|]>
Public Sub [|$$goo|]()
' [|goo|] GOO
' [|goo|]
[|goo|]()
Dim a = "goo"
Dim b = $"{1}goo{2}"
End Sub
Public Sub [|goo|](i As Integer)
[|goo|](i)
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>, host)
Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True, renameInComments:=True)
VerifyFileName(workspace, "Test1")
End Using
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")>
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|](System.Int32)")>
Class Program
''' <[|goo|]> [|goo|]! </[|goo|]>
Public Sub [|$$goo|]()
' [|goo|] GOO
' [|goo|]
[|goo|]()
Dim a = "[|goo|]"
Dim b = $"{1}[|goo|]{2}"
End Sub
Public Sub goo(i As Integer)
goo(i)
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>, host)
Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True, renameInStrings:=True)
VerifyFileName(workspace, "Test1")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub SimpleEditAndCancel(host As RenameTestHost)
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$Goo|]
{
void Blah()
{
[|Goo|] f = new [|Goo|]();
}
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
' Type a bit in the file
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Dim initialTextSnapshot = textBuffer.CurrentSnapshot
textBuffer.Insert(caretPosition, "Bar")
session.Cancel()
' Assert the file is what it started as
Assert.Equal(initialTextSnapshot.GetText(), textBuffer.CurrentSnapshot.GetText())
' Assert the file name didn't change
VerifyFileName(workspace, "Test1.cs")
End Using
End Sub
<WpfTheory>
<WorkItem(539513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539513")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function CanRenameTypeNamedDynamic(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$dynamic|]
{
void M()
{
[|dynamic|] d;
}
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
textBuffer.Insert(caretPosition, "goo")
session.Commit()
Await VerifyTagsAreCorrect(workspace, "goodynamic")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ReadOnlyRegionsCreated(host As RenameTestHost)
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class $$C
{
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Dim buffer = workspace.Documents.Single().GetTextBuffer()
' Typing at the beginning and end of our span should work
Dim cursorPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Assert.False(buffer.IsReadOnly(cursorPosition))
Assert.False(buffer.IsReadOnly(cursorPosition + 1))
' Replacing our span should work
Assert.False(buffer.IsReadOnly(New Span(workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value, length:=1)))
' Make sure we can't type at the start or end
Assert.True(buffer.IsReadOnly(0))
Assert.True(buffer.IsReadOnly(buffer.CurrentSnapshot.Length))
session.Cancel()
' Assert the file name didn't change
VerifyFileName(workspace, "Test1.cs")
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(543018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543018")>
Public Sub ReadOnlyRegionsCreatedWhichHandleBeginningOfFileEdgeCase(host As RenameTestHost)
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$C c; class C { }</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Dim buffer = workspace.Documents.Single().GetTextBuffer()
' Typing at the beginning and end of our span should work
Assert.False(buffer.IsReadOnly(0))
Assert.False(buffer.IsReadOnly(1))
' Replacing our span should work
Assert.False(buffer.IsReadOnly(New Span(workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value, length:=1)))
session.Cancel()
VerifyFileName(workspace, "Test1.cs")
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameWithInheritenceCascadingWithClass(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
abstract class AAAA
{
public abstract void [|Goo|]();
}
class BBBB : AAAA
{
public override void [|Goo|]() { }
}
class DDDD : BBBB
{
public override void [|Goo|]() { }
}
class CCCC : AAAA
{
public override void [|$$Goo|]() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="GooBar")
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(530467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530467")>
Public Async Function VerifyNoRenameTrackingAfterInlineRenameTyping(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$Test1|]
{
void Blah()
{
[|Test1|] f = new [|Test1|]();
}
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Dim document = workspace.Documents.Single()
Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document)
textBuffer.Insert(caretPosition, "Bar")
Await WaitForRename(workspace)
Await VerifyTagsAreCorrect(workspace, "BarTest1")
Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document)
session.Commit()
Await VerifyTagsAreCorrect(workspace, "BarTest1")
VerifyFileName(workspace, "BarTest1")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function VerifyNoRenameTrackingAfterInlineRenameTyping2(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$Test1|]
{
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Dim document = workspace.Documents.Single()
Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document)
textBuffer.Insert(caretPosition, "Bar")
Await WaitForRename(workspace)
Await VerifyTagsAreCorrect(workspace, "BarTest1")
Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document)
session.Commit()
Await VerifyTagsAreCorrect(workspace, "BarTest1")
VerifyFileName(workspace, "BarTest1")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(579210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579210")>
Public Async Function VerifyNoRenameTrackingAfterInlineRenameCommit(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$Test1|]
{
void Blah()
{
[|Test1|] f = new [|Test1|]();
}
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Dim document = workspace.Documents.Single()
Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document)
textBuffer.Insert(caretPosition, "Bar")
Await WaitForRename(workspace)
Await VerifyTagsAreCorrect(workspace, "BarTest1")
session.Commit()
Await VerifyTagsAreCorrect(workspace, "BarTest1")
Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document)
VerifyFileName(workspace, "BarTest1")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(530765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530765")>
Public Async Function VerifyNoRenameTrackingAfterInlineRenameCancel(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$Goo|]
{
void Blah()
{
[|Goo|] f = new [|Goo|]();
}
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Dim document = workspace.Documents.Single()
Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document)
textBuffer.Insert(caretPosition, "Bar")
Await WaitForRename(workspace)
Await VerifyTagsAreCorrect(workspace, "BarGoo")
session.Cancel()
Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document)
VerifyFileName(workspace, "Test1.cs")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function VerifyRenameTrackingWorksAfterInlineRenameCommit(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$Test1|]
{
void Blah()
{
[|Test1|] f = new [|Test1|]();
}
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
Dim document = workspace.Documents.Single()
Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document)
textBuffer.Insert(caretPosition, "Bar")
Await WaitForRename(workspace)
Await VerifyTagsAreCorrect(workspace, "BarTest1")
session.Commit()
Await VerifyTagsAreCorrect(workspace, "BarTest1")
Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document)
VerifyFileName(workspace, "BarTest1")
textBuffer.Insert(caretPosition, "Baz")
Await VerifyRenameTrackingTags(renameTrackingTagger, workspace, document, expectedTagCount:=1)
End Using
End Function
<WpfTheory, WorkItem(978099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/978099")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function VerifyPreviewChangesCalled(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$Goo|]
{
void Blah()
{
[|Goo|] f = new [|Goo|]();
}
}
</Document>
</Project>
</Workspace>, host)
' Preview should not return null
Dim previewService = DirectCast(workspace.Services.GetRequiredService(Of IPreviewDialogService)(), MockPreviewDialogService)
previewService.ReturnsNull = False
Dim session = StartSession(workspace)
' Type a bit in the file
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
textBuffer.Insert(caretPosition, "Bar")
session.Commit(previewChanges:=True)
Await VerifyTagsAreCorrect(workspace, "BarGoo")
Assert.True(previewService.Called)
Assert.Equal(String.Format(EditorFeaturesResources.Preview_Changes_0, EditorFeaturesResources.Rename), previewService.Title)
Assert.Equal(String.Format(EditorFeaturesResources.Rename_0_to_1_colon, "Goo", "BarGoo"), previewService.Description)
Assert.Equal("Goo", previewService.TopLevelName)
Assert.Equal(Glyph.ClassInternal, previewService.TopLevelGlyph)
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function VerifyPreviewChangesCancellation(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$Goo|]
{
void Blah()
{
[|Goo|] f = new [|Goo|]();
}
}
</Document>
</Project>
</Workspace>, host)
Dim previewService = DirectCast(workspace.Services.GetService(Of IPreviewDialogService)(), MockPreviewDialogService)
previewService.ReturnsNull = True
Dim session = StartSession(workspace)
' Type a bit in the file
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
textBuffer.Insert(caretPosition, "Bar")
session.Commit(previewChanges:=True)
Await VerifyTagsAreCorrect(workspace, "BarGoo")
Assert.True(previewService.Called)
' Session should still be up; type some more
caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
textBuffer.Insert(caretPosition, "Cat")
previewService.ReturnsNull = False
previewService.Called = False
session.Commit(previewChanges:=True)
Await VerifyTagsAreCorrect(workspace, "CatBarGoo")
Assert.True(previewService.Called)
VerifyFileName(workspace, "Test1.cs")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function VerifyLinkedFiles_MethodWithReferences(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj" PreprocessorSymbols="Proj1=True">
<Document FilePath="C.vb">
Class C
Sub [|M$$|]()
End Sub
Sub Test()
#If Proj1 Then
[|M|]()
#End If
#If Proj2 Then
[|M|]()
#End If
End Sub
End Class
</Document>
</Project>
<Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Proj2=True">
<Document IsLinkFile="true" LinkAssemblyName="VBProj" LinkFilePath="C.vb"/>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
' Type a bit in the file
Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.First().GetTextBuffer()
textBuffer.Insert(caretPosition, "o")
Await WaitForRename(workspace)
Await VerifyTagsAreCorrect(workspace, "Mo")
textBuffer.Insert(caretPosition + 1, "w")
Await WaitForRename(workspace)
Await VerifyTagsAreCorrect(workspace, "Mow")
session.Commit()
Await VerifyTagsAreCorrect(workspace, "Mow")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function VerifyLinkedFiles_FieldWithReferences(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj" PreprocessorSymbols="Proj1=True">
<Document FilePath="C.vb">
Class C
Dim [|m$$|] As Integer
Sub Test()
#If Proj1 Then
Dim x = [|m|]
#End If
#If Proj2 Then
Dim x = [|m|]
#End If
End Sub
End Class
</Document>
</Project>
<Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Proj2=True">
<Document IsLinkFile="true" LinkAssemblyName="VBProj" LinkFilePath="C.vb"/>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
' Type a bit in the file
Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.First().GetTextBuffer()
textBuffer.Insert(caretPosition, "a")
Await WaitForRename(workspace)
Await VerifyTagsAreCorrect(workspace, "ma")
textBuffer.Insert(caretPosition + 1, "w")
Await WaitForRename(workspace)
Await VerifyTagsAreCorrect(workspace, "maw")
session.Commit()
Await VerifyTagsAreCorrect(workspace, "maw")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)>
<WorkItem(554, "https://github.com/dotnet/roslyn/issues/554")>
Public Async Function CodeActionCannotCommitDuringInlineRename(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj">
<Document FilePath="C.cs">
class C
{
void M()
{
var z = {|introducelocal:5 + 5|};
var q = [|x$$|];
}
int [|x|];
}</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
' Type a bit in the file
Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.First().GetTextBuffer()
textBuffer.Insert(caretPosition, "yz")
Await WaitForRename(workspace)
' Invoke a CodeAction
Dim introduceVariableRefactoringProvider = New IntroduceVariableCodeRefactoringProvider()
Dim actions = New List(Of CodeAction)
Dim context = New CodeRefactoringContext(
workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id),
workspace.Documents.Single().AnnotatedSpans()("introducelocal").Single(),
Sub(a) actions.Add(a),
CancellationToken.None)
workspace.Documents.Single().AnnotatedSpans.Clear()
introduceVariableRefactoringProvider.ComputeRefactoringsAsync(context).Wait()
Dim editHandler = workspace.ExportProvider.GetExportedValue(Of ICodeActionEditHandlerService)
Dim actualSeverity As NotificationSeverity = Nothing
Dim notificationService = DirectCast(workspace.Services.GetService(Of INotificationService)(), INotificationServiceCallback)
notificationService.NotificationCallback = Sub(message, title, severity) actualSeverity = severity
editHandler.Apply(
workspace,
workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id),
Await actions.First().NestedCodeActions.First().GetOperationsAsync(CancellationToken.None),
"unused",
New ProgressTracker(),
CancellationToken.None)
' CodeAction should be rejected
Assert.Equal(NotificationSeverity.Error, actualSeverity)
Assert.Equal("
class C
{
void M()
{
var z = 5 + 5;
var q = xyz;
}
int xyz;
}",
textBuffer.CurrentSnapshot.GetText())
' Rename should still be active
Await VerifyTagsAreCorrect(workspace, "xyz")
textBuffer.Insert(caretPosition + 2, "q")
Await WaitForRename(workspace)
Await VerifyTagsAreCorrect(workspace, "xyzq")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function RenameMethodWithNameof_FromDefinition_NoOverloads(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void [|M$$|]()
{
nameof([|M|]).ToString();
}
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.First().GetTextBuffer()
textBuffer.Insert(caretPosition, "a")
Await WaitForRename(workspace)
Await VerifyTagsAreCorrect(workspace, "Ma")
session.Commit()
Await VerifyTagsAreCorrect(workspace, "Ma")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function RenameMethodWithNameof_FromReference_NoOverloads(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void [|M|]()
{
nameof([|M$$|]).ToString();
}
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.First().GetTextBuffer()
textBuffer.Insert(caretPosition, "a")
Await WaitForRename(workspace)
Await VerifyTagsAreCorrect(workspace, "Ma")
session.Commit()
Await VerifyTagsAreCorrect(workspace, "Ma")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function RenameMethodWithNameof_FromDefinition_WithOverloads(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void [|M$$|]()
{
nameof(M).ToString();
}
void M(int x) { }
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.First().GetTextBuffer()
textBuffer.Insert(caretPosition, "a")
Await WaitForRename(workspace)
Await VerifyTagsAreCorrect(workspace, "Ma")
session.Commit()
Await VerifyTagsAreCorrect(workspace, "Ma")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function RenameMethodWithNameof_FromReference_WithOverloads(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void [|M|]()
{
nameof([|M$$|]).ToString();
}
void [|M|](int x) { }
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.First().GetTextBuffer()
textBuffer.Insert(caretPosition, "a")
Await WaitForRename(workspace)
Await VerifyTagsAreCorrect(workspace, "Ma")
session.Commit()
Await VerifyTagsAreCorrect(workspace, "Ma")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function RenameMethodWithNameof_FromDefinition_WithOverloads_WithRenameOverloadsOption(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void [|$$M|]()
{
nameof([|M|]).ToString();
}
void [|M|](int x) { }
}
</Document>
</Project>
</Workspace>, host)
Await VerifyRenameOptionChangedSessionCommit(workspace, "M", "Sa", renameOverloads:=True)
VerifyFileName(workspace, "Test1")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(1142095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1142095")>
Public Async Function RenameCommitsWhenDebuggingStarts(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$Goo|]
{
void Blah()
{
[|Goo|] f = new [|Goo|]();
}
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
' Type a bit in the file
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
textBuffer.Insert(caretPosition, "Bar")
' Make sure the RenameService's ActiveSession is still there
Dim renameService = workspace.GetService(Of IInlineRenameService)()
Assert.NotNull(renameService.ActiveSession)
Await VerifyTagsAreCorrect(workspace, "BarGoo")
' Simulate starting a debugging session
Dim debuggingService = workspace.Services.GetService(Of IDebuggingWorkspaceService)
debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run)
' Ensure the rename was committed
Assert.Null(renameService.ActiveSession)
Await VerifyTagsAreCorrect(workspace, "BarGoo")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(1142095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1142095")>
Public Async Function RenameCommitsWhenExitingDebuggingBreakMode(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$Goo|]
{
void Blah()
{
[|Goo|] f = new [|Goo|]();
}
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
' Type a bit in the file
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
textBuffer.Insert(caretPosition, "Bar")
' Make sure the RenameService's ActiveSession is still there
Dim renameService = workspace.GetService(Of IInlineRenameService)()
Assert.NotNull(renameService.ActiveSession)
Await VerifyTagsAreCorrect(workspace, "BarGoo")
' Simulate ending break mode in the debugger (by stepping or continuing)
Dim debuggingService = workspace.Services.GetService(Of IDebuggingWorkspaceService)
debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run)
' Ensure the rename was committed
Assert.Null(renameService.ActiveSession)
Await VerifyTagsAreCorrect(workspace, "BarGoo")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(3316, "https://github.com/dotnet/roslyn/issues/3316")>
Public Async Function InvalidInvocationExpression(host As RenameTestHost) As Task
' Everything on the last line of main is parsed as a single invocation expression
' with CType(...) as the receiver and everything else as arguments.
' Rename doesn't expect to see CType as the receiver of an invocation.
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Module1
Sub Main()
Dim [|$$p|] As IEnumerable(Of Integer) = {1, 2, 3}
Dim linked = Enumerable.Aggregate(Of Global.<anonymous type:head As Global.System.Int32, tail As Global.System.Object>)(
CType([|p|], IEnumerable(Of Integer)), Nothing, Function(total, curr) Nothing)
End Sub
End Module
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
' Type a bit in the file
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
textBuffer.Insert(caretPosition, "q")
session.Commit()
Await VerifyTagsAreCorrect(workspace, "qp")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(2445, "https://github.com/dotnet/roslyn/issues/2445")>
Public Async Function InvalidExpansionTarget(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
int x;
x = 2;
void [|$$M|]() { }
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
' Type a bit in the file
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
textBuffer.Delete(New Span(caretPosition, 1))
textBuffer.Insert(caretPosition, "x")
session.Commit()
Await VerifyTagsAreCorrect(workspace, "x")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(9117, "https://github.com/dotnet/roslyn/issues/9117")>
Public Async Function VerifyVBRenameCrashDoesNotRepro(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Class1
Public Property [|$$Field1|] As Integer
End Class
Public Class Class2
Public Shared Property DataSource As IEnumerable(Of Class1)
Public ReadOnly Property Dict As IReadOnlyDictionary(Of Integer, IEnumerable(Of Class1)) =
(
From data
In DataSource
Group By
data.Field1
Into Group1 = Group
).ToDictionary(
Function(group) group.Field1,
Function(group) group.Group1)
End Class
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
' Type a bit in the file
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
textBuffer.Delete(New Span(caretPosition, 1))
textBuffer.Insert(caretPosition, "x")
session.Commit()
Await VerifyTagsAreCorrect(workspace, "xield1")
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(14554, "https://github.com/dotnet/roslyn/issues/14554")>
Public Sub VerifyVBRenameDoesNotCrashOnAsNewClause(host As RenameTestHost)
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub New(a As Action)
End Sub
Public ReadOnly Property Vm As C
Public ReadOnly Property Crash As New C(Sub()
Vm.Sav()
End Sub)
Public Function Sav$$() As Boolean
Return False
End Function
Public Function Save() As Boolean
Return False
End Function
End Class
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
' Ensure the rename doesn't crash
textBuffer.Insert(caretPosition, "e")
session.Commit()
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VerifyNoFileRenameAllowedForPartialType(host As RenameTestHost)
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class [|$$Goo|]
{
void Blah()
{
}
}
</Document>
<Document>
partial class Goo
{
void BlahBlah()
{
}
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Assert.Equal(InlineRenameFileRenameInfo.TypeWithMultipleLocations, session.FileRenameInfo)
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VerifyFileRenameAllowedForPartialTypeWithSingleLocation(host As RenameTestHost)
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class [|$$Test1|]
{
void Blah()
{
}
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo)
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VerifyFileRenameAllowedWithMultipleTypesOnMatchingName(host As RenameTestHost)
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$Test1|]
{
void Blah()
{
}
}
class Test2
{
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo)
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VerifyNoFileRenameAllowedWithMultipleTypes(host As RenameTestHost)
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$Goo|]
{
void Blah()
{
}
}
class Test1
{
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Assert.Equal(InlineRenameFileRenameInfo.TypeDoesNotMatchFileName, session.FileRenameInfo)
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VerifyEnumKindSupportsFileRename(host As RenameTestHost)
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
enum [|$$Test1|]
{
One,
Two,
Three
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo)
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VerifyInterfaceKindSupportsFileRename(host As RenameTestHost)
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface [|$$Test1|]
{
void Blah();
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo)
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VerifyUnsupportedFileRename(host As RenameTestHost)
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface Test1
{
void [|$$Blah|]();
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
Assert.Equal(InlineRenameFileRenameInfo.NotAllowed, session.FileRenameInfo)
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VerifyFileRenameNotAllowedForLinkedFiles(host As RenameTestHost)
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1">
<Document FilePath="C.cs"><![CDATA[public class [|$$C|] { } // [|C|]]]></Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
</Project>
</Workspace>, host)
' Disable document changes to make sure file rename is not supported.
' Linked workspace files will report that applying changes to document
' info is not allowed; this is intended to mimic that behavior
' and make sure inline rename works as intended.
workspace.CanApplyChangeDocument = False
Dim session = StartSession(workspace)
Assert.Equal(InlineRenameFileRenameInfo.NotAllowed, session.FileRenameInfo)
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VerifyFileRenamesCorrectlyWhenCaseChanges(host As RenameTestHost)
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$Test1|]
{
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
' Type a bit in the file
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
textBuffer.Delete(New Span(caretPosition, 1))
textBuffer.Insert(caretPosition, "t")
session.Commit()
VerifyFileName(workspace, "test1")
End Using
End Sub
<WpfTheory, WorkItem(36063, "https://github.com/dotnet/roslyn/issues/36063")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function EditBackToOriginalNameThenCommit(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$Test1|]
{
void Blah()
{
[|Test1|] f = new [|Test1|]();
}
}
</Document>
</Project>
</Workspace>, host)
Dim session = StartSession(workspace)
' Type a bit in the file
Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
Dim textBuffer = workspace.Documents.Single().GetTextBuffer()
textBuffer.Insert(caretPosition, "Bar")
textBuffer.Delete(New Span(caretPosition, "Bar".Length))
Dim committed = session.GetTestAccessor().CommitWorker(previewChanges:=False)
Assert.False(committed)
Await VerifyTagsAreCorrect(workspace, "Test1")
End Using
End Function
<WpfTheory, WorkItem(44576, "https://github.com/dotnet/roslyn/issues/44576")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Async Function RenameFromOtherFile(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Test1
{
void Blah()
{
[|$$Test2|] t2 = new [|Test2|]();
}
}
</Document>
<Document Name="Test2.cs">
class Test2
{
}
</Document>
</Project>
</Workspace>, host)
Dim docToRename = workspace.Documents.First(Function(doc) doc.Name = "Test2.cs")
Await VerifyRenameOptionChangedSessionCommit(workspace, originalTextToRename:="Test2", renameTextPrefix:="Test2Changed", renameFile:=True, fileToRename:=docToRename.Id)
End Using
End Function
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")>
Public Async Function RenameConstructorReferencedInGlobalSuppression(host As RenameTestHost) As Task
Using workspace = CreateWorkspaceWithWaiter(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:[|C|].#ctor")]
class [|C|]
{
public [|$$C|]()
{
}
}]]>
</Document>
</Project>
</Workspace>, host)
Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "D")
VerifyFileName(workspace, "Test1")
End Using
End Function
End Class
End Namespace
|
jmarolf/roslyn
|
src/EditorFeatures/Test2/Rename/InlineRenameTests.vb
|
Visual Basic
|
mit
| 83,919
|
' 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.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation), WorkItem(21769, "https://github.com/dotnet/roslyn/issues/21769")>
<Fact()>
Public Sub PropertyReferenceExpression_PropertyReferenceInWithDerivedTypeUsesDerivedTypeAsInstanceType_LValue()
Dim source = <![CDATA[
Option Strict On
Module M1
Sub Method1()
Dim c2 As C2 = New C2 With {.P1 = New Object}'BIND:"P1"
End Sub
Class C1
Public Overridable Property P1 As Object
End Class
Class C2
Inherits C1
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IPropertyReferenceOperation: Property M1.C1.P1 As System.Object (OperationKind.PropertyReference, Type: System.Object) (Syntax: 'P1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: M1.C2, IsImplicit) (Syntax: 'New C2 With ... New Object}')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation), WorkItem(21769, "https://github.com/dotnet/roslyn/issues/21769")>
<Fact()>
Public Sub PropertyReferenceExpression_PropertyReferenceInWithDerivedTypeUsesDerivedTypeAsInstanceType_RValue()
Dim source = <![CDATA[
Option Strict On
Module M1
Sub Method1()
Dim c2 As C2 = New C2 With {.P2 = .P1}'BIND:".P1"
c2.P1 = Nothing
End Sub
Class C1
Public Overridable Property P1 As Object
Public Property P2 As Object
End Class
Class C2
Inherits C1
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IPropertyReferenceOperation: Property M1.C1.P1 As System.Object (OperationKind.PropertyReference, Type: System.Object) (Syntax: '.P1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: M1.C2, IsImplicit) (Syntax: 'New C2 With {.P2 = .P1}')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IPropertyReference_SharedPropertyWithInstanceReceiver()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
Shared Property P1 As Integer
Shared Sub S2()
Dim c1Instance As New C1
Dim i1 As Integer = c1Instance.P1'BIND:"c1Instance.P1"
End Sub
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IPropertyReferenceOperation: Property M1.C1.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c1Instance.P1')
Instance Receiver:
ILocalReferenceOperation: c1Instance (OperationKind.LocalReference, Type: M1.C1) (Syntax: 'c1Instance')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
Dim i1 As Integer = c1Instance.P1'BIND:"c1Instance.P1"
~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IPropertyReference_SharedPropertyAccessOnClass()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
Shared Property P1 As Integer
Shared Sub S2()
Dim i1 As Integer = C1.P1'BIND:"C1.P1"
End Sub
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IPropertyReferenceOperation: Property M1.C1.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'C1.P1')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IPropertyReference_InstancePropertyAccessOnClass()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
Property P1 As Integer
Shared Sub S2()
Dim i1 As Integer = C1.P1'BIND:"C1.P1"
End Sub
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IPropertyReferenceOperation: Property M1.C1.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'C1.P1')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30469: Reference to a non-shared member requires an object reference.
Dim i1 As Integer = C1.P1'BIND:"C1.P1"
~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IPropertyReference_SharedProperty()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
Shared Property P1 As Integer
Shared Sub S2()
Dim i1 = P1'BIND:"P1"
End Sub
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IPropertyReferenceOperation: Property M1.C1.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'P1')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub PropertyReference_NoControlFlow()
' Verify mix of property references with implicit/explicit/null instance in lvalue/rvalue contexts.
' Also verifies property with arguments.
Dim source = <![CDATA[
Imports System
Friend Class C
Private Property P1 As Integer
Private Shared Property P2 As Integer
Private ReadOnly Property P3(i As Integer) As Integer
Get
Return 0
End Get
End Property
Public Sub M(c As C, i As Integer)'BIND:"Public Sub M(c As C, i As Integer)"
P1 = C.P2 + c.P3(i)
P2 = Me.P1 + c.P1
End Sub
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'P1 = C.P2 + c.P3(i)')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Void, IsImplicit) (Syntax: 'P1 = C.P2 + c.P3(i)')
Left:
IPropertyReferenceOperation: Property C.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'P1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'P1')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32) (Syntax: 'C.P2 + c.P3(i)')
Left:
IPropertyReferenceOperation: Property C.P2 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'C.P2')
Instance Receiver:
null
Right:
IPropertyReferenceOperation: ReadOnly Property C.P3(i As System.Int32) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c.P3(i)')
Instance Receiver:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'i')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'P2 = Me.P1 + c.P1')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Void, IsImplicit) (Syntax: 'P2 = Me.P1 + c.P1')
Left:
IPropertyReferenceOperation: Property C.P2 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'P2')
Instance Receiver:
null
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32) (Syntax: 'Me.P1 + c.P1')
Left:
IPropertyReferenceOperation: Property C.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Me.P1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me')
Right:
IPropertyReferenceOperation: Property C.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c.P1')
Instance Receiver:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub PropertyReference_ControlFlowInReceiver()
Dim source = <![CDATA[
Imports System
Friend Class C
Public ReadOnly Property P1(i As Integer) As Integer
Get
Return 0
End Get
End Property
Public Sub M(c1 As C, c2 As C, i As Integer, p As Integer)'BIND:"Public Sub M(c1 As C, c2 As C, i As Integer, p As Integer)"
p = If(c1, c2).P1(i)
End Sub
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = If(c1, c2).P1(i)')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p = If(c1, c2).P1(i)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'p')
Right:
IPropertyReferenceOperation: ReadOnly Property C.P1(i As System.Int32) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'If(c1, c2).P1(i)')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'i')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B5]
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub PropertyReference_ControlFlowInReceiver_StaticProperty()
Dim source = <![CDATA[
Imports System
Friend Class C
Public Shared ReadOnly Property P1 As Integer
Public Sub M(c1 As C, c2 As C, p1 As Integer, p2 As Integer)'BIND:"Public Sub M(c1 As C, c2 As C, p1 As Integer, p2 As Integer)"
p1 = c1.P1
p2 = If(c1, c2).P1
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p1 = c1.P1')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p1 = c1.P1')
Left:
IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p1')
Right:
IPropertyReferenceOperation: ReadOnly Property C.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c1.P1')
Instance Receiver:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p2 = If(c1, c2).P1')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p2 = If(c1, c2).P1')
Left:
IParameterReferenceOperation: p2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p2')
Right:
IPropertyReferenceOperation: ReadOnly Property C.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'If(c1, c2).P1')
Instance Receiver:
null
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
p1 = c1.P1
~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
p2 = If(c1, c2).P1
~~~~~~~~~~~~~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub PropertyReference_ControlFlowInFirstArgument()
Dim source = <![CDATA[
Imports System
Friend Class C
Public ReadOnly Property P1(i1 As Integer, i2 As Integer) As Integer
Get
Return 0
End Get
End Property
Public Sub M(c As C, i1 As Integer?, i2 As Integer, i3 As Integer, p As Integer)'BIND:"Public Sub M(c As C, i1 As Integer?, i2 As Integer, i3 As Integer, p As Integer)"
p = c.P1(If(i1, i2), i3)
End Sub
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Arguments(0)
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = c.P1(If(i1, i2), i3)')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p = c.P1(If(i1, i2), i3)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'p')
Right:
IPropertyReferenceOperation: ReadOnly Property C.P1(i1 As System.Int32, i2 As System.Int32) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c.P1(If(i1, i2), i3)')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i1) (OperationKind.Argument, Type: null) (Syntax: 'If(i1, i2)')
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i1, i2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i2) (OperationKind.Argument, Type: null) (Syntax: 'i3')
IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B5]
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub PropertyReference_ControlFlowInSecondArgument()
Dim source = <![CDATA[
Imports System
Friend Class C
Public ReadOnly Property P1(i1 As Integer, i2 As Integer) As Integer
Get
Return 0
End Get
End Property
Public Sub M(c As C, i1 As Integer?, i2 As Integer, i3 As Integer, p As Integer)'BIND:"Public Sub M(c As C, i1 As Integer?, i2 As Integer, i3 As Integer, p As Integer)"
p = c.P1(i3, If(i1, i2))
End Sub
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i3')
Value:
IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i3')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1')
Instance Receiver:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Arguments(0)
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = c.P1(i3, If(i1, i2))')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p = c.P1(i3, If(i1, i2))')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'p')
Right:
IPropertyReferenceOperation: ReadOnly Property C.P1(i1 As System.Int32, i2 As System.Int32) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c.P1(i3, If(i1, i2))')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i1) (OperationKind.Argument, Type: null) (Syntax: 'i3')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i2) (OperationKind.Argument, Type: null) (Syntax: 'If(i1, i2)')
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i1, i2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B5]
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub PropertyReference_ControlFlowInReceiverAndArguments()
Dim source = <![CDATA[
Imports System
Friend Class C
Public ReadOnly Property P1(i1 As Integer, i2 As Integer) As Integer
Get
Return 0
End Get
End Property
Public Sub M(c1 As C, c2 As C, i1 As Integer?, i2 As Integer, i3 As Integer?, i4 As Integer, p As Integer)'BIND:"Public Sub M(c1 As C, c2 As C, i1 As Integer?, i2 As Integer, i3 As Integer?, i4 As Integer, p As Integer)"
p = If(c1, c2).P1(If(i1, i2), If(i3, i4))
End Sub
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i1')
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1')
Instance Receiver:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1')
Arguments(0)
Next (Regular) Block[B7]
Block[B6] - Block
Predecessors: [B4]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B5] [B6]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i3')
Value:
IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i3')
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i3')
Operand:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i3')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i3')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i3')
Instance Receiver:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i3')
Arguments(0)
Next (Regular) Block[B10]
Block[B9] - Block
Predecessors: [B7]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i4')
Value:
IParameterReferenceOperation: i4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i4')
Next (Regular) Block[B10]
Block[B10] - Block
Predecessors: [B8] [B9]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = If(c1, ... If(i3, i4))')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p = If(c1, ... If(i3, i4))')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'p')
Right:
IPropertyReferenceOperation: ReadOnly Property C.P1(i1 As System.Int32, i2 As System.Int32) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'If(c1, c2). ... If(i3, i4))')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i1) (OperationKind.Argument, Type: null) (Syntax: 'If(i1, i2)')
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i1, i2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i2) (OperationKind.Argument, Type: null) (Syntax: 'If(i3, i4)')
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i3, i4)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B11]
Block[B11] - Exit
Predecessors: [B10]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
End Class
End Namespace
|
paulvanbrenk/roslyn
|
src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IPropertyReferenceExpression.vb
|
Visual Basic
|
apache-2.0
| 36,574
|
' 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.VisualBasic.Symbols
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
''' <summary>
''' A simple type parameter with no constraints.
''' </summary>
Friend NotInheritable Class SimpleTypeParameterSymbol
Inherits TypeParameterSymbol
Private ReadOnly _container As Symbol
Private ReadOnly _ordinal As Integer
Private ReadOnly _name As String
Public Sub New(container As Symbol, ordinal As Integer, name As String)
_container = container
_ordinal = ordinal
_name = name
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return _name
End Get
End Property
Public Overrides ReadOnly Property Ordinal As Integer
Get
Return _ordinal
End Get
End Property
Public Overrides ReadOnly Property TypeParameterKind As TypeParameterKind
Get
Return TypeParameterKind.Type
End Get
End Property
Public Overrides ReadOnly Property HasConstructorConstraint As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property HasReferenceTypeConstraint As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property HasValueTypeConstraint As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property Variance As VarianceKind
Get
Return VarianceKind.None
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _container
End Get
End Property
Friend Overrides ReadOnly Property ConstraintTypesNoUseSiteDiagnostics As ImmutableArray(Of TypeSymbol)
Get
Return ImmutableArray(Of TypeSymbol).Empty
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
Friend Overrides Sub EnsureAllConstraintsAreResolved()
Throw ExceptionUtilities.Unreachable
End Sub
End Class
End Namespace
|
mmitche/roslyn
|
src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/SimpleTypeParameterSymbol.vb
|
Visual Basic
|
apache-2.0
| 2,958
|
' 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.Runtime.InteropServices
Imports System.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents a type other than an array, a type parameter.
''' </summary>
Friend MustInherit Class NamedTypeSymbol
Inherits TypeSymbol
Implements INamedTypeSymbol
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
' Changes to the public interface of this class should remain synchronized with the C# version.
' Do not make any changes to the public interface without making the corresponding change
' to the C# version.
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
''' <summary>
''' Returns the arity of this type, or the number of type parameters it takes.
''' A non-generic type has zero arity.
''' </summary>
Public MustOverride ReadOnly Property Arity As Integer
''' <summary>
''' Returns the type parameters that this type has. If this is a non-generic type,
''' returns an empty ImmutableArray.
''' </summary>
Public MustOverride ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
''' <summary>
''' Returns the type arguments that have been substituted for the type parameters.
''' If nothing has been substituted for a give type parameters,
''' then the type parameter itself is consider the type argument.
''' </summary>
Public ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol)
Get
Return TypeArgumentsNoUseSiteDiagnostics
End Get
End Property
''' <summary>
''' Returns custom modifiers for the type arguments that have been substituted for the type parameters.
''' </summary>
Friend MustOverride ReadOnly Property TypeArgumentsCustomModifiers As ImmutableArray(Of ImmutableArray(Of CustomModifier))
Friend Function CreateEmptyTypeArgumentsCustomModifiers() As ImmutableArray(Of ImmutableArray(Of CustomModifier))
Dim arity = Me.Arity
If arity > 0 Then
Return CreateEmptyTypeArgumentsCustomModifiers(arity)
Else
Return ImmutableArray(Of ImmutableArray(Of CustomModifier)).Empty
End If
End Function
Friend Shared Function CreateEmptyTypeArgumentsCustomModifiers(arity As Integer) As ImmutableArray(Of ImmutableArray(Of CustomModifier))
Debug.Assert(arity > 0)
Return ArrayBuilder(Of ImmutableArray(Of CustomModifier)).GetInstance(arity, ImmutableArray(Of CustomModifier).Empty).ToImmutableAndFree()
End Function
Friend MustOverride ReadOnly Property HasTypeArgumentsCustomModifiers As Boolean
Friend MustOverride ReadOnly Property TypeArgumentsNoUseSiteDiagnostics As ImmutableArray(Of TypeSymbol)
Friend Function TypeArgumentsWithDefinitionUseSiteDiagnostics(<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ImmutableArray(Of TypeSymbol)
Dim result = TypeArgumentsNoUseSiteDiagnostics
For Each typeArgument In result
typeArgument.OriginalDefinition.AddUseSiteDiagnostics(useSiteDiagnostics)
Next
Return result
End Function
Friend Function TypeArgumentWithDefinitionUseSiteDiagnostics(index As Integer, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As TypeSymbol
Dim result = TypeArgumentsNoUseSiteDiagnostics(index)
result.OriginalDefinition.AddUseSiteDiagnostics(useSiteDiagnostics)
Return result
End Function
''' <summary>
''' Returns the type symbol that this type was constructed from. This type symbol
''' has the same containing type, but has type arguments that are the same
''' as the type parameters (although its containing type might not).
''' </summary>
Public MustOverride ReadOnly Property ConstructedFrom As NamedTypeSymbol
''' <summary>
''' For enum types, gets the underlying type. Returns null on all other
''' kinds of types.
''' </summary>
Public Overridable ReadOnly Property EnumUnderlyingType As NamedTypeSymbol
Get
Return Nothing
End Get
End Property
Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol
Get
Return TryCast(Me.ContainingSymbol, NamedTypeSymbol)
End Get
End Property
''' <summary>
''' For implicitly declared delegate types returns the EventSymbol that caused this
''' delegate type to be generated.
''' For all other types returns null.
''' Note, the set of possible associated symbols might be expanded in the future to
''' reflect changes in the languages.
''' </summary>
Public Overridable ReadOnly Property AssociatedSymbol As Symbol
Get
Return Nothing
End Get
End Property
''' <summary>
''' Returns True for one of the types from a set of Structure types if
''' that set represents a cycle. This property is intended for flow
''' analysis only since it is only implemented for source types,
''' and only returns True for one of the types within a cycle, not all.
''' </summary>
Friend Overridable ReadOnly Property KnownCircularStruct As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Is this a NoPia local type explicitly declared in source, i.e.
''' top level type with a TypeIdentifier attribute on it?
''' </summary>
Friend Overridable ReadOnly Property IsExplicitDefinitionOfNoPiaLocalType As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Returns true and a string from the first GuidAttribute on the type,
''' the string might be null or an invalid guid representation. False,
''' if there is no GuidAttribute with string argument.
''' </summary>
Friend Overridable Function GetGuidString(ByRef guidString As String) As Boolean
Return GetGuidStringDefaultImplementation(guidString)
End Function
' Named types have the arity suffix added to the metadata name.
Public Overrides ReadOnly Property MetadataName As String
Get
' CLR generally allows names with dots, however some APIs like IMetaDataImport
' can only return full type names combined with namespaces.
' see: http://msdn.microsoft.com/en-us/library/ms230143.aspx (IMetaDataImport::GetTypeDefProps)
' When working with such APIs, names with dots become ambiguous since metadata
' consumer cannot figure where namespace ends and actual type name starts.
' Therefore it is a good practice to avoid type names with dots.
Debug.Assert(Me.IsErrorType OrElse Not (TypeOf Me Is SourceNamedTypeSymbol) OrElse Not Name.Contains("."), "type name contains dots: " + Name)
Return If(MangleName, MetadataHelpers.ComposeAritySuffixedMetadataName(Name, Arity), Name)
End Get
End Property
''' <summary>
''' Should the name returned by Name property be mangled with [`arity] suffix in order to get metadata name.
''' Must return False for a type with Arity == 0.
''' </summary>
''' <remarks>
''' Default implementation to force consideration of appropriate implementation for each new subclass
''' </remarks>
Friend MustOverride ReadOnly Property MangleName As Boolean
''' <summary>
''' True if this symbol has a special name (metadata flag SpecialName is set).
''' </summary>
Friend MustOverride ReadOnly Property HasSpecialName As Boolean
''' <summary>
''' True if this type is considered serializable (metadata flag Serializable is set).
''' </summary>
Friend MustOverride ReadOnly Property IsSerializable As Boolean
''' <summary>
''' Type layout information (ClassLayout metadata and layout kind flags).
''' </summary>
Friend MustOverride ReadOnly Property Layout As TypeLayout
''' <summary>
''' The default charset used for type marshalling.
''' Can be changed via <see cref="DefaultCharSetAttribute"/> applied on the containing module.
''' </summary>
Protected ReadOnly Property DefaultMarshallingCharSet As CharSet
Get
Return If(EffectiveDefaultMarshallingCharSet, CharSet.Ansi)
End Get
End Property
''' <summary>
''' Marshalling charset of string data fields within the type (string formatting flags in metadata).
''' </summary>
Friend MustOverride ReadOnly Property MarshallingCharSet As CharSet
''' <summary>
''' For delegate types, gets the delegate's invoke method. Returns null on
''' all other kinds of types. Note that is is possible to have an ill-formed
''' delegate type imported from metadata which does not have an Invoke method.
''' Such a type will be classified as a delegate but its DelegateInvokeMethod
''' would be null.
''' </summary>
Public Overridable ReadOnly Property DelegateInvokeMethod As MethodSymbol
Get
If TypeKind <> TypeKind.Delegate Then
Return Nothing
End If
Dim methods As ImmutableArray(Of Symbol) = GetMembers(WellKnownMemberNames.DelegateInvokeName)
If methods.Length <> 1 Then
Return Nothing
End If
Dim method = TryCast(methods(0), MethodSymbol)
'EDMAURER we used to also check 'method.IsOverridable' because section 13.6
'of the CLI spec dictates that it be virtual, but real world
'working metadata has been found that contains an Invoke method that is
'marked as virtual but not newslot (both of those must be combined to
'meet the definition of virtual). Rather than weaken the check
'I've removed it, as the Dev10 C# compiler makes no check, and we don't
'stand to gain anything by having it.
'Return If(method IsNot Nothing AndAlso method.IsOverridable, method, Nothing)
Return method
End Get
End Property
''' <summary>
''' Returns true if this type was declared as requiring a derived class;
''' i.e., declared with the "MustInherit" modifier. Always true for interfaces.
''' </summary>
Public MustOverride ReadOnly Property IsMustInherit As Boolean
''' <summary>
''' Returns true if this type does not allow derived types; i.e., declared
''' with the NotInheritable modifier, or else declared as a Module, Structure,
''' Enum, or Delegate.
''' </summary>
Public MustOverride ReadOnly Property IsNotInheritable As Boolean
''' <summary>
''' If this property returns false, it is certain that there are no extension
''' methods inside this type. If this property returns true, it is highly likely
''' (but not certain) that this type contains extension methods. This property allows
''' the search for extension methods to be narrowed much more quickly.
'''
''' !!! Note that this property can mutate during lifetime of the symbol !!!
''' !!! from True to False, as we learn more about the type. !!!
''' </summary>
Public MustOverride ReadOnly Property MightContainExtensionMethods As Boolean Implements INamedTypeSymbol.MightContainExtensionMethods
''' <summary>
''' Returns True if the type is marked by 'Microsoft.VisualBasic.Embedded' attribute.
''' </summary>
Friend MustOverride ReadOnly Property HasEmbeddedAttribute As Boolean
''' <summary>
''' A Named type is an extensible interface if both the following are true:
''' (a) It is an interface type and
''' (b) It is either marked with 'TypeLibTypeAttribute( flags w/o TypeLibTypeFlags.FNonExtensible )' attribute OR
''' is marked with 'InterfaceTypeAttribute( flags with ComInterfaceType.InterfaceIsIDispatch )' attribute OR
''' inherits from an extensible interface type.
''' Member resolution for Extensible interfaces is late bound, i.e. members are resolved at run time by looking up the identifier on the actual run-time type of the expression.
''' </summary>
Friend MustOverride ReadOnly Property IsExtensibleInterfaceNoUseSiteDiagnostics As Boolean
''' <summary>
''' This method is an entry point for the Binder to collect extension methods with the given name
''' declared within this named type. Overridden by RetargetingNamedTypeSymbol.
''' </summary>
Friend Overridable Sub AppendProbableExtensionMethods(name As String, methods As ArrayBuilder(Of MethodSymbol))
If Me.MightContainExtensionMethods Then
For Each member As Symbol In Me.GetMembers(name)
If member.Kind = SymbolKind.Method Then
Dim method = DirectCast(member, MethodSymbol)
If method.MayBeReducibleExtensionMethod Then
methods.Add(method)
End If
End If
Next
End If
End Sub
''' <summary>
''' This method is called for a type within a namespace when we are building a map of extension methods
''' for the whole (compilation merged or module level) namespace.
'''
''' The 'appendThrough' parameter allows RetargetingNamespaceSymbol to delegate majority of the work
''' to the underlying named type symbols, but still add RetargetingMethodSymbols to the map.
''' </summary>
Friend Overridable Sub BuildExtensionMethodsMap(
map As Dictionary(Of String, ArrayBuilder(Of MethodSymbol)),
appendThrough As NamespaceSymbol
)
If Me.MightContainExtensionMethods Then
Debug.Assert(False, "Possibly using inefficient implementation of AppendProbableExtensionMethods(map As Dictionary(Of String, ArrayBuilder(Of MethodSymbol)))")
appendThrough.BuildExtensionMethodsMap(map,
From name As String In Me.MemberNames
Select New KeyValuePair(Of String, ImmutableArray(Of Symbol))(name, Me.GetMembers(name)))
End If
End Sub
Friend Overridable Sub GetExtensionMethods(
methods As ArrayBuilder(Of MethodSymbol),
appendThrough As NamespaceSymbol,
Name As String
)
If Me.MightContainExtensionMethods Then
Dim candidates = Me.GetSimpleNonTypeMembers(Name)
For Each member In candidates
appendThrough.AddMemberIfExtension(methods, member)
Next
End If
End Sub
''' <summary>
''' This is an entry point for the Binder. Its purpose is to add names of viable extension methods declared
''' in this type to nameSet parameter.
''' </summary>
Friend Overridable Overloads Sub AddExtensionMethodLookupSymbolsInfo(nameSet As LookupSymbolsInfo,
options As LookupOptions,
originalBinder As Binder)
AddExtensionMethodLookupSymbolsInfo(nameSet, options, originalBinder, appendThrough:=Me)
End Sub
''' <summary>
''' Add names of viable extension methods declared in this type to nameSet parameter.
'''
''' The 'appendThrough' parameter allows RetargetingNamedTypeSymbol to delegate majority of the work
''' to the underlying named type symbol, but still perform viability check on RetargetingMethodSymbol.
''' </summary>
Friend Overridable Overloads Sub AddExtensionMethodLookupSymbolsInfo(nameSet As LookupSymbolsInfo,
options As LookupOptions,
originalBinder As Binder,
appendThrough As NamedTypeSymbol)
If Me.MightContainExtensionMethods Then
Debug.Assert(False, "Possibly using inefficient implementation of AppendExtensionMethodNames(nameSet As HashSet(Of String), options As LookupOptions, originalBinder As Binder, appendThrough As NamespaceOrTypeSymbol)")
appendThrough.AddExtensionMethodLookupSymbolsInfo(nameSet, options, originalBinder,
From name As String In Me.MemberNames
Select New KeyValuePair(Of String, ImmutableArray(Of Symbol))(name, Me.GetMembers(name)))
End If
End Sub
''' <summary>
''' Get the instance constructors for this type.
''' </summary>
Public ReadOnly Property InstanceConstructors As ImmutableArray(Of MethodSymbol)
Get
Return GetConstructors(Of MethodSymbol)(includeInstance:=True, includeShared:=False)
End Get
End Property
''' <summary>
''' Get the shared constructors for this type.
''' </summary>
Public ReadOnly Property SharedConstructors As ImmutableArray(Of MethodSymbol)
Get
Return GetConstructors(Of MethodSymbol)(includeInstance:=False, includeShared:=True)
End Get
End Property
''' <summary>
''' Get the instance and shared constructors for this type.
''' </summary>
Public ReadOnly Property Constructors As ImmutableArray(Of MethodSymbol)
Get
Return GetConstructors(Of MethodSymbol)(includeInstance:=True, includeShared:=True)
End Get
End Property
Private Function GetConstructors(Of TMethodSymbol As {IMethodSymbol, Class})(includeInstance As Boolean, includeShared As Boolean) As ImmutableArray(Of TMethodSymbol)
Debug.Assert(includeInstance OrElse includeShared)
Dim instanceCandidates As ImmutableArray(Of Symbol) = If(includeInstance, GetMembers(WellKnownMemberNames.InstanceConstructorName), ImmutableArray(Of Symbol).Empty)
Dim sharedCandidates As ImmutableArray(Of Symbol) = If(includeShared, GetMembers(WellKnownMemberNames.StaticConstructorName), ImmutableArray(Of Symbol).Empty)
If instanceCandidates.IsEmpty AndAlso sharedCandidates.IsEmpty Then
Return ImmutableArray(Of TMethodSymbol).Empty
End If
Dim constructors As ArrayBuilder(Of TMethodSymbol) = ArrayBuilder(Of TMethodSymbol).GetInstance()
For Each candidate In instanceCandidates
If candidate.Kind = SymbolKind.Method Then
Dim method As TMethodSymbol = TryCast(candidate, TMethodSymbol)
Debug.Assert(method IsNot Nothing)
Debug.Assert(method.MethodKind = MethodKind.Constructor)
constructors.Add(method)
End If
Next
For Each candidate In sharedCandidates
If candidate.Kind = SymbolKind.Method Then
Dim method As TMethodSymbol = TryCast(candidate, TMethodSymbol)
Debug.Assert(method IsNot Nothing)
Debug.Assert(method.MethodKind = MethodKind.StaticConstructor)
constructors.Add(method)
End If
Next
Return constructors.ToImmutableAndFree()
End Function
''' <summary>
''' Returns true if this type is known to be a reference type. It is never the case
''' that IsReferenceType and IsValueType both return true. However, for an unconstrained
''' type parameter, IsReferenceType and IsValueType will both return false.
''' </summary>
Public Overrides ReadOnly Property IsReferenceType As Boolean
Get
' TODO: Is this correct for VB Module?
Return TypeKind <> TypeKind.Enum AndAlso TypeKind <> TypeKind.Structure AndAlso
TypeKind <> TypeKind.Error
End Get
End Property
''' <summary>
''' Returns true if this type is known to be a value type. It is never the case
''' that IsReferenceType and IsValueType both return true. However, for an unconstrained
''' type parameter, IsReferenceType and IsValueType will both return false.
''' </summary>
Public Overrides ReadOnly Property IsValueType As Boolean
Get
' TODO: Is this correct for VB Module?
Return TypeKind = TypeKind.Enum OrElse TypeKind = TypeKind.Structure
End Get
End Property
''' <summary>
''' Returns True if this types has Arity >= 1 and Construct can be called. This is primarily useful
''' when deal with error cases.
''' </summary>
Friend MustOverride ReadOnly Property CanConstruct As Boolean
''' <summary>
''' Returns a constructed type given its type arguments.
''' </summary>
Public Function Construct(ParamArray typeArguments() As TypeSymbol) As NamedTypeSymbol
Return Construct(typeArguments.AsImmutableOrNull())
End Function
''' <summary>
''' Returns a constructed type given its type arguments.
''' </summary>
Public Function Construct(typeArguments As IEnumerable(Of TypeSymbol)) As NamedTypeSymbol
Return Construct(typeArguments.AsImmutableOrNull())
End Function
''' <summary>
''' Construct a new type from this type, substituting the given type arguments for the
''' type parameters. This method should only be called if this named type does not have
''' any substitutions applied for its own type arguments with exception of alpha-rename
''' substitution (although it's container might have substitutions applied).
''' </summary>
''' <param name="typeArguments">A set of type arguments to be applied. Must have the same length
''' as the number of type parameters that this type has.</param>
Public MustOverride Function Construct(typeArguments As ImmutableArray(Of TypeSymbol)) As NamedTypeSymbol
''' <summary> Checks for validity of Construct(...) on this type with these type arguments. </summary>
Protected Sub CheckCanConstructAndTypeArguments(typeArguments As ImmutableArray(Of TypeSymbol))
'This helper is used by Public APIs to perform validation. This exception is part of the public
'contract of Construct()
If Not CanConstruct OrElse Me IsNot ConstructedFrom Then
Throw New InvalidOperationException()
End If
' Check type arguments
typeArguments.CheckTypeArguments(Me.Arity)
End Sub
''' <summary>
''' Construct a new type from this type definition, substituting the given type arguments for the
''' type parameters. This method should only be called on the OriginalDefinition. Unlike previous
''' Construct method, this overload supports type parameter substitution on this type and any number
''' of its containing types. See comments for TypeSubstitution type for more information.
''' </summary>
Friend Function Construct(substitution As TypeSubstitution) As NamedTypeSymbol
Debug.Assert(Me.IsDefinition)
Debug.Assert(Me.IsOrInGenericType())
If substitution Is Nothing Then
Return Me
End If
Debug.Assert(substitution.IsValidToApplyTo(Me))
' Validate the map for use of alpha-renamed type parameters.
substitution.ThrowIfSubstitutingToAlphaRenamedTypeParameter()
Return DirectCast(InternalSubstituteTypeParameters(substitution).AsTypeSymbolOnly(), NamedTypeSymbol)
End Function
''' <summary>
''' Returns an unbound generic type of this generic named type.
''' </summary>
Public Function ConstructUnboundGenericType() As NamedTypeSymbol
Return Me.AsUnboundGenericType()
End Function
''' <summary>
''' Returns Default property name for the type.
''' If there is no default property name, then Nothing is returned.
''' </summary>
Friend MustOverride ReadOnly Property DefaultPropertyName As String
''' <summary>
''' If this is a generic type instantiation or a nested type of a generic type instantiation,
''' return TypeSubstitution for this construction. Nothing otherwise.
''' Returned TypeSubstitution should target OriginalDefinition of the symbol.
''' </summary>
Friend MustOverride ReadOnly Property TypeSubstitution As TypeSubstitution
' These properties of TypeRef, NamespaceOrType, or Symbol must be overridden.
''' <summary>
''' Gets the name of this symbol.
''' </summary>
Public MustOverride Overrides ReadOnly Property Name As String
''' <summary>
''' Collection of names of members declared within this type.
''' </summary>
Public MustOverride ReadOnly Property MemberNames As IEnumerable(Of String)
''' <summary>
''' Returns true if the type is a Script class.
''' It might be an interactive submission class or a Script class in a csx file.
''' </summary>
Public Overridable ReadOnly Property IsScriptClass As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Returns true if the type is a submission class.
''' </summary>
Public ReadOnly Property IsSubmissionClass As Boolean
Get
Return TypeKind = TypeKind.Submission
End Get
End Property
Friend Function GetScriptConstructor() As SynthesizedConstructorBase
Debug.Assert(IsScriptClass)
Return DirectCast(InstanceConstructors.Single(), SynthesizedConstructorBase)
End Function
Friend Function GetScriptInitializer() As SynthesizedInteractiveInitializerMethod
Debug.Assert(IsScriptClass)
Return DirectCast(GetMembers(SynthesizedInteractiveInitializerMethod.InitializerName).Single(), SynthesizedInteractiveInitializerMethod)
End Function
Friend Function GetScriptEntryPoint() As SynthesizedEntryPointSymbol
Debug.Assert(IsScriptClass)
Dim name = If(TypeKind = TypeKind.Submission, SynthesizedEntryPointSymbol.FactoryName, SynthesizedEntryPointSymbol.MainName)
Return DirectCast(GetMembers(name).Single(), SynthesizedEntryPointSymbol)
End Function
''' <summary>
''' Returns true if the type is the implicit class that holds onto invalid global members (like methods or
''' statements in a non script file).
''' </summary>
Public Overridable ReadOnly Property IsImplicitClass As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Get all the members of this symbol.
''' </summary>
''' <returns>An ImmutableArray containing all the members of this symbol. If this symbol has no members,
''' returns an empty ImmutableArray. Never returns Nothing.</returns>
Public MustOverride Overrides Function GetMembers() As ImmutableArray(Of Symbol)
''' <summary>
''' Get all the members of this symbol that have a particular name.
''' </summary>
''' <returns>An ImmutableArray containing all the members of this symbol with the given name. If there are
''' no members with this name, returns an empty ImmutableArray. Never returns Nothing.</returns>
Public MustOverride Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol)
''' <summary>
''' Get all the members of this symbol that are types.
''' </summary>
''' <returns>An ImmutableArray containing all the types that are members of this symbol. If this symbol has no type members,
''' returns an empty ImmutableArray. Never returns Nothing.</returns>
Public MustOverride Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol)
''' <summary>
''' Get all the members of this symbol that are types that have a particular name, and any arity.
''' </summary>
''' <returns>An ImmutableArray containing all the types that are members of this symbol with the given name.
''' If this symbol has no type members with this name,
''' returns an empty ImmutableArray. Never returns Nothing.</returns>
Public MustOverride Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol)
''' <summary>
''' Get all the members of this symbol that are types that have a particular name and arity.
''' </summary>
''' <returns>An ImmutableArray containing all the types that are members of this symbol with the given name and arity.
''' If this symbol has no type members with this name and arity,
''' returns an empty ImmutableArray. Never returns Nothing.</returns>
Public MustOverride Overrides Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol)
''' <summary>
''' Get this accessibility that was declared on this symbol. For symbols that do
''' not have accessibility declared on them, returns NotApplicable.
''' </summary>
Public MustOverride Overrides ReadOnly Property DeclaredAccessibility As Accessibility
''' <summary>
''' Supports visitor pattern.
''' </summary>
Friend Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult
Return visitor.VisitNamedType(Me, arg)
End Function
' Only the compiler can created NamedTypeSymbols.
Friend Sub New()
End Sub
''' <summary>
''' Gets the kind of this symbol.
''' </summary>
Public Overrides ReadOnly Property Kind As SymbolKind ' Cannot seal this method because of the ErrorSymbol.
Get
Return SymbolKind.NamedType
End Get
End Property
''' <summary>
''' Returns a flag indicating whether this symbol is ComImport.
''' </summary>
''' <remarks>
''' A type can me marked as a ComImport type in source by applying the <see cref="System.Runtime.InteropServices.ComImportAttribute"/>
''' </remarks>
Friend MustOverride ReadOnly Property IsComImport As Boolean
''' <summary>
''' If CoClassAttribute was applied to the type returns the type symbol for the argument.
''' Type symbol may be an error type if the type was not found. Otherwise returns Nothing
''' </summary>
Friend MustOverride ReadOnly Property CoClassType As TypeSymbol
''' <summary>
''' Returns a sequence of preprocessor symbols specified in <see cref="ConditionalAttribute"/> applied on this symbol, or null if there are none.
''' </summary>
Friend MustOverride Function GetAppliedConditionalSymbols() As ImmutableArray(Of String)
''' <summary>
''' Returns a flag indicating whether this symbol has at least one applied conditional attribute.
''' </summary>
''' <remarks>
''' Forces binding and decoding of attributes.
''' NOTE: Conditional symbols on base type must be inherited by derived type, but the native VB compiler doesn't do so. We maintain compatibility.
''' </remarks>
Friend ReadOnly Property IsConditional As Boolean
Get
Return Me.GetAppliedConditionalSymbols().Any()
End Get
End Property
Friend Overridable ReadOnly Property AreMembersImplicitlyDeclared As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Gets the associated <see cref="AttributeUsageInfo"/> for an attribute type.
''' </summary>
Friend MustOverride Function GetAttributeUsageInfo() As AttributeUsageInfo
''' <summary>
''' Declaration security information associated with this type, or null if there is none.
''' </summary>
Friend MustOverride Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute)
''' <summary>
''' True if the type has declarative security information (HasSecurity flags).
''' </summary>
Friend MustOverride ReadOnly Property HasDeclarativeSecurity As Boolean
'This represents the declared base type and base interfaces, once bound.
Private _lazyDeclaredBase As NamedTypeSymbol = ErrorTypeSymbol.UnknownResultType
Private _lazyDeclaredInterfaces As ImmutableArray(Of NamedTypeSymbol) = Nothing
''' <summary>
''' NamedTypeSymbol calls derived implementations of this method when declared base type
''' is needed for the first time.
'''
''' basesBeingResolved are passed if there are any types already have their bases resolved
''' so that the derived implementation could avoid infinite recursion
''' </summary>
Friend MustOverride Function MakeDeclaredBase(basesBeingResolved As ConsList(Of Symbol), diagnostics As DiagnosticBag) As NamedTypeSymbol
''' <summary>
''' NamedTypeSymbol calls derived implementations of this method when declared interfaces
''' are needed for the first time.
'''
''' basesBeingResolved are passed if there are any types already have their bases resolved
''' so that the derived implementation could avoid infinite recursion
''' </summary>
Friend MustOverride Function MakeDeclaredInterfaces(basesBeingResolved As ConsList(Of Symbol), diagnostics As DiagnosticBag) As ImmutableArray(Of NamedTypeSymbol)
''' <summary>
''' Base type as "declared".
''' Declared base type may contain circularities.
'''
''' If DeclaredBase must be accessed while other DeclaredBases are being resolved,
''' the bases that are being resolved must be specified here to prevent potential infinite recursion.
''' </summary>
Friend Overridable Function GetDeclaredBase(basesBeingResolved As ConsList(Of Symbol)) As NamedTypeSymbol
If _lazyDeclaredBase Is ErrorTypeSymbol.UnknownResultType Then
Dim diagnostics = DiagnosticBag.GetInstance()
AtomicStoreReferenceAndDiagnostics(_lazyDeclaredBase, MakeDeclaredBase(basesBeingResolved, diagnostics), diagnostics, ErrorTypeSymbol.UnknownResultType)
diagnostics.Free()
End If
Return _lazyDeclaredBase
End Function
Friend Overridable Function GetSimpleNonTypeMembers(name As String) As ImmutableArray(Of Symbol)
Return GetMembers(name)
End Function
Private Sub AtomicStoreReferenceAndDiagnostics(Of T As Class)(ByRef variable As T,
value As T,
diagBag As DiagnosticBag,
Optional comparand As T = Nothing)
Debug.Assert(value IsNot comparand)
If diagBag Is Nothing OrElse diagBag.IsEmptyWithoutResolution Then
Interlocked.CompareExchange(variable, value, comparand)
Else
Dim sourceModule = TryCast(Me.ContainingModule, SourceModuleSymbol)
If sourceModule IsNot Nothing Then
sourceModule.AtomicStoreReferenceAndDiagnostics(variable, value, diagBag, CompilationStage.Declare, comparand)
End If
End If
End Sub
Friend Sub AtomicStoreArrayAndDiagnostics(Of T)(ByRef variable As ImmutableArray(Of T),
value As ImmutableArray(Of T),
diagBag As DiagnosticBag)
Debug.Assert(Not value.IsDefault)
If diagBag Is Nothing OrElse diagBag.IsEmptyWithoutResolution Then
ImmutableInterlocked.InterlockedCompareExchange(variable, value, Nothing)
Else
Dim sourceModule = TryCast(Me.ContainingModule, SourceModuleSymbol)
If sourceModule IsNot Nothing Then
sourceModule.AtomicStoreArrayAndDiagnostics(variable, value, diagBag, CompilationStage.Declare)
End If
End If
End Sub
''' <summary>
''' Interfaces as "declared".
''' Declared interfaces may contain circularities.
'''
''' If DeclaredInterfaces must be accessed while other DeclaredInterfaces are being resolved,
''' the bases that are being resolved must be specified here to prevent potential infinite recursion.
''' </summary>
Friend Overridable Function GetDeclaredInterfacesNoUseSiteDiagnostics(basesBeingResolved As ConsList(Of Symbol)) As ImmutableArray(Of NamedTypeSymbol)
If _lazyDeclaredInterfaces.IsDefault Then
Dim diagnostics = DiagnosticBag.GetInstance()
AtomicStoreArrayAndDiagnostics(_lazyDeclaredInterfaces, MakeDeclaredInterfaces(basesBeingResolved, diagnostics), diagnostics)
diagnostics.Free()
End If
Return _lazyDeclaredInterfaces
End Function
Friend Function GetDeclaredInterfacesWithDefinitionUseSiteDiagnostics(basesBeingResolved As ConsList(Of Symbol), <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ImmutableArray(Of NamedTypeSymbol)
Dim result = GetDeclaredInterfacesNoUseSiteDiagnostics(basesBeingResolved)
For Each iface In result
iface.OriginalDefinition.AddUseSiteDiagnostics(useSiteDiagnostics)
Next
Return result
End Function
Friend Function GetDirectBaseInterfacesNoUseSiteDiagnostics(basesBeingResolved As ConsList(Of Symbol)) As ImmutableArray(Of NamedTypeSymbol)
If Me.TypeKind = TypeKind.Interface Then
If basesBeingResolved Is Nothing Then
Return Me.InterfacesNoUseSiteDiagnostics
Else
Return GetDeclaredBaseInterfacesSafe(basesBeingResolved)
End If
Else
Return ImmutableArray(Of NamedTypeSymbol).Empty
End If
End Function
Friend Overridable Function GetDeclaredBaseInterfacesSafe(basesBeingResolved As ConsList(Of Symbol)) As ImmutableArray(Of NamedTypeSymbol)
Debug.Assert(basesBeingResolved.Any)
If basesBeingResolved.Contains(Me) Then
Return Nothing
End If
Return GetDeclaredInterfacesNoUseSiteDiagnostics(If(basesBeingResolved, ConsList(Of Symbol).Empty).Prepend(Me))
End Function
''' <summary>
''' NamedTypeSymbol calls derived implementations of this method when acyclic base type
''' is needed for the first time.
''' This method typically calls GetDeclaredBase, filters for
''' illegal cycles and other conditions before returning result as acyclic.
''' </summary>
Friend MustOverride Function MakeAcyclicBaseType(diagnostics As DiagnosticBag) As NamedTypeSymbol
''' <summary>
''' NamedTypeSymbol calls derived implementations of this method when acyclic base interfaces
''' are needed for the first time.
''' This method typically calls GetDeclaredInterfaces, filters for
''' illegal cycles and other conditions before returning result as acyclic.
''' </summary>
Friend MustOverride Function MakeAcyclicInterfaces(diagnostics As DiagnosticBag) As ImmutableArray(Of NamedTypeSymbol)
Private _lazyBaseType As NamedTypeSymbol = ErrorTypeSymbol.UnknownResultType
Private _lazyInterfaces As ImmutableArray(Of NamedTypeSymbol)
''' <summary>
''' Base type.
''' Could be Nothing for Interfaces or Object.
''' </summary>
Friend NotOverridable Overrides ReadOnly Property BaseTypeNoUseSiteDiagnostics As NamedTypeSymbol
Get
If Me._lazyBaseType Is ErrorTypeSymbol.UnknownResultType Then
' force resolution of bases in containing type
' to make base resolution errors more deterministic
If ContainingType IsNot Nothing Then
Dim tmp = ContainingType.BaseTypeNoUseSiteDiagnostics
End If
Dim diagnostics = DiagnosticBag.GetInstance
Dim acyclicBase = Me.MakeAcyclicBaseType(diagnostics)
AtomicStoreReferenceAndDiagnostics(Me._lazyBaseType, acyclicBase, diagnostics, ErrorTypeSymbol.UnknownResultType)
diagnostics.Free()
End If
Return Me._lazyBaseType
End Get
End Property
''' <summary>
''' Interfaces that are implemented or inherited (if current type is interface itself).
''' </summary>
Friend NotOverridable Overrides ReadOnly Property InterfacesNoUseSiteDiagnostics As ImmutableArray(Of NamedTypeSymbol)
Get
If Me._lazyInterfaces.IsDefault Then
Dim diagnostics As DiagnosticBag = DiagnosticBag.GetInstance
Dim acyclicInterfaces As ImmutableArray(Of NamedTypeSymbol) = Me.MakeAcyclicInterfaces(diagnostics)
AtomicStoreArrayAndDiagnostics(Me._lazyInterfaces, acyclicInterfaces, diagnostics)
diagnostics.Free()
End If
Return Me._lazyInterfaces
End Get
End Property
''' <summary>
''' Returns declared base type or actual base type if already known
''' This is only used by cycle detection code so that it can observe when cycles are broken
''' while not forcing actual Base to be realized.
''' </summary>
Friend Function GetBestKnownBaseType() As NamedTypeSymbol
'NOTE: we can be at race with another thread here.
' the worst thing that can happen though, is that error on same cycle may be reported twice
' if two threads analyze the same cycle at the same time but start from different ends.
'
' For now we decided that this is something we can live with.
Dim base = Me._lazyBaseType
If base IsNot ErrorTypeSymbol.UnknownResultType Then
Return base
End If
Return GetDeclaredBase(Nothing)
End Function
''' <summary>
''' Returns declared interfaces or actual Interfaces if already known
''' This is only used by cycle detection code so that it can observe when cycles are broken
''' while not forcing actual Interfaces to be realized.
''' </summary>
Friend Function GetBestKnownInterfacesNoUseSiteDiagnostics() As ImmutableArray(Of NamedTypeSymbol)
Dim interfaces = Me._lazyInterfaces
If Not interfaces.IsDefault Then
Return interfaces
End If
Return GetDeclaredInterfacesNoUseSiteDiagnostics(Nothing)
End Function
''' <summary>
''' True iff this type or some containing type has type parameters.
''' </summary>
Public ReadOnly Property IsGenericType As Boolean Implements INamedTypeSymbol.IsGenericType
Get
Dim p As NamedTypeSymbol = Me
Do While p IsNot Nothing
If (p.Arity <> 0) Then
Return True
End If
p = p.ContainingType
Loop
Return False
End Get
End Property
''' <summary>
''' Get the original definition of this symbol. If this symbol is derived from another
''' symbol by (say) type substitution, this gets the original symbol, as it was defined
''' in source or metadata.
''' </summary>
Public Overridable Shadows ReadOnly Property OriginalDefinition As NamedTypeSymbol
Get
' Default implements returns Me.
Return Me
End Get
End Property
Protected NotOverridable Overrides ReadOnly Property OriginalTypeSymbolDefinition As TypeSymbol
Get
Return Me.OriginalDefinition
End Get
End Property
''' <summary>
''' Should return full emitted namespace name for a top level type if the name
''' might be different in case from containing namespace symbol full name, Nothing otherwise.
''' </summary>
Friend Overridable Function GetEmittedNamespaceName() As String
Return Nothing
End Function
''' <summary>
''' Does this type implement all the members of the given interface. Does not include members
''' of interfaces that iface inherits, only direct members.
''' </summary>
Friend Function ImplementsAllMembersOfInterface(iface As NamedTypeSymbol) As Boolean
Dim implementationMap = ExplicitInterfaceImplementationMap
For Each ifaceMember In iface.GetMembersUnordered()
If ifaceMember.RequiresImplementation() AndAlso Not implementationMap.ContainsKey(ifaceMember) Then
Return False
End If
Next
Return True
End Function
Friend Overrides Function GetUseSiteErrorInfo() As DiagnosticInfo
If Me.IsDefinition Then
Return MyBase.GetUseSiteErrorInfo()
End If
' Doing check for constructed types here in order to share implementation across
' constructed non-error and error type symbols.
' Check definition.
Dim definitionErrorInfo As DiagnosticInfo = DeriveUseSiteErrorInfoFromType(Me.OriginalDefinition)
If definitionErrorInfo IsNot Nothing AndAlso definitionErrorInfo.Code = ERRID.ERR_UnsupportedType1 Then
Return definitionErrorInfo
End If
' Check type arguments.
Dim argsErrorInfo As DiagnosticInfo = DeriveUseSiteErrorInfoFromTypeArguments()
Return MergeUseSiteErrorInfo(definitionErrorInfo, argsErrorInfo)
End Function
Private Function DeriveUseSiteErrorInfoFromTypeArguments() As DiagnosticInfo
Dim argsErrorInfo As DiagnosticInfo = Nothing
For Each arg As TypeSymbol In Me.TypeArgumentsNoUseSiteDiagnostics
Dim errorInfo As DiagnosticInfo = DeriveUseSiteErrorInfoFromType(arg)
If errorInfo IsNot Nothing Then
If errorInfo.Code = ERRID.ERR_UnsupportedType1 Then
Return errorInfo
End If
If argsErrorInfo Is Nothing Then
argsErrorInfo = errorInfo
End If
End If
Next
If Me.HasTypeArgumentsCustomModifiers Then
Dim modifiersErrorInfo As DiagnosticInfo = Nothing
For Each modifiers In Me.TypeArgumentsCustomModifiers
modifiersErrorInfo = MergeUseSiteErrorInfo(modifiersErrorInfo, DeriveUseSiteErrorInfoFromCustomModifiers(modifiers))
Next
Return MergeUseSiteErrorInfo(argsErrorInfo, modifiersErrorInfo)
End If
Return argsErrorInfo
End Function
''' <summary>
''' True if this is a reference to an <em>unbound</em> generic type. These occur only
''' within a <code>GetType</code> expression. A generic type is considered <em>unbound</em>
''' if all of the type argument lists in its fully qualified name are empty.
''' Note that the type arguments of an unbound generic type will be returned as error
''' types because they do not really have type arguments. An unbound generic type
''' yields null for its BaseType and an empty result for its Interfaces.
''' </summary>
Public Overridable ReadOnly Property IsUnboundGenericType As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Force all declaration errors to be generated.
''' </summary>
Friend MustOverride Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken)
''' <summary>
''' Return compiler generated nested types that are created at Declare phase, but not exposed through GetMembers and the like APIs.
''' Should return Nothing if there are no such types.
''' </summary>
Friend Overridable Function GetSynthesizedNestedTypes() As IEnumerable(Of Microsoft.Cci.INestedTypeDefinition)
Return Nothing
End Function
''' <summary>
''' True if the type is a Windows runtime type.
''' </summary>
''' <remarks>
''' A type can me marked as a Windows runtime type in source by applying the WindowsRuntimeImportAttribute.
''' WindowsRuntimeImportAttribute is a pseudo custom attribute defined as an internal class in System.Runtime.InteropServices.WindowsRuntime namespace.
''' This is needed to mark Windows runtime types which are redefined in mscorlib.dll and System.Runtime.WindowsRuntime.dll.
''' These two assemblies are special as they implement the CLR's support for WinRT.
''' </remarks>
Friend MustOverride ReadOnly Property IsWindowsRuntimeImport As Boolean
''' <summary>
''' True if the type should have its WinRT interfaces projected onto .NET types and
''' have missing .NET interface members added to the type.
''' </summary>
Friend MustOverride ReadOnly Property ShouldAddWinRTMembers As Boolean
''' <summary>
''' Requires less computation than <see cref="TypeSymbol.TypeKind"/>== <see cref="TypeKind.Interface"/>.
''' </summary>
''' <remarks>
''' Metadata types need to compute their base types in order to know their TypeKinds, And that can lead
''' to cycles if base types are already being computed.
''' </remarks>
''' <returns>True if this Is an interface type.</returns>
Friend MustOverride ReadOnly Property IsInterface As Boolean
#Region "INamedTypeSymbol"
Private ReadOnly Property INamedTypeSymbol_Arity As Integer Implements INamedTypeSymbol.Arity
Get
Return Me.Arity
End Get
End Property
Private ReadOnly Property INamedTypeSymbol_ConstructedFrom As INamedTypeSymbol Implements INamedTypeSymbol.ConstructedFrom
Get
Return Me.ConstructedFrom
End Get
End Property
Private ReadOnly Property INamedTypeSymbol_DelegateInvokeMethod As IMethodSymbol Implements INamedTypeSymbol.DelegateInvokeMethod
Get
Return Me.DelegateInvokeMethod
End Get
End Property
Private ReadOnly Property INamedTypeSymbol_EnumUnderlyingType As INamedTypeSymbol Implements INamedTypeSymbol.EnumUnderlyingType
Get
Return Me.EnumUnderlyingType
End Get
End Property
Private ReadOnly Property INamedTypeSymbol_MemberNames As IEnumerable(Of String) Implements INamedTypeSymbol.MemberNames
Get
Return Me.MemberNames
End Get
End Property
Private ReadOnly Property INamedTypeSymbol_IsUnboundGenericType As Boolean Implements INamedTypeSymbol.IsUnboundGenericType
Get
Return Me.IsUnboundGenericType
End Get
End Property
Private ReadOnly Property INamedTypeSymbol_OriginalDefinition As INamedTypeSymbol Implements INamedTypeSymbol.OriginalDefinition
Get
Return Me.OriginalDefinition
End Get
End Property
Private ReadOnly Property INamedTypeSymbol_TypeArguments As ImmutableArray(Of ITypeSymbol) Implements INamedTypeSymbol.TypeArguments
Get
Return StaticCast(Of ITypeSymbol).From(Me.TypeArgumentsNoUseSiteDiagnostics)
End Get
End Property
Private ReadOnly Property INamedTypeSymbol_TypeParameters As ImmutableArray(Of ITypeParameterSymbol) Implements INamedTypeSymbol.TypeParameters
Get
Return StaticCast(Of ITypeParameterSymbol).From(Me.TypeParameters)
End Get
End Property
Private ReadOnly Property INamedTypeSymbol_IsScriptClass As Boolean Implements INamedTypeSymbol.IsScriptClass
Get
Return Me.IsScriptClass
End Get
End Property
Private ReadOnly Property INamedTypeSymbol_IsImplicitClass As Boolean Implements INamedTypeSymbol.IsImplicitClass
Get
' TODO (tomat):
Return False
End Get
End Property
Private Function INamedTypeSymbol_Construct(ParamArray arguments() As ITypeSymbol) As INamedTypeSymbol Implements INamedTypeSymbol.Construct
For Each arg In arguments
arg.EnsureVbSymbolOrNothing(Of TypeSymbol)("typeArguments")
Next
Return Construct(arguments.Cast(Of TypeSymbol).ToArray())
End Function
Private Function INamedTypeSymbol_ConstructUnboundGenericType() As INamedTypeSymbol Implements INamedTypeSymbol.ConstructUnboundGenericType
Return ConstructUnboundGenericType()
End Function
Private ReadOnly Property INamedTypeSymbol_InstanceConstructors As ImmutableArray(Of IMethodSymbol) Implements INamedTypeSymbol.InstanceConstructors
Get
Return GetConstructors(Of IMethodSymbol)(includeInstance:=True, includeShared:=False)
End Get
End Property
Private ReadOnly Property INamedTypeSymbol_StaticConstructors As ImmutableArray(Of IMethodSymbol) Implements INamedTypeSymbol.StaticConstructors
Get
Return GetConstructors(Of IMethodSymbol)(includeInstance:=False, includeShared:=True)
End Get
End Property
Private ReadOnly Property INamedTypeSymbol_Constructors As ImmutableArray(Of IMethodSymbol) Implements INamedTypeSymbol.Constructors
Get
Return GetConstructors(Of IMethodSymbol)(includeInstance:=True, includeShared:=True)
End Get
End Property
Private ReadOnly Property INamedTypeSymbol_AssociatedSymbol As ISymbol Implements INamedTypeSymbol.AssociatedSymbol
Get
Return Me.AssociatedSymbol
End Get
End Property
#End Region
#Region "ISymbol"
Protected Overrides ReadOnly Property ISymbol_IsAbstract As Boolean
Get
Return Me.IsMustInherit
End Get
End Property
Protected Overrides ReadOnly Property ISymbol_IsSealed As Boolean
Get
Return Me.IsNotInheritable
End Get
End Property
Public Overrides Sub Accept(visitor As SymbolVisitor)
visitor.VisitNamedType(Me)
End Sub
Public Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult
Return visitor.VisitNamedType(Me)
End Function
Public Overrides Sub Accept(visitor As VisualBasicSymbolVisitor)
visitor.VisitNamedType(Me)
End Sub
Public Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult
Return visitor.VisitNamedType(Me)
End Function
#End Region
End Class
End Namespace
|
zmaruo/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/NamedTypeSymbol.vb
|
Visual Basic
|
apache-2.0
| 58,209
|
Imports System.IO
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports MapInfo.MiPro.Interop
Public NotInheritable Class AboutBox1
Private Sub AboutBox1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Set the title of the form.
Dim ApplicationTitle As String
If My.Application.Info.Title <> "" Then
ApplicationTitle = My.Application.Info.Title
Else
ApplicationTitle = System.IO.Path.GetFileNameWithoutExtension(My.Application.Info.AssemblyName)
End If
Me.Text = String.Format("About {0}", ApplicationTitle)
' Initialize all of the text displayed on the About Box.
' TODO: Customize the application's assembly information in the "Application" pane of the project
' properties dialog (under the "Project" menu).
Me.LabelProductName.Text = My.Application.Info.ProductName
Me.LabelVersion.Text = String.Format("Version {0}", My.Application.Info.Version.ToString)
Me.LabelCopyright.Text = My.Application.Info.Copyright
Me.LabelCompanyName.Text = My.Application.Info.CompanyName
Me.TextBoxDescription.Text = My.Application.Info.Description
End Sub
Private Sub OKButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OKButton.Click
Me.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
getHelp()
End Sub
Sub getHelp()
'check help file exists
'save help to MI directory to prevent Microsoft Security Updates 896358 & 840315 from blocking it
'http://stackoverflow.com/questions/11438634/opening-a-chm-file-produces-navigation-to-the-webpage-was-canceled
Dim cur_dir As String = InteropServices.MapInfoApplication.Eval("GetFolderPath$(-4 )")
If File.Exists(cur_dir & "ProfileToolHelp.chm") Then
Else
My.Computer.FileSystem.WriteAllBytes(cur_dir & "ProfileToolHelp.chm", My.Resources.ProfileToolHelp, False)
End If
' MsgBox(cur_dir & "ProfileToolHelp.chm")
'run help file
'System.Windows.Forms.Help.ShowHelp(Me, cur_dir & "ProfileToolHelp.chm", HelpNavigator.TableOfContents)
System.Diagnostics.Process.Start(cur_dir & "ProfileToolHelp.chm")
End Sub
End Class
|
JohnWilcock/MapInfoProfileTool
|
MapInfoProfileTool/AboutBox1.vb
|
Visual Basic
|
mit
| 2,383
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class HostsAbout
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.txAbout = New System.Windows.Forms.TextBox()
Me.SuspendLayout()
'
'txAbout
'
Me.txAbout.AcceptsTab = True
Me.txAbout.Dock = System.Windows.Forms.DockStyle.Fill
Me.txAbout.Location = New System.Drawing.Point(1, 1)
Me.txAbout.Multiline = True
Me.txAbout.Name = "txAbout"
Me.txAbout.ReadOnly = True
Me.txAbout.ScrollBars = System.Windows.Forms.ScrollBars.Horizontal
Me.txAbout.Size = New System.Drawing.Size(482, 359)
Me.txAbout.TabIndex = 1
Me.txAbout.TabStop = False
Me.txAbout.WordWrap = False
'
'HostsAbout
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.BackColor = System.Drawing.Color.White
Me.ClientSize = New System.Drawing.Size(484, 361)
Me.Controls.Add(Me.txAbout)
Me.DoubleBuffered = True
Me.Font = New System.Drawing.Font("Segoe UI", 8.25!)
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow
Me.Name = "HostsAbout"
Me.Padding = New System.Windows.Forms.Padding(1)
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "HostsX About"
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents txAbout As System.Windows.Forms.TextBox
End Class
|
Laicure/HostsX
|
HostsX/Forms/HostsAbout.Designer.vb
|
Visual Basic
|
mit
| 2,361
|
'------------------------------------------------------------------------------
' <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
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.PollApp.My.MySettings
Get
Return Global.PollApp.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
ellore/PollApp
|
PollApp/PollApp/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,920
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rAVencimiento_dVendedor"
'-------------------------------------------------------------------------------------------'
Partial Class rAVencimiento_dVendedor
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 = cusAplicacion.goReportes.paParametrosIniciales(9)
Dim lcParametro10Hasta As String = cusAplicacion.goReportes.paParametrosFinales(10)
Dim lcParametro11Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(11))
Dim lcParametro11Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(11))
Dim lcParametro12Desde As String = cusAplicacion.goReportes.paParametrosFinales(12)
Dim lcParametro13Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(13))
Dim Fecha As String
If lcParametro10Hasta = "Vencimiento" Then
Fecha = "Fec_Fin"
Else
Fecha = "Fec_Ini"
End If
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim loComandoSeleccionar As New StringBuilder()
loComandoSeleccionar.AppendLine(" SELECT ")
loComandoSeleccionar.AppendLine(" ROW_NUMBER() OVER(PARTITION BY Vendedores.Cod_Ven ORDER BY Vendedores.Cod_Ven, Cuentas_Cobrar.Documento, Cuentas_Cobrar.Fec_Ini, Cuentas_Cobrar.Fec_Fin) AS Fila, ")
loComandoSeleccionar.AppendLine(" Vendedores.Cod_Ven, ")
loComandoSeleccionar.AppendLine(" Vendedores.Nom_Ven, ")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN Cuentas_Cobrar.Mon_Sal > 0 THEN 1 ")
loComandoSeleccionar.AppendLine(" ELSE 0 ")
loComandoSeleccionar.AppendLine(" END AS Cant_Doc, ")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN DATEDIFF(d,Cuentas_Cobrar." & Fecha & " , " & lcParametro0Hasta & ") < 1 THEN ")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN Tip_Doc = 'Credito' THEN Cuentas_Cobrar.Mon_Sal*(-1) ")
loComandoSeleccionar.AppendLine(" ELSE Cuentas_Cobrar.Mon_Sal ")
loComandoSeleccionar.AppendLine(" End ")
loComandoSeleccionar.AppendLine(" ELSE 0 ")
loComandoSeleccionar.AppendLine(" END AS Por_Vencer, ")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN (DATEDIFF(d, Cuentas_Cobrar." & Fecha & ", " & lcParametro0Hasta & ") >= 1) AND (DATEDIFF(d, Cuentas_Cobrar." & Fecha & ", " & lcParametro0Hasta & ") <= 30) THEN ")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN Tip_Doc = 'Credito' THEN Cuentas_Cobrar.Mon_Sal*(-1) ")
loComandoSeleccionar.AppendLine(" ELSE Cuentas_Cobrar.Mon_Sal ")
loComandoSeleccionar.AppendLine(" End ")
loComandoSeleccionar.AppendLine(" ELSE 0 ")
loComandoSeleccionar.AppendLine(" END AS a, ")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN (DATEDIFF(d, Cuentas_Cobrar." & Fecha & ", " & lcParametro0Hasta & ") >= 31) AND (DATEDIFF(d, Cuentas_Cobrar." & Fecha & ", " & lcParametro0Hasta & ") <= 60) THEN ")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN Tip_Doc = 'Credito' THEN Cuentas_Cobrar.Mon_Sal*(-1) ")
loComandoSeleccionar.AppendLine(" ELSE Cuentas_Cobrar.Mon_Sal ")
loComandoSeleccionar.AppendLine(" End ")
loComandoSeleccionar.AppendLine(" ELSE 0 ")
loComandoSeleccionar.AppendLine(" END AS b, ")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN (DATEDIFF(d, Cuentas_Cobrar." & Fecha & ", " & lcParametro0Hasta & ") >= 61) AND (DATEDIFF(d, Cuentas_Cobrar." & Fecha & ", " & lcParametro0Hasta & ") <= 90) THEN ")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN Tip_Doc = 'Credito' THEN Cuentas_Cobrar.Mon_Sal*(-1) ")
loComandoSeleccionar.AppendLine(" ELSE Cuentas_Cobrar.Mon_Sal ")
loComandoSeleccionar.AppendLine(" End ")
loComandoSeleccionar.AppendLine(" ELSE 0 ")
loComandoSeleccionar.AppendLine(" END AS c, ")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN DATEDIFF(d, Cuentas_Cobrar." & Fecha & ", " & lcParametro0Hasta & ") >= 91 THEN ")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN Tip_Doc = 'Credito' THEN Cuentas_Cobrar.Mon_Sal*(-1) ")
loComandoSeleccionar.AppendLine(" ELSE Cuentas_Cobrar.Mon_Sal ")
loComandoSeleccionar.AppendLine(" End ")
loComandoSeleccionar.AppendLine(" ELSE 0 ")
loComandoSeleccionar.AppendLine(" END AS D, ")
loComandoSeleccionar.AppendLine(" Cuentas_Cobrar.Cod_Tip, ")
loComandoSeleccionar.AppendLine(" Cuentas_Cobrar.Documento, ")
loComandoSeleccionar.AppendLine(" Cuentas_Cobrar.control, ")
loComandoSeleccionar.AppendLine(" Cuentas_Cobrar.Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Cuentas_Cobrar.Fec_Fin, ")
loComandoSeleccionar.AppendLine(" DATEDIFF(d, Cuentas_Cobrar." & Fecha & ", " & lcParametro0Hasta & ") AS Dias, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN Tip_Doc = 'Credito' THEN cuentas_cobrar.Mon_Net *(-1) Else cuentas_cobrar.Mon_Net End) As Mon_Net, ")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN (DATALENGTH(cuentas_cobrar.comentario) > 1) AND (DATALENGTH(cuentas_cobrar.Notas) > 1) THEN '- '+CAST(cuentas_cobrar.comentario AS VARCHAR(1000))+CHAR(13)+'- '+CAST(cuentas_cobrar.Notas AS VARCHAR(1000)) ")
loComandoSeleccionar.AppendLine(" WHEN (DATALENGTH(cuentas_cobrar.comentario) > 1) AND (DATALENGTH(cuentas_cobrar.Notas) <= 1) THEN '- '+CAST(cuentas_cobrar.comentario AS VARCHAR(1000)) ")
loComandoSeleccionar.AppendLine(" WHEN (DATALENGTH(cuentas_cobrar.comentario) <= 1) AND (DATALENGTH(cuentas_cobrar.Notas) > 1) THEN '- '+CAST(cuentas_cobrar.Notas AS VARCHAR(1000)) ")
loComandoSeleccionar.AppendLine(" ELSE '' ")
loComandoSeleccionar.AppendLine(" END AS Comentario ")
loComandoSeleccionar.AppendLine(" FROM Cuentas_Cobrar ")
loComandoSeleccionar.AppendLine(" JOIN Vendedores ON Vendedores.Cod_Ven = Cuentas_Cobrar.Cod_Ven ")
loComandoSeleccionar.AppendLine(" WHERE cuentas_cobrar.Mon_Sal <> 0 ")
loComandoSeleccionar.AppendLine(" AND cuentas_cobrar.Status <> 'Anulado' ")
loComandoSeleccionar.AppendLine(" AND cuentas_cobrar.Fec_Ini between " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND cuentas_cobrar.Cod_Ven between " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND cuentas_cobrar.Cod_Ven between " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Vendedores.Cod_Zon between " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND cuentas_cobrar.Cod_Mon between " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Vendedores.Cod_Tip between " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Vendedores.Clase between " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND ((" & lcParametro7Desde & " = 'Si' AND (DATEDIFF(d, Cuentas_Cobrar.Fec_Fin, " & lcParametro0Hasta & ") >= 1))")
loComandoSeleccionar.AppendLine(" OR (" & lcParametro7Desde & " <> 'Si' AND ((DATEDIFF(d, Cuentas_Cobrar.Fec_Fin, " & lcParametro0Hasta & ") >= 1) or (DATEDIFF(d, Cuentas_Cobrar.Fec_Fin, " & lcParametro0Hasta & ") < 1))))")
loComandoSeleccionar.AppendLine(" AND Cuentas_Cobrar.Cod_Suc between " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
If lcParametro12Desde = "Igual" Then
loComandoSeleccionar.AppendLine(" AND Cuentas_Cobrar.Cod_Rev between " & lcParametro11Desde)
Else
loComandoSeleccionar.AppendLine(" AND Cuentas_Cobrar.Cod_Rev NOT between " & lcParametro11Desde)
End If
loComandoSeleccionar.AppendLine(" AND " & lcParametro11Hasta)
loComandoSeleccionar.AppendLine(" AND Vendedores.Status In (" & lcParametro13Desde & ")")
loComandoSeleccionar.AppendLine("ORDER BY " & lcOrdenamiento & ", Cuentas_Cobrar.Documento, Cuentas_Cobrar.Fec_Ini, Cuentas_Cobrar.Fec_Fin ")
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("rAVencimiento_dVendedor", laDatosReporte)
If lcParametro9Desde.ToString = "Si" Then
loObjetoReporte.DataDefinition.FormulaFields("Comentario_Notas").Text = 1
CType(loObjetoReporte.ReportDefinition.ReportObjects("Line5"), CrystalDecisions.CrystalReports.Engine.LineObject).Right = 0
CType(loObjetoReporte.ReportDefinition.ReportObjects("Line5"), CrystalDecisions.CrystalReports.Engine.LineObject).Left = 0
Else
loObjetoReporte.DataDefinition.FormulaFields("Comentario_Notas").Text = 0
loObjetoReporte.ReportDefinition.ReportObjects("text2").Height = 0
loObjetoReporte.ReportDefinition.ReportObjects("text3").Height = 0
loObjetoReporte.ReportDefinition.ReportObjects("Comentario1").Height = 0
loObjetoReporte.ReportDefinition.ReportObjects("text2").Top = 0
loObjetoReporte.ReportDefinition.ReportObjects("text3").Top = 0
loObjetoReporte.ReportDefinition.ReportObjects("Comentario1").Top = 0
loObjetoReporte.ReportDefinition.Sections(3).Height = 300
End If
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrAVencimiento_dVendedor.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: 30/06/08: Codigo inicial
'-------------------------------------------------------------------------------------------'
' CMS: 16/07/09: Filtro Calculado por, verificacion de registros
'-------------------------------------------------------------------------------------------'
' CMS: 18/07/09: Se agrego la clomuna Dias
'-------------------------------------------------------------------------------------------'
' CMS: 31/07/09: Filtro “Revisión:”
'-------------------------------------------------------------------------------------------'
' CMS: 03/08/09: Filtro “Tipo Revisión:”
'-------------------------------------------------------------------------------------------'
' CMS: 23/06/10: Filtro “Estatus del Vendedor:”
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
rAVencimiento_dVendedor.aspx.vb
|
Visual Basic
|
mit
| 17,355
|
' --- Copyright (c) notice NevoWeb ---
' Copyright (c) 2008 SARL NevoWeb. www.nevoweb.com. BSD License.
' Author: D.C.Lee
' ------------------------------------------------------------------------
' 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.
' ------------------------------------------------------------------------
' This copyright notice may NOT be removed, obscured or modified without written consent from the author.
' --- End copyright notice ---
Imports System.Runtime.Remoting
Imports NEvoWeb.Modules.NB_Store.SharedFunctions
Imports System.Xml
Namespace NEvoWeb.Modules.NB_Store
Public Class GatewayWrapper
Private _objGateTable As New Hashtable
Private ProviderList As String()
Public Sub New()
End Sub
Public Sub BuildGatewayArray(ByVal PortalID As Integer)
'create provder for all selected gateways
If _objGateTable.Count = 0 Then
Dim ProvKey As String()
Dim ProviderClassList As String
ProviderClassList = GetStoreSetting(PortalID, "gateway.provider", "XX")
If GetStoreSettingBoolean(PortalID, "debug.mode") Then
UpdateLog("ProviderClassList = " & ProviderClassList)
End If
ProviderList = Split(ProviderClassList, ";")
For lp As Integer = 0 To ProviderList.GetUpperBound(0)
If GetStoreSettingBoolean(PortalID, "debug.mode") Then
UpdateLog("ProviderList" & lp.ToString & " = " & ProviderList(lp))
End If
If ProviderList(lp) <> "" Then
ProvKey = Split(ProviderList(lp), ",")
If GetStoreSettingBoolean(PortalID, "debug.mode") Then
UpdateLog("ProvKey = " & ProvKey(0))
End If
_objGateTable.Add(ProvKey(0), GatewayInterface.Instance(ProvKey(0), ProvKey(1)))
End If
Next
End If
End Sub
Public Function GetButtonHtml(ByVal PortalID As Integer, ByVal OrderID As Integer, ByVal Lang As String, ByVal GatewayRef As String) As String
Dim Gateway As GatewayInterface
Dim hTable As Hashtable
BuildGatewayArray(PortalID)
hTable = GetAvailableGatewaysTable(PortalID)
Gateway = CType(_objGateTable(CType(hTable.Item(GatewayRef), NB_Store_GatewayInfo).assembly), GatewayInterface)
Return Gateway.GetButtonHtml(PortalID, OrderID, Lang)
End Function
Public Function GetButtonHtml(ByVal PortalID As Integer, ByVal OrderID As Integer, ByVal Lang As String) As String
Dim strRtn As String = ""
Dim Gateway As GatewayInterface
Dim HtmlSep As String = System.Web.HttpUtility.HtmlDecode(GetStoreSettingText(PortalID, "gatewaysep.template", GetCurrentCulture))
Dim ProvKey As String()
BuildGatewayArray(PortalID)
For lp As Integer = 0 To ProviderList.GetUpperBound(0)
If ProviderList(lp) <> "" Then
ProvKey = Split(ProviderList(lp), ",")
Gateway = CType(_objGateTable(ProvKey(0)), GatewayInterface)
strRtn &= Gateway.GetButtonHtml(PortalID, OrderID, Lang)
strRtn &= HtmlSep
End If
Next
If strRtn.Length > HtmlSep.Length Then
strRtn = strRtn.Substring(0, (strRtn.Length - HtmlSep.Length))
End If
Return strRtn
End Function
Public Sub AutoResponse(ByVal PortalID As Integer, ByVal Request As System.Web.HttpRequest)
Dim Gateway As GatewayInterface
Dim objCtrl As New OrderController
Dim objOInfo As NB_Store_OrdersInfo
Dim ordID As String
BuildGatewayArray(PortalID)
ordID = Request.QueryString("ordID")
If IsNumeric(ordID) Then
objOInfo = objCtrl.GetOrder(ordID)
If Not objOInfo Is Nothing Then
' use GatewayProvider field to tempoary store gateway needed
Gateway = CType(_objGateTable(objOInfo.GatewayProvider), GatewayInterface)
Gateway.AutoResponse(PortalID, Request)
End If
Else
If _objGateTable.Count > 1 Then
UpdateLog("TO SUPPORT MULTIPLE GATEWAYS USE, '.../ordID/[ORDERID]/...' IN THE AUTORESPONSE URL")
Else
Dim keys As ICollection = _objGateTable.Keys
Dim keysArray(_objGateTable.Count - 1) As String
keys.CopyTo(keysArray, 0)
Gateway = CType(_objGateTable.Item(keysArray(0).ToString), GatewayInterface)
Gateway.AutoResponse(PortalID, Request)
End If
End If
End Sub
Public Function GetCompletedHtml(ByVal PortalID As Integer, ByVal UserID As Integer, ByVal Request As System.Web.HttpRequest, ByVal OrderID As Integer) As String
Dim strRtn As String = "No Order found. OrderID=" & OrderID.ToString
Dim Gateway As GatewayInterface
Dim objCtrl As New OrderController
Dim objOInfo As NB_Store_OrdersInfo
BuildGatewayArray(PortalID)
objOInfo = objCtrl.GetOrder(OrderID)
If Not objOInfo Is Nothing Then
' use GatewayProvider field to tempoary store gateway needed
Gateway = CType(_objGateTable(objOInfo.GatewayProvider), GatewayInterface)
strRtn = Gateway.GetCompletedHtml(PortalID, UserID, Request)
End If
Return strRtn
End Function
Public Function GetBankClick(ByVal PortalID As Integer, ByVal Request As System.Web.HttpRequest) As Boolean
Dim blnRtn As Boolean = False
Dim Gateway As GatewayInterface
Dim ProvKey As String()
BuildGatewayArray(PortalID)
For lp As Integer = 0 To ProviderList.GetUpperBound(0)
If ProviderList(lp) <> "" Then
ProvKey = Split(ProviderList(lp), ",")
Gateway = CType(_objGateTable(ProvKey(0)), GatewayInterface)
If Gateway.GetBankClick(PortalID, Request) Then
'update order with provider key
Dim OrdID As Integer = CurrentCart.GetCurrentCart(PortalID).OrderID
Dim objCtrl As New OrderController
Dim objOInfo As NB_Store_OrdersInfo
objOInfo = objCtrl.GetOrder(OrdID)
If Not objOInfo Is Nothing Then
objOInfo.GatewayProvider = ProvKey(0) ' use this field to tempoary store gateway needed
objCtrl.UpdateObjOrder(objOInfo)
blnRtn = True
Exit For
End If
End If
End If
Next
Return blnRtn
End Function
Public Sub SetBankRemotePost(ByVal PortalID As Integer, ByVal OrderID As Integer, ByVal Lang As String, ByVal Request As System.Web.HttpRequest)
Dim Gateway As GatewayInterface
Dim objCtrl As New OrderController
Dim objOInfo As NB_Store_OrdersInfo
BuildGatewayArray(PortalID)
objOInfo = objCtrl.GetOrder(OrderID)
If Not objOInfo Is Nothing Then
' use GatewayProvider field to temporary store gateway needed
Gateway = CType(_objGateTable(objOInfo.GatewayProvider), GatewayInterface)
Gateway.SetBankRemotePost(PortalID, OrderID, Lang, Request)
End If
End Sub
End Class
End Namespace
|
skamphuis/NB_Store
|
Components/General/GatewayWrapper.vb
|
Visual Basic
|
mit
| 8,605
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<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.Lorem_Ipsum.My.MySettings
Get
Return Global.Lorem_Ipsum.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
NikolaLyutsov/TelerikAcademy
|
Homeworks/CSS/CSS Presentation/Lorem Ipsum/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,889
|
' 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.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(30175, "https://github.com/dotnet/roslyn/issues/30175")>
Public Sub ReDimStatement_SingleClause_SimpleArray()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M()
Dim intArray(1) As Integer
ReDim intArray(2)'BIND:"ReDim intArray(2)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IReDimOperation (OperationKind.ReDim, Type: null) (Syntax: 'ReDim intArray(2)')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'intArray(2)')
Operand:
ILocalReferenceOperation: intArray (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'intArray')
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '2')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '2')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ReDimStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(30175, "https://github.com/dotnet/roslyn/issues/30175")>
Public Sub ReDimClause_SimpleArray()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M()
Dim intArray(1) As Integer
ReDim intArray(2)'BIND:"intArray(2)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'intArray(2)')
Operand:
ILocalReferenceOperation: intArray (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'intArray')
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '2')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '2')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of RedimClauseSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(30175, "https://github.com/dotnet/roslyn/issues/30175")>
Public Sub ReDimOperand_SimpleArray()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M()
Dim intArray(1) As Integer
ReDim intArray(2)'BIND:"intArray"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ILocalReferenceOperation: intArray (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'intArray')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(30175, "https://github.com/dotnet/roslyn/issues/30175")>
Public Sub ReDimSize_SimpleArray()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M()
Dim intArray(1) As Integer
ReDim intArray(2)'BIND:"2"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LiteralExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(30175, "https://github.com/dotnet/roslyn/issues/30175")>
Public Sub ReDimStatement_SingleClause_MultiDimensionalArray()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M()
Dim intArray(1, 1) As Integer
ReDim intArray(2, 1)'BIND:"ReDim intArray(2, 1)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IReDimOperation (OperationKind.ReDim, Type: null) (Syntax: 'ReDim intArray(2, 1)')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'intArray(2, 1)')
Operand:
ILocalReferenceOperation: intArray (OperationKind.LocalReference, Type: System.Int32(,)) (Syntax: 'intArray')
DimensionSizes(2):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '2')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '2')
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ReDimStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(30175, "https://github.com/dotnet/roslyn/issues/30175")>
Public Sub ReDimStatement_MultipleClause_DifferentDimensionalArrays()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x(,) As Integer)
Dim intArray(1) As Integer
ReDim intArray(2), x(1, 1)'BIND:"ReDim intArray(2), x(1, 1)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IReDimOperation (OperationKind.ReDim, Type: null) (Syntax: 'ReDim intAr ... 2), x(1, 1)')
Clauses(2):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'intArray(2)')
Operand:
ILocalReferenceOperation: intArray (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'intArray')
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '2')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '2')
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'x(1, 1)')
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'x')
DimensionSizes(2):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1')
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ReDimStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(30175, "https://github.com/dotnet/roslyn/issues/30175")>
Public Sub ReDimClause_FirstClauseFromMultipleClauses()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x(,) As Integer)
Dim intArray(1) As Integer
ReDim intArray(2), x(1, 1)'BIND:"intArray(2)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'intArray(2)')
Operand:
ILocalReferenceOperation: intArray (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'intArray')
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '2')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '2')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of RedimClauseSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(30175, "https://github.com/dotnet/roslyn/issues/30175")>
Public Sub ReDimClause_SecondClauseFromMultipleClauses()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x(,) As Integer)
Dim intArray(1) As Integer
ReDim intArray(2), x(1, 1)'BIND:"x(1, 1)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'x(1, 1)')
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'x')
DimensionSizes(2):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1')
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of RedimClauseSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(30175, "https://github.com/dotnet/roslyn/issues/30175")>
Public Sub ReDimStatement_Preserve_SingleClause()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M()
Dim intArray(1) As Integer
ReDim Preserve intArray(2)'BIND:"ReDim Preserve intArray(2)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IReDimOperation (Preserve) (OperationKind.ReDim, Type: null) (Syntax: 'ReDim Prese ... intArray(2)')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'intArray(2)')
Operand:
ILocalReferenceOperation: intArray (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'intArray')
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '2')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '2')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ReDimStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(30175, "https://github.com/dotnet/roslyn/issues/30175")>
Public Sub ReDimStatement_Preserve_MultipleClause()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x(,) As Integer)
Dim intArray(1) As Integer
ReDim Preserve intArray(2), x(1, 1)'BIND:"ReDim Preserve intArray(2), x(1, 1)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IReDimOperation (Preserve) (OperationKind.ReDim, Type: null) (Syntax: 'ReDim Prese ... 2), x(1, 1)')
Clauses(2):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'intArray(2)')
Operand:
ILocalReferenceOperation: intArray (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'intArray')
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '2')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '2')
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'x(1, 1)')
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'x')
DimensionSizes(2):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1')
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ReDimStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(30175, "https://github.com/dotnet/roslyn/issues/30175")>
Public Sub ReDimStatement_ErrorCase_NoOperandOrIndex()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M()
ReDim'BIND:"ReDim"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IReDimOperation (OperationKind.ReDim, Type: null, IsInvalid) (Syntax: 'ReDim')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null, IsInvalid) (Syntax: '')
Operand:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: '')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
DimensionSizes(0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30201: Expression expected.
ReDim'BIND:"ReDim"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ReDimStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(30175, "https://github.com/dotnet/roslyn/issues/30175")>
Public Sub ReDimStatement_ErrorCase_Preserve_NoOperandOrIndex()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M()
ReDim Preserve'BIND:"ReDim Preserve"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IReDimOperation (Preserve) (OperationKind.ReDim, Type: null, IsInvalid) (Syntax: 'ReDim Preserve')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null, IsInvalid) (Syntax: '')
Operand:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: '')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
DimensionSizes(0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30201: Expression expected.
ReDim Preserve'BIND:"ReDim Preserve"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ReDimStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(30175, "https://github.com/dotnet/roslyn/issues/30175")>
Public Sub ReDimStatement_ErrorCase_NoIndex()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x() As Integer)
ReDim x'BIND:"ReDim x"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IReDimOperation (OperationKind.ReDim, Type: null, IsInvalid) (Syntax: 'ReDim x'BIND:"ReDim x"')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null, IsInvalid) (Syntax: 'x'BIND:"ReDim x"')
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32(), IsInvalid) (Syntax: 'x')
DimensionSizes(0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30670: 'ReDim' statements require a parenthesized list of the new bounds of each dimension of the array.
ReDim x'BIND:"ReDim x"
~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ReDimStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(30175, "https://github.com/dotnet/roslyn/issues/30175")>
Public Sub ReDimStatement_ErrorCase_NoOperand()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M()
ReDim (1)'BIND:"ReDim (1)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IReDimOperation (OperationKind.ReDim, Type: null, IsInvalid) (Syntax: 'ReDim (1)'B ... "ReDim (1)"')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null, IsInvalid) (Syntax: '(1)'BIND:"ReDim (1)"')
Operand:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '(1)')
Children(1):
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '(1)')
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
DimensionSizes(0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30074: Constant cannot be the target of an assignment.
ReDim (1)'BIND:"ReDim (1)"
~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ReDimStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(30175, "https://github.com/dotnet/roslyn/issues/30175")>
Public Sub ReDimStatement_ErrorCase_NonArrayOperandWithoutIndex()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x As Integer)
ReDim x'BIND:"ReDim x"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IReDimOperation (OperationKind.ReDim, Type: null, IsInvalid) (Syntax: 'ReDim x'BIND:"ReDim x"')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null, IsInvalid) (Syntax: 'x'BIND:"ReDim x"')
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
DimensionSizes(0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30049: 'Redim' statement requires an array.
ReDim x'BIND:"ReDim x"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ReDimStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(30175, "https://github.com/dotnet/roslyn/issues/30175")>
Public Sub ReDimStatement_ErrorCase_NonArrayOperandWithIndex()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x As Integer)
ReDim x(1)'BIND:"ReDim x(1)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IReDimOperation (OperationKind.ReDim, Type: null, IsInvalid) (Syntax: 'ReDim x(1)')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null, IsInvalid) (Syntax: 'x(1)')
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30049: 'Redim' statement requires an array.
ReDim x(1)'BIND:"ReDim x(1)"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ReDimStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(30175, "https://github.com/dotnet/roslyn/issues/30175")>
Public Sub ReDimStatement_ErrorCase_ChangeArrayDimensions()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x(,) As Integer)
ReDim x(1)'BIND:"ReDim x(1)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IReDimOperation (OperationKind.ReDim, Type: null, IsInvalid) (Syntax: 'ReDim x(1)')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null, IsInvalid) (Syntax: 'x(1)')
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32(,), IsInvalid) (Syntax: 'x')
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, Constant: 2, IsInvalid, IsImplicit) (Syntax: '1')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30415: 'ReDim' cannot change the number of dimensions of an array.
ReDim x(1)'BIND:"ReDim x(1)"
~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ReDimStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(30175, "https://github.com/dotnet/roslyn/issues/30175")>
Public Sub ReDimStatement_ErrorCase_MissingIndexArgument()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x(,) As Integer)
ReDim x(1,)'BIND:"ReDim x(1,)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IReDimOperation (OperationKind.ReDim, Type: null, IsInvalid) (Syntax: 'ReDim x(1,)')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null, IsInvalid) (Syntax: 'x(1,)')
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'x')
DimensionSizes(2):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1')
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '')
Left:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '')
Children(0)
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30306: Array subscript expression missing.
ReDim x(1,)'BIND:"ReDim x(1,)"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ReDimStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(30175, "https://github.com/dotnet/roslyn/issues/30175")>
Public Sub ReDimStatement_ErrorCase_MissingClause()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x() As Integer)
ReDim x(1), 'BIND:"ReDim x(1), "
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IReDimOperation (OperationKind.ReDim, Type: null, IsInvalid) (Syntax: 'ReDim x(1), ')
Clauses(2):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'x(1)')
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'x')
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1')
IReDimClauseOperation (OperationKind.ReDimClause, Type: null, IsInvalid) (Syntax: '')
Operand:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: '')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
DimensionSizes(0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30201: Expression expected.
ReDim x(1), 'BIND:"ReDim x(1), "
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ReDimStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ReDimStatement_NoControlFlow()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x() As Integer, a As Integer)'BIND:"Public Sub M(x() As Integer, a As Integer)"
ReDim x(a)
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IReDimOperation (OperationKind.ReDim, Type: null) (Syntax: 'ReDim x(a)')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'x(a)')
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'x')
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'a')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ReDimStatement_ControlFlowInClauseOperand()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x1() As Integer, x2() As Integer, a As Integer)'BIND:"Public Sub M(x1() As Integer, x2() As Integer, a As Integer)"
ReDim If(x1, x2)(a)
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x1')
Value:
IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32(), IsInvalid) (Syntax: 'x1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'x1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'x1')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'x1')
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x2')
Value:
IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32(), IsInvalid) (Syntax: 'x2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IReDimOperation (OperationKind.ReDim, Type: null, IsInvalid) (Syntax: 'ReDim If(x1, x2)(a)')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null, IsInvalid) (Syntax: 'If(x1, x2)(a)')
Operand:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'If(x1, x2)')
Children(1):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'If(x1, x2)')
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'a')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'a')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30068: Expression is a value and therefore cannot be the target of an assignment.
ReDim If(x1, x2)(a)
~~~~~~~~~~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ReDimStatement_ControlFlowInFirstIndex()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x(,) As Integer, a1 As Integer?, a2 As Integer, b As Integer)'BIND:"Public Sub M(x(,) As Integer, a1 As Integer?, a2 As Integer, b As Integer)"
ReDim x(If(a1, a2), b)
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'x')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a1')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a2')
Value:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IReDimOperation (OperationKind.ReDim, Type: null) (Syntax: 'ReDim x(If(a1, a2), b)')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'x(If(a1, a2), b)')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32(,), IsImplicit) (Syntax: 'x')
DimensionSizes(2):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'If(a1, a2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a1, a2)')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'If(a1, a2)')
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'b')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'b')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ReDimStatement_ControlFlowInSecondIndex()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x(,) As Integer, a1 As Integer?, a2 As Integer, b As Integer)'BIND:"Public Sub M(x(,) As Integer, a1 As Integer?, a2 As Integer, b As Integer)"
ReDim x(b, If(a1, a2))
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [3]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'x')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'b')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'b')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a1')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a1')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a2')
Value:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IReDimOperation (OperationKind.ReDim, Type: null) (Syntax: 'ReDim x(b, If(a1, a2))')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'x(b, If(a1, a2))')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32(,), IsImplicit) (Syntax: 'x')
DimensionSizes(2):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b')
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'If(a1, a2)')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a1, a2)')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'If(a1, a2)')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ReDimStatement_ControlFlowInMultipleDimensionSizes()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x(,) As Integer, a1 As Integer?, a2 As Integer, b1 As Integer?, b2 As Integer)'BIND:"Public Sub M(x(,) As Integer, a1 As Integer?, a2 As Integer, b1 As Integer?, b2 As Integer)"
ReDim x(If(a1, a2), If(b1, b2))
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [3] [5]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'x')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.locals {R2}
{
CaptureIds: [2]
.locals {R3}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a1')
Leaving: {R3}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a1')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a2')
Value:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(a1, a2)')
Value:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'If(a1, a2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a1, a2)')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'If(a1, a2)')
Next (Regular) Block[B6]
Leaving: {R2}
Entering: {R4}
}
.locals {R4}
{
CaptureIds: [4]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b1')
Value:
IParameterReferenceOperation: b1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'b1')
Jump if True (Regular) to Block[B8]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b1')
Operand:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'b1')
Leaving: {R4}
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b1')
Instance Receiver:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'b1')
Arguments(0)
Next (Regular) Block[B9]
Leaving: {R4}
}
Block[B8] - Block
Predecessors: [B6]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b2')
Value:
IParameterReferenceOperation: b2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b2')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (1)
IReDimOperation (OperationKind.ReDim, Type: null) (Syntax: 'ReDim x(If( ... If(b1, b2))')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'x(If(a1, a2 ... If(b1, b2))')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32(,), IsImplicit) (Syntax: 'x')
DimensionSizes(2):
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a1, a2)')
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'If(b1, b2)')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b1, b2)')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'If(b1, b2)')
Next (Regular) Block[B10]
Leaving: {R1}
}
Block[B10] - Exit
Predecessors: [B9]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ReDimStatement_ControlFlowInOperandAndDimensionSizes()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x1(,) As Integer, x2(,) As Integer, a1 As Integer?, a2 As Integer, b1 As Integer?, b2 As Integer)'BIND:"Public Sub M(x1(,) As Integer, x2(,) As Integer, a1 As Integer?, a2 As Integer, b1 As Integer?, b2 As Integer)"
ReDim If(x1, x2)(If(a1, a2), If(b1, b2))
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3}
.locals {R1}
{
CaptureIds: [2] [5] [7]
.locals {R2}
{
CaptureIds: [1]
.locals {R3}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x1')
Value:
IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32(,), IsInvalid) (Syntax: 'x1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'x1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32(,), IsInvalid, IsImplicit) (Syntax: 'x1')
Leaving: {R3}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32(,), IsInvalid, IsImplicit) (Syntax: 'x1')
Next (Regular) Block[B4]
Leaving: {R3}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x2')
Value:
IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32(,), IsInvalid) (Syntax: 'x2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'If(x1, x2)')
Value:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'If(x1, x2)')
Children(1):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32(,), IsInvalid, IsImplicit) (Syntax: 'If(x1, x2)')
Next (Regular) Block[B5]
Leaving: {R2}
Entering: {R4} {R5}
}
.locals {R4}
{
CaptureIds: [4]
.locals {R5}
{
CaptureIds: [3]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a1')
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a1')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a1')
Leaving: {R5}
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a1')
Instance Receiver:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a1')
Arguments(0)
Next (Regular) Block[B8]
Leaving: {R5}
}
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a2')
Value:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(a1, a2)')
Value:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'If(a1, a2)')
Left:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a1, a2)')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'If(a1, a2)')
Next (Regular) Block[B9]
Leaving: {R4}
Entering: {R6}
}
.locals {R6}
{
CaptureIds: [6]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b1')
Value:
IParameterReferenceOperation: b1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'b1')
Jump if True (Regular) to Block[B11]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b1')
Operand:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'b1')
Leaving: {R6}
Next (Regular) Block[B10]
Block[B10] - Block
Predecessors: [B9]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b1')
Instance Receiver:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'b1')
Arguments(0)
Next (Regular) Block[B12]
Leaving: {R6}
}
Block[B11] - Block
Predecessors: [B9]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b2')
Value:
IParameterReferenceOperation: b2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b2')
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B10] [B11]
Statements (1)
IReDimOperation (OperationKind.ReDim, Type: null, IsInvalid) (Syntax: 'ReDim If(x1 ... If(b1, b2))')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null, IsInvalid) (Syntax: 'If(x1, x2)( ... If(b1, b2))')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'If(x1, x2)')
DimensionSizes(2):
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a1, a2)')
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'If(b1, b2)')
Left:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b1, b2)')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'If(b1, b2)')
Next (Regular) Block[B13]
Leaving: {R1}
}
Block[B13] - Exit
Predecessors: [B12]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30068: Expression is a value and therefore cannot be the target of an assignment.
ReDim If(x1, x2)(If(a1, a2), If(b1, b2))
~~~~~~~~~~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ReDimStatement_ControlFlowInFirstClause()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x1() As Integer, x2() As Integer, a1 As Integer?, a2 As Integer, b As Integer)'BIND:"Public Sub M(x1() As Integer, x2() As Integer, a1 As Integer?, a2 As Integer, b As Integer)"
ReDim x1(If(a1, a2)), x2(b)
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x1')
Value:
IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'x1')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a1')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a2')
Value:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IReDimOperation (OperationKind.ReDim, Type: null, IsImplicit) (Syntax: 'ReDim x1(If ... a2)), x2(b)')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'x1(If(a1, a2))')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32(), IsImplicit) (Syntax: 'x1')
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'If(a1, a2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a1, a2)')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'If(a1, a2)')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IReDimOperation (OperationKind.ReDim, Type: null, IsImplicit) (Syntax: 'ReDim x1(If ... a2)), x2(b)')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'x2(b)')
Operand:
IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'x2')
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'b')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'b')
Next (Regular) Block[B7]
Block[B7] - Exit
Predecessors: [B6]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ReDimStatement_ControlFlowInSecondClause()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x1() As Integer, x2() As Integer, a1 As Integer?, a2 As Integer, b As Integer)'BIND:"Public Sub M(x1() As Integer, x2() As Integer, a1 As Integer?, a2 As Integer, b As Integer)"
ReDim x1(b), x2(If(a1, a2))
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IReDimOperation (OperationKind.ReDim, Type: null, IsImplicit) (Syntax: 'ReDim x1(b) ... If(a1, a2))')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'x1(b)')
Operand:
IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'x1')
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'b')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'b')
Next (Regular) Block[B2]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x2')
Value:
IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'x2')
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a1')
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a1')
Leaving: {R2}
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a1')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a1')
Arguments(0)
Next (Regular) Block[B6]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a2')
Value:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a2')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (1)
IReDimOperation (OperationKind.ReDim, Type: null, IsImplicit) (Syntax: 'ReDim x1(b) ... If(a1, a2))')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'x2(If(a1, a2))')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32(), IsImplicit) (Syntax: 'x2')
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'If(a1, a2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a1, a2)')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'If(a1, a2)')
Next (Regular) Block[B7]
Leaving: {R1}
}
Block[B7] - Exit
Predecessors: [B6]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ReDimStatement_ControlFlowInMultipleClauses()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x1() As Integer, x2() As Integer, a1 As Integer?, a2 As Integer, b1 As Integer?, b2 As Integer)'BIND:"Public Sub M(x1() As Integer, x2() As Integer, a1 As Integer?, a2 As Integer, b1 As Integer?, b2 As Integer)"
ReDim x1(If(a1, a2)), x2(If(b1, b2))
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x1')
Value:
IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'x1')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a1')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a2')
Value:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IReDimOperation (OperationKind.ReDim, Type: null, IsImplicit) (Syntax: 'ReDim x1(If ... If(b1, b2))')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'x1(If(a1, a2))')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32(), IsImplicit) (Syntax: 'x1')
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'If(a1, a2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a1, a2)')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'If(a1, a2)')
Next (Regular) Block[B6]
Leaving: {R1}
Entering: {R3}
}
.locals {R3}
{
CaptureIds: [3] [5]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x2')
Value:
IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'x2')
Next (Regular) Block[B7]
Entering: {R4}
.locals {R4}
{
CaptureIds: [4]
Block[B7] - Block
Predecessors: [B6]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b1')
Value:
IParameterReferenceOperation: b1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'b1')
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b1')
Operand:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'b1')
Leaving: {R4}
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b1')
Instance Receiver:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'b1')
Arguments(0)
Next (Regular) Block[B10]
Leaving: {R4}
}
Block[B9] - Block
Predecessors: [B7]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b2')
Value:
IParameterReferenceOperation: b2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b2')
Next (Regular) Block[B10]
Block[B10] - Block
Predecessors: [B8] [B9]
Statements (1)
IReDimOperation (OperationKind.ReDim, Type: null, IsImplicit) (Syntax: 'ReDim x1(If ... If(b1, b2))')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'x2(If(b1, b2))')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32(), IsImplicit) (Syntax: 'x2')
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'If(b1, b2)')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b1, b2)')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'If(b1, b2)')
Next (Regular) Block[B11]
Leaving: {R3}
}
Block[B11] - Exit
Predecessors: [B10]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ReDimStatement_NoControlFlowPropertyInvocationReturningArray()
Dim source = <![CDATA[
Module Module1
Public Sub Main(a1 As Integer, a2 As Integer, a3 As Integer)'BIND:"Public Sub Main(a1 As Integer, a2 As Integer, a3 As Integer)"
ReDim X(a1)(a2), Y(a3)
End Sub
Property X(z As Integer) As Integer()
Get
Return Nothing
End Get
Set(value As Integer())
End Set
End Property
Property Y As Integer()
Get
Return Nothing
End Get
Set(value As Integer())
End Set
End Property
End Module
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IReDimOperation (OperationKind.ReDim, Type: null, IsImplicit) (Syntax: 'ReDim X(a1)(a2), Y(a3)')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'X(a1)(a2)')
Operand:
IPropertyReferenceOperation: Property Module1.X(z As System.Int32) As System.Int32() (Static) (OperationKind.PropertyReference, Type: System.Int32()) (Syntax: 'X(a1)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: z) (OperationKind.Argument, Type: null) (Syntax: 'a1')
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'a2')
Left:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'a2')
IReDimOperation (OperationKind.ReDim, Type: null, IsImplicit) (Syntax: 'ReDim X(a1)(a2), Y(a3)')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'Y(a3)')
Operand:
IPropertyReferenceOperation: Property Module1.Y As System.Int32() (Static) (OperationKind.PropertyReference, Type: System.Int32()) (Syntax: 'Y')
Instance Receiver:
null
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'a3')
Left:
IParameterReferenceOperation: a3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a3')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'a3')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ReDimStatement_ControlFlowInFirstClauseOperand_PropertyInvocationReturningArray()
Dim source = <![CDATA[
Module Module1
Public Sub Main(a1 As Integer?, a2 As Integer, a3 As Integer, a4 As Integer)'BIND:"Public Sub Main(a1 As Integer?, a2 As Integer, a3 As Integer, a4 As Integer)"
ReDim X(If(a1, a2))(a3), Y(a4)
End Sub
Property X(z As Integer) As Integer()
Get
Return Nothing
End Get
Set(value As Integer())
End Set
End Property
Property Y As Integer()
Get
Return Nothing
End Get
Set(value As Integer())
End Set
End Property
End Module
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a1')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a1')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a1')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a2')
Value:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IReDimOperation (OperationKind.ReDim, Type: null, IsImplicit) (Syntax: 'ReDim X(If( ... (a3), Y(a4)')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'X(If(a1, a2))(a3)')
Operand:
IPropertyReferenceOperation: Property Module1.X(z As System.Int32) As System.Int32() (Static) (OperationKind.PropertyReference, Type: System.Int32()) (Syntax: 'X(If(a1, a2))')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: z) (OperationKind.Argument, Type: null) (Syntax: 'If(a1, a2)')
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a1, a2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'a3')
Left:
IParameterReferenceOperation: a3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a3')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'a3')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IReDimOperation (OperationKind.ReDim, Type: null, IsImplicit) (Syntax: 'ReDim X(If( ... (a3), Y(a4)')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'Y(a4)')
Operand:
IPropertyReferenceOperation: Property Module1.Y As System.Int32() (Static) (OperationKind.PropertyReference, Type: System.Int32()) (Syntax: 'Y')
Instance Receiver:
null
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'a4')
Left:
IParameterReferenceOperation: a4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a4')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'a4')
Next (Regular) Block[B6]
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ReDimStatement_ControlFlowInFirstClauseDimension_PropertyInvocationReturningArray()
Dim source = <![CDATA[
Module Module1
Public Sub Main(a1 As Integer, a2 As Integer?, a3 As Integer, a4 As Integer)'BIND:"Public Sub Main(a1 As Integer, a2 As Integer?, a3 As Integer, a4 As Integer)"
ReDim X(a1)(If(a2, a3)), Y(a4)
End Sub
Property X(z As Integer) As Integer()
Get
Return Nothing
End Get
Set(value As Integer())
End Set
End Property
Property Y As Integer()
Get
Return Nothing
End Get
Set(value As Integer())
End Set
End Property
End Module
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'X(a1)')
Value:
IPropertyReferenceOperation: Property Module1.X(z As System.Int32) As System.Int32() (Static) (OperationKind.PropertyReference, Type: System.Int32()) (Syntax: 'X(a1)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: z) (OperationKind.Argument, Type: null) (Syntax: 'a1')
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a2')
Value:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a2')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a2')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a2')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a2')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a2')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a2')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a3')
Value:
IParameterReferenceOperation: a3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a3')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IReDimOperation (OperationKind.ReDim, Type: null, IsImplicit) (Syntax: 'ReDim X(a1) ... a3)), Y(a4)')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'X(a1)(If(a2, a3))')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32(), IsImplicit) (Syntax: 'X(a1)')
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'If(a2, a3)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a2, a3)')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'If(a2, a3)')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IReDimOperation (OperationKind.ReDim, Type: null, IsImplicit) (Syntax: 'ReDim X(a1) ... a3)), Y(a4)')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'Y(a4)')
Operand:
IPropertyReferenceOperation: Property Module1.Y As System.Int32() (Static) (OperationKind.PropertyReference, Type: System.Int32()) (Syntax: 'Y')
Instance Receiver:
null
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'a4')
Left:
IParameterReferenceOperation: a4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a4')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'a4')
Next (Regular) Block[B7]
Block[B7] - Exit
Predecessors: [B6]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ReDimStatement_ControlFlowInSecondClause_PropertyInvocationReturningArray()
Dim source = <![CDATA[
Module Module1
Public Sub Main(a1 As Integer, a2 As Integer, a3 As Integer?, a4 As Integer)'BIND:"Public Sub Main(a1 As Integer, a2 As Integer, a3 As Integer?, a4 As Integer)"
ReDim X(a1)(a2), Y(If(a3, a4))
End Sub
Property X(z As Integer) As Integer()
Get
Return Nothing
End Get
Set(value As Integer())
End Set
End Property
Property Y As Integer()
Get
Return Nothing
End Get
Set(value As Integer())
End Set
End Property
End Module
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IReDimOperation (OperationKind.ReDim, Type: null, IsImplicit) (Syntax: 'ReDim X(a1) ... If(a3, a4))')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'X(a1)(a2)')
Operand:
IPropertyReferenceOperation: Property Module1.X(z As System.Int32) As System.Int32() (Static) (OperationKind.PropertyReference, Type: System.Int32()) (Syntax: 'X(a1)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: z) (OperationKind.Argument, Type: null) (Syntax: 'a1')
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'a2')
Left:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'a2')
Next (Regular) Block[B2]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Y')
Value:
IPropertyReferenceOperation: Property Module1.Y As System.Int32() (Static) (OperationKind.PropertyReference, Type: System.Int32()) (Syntax: 'Y')
Instance Receiver:
null
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a3')
Value:
IParameterReferenceOperation: a3 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a3')
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a3')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a3')
Leaving: {R2}
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a3')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a3')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a3')
Arguments(0)
Next (Regular) Block[B6]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a4')
Value:
IParameterReferenceOperation: a4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a4')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (1)
IReDimOperation (OperationKind.ReDim, Type: null, IsImplicit) (Syntax: 'ReDim X(a1) ... If(a3, a4))')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'Y(If(a3, a4))')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32(), IsImplicit) (Syntax: 'Y')
DimensionSizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'If(a3, a4)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a3, a4)')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'If(a3, a4)')
Next (Regular) Block[B7]
Leaving: {R1}
}
Block[B7] - Exit
Predecessors: [B6]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ReDimStatement_ControlFlow_PreserveFlag()
Dim source = <![CDATA[
Imports System
Friend Class [Class]
Public Sub M(x(,) As Integer, a1 As Integer?, a2 As Integer, b As Integer)'BIND:"Public Sub M(x(,) As Integer, a1 As Integer?, a2 As Integer, b As Integer)"
ReDim Preserve x(If(a1, a2), b)
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'x')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a1')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a2')
Value:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IReDimOperation (Preserve) (OperationKind.ReDim, Type: null) (Syntax: 'ReDim Prese ... a1, a2), b)')
Clauses(1):
IReDimClauseOperation (OperationKind.ReDimClause, Type: null) (Syntax: 'x(If(a1, a2), b)')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32(,), IsImplicit) (Syntax: 'x')
DimensionSizes(2):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'If(a1, a2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a1, a2)')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'If(a1, a2)')
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.BinaryOperator, Type: System.Int32, IsImplicit) (Syntax: 'b')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'b')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
End Class
End Namespace
|
xasx/roslyn
|
src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IReDimOperation.vb
|
Visual Basic
|
apache-2.0
| 107,613
|
Imports BVSoftware.BVC5.Core
Partial Class BVAdmin_Controls_ContentColumnEditor
Inherits System.Web.UI.UserControl
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
LoadBlockList()
LoadColumn()
End If
End Sub
Public Property ColumnId() As String
Get
Dim obj As Object = ViewState("ColumnId")
If obj IsNot Nothing Then
Return CStr(obj)
Else
Return ""
End If
End Get
Set(ByVal value As String)
ViewState("ColumnId") = value
End Set
End Property
Private Sub LoadBlockList()
Me.lstBlocks.DataSource = Content.ModuleController.FindContentBlocks
Me.lstBlocks.DataBind()
End Sub
Public Sub LoadColumn()
Dim c As Content.ContentColumn = Content.ContentColumn.FindByBvin(Me.ColumnId)
Me.lblTitle.Text = c.DisplayName
Me.GridView1.DataSource = c.Blocks
Me.GridView1.DataBind()
End Sub
Protected Sub btnNew_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnNew.Click
Dim b As New Content.ContentBlock
b.ControlName = Me.lstBlocks.SelectedValue
b.ColumnId = Me.ColumnId
Content.ContentBlock.Insert(b)
LoadColumn()
End Sub
Protected Sub GridView1_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GridView1.RowCancelingEdit
Dim bvin As String = String.Empty
Me.GridView1.UpdateAfterCallBack = True
bvin = CType(sender, GridView).DataKeys(e.RowIndex).Value.ToString
Content.ContentBlock.MoveDown(bvin, Me.ColumnId)
LoadColumn()
End Sub
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating
Dim bvin As String = String.Empty
Me.GridView1.UpdateAfterCallBack = True
bvin = CType(sender, GridView).DataKeys(e.RowIndex).Value.ToString
Content.ContentBlock.MoveUp(bvin, Me.ColumnId)
LoadColumn()
End Sub
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim b As Content.ContentBlock = CType(e.Row.DataItem, Content.ContentBlock)
Dim controlFound As Boolean = False
Dim viewControl As System.Web.UI.Control
viewControl = Content.ModuleController.LoadContentBlockAdminView(b.ControlName, Me.Page)
If viewControl Is Nothing Then
'No admin view, try standard view
viewControl = Content.ModuleController.LoadContentBlock(b.ControlName, Me.Page)
End If
If viewControl IsNot Nothing Then
If TypeOf viewControl Is Content.BVModule Then
CType(viewControl, Content.BVModule).BlockId = b.Bvin
controlFound = True
e.Row.Cells(0).Controls.Add(viewControl)
End If
End If
If controlFound = True Then
' Check for Editor
Dim lnkEdit As HyperLink = e.Row.FindControl("lnkEdit")
If lnkEdit IsNot Nothing Then
lnkEdit.Visible = EditorExists(b.ControlName)
End If
Else
e.Row.Cells(0).Controls.Add(New LiteralControl("Control " & b.ControlName & "could not be located"))
End If
End If
End Sub
Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
Dim bvin As String = String.Empty
Me.GridView1.UpdateAfterCallBack = True
bvin = CType(sender, GridView).DataKeys(e.RowIndex).Value.ToString
Content.ContentBlock.Delete(bvin)
LoadColumn()
End Sub
Private Function EditorExists(ByVal controlName As String) As Boolean
Dim result As Boolean = False
Dim editorControl As System.Web.UI.Control
editorControl = Content.ModuleController.LoadContentBlockEditor(controlName, Me.Page)
If editorControl IsNot Nothing Then
If TypeOf editorControl Is Content.BVModule Then
result = True
End If
End If
Return result
End Function
End Class
|
ajaydex/Scopelist_2015
|
BVAdmin/Controls/ContentColumnEditor.ascx.vb
|
Visual Basic
|
apache-2.0
| 4,645
|
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.Visualization
Public Class CameraPath
Inherits AnimatGUI.Framework.DataObject
#Region " Attributes "
Protected m_aryWaypoints As New Collections.SortedWaypointsList(Me)
Protected m_aryWaypointsByName As New Collections.OrderedWaypointsList(Me)
Protected m_thLinkedStructure As AnimatGUI.TypeHelpers.LinkedStructureList
Protected m_thLinkedPart As AnimatGUI.TypeHelpers.LinkedBodyPartList
Protected m_clLineColor As System.Drawing.Color = System.Drawing.Color.Red
Protected m_bVisible As Boolean = True
Protected m_bVisibleInSim As Boolean = False
Protected m_bShowWaypoints As Boolean = False
'Only used during loading
Protected m_strLinkedStructureID As String = ""
Protected m_strLinkedBodyPartID As String = ""
Protected m_SimWindow As Forms.Tools.ScriptedSimulationWindow
Protected m_snStartTime As Framework.ScaledNumber
Protected m_snEndTime As Framework.ScaledNumber
#End Region
#Region " Properties "
Public Overridable ReadOnly Property Type() As String
Get
Return "CameraPath"
End Get
End Property
Public Overrides ReadOnly Property WorkspaceImageName As String
Get
Return "AnimatGUI.CameraPaths.gif"
End Get
End Property
<Browsable(False)> _
Public Overridable Property LineColor() As System.Drawing.Color
Get
Return m_clLineColor
End Get
Set(ByVal Value As System.Drawing.Color)
SetSimData("LineColor", Util.SaveColorXml("LineColor", Value), True)
m_clLineColor = Value
End Set
End Property
<Browsable(False)> _
Public Overridable ReadOnly Property Waypoints() As Collections.SortedWaypointsList
Get
Return m_aryWaypoints
End Get
End Property
<Browsable(False)> _
Public Overridable ReadOnly Property WaypointsByName() As Collections.OrderedWaypointsList
Get
Return m_aryWaypointsByName
End Get
End Property
<Browsable(False)> _
Public Overridable Property LinkedStructure() As AnimatGUI.TypeHelpers.LinkedStructureList
Get
Return m_thLinkedStructure
End Get
Set(ByVal Value As AnimatGUI.TypeHelpers.LinkedStructureList)
Dim thPrevLinked As AnimatGUI.TypeHelpers.LinkedStructureList = m_thLinkedStructure
DiconnectLinkedEvents()
m_thLinkedStructure = Value
If Not m_thLinkedStructure.PhysicalStructure Is thPrevLinked.PhysicalStructure Then
m_thLinkedPart = New TypeHelpers.LinkedBodyPartList(m_thLinkedStructure.PhysicalStructure, Nothing, GetType(AnimatGUI.DataObjects.Physical.BodyPart))
End If
ConnectLinkedEvents()
End Set
End Property
<Browsable(False)> _
Public Overridable Property LinkedPart() As AnimatGUI.TypeHelpers.LinkedBodyPartList
Get
Return m_thLinkedPart
End Get
Set(ByVal Value As AnimatGUI.TypeHelpers.LinkedBodyPartList)
Dim thPrevLinked As AnimatGUI.TypeHelpers.LinkedBodyPartList = m_thLinkedPart
If Not Value Is Nothing AndAlso Not Value.BodyPart Is Nothing Then
SetSimData("TrackPartID", Value.BodyPart.ID, True)
Else
SetSimData("TrackPartID", "", True)
End If
DiconnectLinkedEvents()
m_thLinkedPart = Value
ConnectLinkedEvents()
End Set
End Property
Public Overridable Property StartTime() As Framework.ScaledNumber
Get
Return m_snStartTime
End Get
Set(ByVal value As Framework.ScaledNumber)
If value.ActualValue < 0 Then
Throw New System.Exception("You cannot specify a start time less than zero.")
End If
'Check to see if there is already a path with the given start time
If Not m_SimWindow Is Nothing AndAlso m_SimWindow.HasPathWithStartTime(value.ActualValue) Then
Throw New System.Exception("A path with a start time of '" & value.ActualValue & "' already exists.")
End If
Me.SetSimData("StartTime", value.ToString, True)
m_snStartTime.CopyData(value)
RecalculateTimes()
End Set
End Property
Public Overridable Property EndTime() As Framework.ScaledNumber
Get
Return m_snEndTime
End Get
Set(ByVal value As Framework.ScaledNumber)
Me.SetSimData("EndTime", value.ToString, True)
m_snEndTime.CopyData(value)
m_snEndTime.PropertiesReadOnly = True
End Set
End Property
Public Overridable Property Visible() As Boolean
Get
Return m_bVisible
End Get
Set(ByVal value As Boolean)
Me.SetSimData("Visible", value.ToString, True)
m_bVisible = value
End Set
End Property
Public Overridable Property VisibleInSim() As Boolean
Get
Return m_bVisibleInSim
End Get
Set(ByVal value As Boolean)
Me.SetSimData("VisibleInSim", value.ToString, True)
m_bVisibleInSim = value
End Set
End Property
Public Overridable Property ShowWaypoints() As Boolean
Get
Return m_bShowWaypoints
End Get
Set(ByVal value As Boolean)
Me.SetSimData("ShowWaypoints", value.ToString, True)
m_bShowWaypoints = value
End Set
End Property
#End Region
#Region " Methods "
Public Sub New(ByVal doParent As Framework.DataObject)
MyBase.New(doParent)
If TypeOf (doParent) Is DataObjects.FormHelper Then
Dim doHelper As DataObjects.FormHelper = DirectCast(doParent, DataObjects.FormHelper)
If Not doHelper.AnimatParent Is Nothing AndAlso Util.IsTypeOf(doHelper.AnimatParent.GetType(), GetType(Forms.Tools.ScriptedSimulationWindow), False) Then
m_SimWindow = DirectCast(doHelper.AnimatParent, Forms.Tools.ScriptedSimulationWindow)
End If
End If
m_thLinkedStructure = New AnimatGUI.TypeHelpers.LinkedStructureList(Nothing, TypeHelpers.LinkedStructureList.enumStructureType.All)
m_thLinkedPart = New AnimatGUI.TypeHelpers.LinkedBodyPartList(Nothing, Nothing, GetType(AnimatGUI.DataObjects.Physical.BodyPart))
m_snStartTime = New ScaledNumber(Me, "StartTime", 0, ScaledNumber.enumNumericScale.None, "s", "s")
m_snEndTime = New ScaledNumber(Me, "EndTime", 1, ScaledNumber.enumNumericScale.None, "s", "s")
m_snEndTime.PropertiesReadOnly = True
End Sub
Public Overrides Sub ClearIsDirty()
MyBase.ClearIsDirty()
If Not m_aryWaypoints Is Nothing Then m_aryWaypoints.ClearIsDirty()
If Not m_aryWaypointsByName Is Nothing Then m_aryWaypointsByName.ClearIsDirty()
If Not m_thLinkedStructure Is Nothing Then m_thLinkedStructure.ClearIsDirty()
If Not m_thLinkedPart Is Nothing Then m_thLinkedPart.ClearIsDirty()
If Not m_snStartTime Is Nothing Then m_snStartTime.ClearIsDirty()
If Not m_snEndTime Is Nothing Then m_snEndTime.ClearIsDirty()
End Sub
Public Overrides Sub BuildProperties(ByRef propTable As AnimatGuiCtrls.Controls.PropertyTable)
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Name", Me.Name.GetType(), "Name", _
"Path Properties", "Name", Me.Name))
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("ID", Me.ID.GetType(), "ID", _
"Path Properties", "ID", Me.ID, True))
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Line Color", m_clLineColor.GetType(), "LineColor", _
"Path Properties", "Sets the pen color used to draw the path.", m_clLineColor))
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Visible", Me.Visible.GetType(), "Visible", _
"Path Properties", "Sets whether the path is visible while the simulation is not running.", Me.Visible))
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Visible In Sim", Me.Visible.GetType(), "VisibleInSim", _
"Path Properties", "Sets whether the path is visible while the simulation is running.", Me.VisibleInSim))
'propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Show Waypoints", Me.Visible.GetType(), "ShowWaypoints", _
' "Path Properties", "Determines whether the waypoints and lines between them are shown or not.", Me.ShowWaypoints))
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("LinkedStructure", m_thLinkedStructure.GetType, "LinkedStructure", _
"Part Properties", "Associates this camera path to a structure to look at during its movement.", m_thLinkedStructure, _
GetType(AnimatGUI.TypeHelpers.DropDownListEditor), _
GetType(AnimatGUI.TypeHelpers.LinkedStructureTypeConverter)))
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("LinkedPart", m_thLinkedPart.GetType, "LinkedPart", _
"Part Properties", "Associates this camera path to a part to look at during its movement.", m_thLinkedPart, _
GetType(AnimatGUI.TypeHelpers.DropDownListEditor), _
GetType(AnimatGUI.TypeHelpers.LinkedBodyPartTypeConverter)))
Dim pbNumberBag As AnimatGuiCtrls.Controls.PropertyBag = m_snStartTime.Properties
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Start Time", pbNumberBag.GetType(), "StartTime", _
"Time Properties", "Sets the time when this path will begin playing.", pbNumberBag, _
"", GetType(AnimatGUI.Framework.ScaledNumber.ScaledNumericPropBagConverter)))
pbNumberBag = m_snEndTime.Properties
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("End Time", pbNumberBag.GetType(), "EndTime", _
"Time Properties", "The time when this path will stop playing.", pbNumberBag, _
"", GetType(AnimatGUI.Framework.ScaledNumber.ScaledNumericPropBagConverter), True))
End Sub
Protected Overrides Sub CloneInternal(ByVal doOriginal As Framework.DataObject, ByVal bCutData As Boolean, ByVal doRoot As Framework.DataObject)
MyBase.CloneInternal(doOriginal, bCutData, doRoot)
Dim bpOrig As CameraPath = DirectCast(doOriginal, CameraPath)
m_aryWaypoints = DirectCast(bpOrig.m_aryWaypoints.Clone(Me, bCutData, doRoot), Collections.SortedWaypointsList)
m_aryWaypointsByName = DirectCast(bpOrig.m_aryWaypointsByName.Clone(Me, bCutData, doRoot), Collections.OrderedWaypointsList)
m_thLinkedStructure = DirectCast(bpOrig.m_thLinkedStructure.Clone(Me, bCutData, doRoot), TypeHelpers.LinkedStructureList)
m_thLinkedPart = DirectCast(bpOrig.m_thLinkedPart.Clone(Me, bCutData, doRoot), TypeHelpers.LinkedBodyPartList)
m_clLineColor = bpOrig.m_clLineColor
m_snStartTime = DirectCast(bpOrig.m_snStartTime.Clone(Me, bCutData, doRoot), Framework.ScaledNumber)
m_snEndTime = DirectCast(bpOrig.m_snEndTime.Clone(Me, bCutData, doRoot), Framework.ScaledNumber)
m_bVisible = bpOrig.m_bVisible
m_bVisibleInSim = bpOrig.m_bVisibleInSim
m_bShowWaypoints = bpOrig.m_bShowWaypoints
End Sub
Public Overrides Function Clone(ByVal doParent As Framework.DataObject, ByVal bCutData As Boolean, ByVal doRoot As Framework.DataObject) As Framework.DataObject
Dim oNewNode As New CameraPath(doParent)
oNewNode.CloneInternal(Me, bCutData, doRoot)
If Not doRoot Is Nothing AndAlso doRoot Is Me Then oNewNode.AfterClone(Me, bCutData, doRoot, oNewNode)
Return oNewNode
End Function
Public Overrides Function FindObjectByID(ByVal strID As String) As Framework.DataObject
Dim doObject As AnimatGUI.Framework.DataObject = MyBase.FindObjectByID(strID)
If doObject Is Nothing AndAlso Not m_aryWaypoints Is Nothing Then doObject = m_aryWaypoints.FindObjectByID(strID)
Return doObject
End Function
#Region " Add-Remove to List Methods "
Public Overrides Sub AddToSim(ByVal bThrowError As Boolean, Optional ByVal bDoNotInit As Boolean = False)
If Not Util.Simulation Is Nothing AndAlso Not m_SimWindow Is Nothing Then
Util.Application.SimulationInterface.AddItem(m_SimWindow.ID, "CameraPath", Me.ID, Me.GetSimulationXml("CameraPath"), bThrowError, bDoNotInit)
InitializeSimulationReferences()
End If
End Sub
Public Overrides Sub RemoveFromSim(ByVal bThrowError As Boolean)
If Not Util.Simulation Is Nothing AndAlso Not m_doInterface Is Nothing AndAlso Not m_SimWindow Is Nothing Then
Util.Application.SimulationInterface.RemoveItem(m_SimWindow.ID, "CameraPath", Me.ID, bThrowError)
End If
m_doInterface = Nothing
End Sub
#End Region
Public Overridable Sub AddWaypoint(ByVal doWaypoint As Waypoint, Optional ByVal bCallSimMethods As Boolean = True)
m_aryWaypoints.Add(doWaypoint.ID, doWaypoint, bCallSimMethods)
If Not IsNumeric(doWaypoint.Name) Then
Throw New System.Exception("New waypoint names must be numeric")
End If
m_aryWaypointsByName.Add(CInt(doWaypoint.Name), doWaypoint)
End Sub
Protected Overridable Function FindLastWaypoint() As Waypoint
Dim dblStart As Double = -1
Dim doWaypoint As Waypoint
Dim doLast As Waypoint
For Each deEntry As DictionaryEntry In m_aryWaypointsByName
doWaypoint = DirectCast(deEntry.Value, Waypoint)
If doWaypoint.StartTime.ActualValue > dblStart Then
doLast = doWaypoint
dblStart = doWaypoint.StartTime.ActualValue
End If
Next
Return doLast
End Function
Public Overridable Sub AddWaypointSetTimes(ByVal doWaypoint As Waypoint, Optional ByVal bCallSimMethods As Boolean = True)
If Not IsNumeric(doWaypoint.Name) Then
Throw New System.Exception("New waypoint names must be numeric")
End If
If m_aryWaypointsByName.Count > 0 Then
Dim doEndWaypoint As Waypoint = FindLastWaypoint()
doWaypoint.EndTime.ActualValue = doEndWaypoint.EndTime.ActualValue + doWaypoint.TimeSpan.ActualValue
doWaypoint.StartTime.ActualValue = doEndWaypoint.EndTime.ActualValue
End If
doWaypoint.InitializeAfterLoad()
m_aryWaypoints.Add(doWaypoint.ID, doWaypoint, bCallSimMethods)
m_aryWaypointsByName.Add(CInt(doWaypoint.Name), doWaypoint)
RecalculateTimes()
End Sub
Public Overridable Sub RemoveWaypoint(ByVal doWaypoint As Waypoint)
m_aryWaypoints.Remove(doWaypoint.ID)
m_aryWaypointsByName.Remove(CInt(doWaypoint.Name))
RecalculateTimes()
End Sub
Public Overridable Function NextWaypointName() As String
Dim iMaxName As Integer = -1
Dim doWaypoint As Waypoint
For Each deEntry As DictionaryEntry In m_aryWaypointsByName
doWaypoint = DirectCast(deEntry.Value, Waypoint)
Dim iName As Integer = CInt(doWaypoint.Name)
If iName > iMaxName Then
iMaxName = iName
End If
Next
iMaxName = iMaxName + 1
Return iMaxName.ToString("D3")
End Function
Public Overridable Sub RecalculateTimes()
Dim dblAccumualted As Double = 0
Dim dblLastStartTime As Double = 0
Dim doWaypoint As Waypoint
Dim doPrevWaypoint As Waypoint
For Each deEntry As DictionaryEntry In m_aryWaypointsByName
doWaypoint = DirectCast(deEntry.Value, Waypoint)
Dim dblStart As Double = Me.StartTime.ActualValue + dblAccumualted
Dim dblEnd As Double = Me.StartTime.ActualValue + dblAccumualted + doWaypoint.TimeSpan.ActualValue
doWaypoint.SetStartEndTime(dblStart, dblEnd)
If Not doPrevWaypoint Is Nothing Then
Dim vDist As Vec3d = doPrevWaypoint.Position.Point - doWaypoint.Position.Point
Dim dblDist As Double = vDist.Magnitude
Dim dblVelocity As Double = dblDist / doPrevWaypoint.TimeSpan.ActualValue
doPrevWaypoint.SetDistanceVelocity(dblDist, dblVelocity)
End If
dblAccumualted = dblAccumualted + doWaypoint.TimeSpan.ActualValue
dblLastStartTime = dblStart
doWaypoint.LastWaypoint = False
doPrevWaypoint = doWaypoint
Next
'Get the last waypoint
If Not doPrevWaypoint Is Nothing Then
doPrevWaypoint.LastWaypoint = True
doPrevWaypoint.SetDistanceVelocity(0, 0)
End If
'The end time for the entire path is actually the start time of the last waypoint.
If m_aryWaypoints.Count > 0 Then
Me.EndTime = New ScaledNumber(Me, "EndTime", dblLastStartTime, ScaledNumber.enumNumericScale.None, "s", "s")
Else
Me.EndTime = New ScaledNumber(Me, "EndTime", Me.StartTime.ActualValue + 1, ScaledNumber.enumNumericScale.None, "s", "s")
End If
If Not Util.ProjectProperties Is Nothing Then
Util.ProjectProperties.RefreshProperties()
End If
End Sub
Public Overrides Sub AddToReplaceIDList(ByVal aryReplaceIDList As ArrayList, ByVal arySelectedItems As ArrayList)
MyBase.AddToReplaceIDList(aryReplaceIDList, arySelectedItems)
m_aryWaypoints.AddToReplaceIDList(aryReplaceIDList, arySelectedItems)
End Sub
Public Overrides Sub AddToRecursiveSelectedItemsList(ByVal arySelectedItems As ArrayList)
MyBase.AddToRecursiveSelectedItemsList(arySelectedItems)
m_aryWaypoints.AddToRecursiveSelectedItemsList(arySelectedItems)
End Sub
Public Overrides Sub InitializeAfterLoad()
MyBase.InitializeAfterLoad()
Dim doChild As AnimatGUI.Framework.DataObject
For Each deEntry As DictionaryEntry In m_aryWaypoints
doChild = DirectCast(deEntry.Value, AnimatGUI.Framework.DataObject)
doChild.InitializeAfterLoad()
Next
Dim bpPart As AnimatGUI.DataObjects.Physical.BodyPart
If (Not Me.LinkedPart Is Nothing AndAlso Me.LinkedPart.BodyPart Is Nothing) AndAlso (m_strLinkedBodyPartID.Length > 0) Then
bpPart = DirectCast(Util.Simulation.FindObjectByID(m_strLinkedBodyPartID), DataObjects.Physical.BodyPart)
If Not bpPart Is Nothing Then
Me.LinkedStructure = New TypeHelpers.LinkedStructureList(bpPart.ParentStructure, TypeHelpers.LinkedStructureList.enumStructureType.All)
Me.LinkedPart = New TypeHelpers.LinkedBodyPartList(bpPart.ParentStructure, bpPart, GetType(AnimatGUI.DataObjects.Physical.BodyPart))
End If
End If
'Do this after settign the body part. Body part structure has precedence
Dim doStruct As AnimatGUI.DataObjects.Physical.PhysicalStructure
If (Not Me.LinkedStructure Is Nothing AndAlso Me.LinkedStructure.PhysicalStructure Is Nothing) AndAlso (m_strLinkedStructureID.Length > 0) Then
doStruct = DirectCast(Util.Simulation.FindObjectByID(m_strLinkedStructureID), DataObjects.Physical.PhysicalStructure)
If Not doStruct Is Nothing Then
Me.LinkedStructure = New TypeHelpers.LinkedStructureList(doStruct, TypeHelpers.LinkedStructureList.enumStructureType.All)
End If
End If
End Sub
Public Overrides Sub Automation_SetLinkedItem(ByVal strItemPath As String, ByVal strLinkedItemPath As String)
Dim tnLinkedNode As Crownwood.DotNetMagic.Controls.Node = Util.FindTreeNodeByPath(strLinkedItemPath, Util.ProjectWorkspace.TreeView.Nodes)
If tnLinkedNode Is Nothing OrElse tnLinkedNode.Tag Is Nothing OrElse Not Util.IsTypeOf(tnLinkedNode.Tag.GetType, GetType(DataObjects.Physical.BodyPart), False) Then
Throw New System.Exception("The path to the specified linked node was not the correct node type.")
End If
Dim bpLinkedPart As DataObjects.Physical.BodyPart = DirectCast(tnLinkedNode.Tag, DataObjects.Physical.BodyPart)
Me.LinkedStructure = New TypeHelpers.LinkedStructureList(bpLinkedPart.ParentStructure, TypeHelpers.LinkedStructureList.enumStructureType.All)
Me.LinkedPart = New TypeHelpers.LinkedBodyPartList(bpLinkedPart.ParentStructure, bpLinkedPart, GetType(AnimatGUI.DataObjects.Physical.BodyPart))
Util.ProjectWorkspace.RefreshProperties()
End Sub
Public Overrides Sub InitializeSimulationReferences(Optional ByVal bShowError As Boolean = True)
'Only do this if not already initialized.
If m_doInterface Is Nothing Then
MyBase.InitializeSimulationReferences(bShowError)
Dim doChild As AnimatGUI.Framework.DataObject
For Each deEntry As DictionaryEntry In m_aryWaypoints
doChild = DirectCast(deEntry.Value, AnimatGUI.Framework.DataObject)
doChild.InitializeSimulationReferences(bShowError)
Next
End If
End Sub
Protected Overridable Sub ConnectLinkedEvents()
DiconnectLinkedEvents()
If Not m_thLinkedStructure Is Nothing AndAlso Not m_thLinkedStructure.PhysicalStructure Is Nothing Then
AddHandler m_thLinkedStructure.PhysicalStructure.AfterRemoveItem, AddressOf Me.OnAfterRemoveLinkedStructure
End If
If Not m_thLinkedPart Is Nothing AndAlso Not m_thLinkedPart.BodyPart Is Nothing Then
AddHandler m_thLinkedPart.BodyPart.AfterRemoveItem, AddressOf Me.OnAfterRemoveLinkedPart
End If
End Sub
Protected Overridable Sub DiconnectLinkedEvents()
If Not m_thLinkedStructure Is Nothing AndAlso Not m_thLinkedStructure.PhysicalStructure Is Nothing Then
RemoveHandler m_thLinkedStructure.PhysicalStructure.AfterRemoveItem, AddressOf Me.OnAfterRemoveLinkedStructure
End If
If Not m_thLinkedPart Is Nothing AndAlso Not m_thLinkedPart.BodyPart Is Nothing Then
RemoveHandler m_thLinkedPart.BodyPart.AfterRemoveItem, AddressOf Me.OnAfterRemoveLinkedPart
End If
End Sub
#Region " Treeview/Menu Methods "
Public Overrides Sub CreateWorkspaceTreeView(ByVal doParent As Framework.DataObject, _
ByVal tnParentNode As Crownwood.DotNetMagic.Controls.Node, _
Optional ByVal bRootObject As Boolean = False)
MyBase.CreateWorkspaceTreeView(doParent, tnParentNode, bRootObject)
Dim doWaypoint As AnimatGUI.DataObjects.Visualization.Waypoint
For Each deEntry As DictionaryEntry In m_aryWaypoints
doWaypoint = DirectCast(deEntry.Value, AnimatGUI.DataObjects.Visualization.Waypoint)
doWaypoint.CreateWorkspaceTreeView(Me, m_tnWorkspaceNode)
Next
End Sub
Public Overrides Function WorkspaceTreeviewPopupMenu(ByRef tnSelectedNode As Crownwood.DotNetMagic.Controls.Node, ByVal ptPoint As Point) As Boolean
If tnSelectedNode Is m_tnWorkspaceNode Then
Dim mcDelete As New System.Windows.Forms.ToolStripMenuItem("Delete Camera Path", Util.Application.ToolStripImages.GetImage("AnimatGUI.Delete.gif"), New EventHandler(AddressOf Util.Application.OnDeleteFromWorkspace))
Dim mcAddWaypoint As New System.Windows.Forms.ToolStripMenuItem("New Waypoint", Util.Application.ToolStripImages.GetImage("AnimatGUI.AddCameraWaypoint.gif"), New EventHandler(AddressOf Me.AddCameraWaypoint))
Dim mcSepExpand As New ToolStripSeparator()
Dim mcExpandAll As New System.Windows.Forms.ToolStripMenuItem("Expand All", Util.Application.ToolStripImages.GetImage("AnimatGUI.Expand.gif"), New EventHandler(AddressOf Me.OnExpandAll))
Dim mcCollapseAll As New System.Windows.Forms.ToolStripMenuItem("Collapse All", Util.Application.ToolStripImages.GetImage("AnimatGUI.Collapse.gif"), New EventHandler(AddressOf Me.OnCollapseAll))
mcExpandAll.Tag = tnSelectedNode
mcCollapseAll.Tag = tnSelectedNode
' Create the popup menu object
Dim popup As New AnimatContextMenuStrip("AnimatGUI.DataObjects.Charting.Axis.WorkspaceTreeviewPopupMenu", Util.SecurityMgr)
popup.Items.AddRange(New System.Windows.Forms.ToolStripItem() {mcDelete, mcAddWaypoint, mcSepExpand, mcExpandAll, mcCollapseAll})
Util.ProjectWorkspace.ctrlTreeView.ContextMenuNode = popup
Return True
End If
Return False
End Function
#End Region
Public Overrides Function Delete(Optional ByVal bAskToDelete As Boolean = True, Optional ByVal e As Crownwood.DotNetMagic.Controls.TGCloseRequestEventArgs = Nothing) As Boolean
Try
If bAskToDelete AndAlso Util.ShowMessage("Are you certain that you want to delete this " & _
"camera path and all its waypoints?", "Delete Node", MessageBoxButtons.YesNo) <> DialogResult.Yes Then
Return False
End If
Util.Application.AppIsBusy = True
If Not m_SimWindow Is Nothing Then
m_SimWindow.CameraPaths.Remove(Me.ID)
Me.RemoveWorksapceTreeView()
End If
Return True
Catch ex As System.Exception
AnimatGUI.Framework.Util.DisplayError(ex)
Finally
Util.Application.AppIsBusy = False
End Try
End Function
Public Overrides Sub LoadData(ByVal oXml As ManagedAnimatInterfaces.IStdXml)
oXml.IntoElem()
Me.Name = oXml.GetChildString("Name")
Me.ID = oXml.GetChildString("ID")
m_strLinkedStructureID = Util.LoadID(oXml, "LinkedStructure", True, "")
m_strLinkedBodyPartID = Util.LoadID(oXml, "LinkedBodyPart", True, "")
m_clLineColor = Util.LoadColor(oXml, "LineColor")
m_snStartTime.LoadData(oXml, "StartTime")
m_snEndTime.LoadData(oXml, "EndTime")
m_bVisible = oXml.GetChildBool("Visible", m_bVisible)
m_bVisibleInSim = oXml.GetChildBool("VisibleInSim", m_bVisibleInSim)
m_bShowWaypoints = oXml.GetChildBool("ShowWaypoints", m_bShowWaypoints)
If oXml.FindChildElement("Waypoints", False) Then
Dim doWaypoint As Waypoint
oXml.IntoElem() 'Into Waypoint Element
Dim iCount As Integer = oXml.NumberOfChildren() - 1
For iIndex As Integer = 0 To iCount
oXml.FindChildByIndex(iIndex)
doWaypoint = New Waypoint(Me)
doWaypoint.LoadData(oXml)
'Do not call the sim add method here. We will need to do that later when the window is created.
AddWaypoint(doWaypoint, False)
Next
oXml.OutOfElem() 'Outof Waypoint Element
End If
oXml.OutOfElem()
RecalculateTimes()
End Sub
Public Overrides Sub SaveData(ByVal oXml As ManagedAnimatInterfaces.IStdXml)
oXml.AddChildElement("CameraPath")
oXml.IntoElem()
oXml.AddChildElement("AssemblyFile", Me.AssemblyFile)
oXml.AddChildElement("ClassName", Me.ClassName)
oXml.AddChildElement("ID", Me.ID)
oXml.AddChildElement("Name", Me.Name)
m_snStartTime.SaveData(oXml, "StartTime")
m_snEndTime.SaveData(oXml, "EndTime")
oXml.AddChildElement("Visible", Me.Visible)
oXml.AddChildElement("VisibleInSim", Me.VisibleInSim)
oXml.AddChildElement("ShowWaypoints", m_bShowWaypoints)
If Not m_thLinkedStructure Is Nothing AndAlso Not m_thLinkedStructure.PhysicalStructure Is Nothing Then
oXml.AddChildElement("LinkedStructureID", m_thLinkedStructure.PhysicalStructure.ID)
End If
If Not m_thLinkedPart Is Nothing AndAlso Not m_thLinkedPart.BodyPart Is Nothing Then
oXml.AddChildElement("LinkedBodyPartID", m_thLinkedPart.BodyPart.ID)
End If
Util.SaveColor(oXml, "LineColor", m_clLineColor)
If m_aryWaypoints.Count > 0 Then
oXml.AddChildElement("Waypoints")
oXml.IntoElem()
Dim doWaypoint As Waypoint
For Each deEntry As DictionaryEntry In m_aryWaypointsByName
doWaypoint = DirectCast(deEntry.Value, AnimatGUI.DataObjects.Visualization.Waypoint)
doWaypoint.SaveData(oXml)
Next
oXml.OutOfElem() 'Outof Waypoints Element
End If
oXml.OutOfElem()
End Sub
Public Overrides Sub SaveSimulationXml(ByVal oXml As ManagedAnimatInterfaces.IStdXml, Optional ByRef nmParentControl As AnimatGUI.Framework.DataObject = Nothing, Optional ByVal strName As String = "")
oXml.AddChildElement("CameraPath")
oXml.IntoElem()
oXml.AddChildElement("ModuleName", Me.ModuleName)
oXml.AddChildElement("Type", Me.Type)
oXml.AddChildElement("Name", m_strName)
oXml.AddChildElement("ID", m_strID)
m_snStartTime.SaveSimulationXml(oXml, Me, "StartTime")
m_snEndTime.SaveSimulationXml(oXml, Me, "EndTime")
oXml.AddChildElement("Visible", Me.Visible)
oXml.AddChildElement("VisibleInSim", Me.VisibleInSim)
oXml.AddChildElement("ShowWaypoints", m_bShowWaypoints)
If Not m_thLinkedStructure Is Nothing AndAlso Not m_thLinkedStructure.PhysicalStructure Is Nothing Then
oXml.AddChildElement("LinkedStructureID", m_thLinkedStructure.PhysicalStructure.ID)
End If
If Not m_thLinkedPart Is Nothing AndAlso Not m_thLinkedPart.BodyPart Is Nothing Then
oXml.AddChildElement("LinkedBodyPartID", m_thLinkedPart.BodyPart.ID)
End If
Util.SaveColor(oXml, "LineColor", m_clLineColor)
If m_aryWaypoints.Count > 0 Then
oXml.AddChildElement("Waypoints")
oXml.IntoElem()
Dim doWaypoint As Waypoint
For Each deEntry As DictionaryEntry In m_aryWaypointsByName
doWaypoint = DirectCast(deEntry.Value, AnimatGUI.DataObjects.Visualization.Waypoint)
doWaypoint.SaveSimulationXml(oXml, Me)
Next
oXml.OutOfElem() 'Outof Waypoints Element
End If
oXml.OutOfElem()
End Sub
#End Region
#Region "Events"
Private Sub OnAfterRemoveLinkedStructure(ByRef doObject As Framework.DataObject)
Try
Me.LinkedStructure = New TypeHelpers.LinkedStructureList(Nothing, TypeHelpers.LinkedStructureList.enumStructureType.All)
Catch ex As Exception
AnimatGUI.Framework.Util.DisplayError(ex)
End Try
End Sub
Private Sub OnAfterRemoveLinkedPart(ByRef doObject As Framework.DataObject)
Try
Me.LinkedPart = New TypeHelpers.LinkedBodyPartList(Me.LinkedStructure.PhysicalStructure, Nothing, GetType(AnimatGUI.DataObjects.Physical.BodyPart))
Catch ex As Exception
AnimatGUI.Framework.Util.DisplayError(ex)
End Try
End Sub
Private Sub AddCameraWaypoint(sender As Object, e As System.EventArgs)
Try
If Not m_SimWindow Is Nothing Then
m_SimWindow.AddWaypointToolStripButton_Click(sender, e)
End If
Catch ex As System.Exception
AnimatGUI.Framework.Util.DisplayError(ex)
End Try
End Sub
#End Region
End Class
End Namespace
|
NeuroRoboticTech/AnimatLabPublicSource
|
Libraries/AnimatGUI/DataObjects/Visualization/CameraPath.vb
|
Visual Basic
|
bsd-3-clause
| 35,182
|
'------------------------------------------------------------------------------
' <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("Samples.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
|
neozhu/WebFormsScaffolding
|
Samples.VB/My Project/Resources.Designer.vb
|
Visual Basic
|
apache-2.0
| 2,713
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.ComponentModel.Composition
Imports System.ComponentModel.Composition.Primitives
Imports Microsoft.VisualStudio.ComponentModelHost
Imports Microsoft.VisualStudio.Composition
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests
Friend NotInheritable Class MockComponentModel
Implements IComponentModel
Private ReadOnly _exportProvider As ExportProvider
Private ReadOnly _providedServices As New Dictionary(Of Type, Object)
Public Sub New(exportProvider As ExportProvider)
_exportProvider = exportProvider
End Sub
#Disable Warning BC40000 ' Type or member is obsolete
Public ReadOnly Property DefaultCatalog As ComposablePartCatalog Implements IComponentModel.DefaultCatalog
Get
Throw New NotImplementedException
End Get
End Property
#Enable Warning BC40000 ' Type or member is obsolete
Public ReadOnly Property DefaultCompositionService As ICompositionService Implements IComponentModel.DefaultCompositionService
Get
Throw New NotImplementedException
End Get
End Property
Public ReadOnly Property DefaultExportProvider As Hosting.ExportProvider Implements IComponentModel.DefaultExportProvider
Get
Return _exportProvider.AsExportProvider()
End Get
End Property
Public Function GetCatalog(catalogName As String) As ComposablePartCatalog Implements IComponentModel.GetCatalog
Throw New NotImplementedException
End Function
Friend Sub ProvideService(Of T)(export As T)
_providedServices.Add(GetType(T), export)
End Sub
Public Function GetExtensions(Of T As Class)() As IEnumerable(Of T) Implements IComponentModel.GetExtensions
Return _exportProvider.GetExportedValues(Of T)()
End Function
Public Function GetService(Of T As Class)() As T Implements IComponentModel.GetService
Dim possibleService As Object = Nothing
If _providedServices.TryGetValue(GetType(T), possibleService) Then
Return DirectCast(possibleService, T)
End If
Return _exportProvider.GetExportedValue(Of T)()
End Function
End Class
End Namespace
|
nguerrera/roslyn
|
src/VisualStudio/TestUtilities2/MockComponentModel.vb
|
Visual Basic
|
apache-2.0
| 2,498
|
' 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.Hosting
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.AutomaticCompletion
Imports Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion
Imports System.Threading.Tasks
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AutomaticCompletion
Public Class AutomaticLessAndGreaterThanCompletionTests
Inherits AbstractAutomaticBraceCompletionTests
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Async Function TestCreation() As Task
Using session = Await CreateSessionAsync("$$")
Assert.NotNull(session)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Async Function TestAttribute_LessThan() As Task
Using session = Await CreateSessionAsync("$$")
Assert.NotNull(session)
CheckStart(session.Session)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Async Function TestInvalidLocation_LessThan() As Task
Using session = Await CreateSessionAsync("Imports System$$")
Assert.NotNull(session)
CheckStart(session.Session, expectValidSession:=False)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Async Function TestInvalidLocation_String() As Task
Dim code = <code>Class C
Dim s As String = "$$
End Class</code>
Using session = Await CreateSessionAsync(code)
Assert.Null(session)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Async Function TestInvalidLocation_Comment() As Task
Dim code = <code>Class C
' $$
End Class</code>
Using session = Await CreateSessionAsync(code)
Assert.Null(session)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Async Function TestInvalidLocation_DocComment() As Task
Dim code = <code>Class C
''' $$
End Class</code>
Using session = Await CreateSessionAsync(code)
Assert.Null(session)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Async Function TestAttribute_LessThan_Method() As Task
Dim code = <code>Class C
Sub Method($$
End Sub
End Class</code>
Using session = Await CreateSessionAsync(code)
Assert.NotNull(session)
CheckStart(session.Session)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Async Function TestXmlNamespaceImport_LessThan() As Task
Dim code = <code>Imports $$</code>
Using session = Await CreateSessionAsync(code)
Assert.NotNull(session)
CheckStart(session.Session)
CheckOverType(session.Session)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Async Function TestBracketName_Member() As Task
Dim code = <code>Class C
Sub Method()
Dim a = <start></start>
a.$$
End Sub
End Class</code>
Using session = Await CreateSessionAsync(code)
Assert.NotNull(session)
CheckStart(session.Session)
End Using
End Function
Friend Overloads Function CreateSessionAsync(code As XElement) As Threading.Tasks.Task(Of Holder)
Return CreateSessionAsync(code.NormalizedValue())
End Function
Friend Overloads Async Function CreateSessionAsync(code As String) As Threading.Tasks.Task(Of Holder)
Return CreateSession(
Await VisualBasicWorkspaceFactory.CreateWorkspaceFromFileAsync(code),
BraceCompletionSessionProvider.LessAndGreaterThan.OpenCharacter, BraceCompletionSessionProvider.LessAndGreaterThan.CloseCharacter)
End Function
End Class
End Namespace
|
mseamari/Stuff
|
src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticLessAndGreaterThanCompletionTests.vb
|
Visual Basic
|
apache-2.0
| 4,815
|
' 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.CompilerServices
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
Friend Module SymbolExtensions
<Extension>
Public Function IsContainingSymbolOfAllTypeParameters(containingSymbol As Symbol, type As TypeSymbol) As Boolean
Return type.VisitType(HasInvalidTypeParameterFunc, containingSymbol) Is Nothing
End Function
Private ReadOnly HasInvalidTypeParameterFunc As Func(Of TypeSymbol, Symbol, Boolean) = AddressOf HasInvalidTypeParameter
Private Function HasInvalidTypeParameter(type As TypeSymbol, containingSymbol As Symbol) As Boolean
If type.TypeKind = TypeKind.TypeParameter Then
Dim symbol = type.ContainingSymbol
While containingSymbol IsNot Nothing AndAlso containingSymbol.Kind <> SymbolKind.Namespace
If containingSymbol = symbol Then
Return False
End If
containingSymbol = containingSymbol.ContainingSymbol
End While
Return True
End If
Return False
End Function
''' <summary>
''' In VB, the type parameters of state machine classes (i.e. for implementing async
''' or iterator methods) are mangled. We unmangle them here so that the unmangled
''' names will bind properly. (Code gen only uses the ordinal, so the name shouldn't
''' affect behavior).
''' </summary>
<Extension>
Public Function GetUnmangledName(sourceTypeParameter As TypeParameterSymbol) As String
Dim sourceName = sourceTypeParameter.Name
If sourceName.StartsWith(StringConstants.StateMachineTypeParameterPrefix, StringComparison.Ordinal) Then
Debug.Assert(sourceTypeParameter.ContainingSymbol.Name.
StartsWith(StringConstants.StateMachineTypeNamePrefix, StringComparison.Ordinal))
Debug.Assert(sourceName.Length > StringConstants.StateMachineTypeParameterPrefix.Length)
Return sourceName.Substring(StringConstants.StateMachineTypeParameterPrefix.Length)
End If
Return sourceName
End Function
<Extension>
Friend Function IsClosureOrStateMachineType(type As TypeSymbol) As Boolean
Return type.IsClosureType() OrElse type.IsStateMachineType()
End Function
<Extension>
Friend Function IsClosureType(type As TypeSymbol) As Boolean
Return type.Name.StartsWith(StringConstants.DisplayClassPrefix, StringComparison.Ordinal)
End Function
<Extension>
Friend Function IsStateMachineType(type As TypeSymbol) As Boolean
Return type.Name.StartsWith(StringConstants.StateMachineTypeNamePrefix, StringComparison.Ordinal)
End Function
<Extension>
Friend Function GetAllTypeParameters(method As MethodSymbol) As ImmutableArray(Of TypeParameterSymbol)
Dim builder = ArrayBuilder(Of TypeParameterSymbol).GetInstance()
method.ContainingType.GetAllTypeParameters(builder)
builder.AddRange(method.TypeParameters)
Return builder.ToImmutableAndFree()
End Function
End Module
End Namespace
|
mono/roslyn
|
src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/SymbolExtensions.vb
|
Visual Basic
|
apache-2.0
| 3,571
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.IO
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
Imports Microsoft.VisualStudio.LanguageServices.Implementation.TaskList
Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework
Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.VisualBasicHelpers
Imports Microsoft.VisualStudio.Shell.Interop
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim
Public Class DeferredProjectLoadingTests
<Fact>
<Trait(Traits.Feature, Traits.Features.ProjectSystemShims)>
Sub SimpleDeferredLoading()
Using testEnvironment = New TestEnvironment(solutionIsFullyLoaded:=False)
CreateVisualBasicProject(testEnvironment, "TestProject")
' We should not yet have pushed this project to the workspace
Assert.Empty(testEnvironment.Workspace.CurrentSolution.Projects)
testEnvironment.NotifySolutionAsFullyLoaded()
Assert.Single(testEnvironment.Workspace.CurrentSolution.Projects)
End Using
End Sub
<Fact, WorkItem(1094112)>
<Trait(Traits.Feature, Traits.Features.ProjectSystemShims)>
Sub DoNotDeferLoadIfInNonBackgroundBatch()
Using testEnvironment = New TestEnvironment(solutionIsFullyLoaded:=False)
testEnvironment.GetSolutionLoadEvents().OnBeforeLoadProjectBatch(fIsBackgroundIdleBatch:=False)
CreateVisualBasicProject(testEnvironment, "TestProject")
testEnvironment.GetSolutionLoadEvents().OnAfterLoadProjectBatch(fIsBackgroundIdleBatch:=False)
' We should have pushed this project to the workspace
Assert.Single(testEnvironment.Workspace.CurrentSolution.Projects)
' This should (in theory) do nothing
testEnvironment.NotifySolutionAsFullyLoaded()
Assert.Single(testEnvironment.Workspace.CurrentSolution.Projects)
End Using
End Sub
<Fact, WorkItem(1094112)>
<Trait(Traits.Feature, Traits.Features.ProjectSystemShims)>
Sub AddingProjectInBatchDoesntAddAllProjects()
Using testEnvironment = New TestEnvironment(solutionIsFullyLoaded:=False)
CreateVisualBasicProject(testEnvironment, "TestProject1")
testEnvironment.GetSolutionLoadEvents().OnBeforeLoadProjectBatch(fIsBackgroundIdleBatch:=False)
CreateVisualBasicProject(testEnvironment, "TestProject2")
testEnvironment.GetSolutionLoadEvents().OnAfterLoadProjectBatch(fIsBackgroundIdleBatch:=False)
' We should have pushed the second project only
Assert.Equal("TestProject2", testEnvironment.Workspace.CurrentSolution.Projects.Single().Name)
' This pushes the other project too
testEnvironment.NotifySolutionAsFullyLoaded()
Assert.Equal(2, testEnvironment.Workspace.CurrentSolution.Projects.Count())
End Using
End Sub
<Fact, WorkItem(1094112)>
<Trait(Traits.Feature, Traits.Features.ProjectSystemShims)>
Sub AddingProjectReferenceInBatchMayPushOtherProjects()
Using testEnvironment = New TestEnvironment(solutionIsFullyLoaded:=False)
Dim project1 = CreateVisualBasicProject(testEnvironment, "TestProject1")
' Include a project reference in this batch. This means that project1 must also be pushed
testEnvironment.GetSolutionLoadEvents().OnBeforeLoadProjectBatch(fIsBackgroundIdleBatch:=False)
Dim project2 = CreateVisualBasicProject(testEnvironment, "TestProject2")
project2.AddProjectReference(project1)
testEnvironment.GetSolutionLoadEvents().OnAfterLoadProjectBatch(fIsBackgroundIdleBatch:=False)
' We should have pushed both projects
Assert.Equal(2, testEnvironment.Workspace.CurrentSolution.Projects.Count())
End Using
End Sub
<Fact, WorkItem(1094112)>
<Trait(Traits.Feature, Traits.Features.ProjectSystemShims)>
Sub AddingProjectReferenceAfterBatchMayPushOtherProjects()
Using testEnvironment = New TestEnvironment(solutionIsFullyLoaded:=False)
Dim project1 = CreateVisualBasicProject(testEnvironment, "TestProject1")
' Include a project reference in this batch. This means that project1 must also be pushed
testEnvironment.GetSolutionLoadEvents().OnBeforeLoadProjectBatch(fIsBackgroundIdleBatch:=False)
Dim project2 = CreateVisualBasicProject(testEnvironment, "TestProject2")
testEnvironment.GetSolutionLoadEvents().OnAfterLoadProjectBatch(fIsBackgroundIdleBatch:=False)
' We should have pushed the second project only
Assert.Equal("TestProject2", testEnvironment.Workspace.CurrentSolution.Projects.Single().Name)
project2.AddProjectReference(project1)
' We should have pushed both projects
Assert.Equal(2, testEnvironment.Workspace.CurrentSolution.Projects.Count())
End Using
End Sub
End Class
End Namespace
|
DavidKarlas/roslyn
|
src/VisualStudio/Core/Test/ProjectSystemShim/DeferredProjectLoadingTests.vb
|
Visual Basic
|
apache-2.0
| 5,578
|
' 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 Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend NotInheritable Class Rewriter
Public Shared Function LowerBodyOrInitializer(
method As MethodSymbol,
methodOrdinal As Integer,
body As BoundBlock,
previousSubmissionFields As SynthesizedSubmissionFields,
compilationState As TypeCompilationState,
diagnostics As DiagnosticBag,
ByRef lambdaOrdinalDispenser As Integer,
ByRef scopeOrdinalDispenser As Integer,
ByRef delegateRelaxationIdDispenser As Integer,
<Out> ByRef stateMachineTypeOpt As StateMachineTypeSymbol,
<Out> ByRef variableSlotAllocatorOpt As VariableSlotAllocator,
allowOmissionOfConditionalCalls As Boolean,
isBodySynthesized As Boolean) As BoundBlock
Debug.Assert(Not body.HasErrors)
' performs node-specific lowering.
Dim sawLambdas As Boolean
Dim symbolsCapturedWithoutCopyCtor As ISet(Of Symbol) = Nothing
Dim rewrittenNodes As HashSet(Of BoundNode) = Nothing
Dim flags = If(allowOmissionOfConditionalCalls, LocalRewriter.RewritingFlags.AllowOmissionOfConditionalCalls, LocalRewriter.RewritingFlags.Default)
Dim loweredBody = LocalRewriter.Rewrite(body,
method,
compilationState,
previousSubmissionFields,
diagnostics,
rewrittenNodes,
sawLambdas,
symbolsCapturedWithoutCopyCtor,
flags,
currentMethod:=Nothing)
If loweredBody.HasErrors Then
Return loweredBody
End If
#If DEBUG Then
For Each node In rewrittenNodes.ToArray
If node.Kind = BoundKind.Literal Then
rewrittenNodes.Remove(node)
End If
Next
#End If
' Lowers lambda expressions into expressions that construct delegates.
Dim bodyWithoutLambdas = loweredBody
If sawLambdas Then
bodyWithoutLambdas = LambdaRewriter.Rewrite(loweredBody,
method,
methodOrdinal,
lambdaOrdinalDispenser,
scopeOrdinalDispenser,
delegateRelaxationIdDispenser,
variableSlotAllocatorOpt,
compilationState,
If(symbolsCapturedWithoutCopyCtor, SpecializedCollections.EmptySet(Of Symbol)),
diagnostics,
rewrittenNodes)
End If
If bodyWithoutLambdas.HasErrors Then
Return bodyWithoutLambdas
End If
If compilationState.ModuleBuilderOpt IsNot Nothing Then
variableSlotAllocatorOpt = compilationState.ModuleBuilderOpt.TryCreateVariableSlotAllocator(method)
End If
Return RewriteIteratorAndAsync(bodyWithoutLambdas, method, methodOrdinal, compilationState, diagnostics, variableSlotAllocatorOpt, stateMachineTypeOpt)
End Function
Friend Shared Function RewriteIteratorAndAsync(bodyWithoutLambdas As BoundBlock,
method As MethodSymbol,
methodOrdinal As Integer,
compilationState As TypeCompilationState,
diagnostics As DiagnosticBag,
slotAllocatorOpt As VariableSlotAllocator,
<Out> ByRef stateMachineTypeOpt As StateMachineTypeSymbol) As BoundBlock
Dim iteratorStateMachine As IteratorStateMachine = Nothing
Dim bodyWithoutIterators = IteratorRewriter.Rewrite(bodyWithoutLambdas,
method,
methodOrdinal,
slotAllocatorOpt,
compilationState,
diagnostics,
iteratorStateMachine)
If bodyWithoutIterators.HasErrors Then
Return bodyWithoutIterators
End If
Dim asyncStateMachine As AsyncStateMachine = Nothing
Dim bodyWithoutAsync = AsyncRewriter.Rewrite(bodyWithoutIterators,
method,
methodOrdinal,
slotAllocatorOpt,
compilationState,
diagnostics,
asyncStateMachine)
Debug.Assert(iteratorStateMachine Is Nothing OrElse asyncStateMachine Is Nothing)
stateMachineTypeOpt = If(iteratorStateMachine, DirectCast(asyncStateMachine, StateMachineTypeSymbol))
Return bodyWithoutAsync
End Function
End Class
End Namespace
|
DavidKarlas/roslyn
|
src/Compilers/VisualBasic/Portable/Lowering/Rewriter.vb
|
Visual Basic
|
apache-2.0
| 6,459
|
' Licensed to the .NET Foundation under one or more 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.UnitTests.IntelliSense
<[UseExportProvider]>
Public Class CSharpCompletionCommandHandlerTests_XmlDoc
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitSummary(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("summ")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendReturn()
Await state.AssertNoCompletionSession()
Await state.AssertLineTextAroundCaret(" /// summary", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitSummaryOnTab(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("summ")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTab()
Await state.AssertNoCompletionSession()
' /// summary$$
Await state.AssertLineTextAroundCaret(" /// summary", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitSummaryOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("summ")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// summary>$$
Await state.AssertLineTextAroundCaret(" /// summary>", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitSummary(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("summ")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendReturn()
Await state.AssertNoCompletionSession()
' /// <summary$$
Await state.AssertLineTextAroundCaret(" /// <summary", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitSummaryOnTab(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("summ")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTab()
Await state.AssertNoCompletionSession()
' /// <summary$$
Await state.AssertLineTextAroundCaret(" /// <summary", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitSummaryOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("summ")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// <summary>$$
Await state.AssertLineTextAroundCaret(" /// <summary>", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitRemarksOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("rema")
Await state.AssertSelectedCompletionItem(displayText:="remarks")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// remarks>$$
Await state.AssertLineTextAroundCaret(" /// remarks>", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitRemarksOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("rema")
Await state.AssertSelectedCompletionItem(displayText:="remarks")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// <remarks>$$
Await state.AssertLineTextAroundCaret(" /// <remarks>", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitReturnsOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
int goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("retur")
Await state.AssertSelectedCompletionItem(displayText:="returns")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// returns>$$
Await state.AssertLineTextAroundCaret(" /// returns>", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitReturnsOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
int goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("retur")
Await state.AssertSelectedCompletionItem(displayText:="returns")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// <returns>$$
Await state.AssertLineTextAroundCaret(" /// <returns>", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitExampleOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("examp")
Await state.AssertSelectedCompletionItem(displayText:="example")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// example>$$
Await state.AssertLineTextAroundCaret(" /// example>", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitExampleOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("examp")
Await state.AssertSelectedCompletionItem(displayText:="example")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// <example>$$
Await state.AssertLineTextAroundCaret(" /// <example>", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitExceptionNoOpenAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("except")
Await state.AssertSelectedCompletionItem(displayText:="exception")
state.SendReturn()
Await state.AssertNoCompletionSession()
' /// <exception cref="$$"
Await state.AssertLineTextAroundCaret(" /// <exception cref=""", """")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitExceptionOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("except")
Await state.AssertSelectedCompletionItem(displayText:="exception")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// <exception cref=">$$"
Await state.AssertLineTextAroundCaret(" /// <exception cref="">", """")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitCommentNoOpenAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendSelectCompletionItem("!--")
state.SendReturn()
Await state.AssertNoCompletionSession()
' /// <!--$$-->
Await state.AssertLineTextAroundCaret(" /// <!--", "-->")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitCommentOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendSelectCompletionItem("!--")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// <!-->$$-->
Await state.AssertLineTextAroundCaret(" /// <!-->", "-->")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitCdataNoOpenAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("![CDAT")
Await state.AssertSelectedCompletionItem(displayText:="![CDATA[")
state.SendReturn()
Await state.AssertNoCompletionSession()
' /// <![CDATA[$$]]>
Await state.AssertLineTextAroundCaret(" /// <![CDATA[", "]]>")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitCdataOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("![CDAT")
Await state.AssertSelectedCompletionItem(displayText:="![CDATA[")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// <![CDATA[>$$]]>
Await state.AssertLineTextAroundCaret(" /// <![CDATA[>", "]]>")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitIncludeNoOpenAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("inclu")
Await state.AssertSelectedCompletionItem(displayText:="include")
state.SendReturn()
Await state.AssertNoCompletionSession()
' /// <include file='$$' path='[@name=""]'/>
Await state.AssertLineTextAroundCaret(" /// <include file='", "' path='[@name=""""]'/>")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitIncludeOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("inclu")
Await state.AssertSelectedCompletionItem(displayText:="include")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// <include file='>$$' path='[@name=""]'/>
Await state.AssertLineTextAroundCaret(" /// <include file='>", "' path='[@name=""""]'/>")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitPermissionNoOpenAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("permiss")
Await state.AssertSelectedCompletionItem(displayText:="permission")
state.SendReturn()
Await state.AssertNoCompletionSession()
' /// <permission cref="$$"
Await state.AssertLineTextAroundCaret(" /// <permission cref=""", """")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitPermissionOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("permiss")
Await state.AssertSelectedCompletionItem(displayText:="permission")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// <permission cref=">$$"
Await state.AssertLineTextAroundCaret(" /// <permission cref="">", """")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitSeeNoOpenAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("see")
Await state.AssertSelectedCompletionItem(displayText:="see")
state.SendReturn()
Await state.AssertNoCompletionSession()
' /// <see cref="$$"/>
Await state.AssertLineTextAroundCaret(" /// <see cref=""", """/>")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitSeeOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("see")
Await state.AssertSelectedCompletionItem(displayText:="see")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// <see cref=">$$"/>
Await state.AssertLineTextAroundCaret(" /// <see cref="">", """/>")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(22789, "https://github.com/dotnet/roslyn/issues/22789")>
Public Async Function InvokeWithOpenAngleCommitSeeOnTab(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("se")
Await state.AssertSelectedCompletionItem(displayText:="see")
state.SendTab()
Await state.AssertNoCompletionSession()
' /// <see cref="$$"/>
Await state.AssertLineTextAroundCaret(" /// <see cref=""", """/>")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitSeeOnSpace(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// <summary>
/// $$
/// </summary>
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("see")
Await state.AssertSelectedCompletionItem(displayText:="see")
state.SendTypeChars(" ")
' /// <see cref="$$"/>
Await state.AssertLineTextAroundCaret(" /// <see cref=""", """/>")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithNullKeywordCommitSeeLangword(showCompletionInArgumentLists As Boolean) As Task
Return InvokeWithKeywordCommitSeeLangword("null", showCompletionInArgumentLists)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithStaticKeywordCommitSeeLangword(showCompletionInArgumentLists As Boolean) As Task
Return InvokeWithKeywordCommitSeeLangword("static", showCompletionInArgumentLists)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithVirtualKeywordCommitSeeLangword(showCompletionInArgumentLists As Boolean) As Task
Return InvokeWithKeywordCommitSeeLangword("virtual", showCompletionInArgumentLists)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithTrueKeywordCommitSeeLangword(showCompletionInArgumentLists As Boolean) As Task
Return InvokeWithKeywordCommitSeeLangword("true", showCompletionInArgumentLists)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithFalseKeywordCommitSeeLangword(showCompletionInArgumentLists As Boolean) As Task
Return InvokeWithKeywordCommitSeeLangword("false", showCompletionInArgumentLists)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithAbstractKeywordCommitSeeLangword(showCompletionInArgumentLists As Boolean) As Task
Return InvokeWithKeywordCommitSeeLangword("abstract", showCompletionInArgumentLists)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithSealedKeywordCommitSeeLangword(showCompletionInArgumentLists As Boolean) As Task
Return InvokeWithKeywordCommitSeeLangword("sealed", showCompletionInArgumentLists)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithAsyncKeywordCommitSeeLangword(showCompletionInArgumentLists As Boolean) As Task
Return InvokeWithKeywordCommitSeeLangword("async", showCompletionInArgumentLists)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithAwaitKeywordCommitSeeLangword(showCompletionInArgumentLists As Boolean) As Task
Return InvokeWithKeywordCommitSeeLangword("await", showCompletionInArgumentLists)
End Function
Private Shared Async Function InvokeWithKeywordCommitSeeLangword(keyword As String, showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// <summary>
/// $$
/// </summary>
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
' Omit the last letter of the keyword to make it easier to diagnose failures (inserted the wrong text,
' or did not insert text at all).
state.SendTypeChars(keyword.Substring(0, keyword.Length - 1))
state.SendInvokeCompletionList()
Await state.SendCommitUniqueCompletionListItemAsync()
Await state.AssertNoCompletionSession()
' /// <see langword="keyword"/>$$
Await state.AssertLineTextAroundCaret(" /// <see langword=""" + keyword + """/>", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitSeealsoNoOpenAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("seeal")
Await state.AssertSelectedCompletionItem(displayText:="seealso")
state.SendReturn()
Await state.AssertNoCompletionSession()
' /// <seealso cref="$$"/>
Await state.AssertLineTextAroundCaret(" /// <seealso cref=""", """/>")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitSeealsoOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// $$
void goo() { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("seeal")
Await state.AssertSelectedCompletionItem(displayText:="seealso")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// <seealso cref=">$$"/>
Await state.AssertLineTextAroundCaret(" /// <seealso cref="">", """/>")
End Using
End Function
<WorkItem(623219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/623219")>
<WorkItem(746919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/746919")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitParam(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c<T>
{
/// <param$$
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendReturn()
Await state.AssertNoCompletionSession()
' /// <param name="bar"$$
Await state.AssertLineTextAroundCaret(" /// <param name=""bar""", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitParam_Record(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
/// <param$$
record R(int I);
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="param name=""I""")
state.SendReturn()
Await state.AssertNoCompletionSession()
' /// <param name="I"$$
Await state.AssertLineTextAroundCaret("/// <param name=""I""", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitParamNoOpenAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c<T>
{
/// $$
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("param")
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendReturn()
Await state.AssertNoCompletionSession()
' /// param name="bar"$$
Await state.AssertLineTextAroundCaret(" /// param name=""bar""", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitParamNoOpenAngleOnTab(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c<T>
{
/// $$
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("param")
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendTab()
Await state.AssertNoCompletionSession()
' /// param name="bar"$$
Await state.AssertLineTextAroundCaret(" /// param name=""bar""", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitParamNoOpenAngleOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c<T>
{
/// $$
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("param")
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// param name="bar">$$
Await state.AssertLineTextAroundCaret(" /// param name=""bar"">", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitParam(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c<T>
{
/// $$
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("param")
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendReturn()
Await state.AssertNoCompletionSession()
' /// <param name="bar"$$
Await state.AssertLineTextAroundCaret(" /// <param name=""bar""", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitParamOnTab(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c<T>
{
/// $$
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("param")
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendTab()
Await state.AssertNoCompletionSession()
' /// <param name="bar"$$
Await state.AssertLineTextAroundCaret(" /// <param name=""bar""", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitParamOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c<T>
{
/// $$
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("param")
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// <param name="bar">$$
Await state.AssertLineTextAroundCaret(" /// <param name=""bar"">", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitTypeparamNoOpenAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c<T>
{
/// $$
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("typepara")
Await state.AssertSelectedCompletionItem(displayText:="typeparam name=""T""")
state.SendReturn()
Await state.AssertNoCompletionSession()
' /// typeparam name="T"$$
Await state.AssertLineTextAroundCaret(" /// typeparam name=""T""", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitTypeparamNoOpenAngleOnTab(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c<T>
{
/// $$
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("typepara")
Await state.AssertSelectedCompletionItem(displayText:="typeparam name=""T""")
state.SendTab()
Await state.AssertNoCompletionSession()
' /// typeparam name="T"$$
Await state.AssertLineTextAroundCaret(" /// typeparam name=""T""", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitTypeparamNoOpenAngleOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c<T>
{
/// $$
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("typepara")
Await state.AssertSelectedCompletionItem(displayText:="typeparam name=""T""")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// typeparam name="T">$$
Await state.AssertLineTextAroundCaret(" /// typeparam name=""T"">", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitTypeparam(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c<T>
{
/// $$
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("typepara")
Await state.AssertSelectedCompletionItem(displayText:="typeparam name=""T""")
state.SendReturn()
Await state.AssertNoCompletionSession()
' /// <typeparam name="T"$$
Await state.AssertLineTextAroundCaret(" /// <typeparam name=""T""", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitTypeparamOnTab(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c<T>
{
/// $$
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("typepara")
Await state.AssertSelectedCompletionItem(displayText:="typeparam name=""T""")
state.SendTab()
Await state.AssertNoCompletionSession()
' /// <typeparam name="T"$$
Await state.AssertLineTextAroundCaret(" /// <typeparam name=""T""", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitTypeparamOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c<T>
{
/// $$
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("typepara")
Await state.AssertSelectedCompletionItem(displayText:="typeparam name=""T""")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// <typeparam name="T">$$
Await state.AssertLineTextAroundCaret(" /// <typeparam name=""T"">", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitList(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c<T>
{
/// <summary>
/// $$
/// </summary>
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("lis")
Await state.AssertSelectedCompletionItem(displayText:="list")
state.SendReturn()
Await state.AssertNoCompletionSession()
' /// <list type="$$"
Await state.AssertLineTextAroundCaret(" /// <list type=""", """")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitListOnCloseAngle(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c<T>
{
/// <summary>
/// $$
/// </summary>
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("lis")
Await state.AssertSelectedCompletionItem(displayText:="list")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// <list type=">$$"
Await state.AssertLineTextAroundCaret(" /// <list type="">", """")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestTagCompletion1(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c<T>
{
/// <$$
/// </summary>
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("summa")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// <summary>$$
Await state.AssertLineTextAroundCaret(" /// <summary>", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestTagCompletion2(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c<T>
{
/// <$$
/// <remarks></remarks>
/// </summary>
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("summa")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// <summary>$$
Await state.AssertLineTextAroundCaret(" /// <summary>", "")
End Using
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestTagCompletion3(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c<T>
{
/// <$$
/// <remarks>
/// </summary>
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("summa")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' /// <summary>$$
Await state.AssertLineTextAroundCaret(" /// <summary>", "")
End Using
End Function
<WorkItem(638653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638653")>
<WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/21481"), CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function AllowTypingDoubleQuote(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// <param$$
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendTypeChars(" name=""")
' /// <param name="$$
Await state.AssertLineTextAroundCaret(" /// <param name=""", "")
' Because the item contains a double quote, the completionImplementation list should still be present with the same selection
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
End Using
End Function
<WorkItem(638653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638653")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function AllowTypingSpace(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateCSharpTestState(
<Document><![CDATA[
class c
{
/// <param$$
void goo<T>(T bar) { }
}
]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendTypeChars(" ")
' /// <param $$
Await state.AssertLineTextAroundCaret(" /// <param ", "")
' Because the item contains a space, the completionImplementation list should still be present with the same selection
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
End Using
End Function
<WorkItem(44472, "https://github.com/dotnet/roslyn/issues/44472")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithAliasAndImportedNamespace(showCompletionInArgumentLists As Boolean) As Task
Using state = TestStateFactory.CreateTestStateFromWorkspace(
<Workspace>
<Project Language="C#" AssemblyName="Assembly1" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Text;
namespace First.NestedA
{
public class MyClass
{
}
}
</Document>
<Document>
using First.NestedA;
using MyClassLongDescription = First.NestedA.MyClass;
namespace Second.NestedB
{
class OtherClass
{
/// <summary>
/// This is from <see cref="MyClassL$$"/>
/// </summary>
public void Method()
{
}
}
}
</Document>
</Project>
</Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="MyClassLongDescription")
state.SendTab()
Await state.AssertNoCompletionSession()
Await state.AssertLineTextAroundCaret(" /// This is from <see cref=""MyClassLongDescription", """/>")
End Using
End Function
End Class
End Namespace
|
CyrusNajmabadi/roslyn
|
src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_XmlDoc.vb
|
Visual Basic
|
mit
| 52,474
|
' Licensed to the .NET Foundation under one or more 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.OptionStatements
Public Class OptionKeywordRecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OptionInBlankFileTest()
VerifyRecommendationsContain(<File>|</File>, "Option")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OptionAfterAnotherOptionStatementTest()
VerifyRecommendationsContain(<File>
Option Strict On
|</File>, "Option")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OptionAfterBlankLineTest()
VerifyRecommendationsContain(<File>
Option Strict On
|</File>, "Option")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OptionNotAfterImportsTest()
VerifyRecommendationsMissing(<File>
Imports Goo
|</File>, "Option")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OptionNotAfterTypeTest()
VerifyRecommendationsMissing(<File>
Class Goo
End Class
|</File>, "Option")
End Sub
<WorkItem(543008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543008")>
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OptionNotAfterRegionKeywordTest()
VerifyRecommendationsMissing(<File>
#Region |
</File>, "Option")
End Sub
End Class
End Namespace
|
ErikSchierboom/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/OptionStatements/OptionKeywordRecommenderTests.vb
|
Visual Basic
|
apache-2.0
| 1,845
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend Module DiagnosticBagExtensions
''' <summary>
''' Add a diagnostic to the bag.
''' </summary>
''' <param name = "diagnostics"></param>
''' <param name = "code"></param>
''' <param name = "location"></param>
''' <returns></returns>
<System.Runtime.CompilerServices.Extension()>
Friend Function Add(diagnostics As DiagnosticBag, code As ERRID, location As Location) As DiagnosticInfo
Dim info = ErrorFactory.ErrorInfo(code)
Dim diag = New VBDiagnostic(info, location)
diagnostics.Add(diag)
Return info
End Function
''' <summary>
''' Add a diagnostic to the bag.
''' </summary>
''' <param name = "diagnostics"></param>
''' <param name = "code"></param>
''' <param name = "location"></param>
''' <param name = "args"></param>
''' <returns></returns>
<System.Runtime.CompilerServices.Extension()>
Friend Function Add(diagnostics As DiagnosticBag, code As ERRID, location As Location, ParamArray args As Object()) As DiagnosticInfo
Dim info = ErrorFactory.ErrorInfo(code, args)
Dim diag = New VBDiagnostic(info, location)
diagnostics.Add(diag)
Return info
End Function
<System.Runtime.CompilerServices.Extension()>
Friend Sub Add(diagnostics As DiagnosticBag, info As DiagnosticInfo, location As Location)
Dim diag = New VBDiagnostic(info, location)
diagnostics.Add(diag)
End Sub
''' <summary>
''' Appends diagnostics from useSiteDiagnostics into diagnostics and returns True if there were any errors.
''' </summary>
<System.Runtime.CompilerServices.Extension()>
Friend Function Add(
diagnostics As DiagnosticBag,
node As VisualBasicSyntaxNode,
useSiteDiagnostics As IReadOnlyCollection(Of DiagnosticInfo)
) As Boolean
Return Not useSiteDiagnostics.IsNullOrEmpty AndAlso diagnostics.Add(node.GetLocation, useSiteDiagnostics)
End Function
<System.Runtime.CompilerServices.Extension()>
Friend Function Add(
diagnostics As DiagnosticBag,
node As BoundNode,
useSiteDiagnostics As IReadOnlyCollection(Of DiagnosticInfo)
) As Boolean
Return Not useSiteDiagnostics.IsNullOrEmpty AndAlso diagnostics.Add(node.Syntax.GetLocation, useSiteDiagnostics)
End Function
<System.Runtime.CompilerServices.Extension()>
Friend Function Add(
diagnostics As DiagnosticBag,
node As SyntaxNodeOrToken,
useSiteDiagnostics As IReadOnlyCollection(Of DiagnosticInfo)
) As Boolean
Return Not useSiteDiagnostics.IsNullOrEmpty AndAlso diagnostics.Add(node.GetLocation, useSiteDiagnostics)
End Function
<System.Runtime.CompilerServices.Extension()>
Friend Function Add(
diagnostics As DiagnosticBag,
location As Location,
useSiteDiagnostics As IReadOnlyCollection(Of DiagnosticInfo)
) As Boolean
If useSiteDiagnostics.IsNullOrEmpty Then
Return False
End If
For Each info In useSiteDiagnostics
Debug.Assert(info.Severity = DiagnosticSeverity.Error)
Dim diag As New VBDiagnostic(info, location)
diagnostics.Add(diag)
Next
Return True
End Function
End Module
End Namespace
|
shyamnamboodiripad/roslyn
|
src/Compilers/VisualBasic/Portable/Errors/DiagnosticBagExtensions.vb
|
Visual Basic
|
apache-2.0
| 4,104
|
' 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.Shared.Options
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.LineCommit
<[UseExportProvider]>
Public Class CommitOnMiscellaneousCommandsTests
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub TestCommitOnMultiLinePaste()
Using testData = CommitTestData.Create(<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>$$
</Document>
</Project>
</Workspace>)
testData.CommandHandler.ExecuteCommand(New PasteCommandArgs(testData.View, testData.Buffer),
Sub() testData.EditorOperations.InsertText(" imports system" & vbCrLf & " imports system.text"),
TestCommandExecutionContext.Create())
Assert.Equal("Imports System", testData.Buffer.CurrentSnapshot.GetLineFromLineNumber(0).GetText())
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
<WorkItem(14391, "https://github.com/dotnet/roslyn/issues/14391")>
Public Sub TestCommitLineWithTupleType()
Using testData = CommitTestData.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Public Class C
Shared Sub Main()
Dim t As (In$$)
End Sub
Shared Sub Int()
End Sub
End Class
</Document>
</Project>
</Workspace>)
testData.CommandHandler.ExecuteCommand(New PasteCommandArgs(testData.View, testData.Buffer),
Sub() testData.EditorOperations.InsertText("t"),
TestCommandExecutionContext.Create())
testData.CommandHandler.ExecuteCommand(New SaveCommandArgs(testData.View, testData.Buffer),
Sub() Exit Sub,
TestCommandExecutionContext.Create())
testData.AssertHadCommit(True)
' The code cleanup should not add parens after the Int, so no exception.
End Using
End Sub
<WpfFact>
<WorkItem(1944, "https://github.com/dotnet/roslyn/issues/1944")>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub TestDontCommitOnMultiLinePasteWithPrettyListingOff()
Using testData = CommitTestData.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>$$
</Document>
</Project>
</Workspace>)
testData.Workspace.Options = testData.Workspace.Options.WithChangedOption(FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic, False)
testData.CommandHandler.ExecuteCommand(New PasteCommandArgs(testData.View, testData.Buffer),
Sub() testData.EditorOperations.InsertText("Class Program" & vbCrLf & " Sub M(abc As Integer)" & vbCrLf & " Dim a = 7" & vbCrLf & " End Sub" & vbCrLf & "End Class"),
TestCommandExecutionContext.Create())
Assert.Equal(" Dim a = 7", testData.Buffer.CurrentSnapshot.GetLineFromLineNumber(2).GetText())
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
<WorkItem(545493, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545493")>
Public Sub TestNoCommitOnSingleLinePaste()
Using testData = CommitTestData.Create(<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>$$
</Document>
</Project>
</Workspace>)
testData.CommandHandler.ExecuteCommand(New PasteCommandArgs(testData.View, testData.Buffer),
Sub() testData.EditorOperations.InsertText(" imports system"),
TestCommandExecutionContext.Create())
Assert.Equal(" imports system", testData.Buffer.CurrentSnapshot.GetLineFromLineNumber(0).GetText())
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub TestCommitOnSave()
Using testData = CommitTestData.Create(<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>$$
</Document>
</Project>
</Workspace>)
testData.Buffer.Insert(0, " imports system")
testData.CommandHandler.ExecuteCommand(New SaveCommandArgs(testData.View, testData.Buffer), Sub() Exit Sub, TestCommandExecutionContext.Create())
Assert.Equal("Imports System", testData.Buffer.CurrentSnapshot.GetLineFromLineNumber(0).GetText())
End Using
End Sub
<WpfFact, WorkItem(1944, "https://github.com/dotnet/roslyn/issues/1944")>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub TestDontCommitOnSavePrettyListingOff()
Using testData = CommitTestData.Create(<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Program
Sub M(abc As Integer)
Dim a $$= 7
End Sub
End Class
</Document>
</Project>
</Workspace>)
testData.Workspace.Options = testData.Workspace.Options.WithChangedOption(FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic, False)
testData.Buffer.Insert(57, " ")
testData.CommandHandler.ExecuteCommand(New SaveCommandArgs(testData.View, testData.Buffer), Sub() Exit Sub, TestCommandExecutionContext.Create())
Assert.Equal(" Dim a = 7", testData.Buffer.CurrentSnapshot.GetLineFromLineNumber(3).GetText())
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Formatting)>
<WorkItem(545493, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545493")>
Public Sub TestPerformAddMissingTokenOnFormatDocument()
Using testData = CommitTestData.Create(<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>$$Module Program
Sub Main()
goo
End Sub
Private Sub goo()
End Sub
End Module
</Document>
</Project>
</Workspace>)
testData.CommandHandler.ExecuteCommand(New FormatDocumentCommandArgs(testData.View, testData.Buffer), Sub() Exit Sub, TestCommandExecutionContext.Create())
Assert.Equal(" goo()", testData.Buffer.CurrentSnapshot.GetLineFromLineNumber(2).GetText())
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Formatting)>
<WorkItem(867153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/867153")>
Public Sub TestFormatDocumentWithPrettyListingDisabled()
Using testData = CommitTestData.Create(<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Program
$$Sub Main()
goo
End Sub
End Module
</Document>
</Project>
</Workspace>)
' Turn off pretty listing
testData.Workspace.Options = testData.Workspace.Options.WithChangedOption(FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic, False)
testData.CommandHandler.ExecuteCommand(New FormatDocumentCommandArgs(testData.View, testData.Buffer), Sub() Exit Sub, TestCommandExecutionContext.Create())
Assert.Equal(" Sub Main()", testData.Buffer.CurrentSnapshot.GetLineFromLineNumber(1).GetText())
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub TestDoNotCommitWithUnterminatedString()
Using testData = CommitTestData.Create(<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>Module Module1
Sub Main()
$$
End Sub
Sub SomeUnrelatedCode()
Console.WriteLine("<a>")
End Sub
End Module</Document>
</Project>
</Workspace>)
testData.CommandHandler.ExecuteCommand(New PasteCommandArgs(testData.View, testData.Buffer),
Sub() testData.EditorOperations.InsertText("Console.WriteLine(""Hello World"),
TestCommandExecutionContext.Create())
Assert.Equal(testData.Buffer.CurrentSnapshot.GetText(),
<Document>Module Module1
Sub Main()
Console.WriteLine("Hello World
End Sub
Sub SomeUnrelatedCode()
Console.WriteLine("<a>")
End Sub
End Module</Document>.NormalizedValue)
End Using
End Sub
End Class
End Namespace
|
OmarTawfik/roslyn
|
src/EditorFeatures/VisualBasicTest/LineCommit/CommitOnMiscellaneousCommandsTests.vb
|
Visual Basic
|
apache-2.0
| 11,367
|
' Licensed to the .NET Foundation under one or more 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.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports System.Threading
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Extensions
Public Class StatementSyntaxExtensionTests
Private Shared Sub TestStatementDeclarationWithPublicModifier(Of T As StatementSyntax)(node As T)
Dim modifierList = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
Dim newNode = DirectCast(node.WithModifiers(modifierList), T)
Dim actual = newNode.GetModifiers().First().ToString()
Assert.Equal("Public", actual)
End Sub
Private Shared Sub VerifyTokenName(Of T As DeclarationStatementSyntax)(code As String, expectedName As String)
Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of T).First()
Dim actualNameToken = node.GetNameToken()
Assert.Equal(expectedName, actualNameToken.ToString())
End Sub
<Fact>
Public Sub MethodReturnType()
Dim methodDeclaration = SyntaxFactory.FunctionStatement(attributeLists:=Nothing,
modifiers:=Nothing,
identifier:=SyntaxFactory.Identifier("F1"),
typeParameterList:=Nothing,
parameterList:=Nothing,
asClause:=SyntaxFactory.SimpleAsClause(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntegerKeyword))),
handlesClause:=Nothing,
implementsClause:=Nothing)
Assert.True(methodDeclaration.HasReturnType())
Dim result = methodDeclaration.GetReturnType()
Dim returnTypeName = result.ToString()
Assert.Equal("Integer", returnTypeName)
End Sub
<Fact>
Public Sub PropertyReturnType()
Dim propertyDeclaration = SyntaxFactory.PropertyStatement(attributeLists:=Nothing,
modifiers:=Nothing,
identifier:=SyntaxFactory.Identifier("P1"),
parameterList:=Nothing,
asClause:=SyntaxFactory.SimpleAsClause(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ByteKeyword))),
initializer:=Nothing,
implementsClause:=Nothing)
Assert.True(propertyDeclaration.HasReturnType())
Dim result = propertyDeclaration.GetReturnType()
Dim returnTypeName = result.ToString()
Assert.Equal("Byte", returnTypeName)
End Sub
Private Shared Sub TestTypeBlockWithPublicModifier(Of T As TypeBlockSyntax)(code As String)
Dim node = SyntaxFactory.ParseCompilationUnit(code).Members.First()
Dim modifierList = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
Dim newNode = DirectCast(node.WithModifiers(modifierList), T)
Dim actual = newNode.GetModifiers().First().ToString()
Assert.Equal("Public", actual)
End Sub
<Fact>
Public Sub GetClassStatementModifiers()
Dim code = <String>Public Class C</String>.Value
Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of ClassStatementSyntax).First()
Dim actualModifierName = node.Modifiers().First().ToString()
Assert.Equal("Public", actualModifierName)
End Sub
<Fact>
Public Sub GetEnumStatementModifiers()
Dim code = <String>Public Enum E</String>.Value
Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of EnumStatementSyntax).First()
Dim actualModifierName = node.Modifiers().First().ToString()
Assert.Equal("Public", actualModifierName)
End Sub
<Fact>
Public Sub InterfaceBlockWithPublicModifier()
Dim code = <String>Interface I
End Interface</String>.Value
TestTypeBlockWithPublicModifier(Of InterfaceBlockSyntax)(code)
End Sub
<Fact>
Public Sub ModuleBlockWithPublicModifier()
Dim code = <String>Module M
End Module</String>.Value
TestTypeBlockWithPublicModifier(Of ModuleBlockSyntax)(code)
End Sub
<Fact>
Public Sub StructureBlockWithPublicModifier()
Dim code = <string>Structure S
End Structure</string>.Value
TestTypeBlockWithPublicModifier(Of StructureBlockSyntax)(code)
End Sub
<Fact>
Public Sub EnumBlockWithPublicModifier()
Dim code = <String>Enum E
End Enum</String>.Value
Dim node = DirectCast(SyntaxFactory.ParseCompilationUnit(code).Members.First(), EnumBlockSyntax)
TestStatementDeclarationWithPublicModifier(node)
End Sub
<Fact>
Public Sub ClassStatementWithPublicModifier()
Dim node = SyntaxFactory.ClassStatement(SyntaxFactory.Identifier("C"))
TestStatementDeclarationWithPublicModifier(node)
End Sub
<Fact>
Public Sub EnumStatementWithPublicModifier()
Dim node = SyntaxFactory.EnumStatement(SyntaxFactory.Identifier("E"))
TestStatementDeclarationWithPublicModifier(node)
End Sub
<Fact>
Public Sub FieldDeclarationWithPublicModifier()
Dim code = <String>Class C
dim _field as Integer = 1
End Class</String>.Value
Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of FieldDeclarationSyntax).First()
TestStatementDeclarationWithPublicModifier(node)
End Sub
<Fact>
Public Sub EventBlockWithPublicModifier()
Dim code = <String>Custom Event E As EventHandler
End Event</String>.Value
Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of EventBlockSyntax).First()
TestStatementDeclarationWithPublicModifier(node)
End Sub
<Fact>
Public Sub EventStatementWithPublicModifier()
Dim node = SyntaxFactory.EventStatement(SyntaxFactory.Identifier("E"))
TestStatementDeclarationWithPublicModifier(node)
End Sub
<Fact>
Public Sub PropertyBlockWithPublicModifier()
Dim code = <String>Property P as Integer
End Property</String>.Value
Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of PropertyBlockSyntax).First()
TestStatementDeclarationWithPublicModifier(node)
End Sub
<Fact>
Public Sub SubBlockWithPublicModifier()
Dim code = <String>Sub Goo
End Sub</String>.Value
Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of MethodBlockSyntax).First()
TestStatementDeclarationWithPublicModifier(node)
End Sub
<Fact>
Public Sub VerifyClassNameToken()
Dim code = <String>Class C
End Class</String>.Value
VerifyTokenName(Of ClassBlockSyntax)(code, "C")
End Sub
<Fact>
Public Sub VerifyInterfaceNameToken()
Dim code = <String>Interface I
End Interface</String>.Value
VerifyTokenName(Of InterfaceBlockSyntax)(code, "I")
End Sub
<Fact>
Public Sub VerifyStructureNameToken()
Dim code = <String>Structure S
End Structure</String>.Value
VerifyTokenName(Of StructureBlockSyntax)(code, "S")
End Sub
<Fact>
Public Sub VerifyModuleNameToken()
Dim code = <String>Module M
End Module</String>.Value
VerifyTokenName(Of ModuleBlockSyntax)(code, "M")
End Sub
<Fact>
Public Sub VerifyStructureStatementNameToken()
Dim code = <String>Structure SS
</String>.Value
VerifyTokenName(Of StructureStatementSyntax)(code, "SS")
End Sub
<Fact>
Public Sub VerifyConstructorNameTokenIsNothing()
Dim code = <String>Class C
Sub New()
End Class</String>.Value
VerifyTokenName(Of SubNewStatementSyntax)(code, "")
End Sub
<Fact, WorkItem(552823, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552823")>
Public Sub TestIsInStatementBlockOfKindForBrokenCode()
Dim code = <String>End Sub
End Module
End Namespace
d</String>.Value
Dim tree = SyntaxFactory.ParseSyntaxTree(code)
Dim token = tree.GetRoot() _
.DescendantTokens() _
.Where(Function(t) t.Kind = SyntaxKind.NamespaceKeyword) _
.First()
For position = token.SpanStart To token.Span.End
Dim targetToken = tree.GetTargetToken(position, CancellationToken.None)
tree.IsInStatementBlockOfKind(position, targetToken, CancellationToken.None)
Next
End Sub
End Class
End Namespace
|
physhi/roslyn
|
src/EditorFeatures/VisualBasicTest/Extensions/StatementSyntaxExtensionTests.vb
|
Visual Basic
|
apache-2.0
| 9,836
|
' 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
Imports System.Linq
Imports System.Threading
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.Shared.Extensions
Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities
''' <summary>
''' Helper class to analyze the semantic effects of a speculated syntax node replacement on the parenting nodes.
''' Given an expression node from a syntax tree and a new expression from a different syntax tree,
''' it replaces the expression with the new expression to create a speculated syntax tree.
''' It uses the original tree's semantic model to create a speculative semantic model and verifies that
''' the syntax replacement doesn't break the semantics of any parenting nodes of the original expression.
''' </summary>
Friend Class SpeculationAnalyzer
Inherits AbstractSpeculationAnalyzer(Of SyntaxNode, ExpressionSyntax, TypeSyntax, AttributeSyntax,
ArgumentSyntax, ForEachStatementSyntax, ThrowStatementSyntax, SemanticModel, Conversion)
''' <summary>
''' Creates a semantic analyzer for speculative syntax replacement.
''' </summary>
''' <param name="expression">Original expression to be replaced.</param>
''' <param name="newExpression">New expression to replace the original expression.</param>
''' <param name="semanticModel">Semantic model of <paramref name="expression"/> node's syntax tree.</param>
''' <param name="cancellationToken">Cancellation token.</param>
''' <param name="skipVerificationForReplacedNode">
''' True if semantic analysis should be skipped for the replaced node and performed starting from parent of the original and replaced nodes.
''' This could be the case when custom verifications are required to be done by the caller or
''' semantics of the replaced expression are different from the original expression.
''' </param>
''' <param name="failOnOverloadResolutionFailuresInOriginalCode">
''' True if semantic analysis should fail when any of the invocation expression ancestors of <paramref name="expression"/> in original code has overload resolution failures.
''' </param>
Public Sub New(expression As ExpressionSyntax, newExpression As ExpressionSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken, Optional skipVerificationForReplacedNode As Boolean = False, Optional failOnOverloadResolutionFailuresInOriginalCode As Boolean = False)
MyBase.New(expression, newExpression, semanticModel, cancellationToken, skipVerificationForReplacedNode, failOnOverloadResolutionFailuresInOriginalCode)
End Sub
Protected Overrides Function GetSemanticRootForSpeculation(expression As ExpressionSyntax) As SyntaxNode
Debug.Assert(expression IsNot Nothing)
Dim parentNodeToSpeculate = expression _
.AncestorsAndSelf(ascendOutOfTrivia:=False) _
.Where(Function(node) CanSpeculateOnNode(node)) _
.LastOrDefault()
If parentNodeToSpeculate Is Nothing Then
parentNodeToSpeculate = expression
End If
Return parentNodeToSpeculate
End Function
Public Shared Function CanSpeculateOnNode(node As SyntaxNode) As Boolean
Return TypeOf node Is ExecutableStatementSyntax OrElse
TypeOf node Is TypeSyntax OrElse
node.Kind = SyntaxKind.Attribute OrElse
node.Kind = SyntaxKind.EqualsValue OrElse
node.Kind = SyntaxKind.AsNewClause OrElse
node.Kind = SyntaxKind.RangeArgument
End Function
Protected Overrides Function GetSemanticRootOfReplacedExpression(semanticRootOfOriginalExpr As SyntaxNode, annotatedReplacedExpression As ExpressionSyntax) As SyntaxNode
Dim originalExpression = Me.OriginalExpression
' Speculation is not supported for AsNewClauseSyntax nodes.
' Generate an EqualsValueSyntax node with the inner NewExpression of the AsNewClauseSyntax node for speculation.
If semanticRootOfOriginalExpr.Kind = SyntaxKind.AsNewClause Then
' Because the original expression will change identity in the newly generated EqualsValueSyntax node,
' we annotate it here to allow us to get back to it after replace.
Dim originalExprAnnotation = New SyntaxAnnotation()
Dim annotatedOriginalExpression = originalExpression.WithAdditionalAnnotations(originalExprAnnotation)
semanticRootOfOriginalExpr = semanticRootOfOriginalExpr.ReplaceNode(originalExpression, annotatedOriginalExpression)
Dim asNewClauseNode = DirectCast(semanticRootOfOriginalExpr, AsNewClauseSyntax)
semanticRootOfOriginalExpr = SyntaxFactory.EqualsValue(asNewClauseNode.NewExpression)
semanticRootOfOriginalExpr = asNewClauseNode.CopyAnnotationsTo(semanticRootOfOriginalExpr)
originalExpression = DirectCast(semanticRootOfOriginalExpr.GetAnnotatedNodesAndTokens(originalExprAnnotation).Single().AsNode(), ExpressionSyntax)
End If
Return semanticRootOfOriginalExpr.ReplaceNode(originalExpression, annotatedReplacedExpression)
End Function
Protected Overrides Sub ValidateSpeculativeSemanticModel(speculativeSemanticModel As SemanticModel, nodeToSpeculate As SyntaxNode)
Debug.Assert(speculativeSemanticModel IsNot Nothing OrElse
TypeOf nodeToSpeculate Is ExpressionSyntax OrElse
Me.SemanticRootOfOriginalExpression.GetAncestors().Any(Function(node) node.IsKind(SyntaxKind.IncompleteMember)),
"SemanticModel.TryGetSpeculativeSemanticModel() API returned false.")
End Sub
Protected Overrides Function CreateSpeculativeSemanticModel(originalNode As SyntaxNode, nodeToSpeculate As SyntaxNode, semanticModel As SemanticModel) As SemanticModel
Return CreateSpeculativeSemanticModelForNode(originalNode, nodeToSpeculate, semanticModel)
End Function
Public Shared Function CreateSpeculativeSemanticModelForNode(originalNode As SyntaxNode, nodeToSpeculate As SyntaxNode, semanticModel As SemanticModel) As SemanticModel
Dim position = originalNode.SpanStart
Dim isInNamespaceOrTypeContext = SyntaxFacts.IsInNamespaceOrTypeContext(TryCast(originalNode, ExpressionSyntax))
Return CreateSpeculativeSemanticModelForNode(nodeToSpeculate, semanticModel, position, isInNamespaceOrTypeContext)
End Function
Public Shared Function CreateSpeculativeSemanticModelForNode(nodeToSpeculate As SyntaxNode, semanticModel As SemanticModel, position As Integer, isInNamespaceOrTypeContext As Boolean) As SemanticModel
If semanticModel.IsSpeculativeSemanticModel Then
' Chaining speculative model Not supported, speculate off the original model.
Debug.Assert(semanticModel.ParentModel IsNot Nothing)
Debug.Assert(Not semanticModel.ParentModel.IsSpeculativeSemanticModel)
position = semanticModel.OriginalPositionForSpeculation
semanticModel = semanticModel.ParentModel
End If
Dim speculativeModel As SemanticModel = Nothing
Dim statementNode = TryCast(nodeToSpeculate, ExecutableStatementSyntax)
If statementNode IsNot Nothing Then
semanticModel.TryGetSpeculativeSemanticModel(position, statementNode, speculativeModel)
Return speculativeModel
End If
Dim type = TryCast(nodeToSpeculate, TypeSyntax)
If type IsNot Nothing Then
Dim bindingOption = If(isInNamespaceOrTypeContext,
SpeculativeBindingOption.BindAsTypeOrNamespace,
SpeculativeBindingOption.BindAsExpression)
semanticModel.TryGetSpeculativeSemanticModel(position, type, speculativeModel, bindingOption)
Return speculativeModel
End If
Select Case nodeToSpeculate.Kind
Case SyntaxKind.Attribute
semanticModel.TryGetSpeculativeSemanticModel(position, DirectCast(nodeToSpeculate, AttributeSyntax), speculativeModel)
Return speculativeModel
Case SyntaxKind.EqualsValue
semanticModel.TryGetSpeculativeSemanticModel(position, DirectCast(nodeToSpeculate, EqualsValueSyntax), speculativeModel)
Return speculativeModel
Case SyntaxKind.RangeArgument
semanticModel.TryGetSpeculativeSemanticModel(position, DirectCast(nodeToSpeculate, RangeArgumentSyntax), speculativeModel)
Return speculativeModel
End Select
' CONSIDER: Do we care about this case?
Debug.Assert(TypeOf nodeToSpeculate Is ExpressionSyntax)
Return Nothing
End Function
#Region "Semantic comparison helpers"
Private Function QuerySymbolsAreCompatible(originalNode As CollectionRangeVariableSyntax, newNode As CollectionRangeVariableSyntax) As Boolean
Debug.Assert(originalNode IsNot Nothing)
Debug.Assert(Me.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalNode))
Debug.Assert(newNode IsNot Nothing)
Debug.Assert(Me.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newNode))
Dim originalSymbolInfo = Me.OriginalSemanticModel.GetCollectionRangeVariableSymbolInfo(originalNode)
Dim newSymbolInfo = Me.SpeculativeSemanticModel.GetCollectionRangeVariableSymbolInfo(newNode)
Return SymbolInfosAreCompatible(originalSymbolInfo, newSymbolInfo)
End Function
Private Function QuerySymbolsAreCompatible(originalNode As AggregateClauseSyntax, newNode As AggregateClauseSyntax) As Boolean
Debug.Assert(originalNode IsNot Nothing)
Debug.Assert(Me.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalNode))
Debug.Assert(newNode IsNot Nothing)
Debug.Assert(Me.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newNode))
Dim originalSymbolInfo = Me.OriginalSemanticModel.GetAggregateClauseSymbolInfo(originalNode)
Dim newSymbolInfo = Me.SpeculativeSemanticModel.GetAggregateClauseSymbolInfo(newNode)
Return SymbolInfosAreCompatible(originalSymbolInfo, newSymbolInfo)
End Function
Private Function QuerySymbolsAreCompatible(originalNode As ExpressionRangeVariableSyntax, newNode As ExpressionRangeVariableSyntax) As Boolean
Debug.Assert(originalNode IsNot Nothing)
Debug.Assert(Me.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalNode))
Debug.Assert(newNode IsNot Nothing)
Debug.Assert(Me.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newNode))
Dim originalSymbolInfo = Me.OriginalSemanticModel.GetSymbolInfo(originalNode)
Dim newSymbolInfo = Me.SpeculativeSemanticModel.GetSymbolInfo(newNode)
Return SymbolInfosAreCompatible(originalSymbolInfo, newSymbolInfo)
End Function
Private Function QuerySymbolsAreCompatible(originalNode As OrderingSyntax, newNode As OrderingSyntax) As Boolean
Debug.Assert(originalNode IsNot Nothing)
Debug.Assert(Me.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalNode))
Debug.Assert(newNode IsNot Nothing)
Debug.Assert(Me.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newNode))
Dim originalSymbolInfo = Me.OriginalSemanticModel.GetSymbolInfo(originalNode)
Dim newSymbolInfo = Me.SpeculativeSemanticModel.GetSymbolInfo(newNode)
Return SymbolInfosAreCompatible(originalSymbolInfo, newSymbolInfo)
End Function
Private Function QuerySymbolsAreCompatible(originalNode As QueryClauseSyntax, newNode As QueryClauseSyntax) As Boolean
Debug.Assert(originalNode IsNot Nothing)
Debug.Assert(Me.SemanticRootOfOriginalExpression.DescendantNodesAndSelf().Contains(originalNode))
Debug.Assert(newNode IsNot Nothing)
Debug.Assert(Me.SemanticRootOfReplacedExpression.DescendantNodesAndSelf().Contains(newNode))
Dim originalSymbolInfo = Me.OriginalSemanticModel.GetSymbolInfo(originalNode)
Dim newSymbolInfo = Me.SpeculativeSemanticModel.GetSymbolInfo(newNode)
Return SymbolInfosAreCompatible(originalSymbolInfo, newSymbolInfo)
End Function
Private Overloads Function SymbolInfosAreCompatible(originalSymbolInfo As CollectionRangeVariableSymbolInfo, newSymbolInfo As CollectionRangeVariableSymbolInfo) As Boolean
Return SymbolInfosAreCompatible(originalSymbolInfo.ToQueryableCollectionConversion, newSymbolInfo.ToQueryableCollectionConversion) AndAlso
SymbolInfosAreCompatible(originalSymbolInfo.AsClauseConversion, newSymbolInfo.AsClauseConversion) AndAlso
SymbolInfosAreCompatible(originalSymbolInfo.SelectMany, newSymbolInfo.SelectMany)
End Function
Private Overloads Function SymbolInfosAreCompatible(originalSymbolInfo As AggregateClauseSymbolInfo, newSymbolInfo As AggregateClauseSymbolInfo) As Boolean
Return SymbolInfosAreCompatible(originalSymbolInfo.Select1, newSymbolInfo.Select1) AndAlso
SymbolInfosAreCompatible(originalSymbolInfo.Select2, newSymbolInfo.Select2)
End Function
#End Region
''' <summary>
''' Determines whether performing the syntax replacement in one of the sibling nodes of the given lambda expressions will change the lambda binding semantics.
''' This is done by first determining the lambda parameters whose type differs in the replaced lambda node.
''' For each of these parameters, we find the descendant identifier name nodes in the lambda body and check if semantics of any of the parenting nodes of these
''' identifier nodes have changed in the replaced lambda.
''' </summary>
Public Function ReplacementChangesSemanticsOfUnchangedLambda(originalLambda As ExpressionSyntax, replacedLambda As ExpressionSyntax) As Boolean
originalLambda = originalLambda.WalkDownParentheses()
replacedLambda = replacedLambda.WalkDownParentheses()
Dim originalLambdaBody As SyntaxNode, replacedLambdaBody As SyntaxNode
Dim originalParams As SeparatedSyntaxList(Of ParameterSyntax), replacedParams As SeparatedSyntaxList(Of ParameterSyntax)
Select Case originalLambda.Kind
Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression
Dim originalSingleLineLambda = DirectCast(originalLambda, SingleLineLambdaExpressionSyntax)
Dim replacedSingleLineLambda = DirectCast(replacedLambda, SingleLineLambdaExpressionSyntax)
originalParams = originalSingleLineLambda.SubOrFunctionHeader.ParameterList.Parameters
replacedParams = replacedSingleLineLambda.SubOrFunctionHeader.ParameterList.Parameters
originalLambdaBody = originalSingleLineLambda.Body
replacedLambdaBody = replacedSingleLineLambda.Body
Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression
Dim originalMultiLineLambda = DirectCast(originalLambda, MultiLineLambdaExpressionSyntax)
Dim replacedMultiLineLambda = DirectCast(replacedLambda, MultiLineLambdaExpressionSyntax)
originalParams = originalMultiLineLambda.SubOrFunctionHeader.ParameterList.Parameters
replacedParams = replacedMultiLineLambda.SubOrFunctionHeader.ParameterList.Parameters
originalLambdaBody = originalMultiLineLambda
replacedLambdaBody = replacedMultiLineLambda
Case Else
Throw ExceptionUtilities.UnexpectedValue(originalLambda.Kind)
End Select
Debug.Assert(originalParams.Count = replacedParams.Count)
If Not originalParams.Any() Then
Return False
End If
Dim paramNames = New List(Of String)()
For i As Integer = 0 To originalParams.Count - 1
Dim originalParam = originalParams(i)
Dim replacedParam = replacedParams(i)
If Not HaveSameParameterType(originalParam, replacedParam) Then
paramNames.Add(originalParam.Identifier.Identifier.ValueText)
End If
Next
If Not paramNames.Any() Then
Return False
End If
Dim originalIdentifierNodes = originalLambdaBody _
.DescendantNodes() _
.OfType(Of IdentifierNameSyntax)() _
.Where(Function(node) paramNames.Contains(node.Identifier.ValueText))
If Not originalIdentifierNodes.Any() Then
Return False
End If
Dim replacedIdentifierNodes = replacedLambdaBody _
.DescendantNodes() _
.OfType(Of IdentifierNameSyntax)() _
.Where(Function(node) paramNames.Contains(node.Identifier.ValueText))
Return ReplacementChangesSemanticsForNodes(originalIdentifierNodes, replacedIdentifierNodes, originalLambdaBody, replacedLambdaBody)
End Function
Private Function HaveSameParameterType(originalParam As ParameterSyntax, replacedParam As ParameterSyntax) As Boolean
Dim originalParamType = Me.OriginalSemanticModel.GetDeclaredSymbol(originalParam).Type
Dim replacedParamType = Me.SpeculativeSemanticModel.GetDeclaredSymbol(replacedParam).Type
Return Equals(originalParamType, replacedParamType)
End Function
Private Function ReplacementChangesSemanticsForNodes(
originalIdentifierNodes As IEnumerable(Of IdentifierNameSyntax),
replacedIdentifierNodes As IEnumerable(Of IdentifierNameSyntax),
originalRoot As SyntaxNode,
replacedRoot As SyntaxNode) As Boolean
Debug.Assert(originalIdentifierNodes.Any())
Debug.Assert(originalIdentifierNodes.Count() = replacedIdentifierNodes.Count())
Dim originalChildNodeEnum = originalIdentifierNodes.GetEnumerator()
Dim replacedChildNodeEnum = replacedIdentifierNodes.GetEnumerator()
While originalChildNodeEnum.MoveNext()
replacedChildNodeEnum.MoveNext()
If ReplacementChangesSemantics(originalChildNodeEnum.Current, replacedChildNodeEnum.Current, originalRoot, skipVerificationForCurrentNode:=True) Then
Return True
End If
End While
Return False
End Function
Protected Overrides Function ReplacementChangesSemanticsForNodeLanguageSpecific(currentOriginalNode As SyntaxNode, currentReplacedNode As SyntaxNode, previousOriginalNode As SyntaxNode, previousReplacedNode As SyntaxNode) As Boolean
Debug.Assert(previousOriginalNode Is Nothing OrElse previousOriginalNode.Parent Is currentOriginalNode)
Debug.Assert(previousReplacedNode Is Nothing OrElse previousReplacedNode.Parent Is currentReplacedNode)
If TypeOf currentOriginalNode Is BinaryExpressionSyntax Then
' If replacing the node will result in a broken binary expression, we won't remove it.
Dim originalExpression = DirectCast(currentOriginalNode, BinaryExpressionSyntax)
Dim newExpression = DirectCast(currentReplacedNode, BinaryExpressionSyntax)
If ReplacementBreaksBinaryExpression(originalExpression, newExpression) Then
Return True
End If
Return Not ImplicitConversionsAreCompatible(originalExpression, newExpression)
ElseIf TypeOf currentOriginalNode Is AssignmentStatementSyntax Then
Dim originalAssignmentStatement = DirectCast(currentOriginalNode, AssignmentStatementSyntax)
If SyntaxFacts.IsAssignmentStatementOperatorToken(originalAssignmentStatement.OperatorToken.Kind()) Then
Dim newAssignmentStatement = DirectCast(currentReplacedNode, AssignmentStatementSyntax)
If ReplacementBreaksCompoundAssignment(originalAssignmentStatement.Left, originalAssignmentStatement.Right, newAssignmentStatement.Left, newAssignmentStatement.Right) Then
Return True
End If
End If
ElseIf currentOriginalNode.Kind = SyntaxKind.ConditionalAccessExpression Then
Dim originalExpression = DirectCast(currentOriginalNode, ConditionalAccessExpressionSyntax)
Dim newExpression = DirectCast(currentReplacedNode, ConditionalAccessExpressionSyntax)
Return ReplacementBreaksConditionalAccessExpression(originalExpression, newExpression)
ElseIf currentOriginalNode.Kind = SyntaxKind.VariableDeclarator Then
' Heuristic: If replacing the node will result in changing the type of a local variable
' that is type-inferred, we won't remove it. It's possible to do this analysis, but it's
' very expensive and the benefit to the user is small.
Dim originalDeclarator = DirectCast(currentOriginalNode, VariableDeclaratorSyntax)
Dim newDeclarator = DirectCast(currentReplacedNode, VariableDeclaratorSyntax)
If originalDeclarator.IsTypeInferred(Me.OriginalSemanticModel) AndAlso Not ConvertedTypesAreCompatible(originalDeclarator.Initializer.Value, newDeclarator.Initializer.Value) Then
Return True
End If
Return False
ElseIf currentOriginalNode.Kind = SyntaxKind.CollectionInitializer Then
Return _
previousOriginalNode IsNot Nothing AndAlso
ReplacementBreaksCollectionInitializerAddMethod(DirectCast(previousOriginalNode, ExpressionSyntax), DirectCast(previousReplacedNode, ExpressionSyntax))
ElseIf currentOriginalNode.Kind = SyntaxKind.Interpolation Then
Dim orignalInterpolation = DirectCast(currentOriginalNode, InterpolationSyntax)
Dim newInterpolation = DirectCast(currentReplacedNode, InterpolationSyntax)
Return ReplacementBreaksInterpolation(orignalInterpolation, newInterpolation)
Else
Dim originalCollectionRangeVariableSyntax = TryCast(currentOriginalNode, CollectionRangeVariableSyntax)
If originalCollectionRangeVariableSyntax IsNot Nothing Then
Dim newCollectionRangeVariableSyntax = DirectCast(currentReplacedNode, CollectionRangeVariableSyntax)
Return Not QuerySymbolsAreCompatible(originalCollectionRangeVariableSyntax, newCollectionRangeVariableSyntax)
End If
Dim originalAggregateSyntax = TryCast(currentOriginalNode, AggregateClauseSyntax)
If originalAggregateSyntax IsNot Nothing Then
Dim newAggregateSyntax = DirectCast(currentReplacedNode, AggregateClauseSyntax)
Return Not QuerySymbolsAreCompatible(originalAggregateSyntax, newAggregateSyntax)
End If
Dim originalExprRangeVariableSyntax = TryCast(currentOriginalNode, ExpressionRangeVariableSyntax)
If originalExprRangeVariableSyntax IsNot Nothing Then
Dim newExprRangeVariableSyntax = DirectCast(currentReplacedNode, ExpressionRangeVariableSyntax)
Return Not QuerySymbolsAreCompatible(originalExprRangeVariableSyntax, newExprRangeVariableSyntax)
End If
Dim originalFunctionAggregationSyntax = TryCast(currentOriginalNode, FunctionAggregationSyntax)
If originalFunctionAggregationSyntax IsNot Nothing Then
Dim newFunctionAggregationSyntax = DirectCast(currentReplacedNode, FunctionAggregationSyntax)
Return Not SymbolsAreCompatible(originalFunctionAggregationSyntax, newFunctionAggregationSyntax)
End If
Dim originalOrderingSyntax = TryCast(currentOriginalNode, OrderingSyntax)
If originalOrderingSyntax IsNot Nothing Then
Dim newOrderingSyntax = DirectCast(currentReplacedNode, OrderingSyntax)
Return Not QuerySymbolsAreCompatible(originalOrderingSyntax, newOrderingSyntax)
End If
Dim originalQueryClauseSyntax = TryCast(currentOriginalNode, QueryClauseSyntax)
If originalQueryClauseSyntax IsNot Nothing Then
Dim newQueryClauseSyntax = DirectCast(currentReplacedNode, QueryClauseSyntax)
Return Not QuerySymbolsAreCompatible(originalQueryClauseSyntax, newQueryClauseSyntax)
End If
End If
Return False
End Function
Private Function ReplacementBreaksCollectionInitializerAddMethod(originalInitializer As ExpressionSyntax, newInitializer As ExpressionSyntax) As Boolean
Dim originalSymbol = Me.OriginalSemanticModel.GetCollectionInitializerSymbolInfo(originalInitializer, CancellationToken).Symbol
Dim newSymbol = Me.SpeculativeSemanticModel.GetCollectionInitializerSymbolInfo(newInitializer, CancellationToken).Symbol
Return Not SymbolsAreCompatible(originalSymbol, newSymbol)
End Function
Protected Overrides Function IsForEachTypeInferred(forEachStatement As ForEachStatementSyntax, semanticModel As SemanticModel) As Boolean
Dim forEachControlVariable = TryCast(forEachStatement.ControlVariable, VariableDeclaratorSyntax)
Return forEachControlVariable IsNot Nothing AndAlso forEachControlVariable.IsTypeInferred(Me.OriginalSemanticModel)
End Function
Protected Overrides Function IsInvocableExpression(node As SyntaxNode) As Boolean
If node.IsKind(SyntaxKind.InvocationExpression) OrElse node.IsKind(SyntaxKind.ObjectCreationExpression) Then
Return True
End If
If node.IsKind(SyntaxKind.SimpleMemberAccessExpression) AndAlso
Not node.IsParentKind(SyntaxKind.InvocationExpression) AndAlso
Not node.IsParentKind(SyntaxKind.ObjectCreationExpression) Then
Return True
End If
Return False
End Function
Protected Overrides Function GetReceiver(expression As ExpressionSyntax) As ExpressionSyntax
expression = expression.WalkDownParentheses()
Select Case expression.Kind
Case SyntaxKind.SimpleMemberAccessExpression
Return DirectCast(expression, MemberAccessExpressionSyntax).Expression.WalkDownParentheses()
Case SyntaxKind.InvocationExpression
Dim result = DirectCast(expression, InvocationExpressionSyntax).Expression.WalkDownParentheses()
If result.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then
Return GetReceiver(result)
End If
Return result
Case Else
Return Nothing
End Select
End Function
Protected Overrides Function IsNamedArgument(argument As ArgumentSyntax) As Boolean
Return argument.IsNamed
End Function
Protected Overrides Function GetNamedArgumentIdentifierValueText(argument As ArgumentSyntax) As String
Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText
End Function
Protected Overrides Function GetArguments(expression As ExpressionSyntax) As ImmutableArray(Of ArgumentSyntax)
Dim argumentList = GetArgumentList(expression)
Return If(argumentList IsNot Nothing,
argumentList.Arguments.AsImmutable(),
ImmutableArray.Create(Of ArgumentSyntax)())
End Function
Private Shared Function GetArgumentList(expression As ExpressionSyntax) As ArgumentListSyntax
expression = expression.WalkDownParentheses()
Select Case expression.Kind
Case SyntaxKind.InvocationExpression
Return DirectCast(expression, InvocationExpressionSyntax).ArgumentList
Case SyntaxKind.ObjectCreationExpression
Return DirectCast(expression, ObjectCreationExpressionSyntax).ArgumentList
Case Else
Return Nothing
End Select
End Function
Private Function ReplacementBreaksBinaryExpression(binaryExpression As BinaryExpressionSyntax, newBinaryExpression As BinaryExpressionSyntax) As Boolean
Dim operatorTokenKind = binaryExpression.OperatorToken.Kind
If SyntaxFacts.IsAssignmentStatementOperatorToken(operatorTokenKind) AndAlso
operatorTokenKind <> SyntaxKind.LessThanLessThanEqualsToken AndAlso
operatorTokenKind <> SyntaxKind.GreaterThanGreaterThanEqualsToken AndAlso
ReplacementBreaksCompoundAssignment(binaryExpression.Left, binaryExpression.Right, newBinaryExpression.Left, newBinaryExpression.Right) Then
Return True
End If
Return Not SymbolsAreCompatible(binaryExpression, newBinaryExpression) OrElse
Not TypesAreCompatible(binaryExpression, newBinaryExpression)
End Function
Private Function ReplacementBreaksConditionalAccessExpression(conditionalAccessExpression As ConditionalAccessExpressionSyntax, newConditionalAccessExpression As ConditionalAccessExpressionSyntax) As Boolean
Return _
Not SymbolsAreCompatible(conditionalAccessExpression, newConditionalAccessExpression) OrElse
Not TypesAreCompatible(conditionalAccessExpression, newConditionalAccessExpression) OrElse
Not SymbolsAreCompatible(conditionalAccessExpression.WhenNotNull, newConditionalAccessExpression.WhenNotNull) OrElse
Not TypesAreCompatible(conditionalAccessExpression.WhenNotNull, newConditionalAccessExpression.WhenNotNull)
End Function
Private Function ReplacementBreaksInterpolation(interpolation As InterpolationSyntax, newInterpolation As InterpolationSyntax) As Boolean
Return Not TypesAreCompatible(interpolation.Expression, newInterpolation.Expression)
End Function
Protected Overrides Function GetForEachStatementExpression(forEachStatement As ForEachStatementSyntax) As ExpressionSyntax
Return forEachStatement.Expression
End Function
Protected Overrides Function GetThrowStatementExpression(throwStatement As ThrowStatementSyntax) As ExpressionSyntax
Return throwStatement.Expression
End Function
Protected Overrides Function IsInNamespaceOrTypeContext(node As ExpressionSyntax) As Boolean
Return SyntaxFacts.IsInNamespaceOrTypeContext(node)
End Function
Protected Overrides Function IsParenthesizedExpression(node As SyntaxNode) As Boolean
Return node.IsKind(SyntaxKind.ParenthesizedExpression)
End Function
Protected Overrides Function ConversionsAreCompatible(originalModel As SemanticModel, originalExpression As ExpressionSyntax, newModel As SemanticModel, newExpression As ExpressionSyntax) As Boolean
Return ConversionsAreCompatible(originalModel.GetConversion(originalExpression), newModel.GetConversion(newExpression))
End Function
Protected Overrides Function ConversionsAreCompatible(originalExpression As ExpressionSyntax, originalTargetType As ITypeSymbol, newExpression As ExpressionSyntax, newTargetType As ITypeSymbol) As Boolean
Dim originalConversion As Conversion?
Dim newConversion As Conversion?
Me.GetConversions(originalExpression, originalTargetType, newExpression, newTargetType, originalConversion, newConversion)
If originalConversion Is Nothing OrElse newConversion Is Nothing
Return False
End If
' When Option Strict is not Off and the new expression has a constant value, it's possible that
' there Is a hidden narrowing conversion that will be missed. In that case, use the
' conversion between the type of the new expression and the new target type.
If Me.OriginalSemanticModel.OptionStrict() <> OptionStrict.Off AndAlso
Me.SpeculativeSemanticModel.GetConstantValue(newExpression).HasValue Then
Dim newExpressionType = Me.SpeculativeSemanticModel.GetTypeInfo(newExpression).ConvertedType
newConversion = Me.OriginalSemanticModel.Compilation.ClassifyConversion(newExpressionType, newTargetType)
End If
Return ConversionsAreCompatible(originalConversion.Value, newConversion.Value)
End Function
Private Overloads Function ConversionsAreCompatible(originalConversion As Conversion, newConversion As Conversion) As Boolean
If originalConversion.Exists <> newConversion.Exists OrElse
((Not originalConversion.IsNarrowing) AndAlso newConversion.IsNarrowing) Then
Return False
End If
Dim originalIsUserDefined = originalConversion.IsUserDefined
Dim newIsUserDefined = newConversion.IsUserDefined
If (originalIsUserDefined <> newIsUserDefined) Then
Return False
End If
If (originalIsUserDefined OrElse originalConversion.MethodSymbol IsNot Nothing OrElse newConversion.MethodSymbol IsNot Nothing) Then
Return SymbolsAreCompatible(originalConversion.MethodSymbol, newConversion.MethodSymbol)
End If
Return True
End Function
Protected Overrides Function ForEachConversionsAreCompatible(originalModel As SemanticModel, originalForEach As ForEachStatementSyntax, newModel As SemanticModel, newForEach As ForEachStatementSyntax) As Boolean
Dim originalInfo = originalModel.GetForEachStatementInfo(originalForEach)
Dim newInfo = newModel.GetForEachStatementInfo(newForEach)
Return ConversionsAreCompatible(originalInfo.CurrentConversion, newInfo.CurrentConversion) AndAlso ConversionsAreCompatible(originalInfo.ElementConversion, newInfo.ElementConversion)
End Function
Protected Overrides Sub GetForEachSymbols(model As SemanticModel, forEach As ForEachStatementSyntax, ByRef getEnumeratorMethod As IMethodSymbol, ByRef elementType As ITypeSymbol)
Dim info = model.GetForEachStatementInfo(forEach)
getEnumeratorMethod = info.GetEnumeratorMethod
elementType = info.ElementType
End Sub
Protected Overrides Function IsReferenceConversion(compilation As Compilation, sourceType As ITypeSymbol, targetType As ITypeSymbol) As Boolean
Return compilation.ClassifyConversion(sourceType, targetType).IsReference
End Function
Protected Overrides Function ClassifyConversion(model As SemanticModel, expression As ExpressionSyntax, targetType As ITypeSymbol) As Conversion
Return model.ClassifyConversion(expression, targetType)
End Function
Protected Overrides Function ClassifyConversion(model As SemanticModel, originalType As ITypeSymbol, targetType As ITypeSymbol) As Conversion
Return model.Compilation.ClassifyConversion(originalType, targetType)
End Function
End Class
End Namespace
|
ValentinRueda/roslyn
|
src/Workspaces/VisualBasic/Portable/Utilities/SpeculationAnalyzer.vb
|
Visual Basic
|
apache-2.0
| 36,988
|
Module Module1
Function Factorial(n As Double) As Double
If n < 1 Then
Return 1
End If
Dim result = 1.0
For i = 1 To n
result = result * i
Next
Return result
End Function
Function FirstOption(n As Double) As Double
Return Factorial(2 * n) / (Factorial(n + 1) * Factorial(n))
End Function
Function SecondOption(n As Double) As Double
If n = 0 Then
Return 1
End If
Dim sum = 0
For i = 0 To n - 1
sum = sum + SecondOption(i) * SecondOption((n - 1) - i)
Next
Return sum
End Function
Function ThirdOption(n As Double) As Double
If n = 0 Then
Return 1
End If
Return ((2 * (2 * n - 1)) / (n + 1)) * ThirdOption(n - 1)
End Function
Sub Main()
Const MaxCatalanNumber = 15
Dim initial As DateTime
Dim final As DateTime
Dim ts As TimeSpan
initial = DateTime.Now
For i = 0 To MaxCatalanNumber
Console.WriteLine("CatalanNumber({0}:{1})", i, FirstOption(i))
Next
final = DateTime.Now
ts = final - initial
Console.WriteLine("It took {0}.{1} to execute", ts.Seconds, ts.Milliseconds)
Console.WriteLine()
initial = DateTime.Now
For i = 0 To MaxCatalanNumber
Console.WriteLine("CatalanNumber({0}:{1})", i, SecondOption(i))
Next
final = DateTime.Now
ts = final - initial
Console.WriteLine("It took {0}.{1} to execute", ts.Seconds, ts.Milliseconds)
Console.WriteLine()
initial = DateTime.Now
For i = 0 To MaxCatalanNumber
Console.WriteLine("CatalanNumber({0}:{1})", i, ThirdOption(i))
Next
final = DateTime.Now
ts = final - initial
Console.WriteLine("It took {0}.{1} to execute", ts.Seconds, ts.Milliseconds)
End Sub
End Module
|
ncoe/rosetta
|
Catalan_numbers/Visual Basic .NET/CatalanNumbers/CatalanNumbers/Module1.vb
|
Visual Basic
|
mit
| 1,981
|
Namespace MyEntities
Public Interface ICTCallModel
Property CallId() As Integer
Property CallDate() As DateTime
Property CallerName() As String
Property CallerAddress() As String
Property CallerCity() As String
Property CityId() As Integer
Property Region() As String
Property UtilityType() As String
Property CallBackNumber() As Integer
Property CrossStreet() As String
Property Comments() As String
Property CallType() As String
Property DispatchFlag() As Integer
Property createdByUserId() As Integer
Property lastModifiedByUserId() As Integer
Property CSR() As String
Property createdOnDate() As DateTime
Property lastModifiedOnDate() As DateTime
Property moduleId() As Integer
End Interface
End Namespace
|
dmcdonald11/CallTrackerLite
|
Entities/ICTCallModel.vb
|
Visual Basic
|
mit
| 879
|
Namespace Entities
Public Class HoaDonDTO
Private _maKhamBenh As String
Private _tienKhamThucTe As Integer
Public Property MaKhamBenh As String
Get
Return _maKhamBenh
End Get
Set(value As String)
_maKhamBenh = value
End Set
End Property
Public Property TienKham As Integer
Get
Return _tienKhamThucTe
End Get
Set(value As Integer)
_tienKhamThucTe = value
End Set
End Property
Public Sub New()
End Sub
''' <summary>
''' Lấy dữ liệu từ datarow
''' </summary>
''' <param name="row"></param>
Public Sub New(ByVal row As DataRow)
MaKhamBenh = row.Field(Of String)("makhambenh")
TienKham = row.Field(Of Decimal)("tienkhamthucte")
End Sub
End Class
End Namespace
|
trumpsilver/ScrapTest
|
Entities/HoaDonDTO.vb
|
Visual Basic
|
mit
| 975
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.MenuStrip1 = New System.Windows.Forms.MenuStrip()
Me.mnuFile = New System.Windows.Forms.ToolStripMenuItem()
Me.mnuFileNew = New System.Windows.Forms.ToolStripMenuItem()
Me.mnuFileOpen = New System.Windows.Forms.ToolStripMenuItem()
Me.mnuFileSave = New System.Windows.Forms.ToolStripMenuItem()
Me.mnuFileSaveAs = New System.Windows.Forms.ToolStripMenuItem()
Me.ToolStripSeparator1 = New System.Windows.Forms.ToolStripSeparator()
Me.mnuFileExit = New System.Windows.Forms.ToolStripMenuItem()
Me.mnuHelp = New System.Windows.Forms.ToolStripMenuItem()
Me.mnuHelpAbout = New System.Windows.Forms.ToolStripMenuItem()
Me.txtDocument = New System.Windows.Forms.TextBox()
Me.sfdSaveFile = New System.Windows.Forms.SaveFileDialog()
Me.ofdOpenFile = New System.Windows.Forms.OpenFileDialog()
Me.StatusStrip1 = New System.Windows.Forms.StatusStrip()
Me.stsLabel = New System.Windows.Forms.ToolStripStatusLabel()
Me.MenuStrip1.SuspendLayout()
Me.StatusStrip1.SuspendLayout()
Me.SuspendLayout()
'
'MenuStrip1
'
Me.MenuStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.mnuFile, Me.mnuHelp})
Me.MenuStrip1.Location = New System.Drawing.Point(0, 0)
Me.MenuStrip1.Name = "MenuStrip1"
Me.MenuStrip1.Size = New System.Drawing.Size(710, 28)
Me.MenuStrip1.TabIndex = 0
Me.MenuStrip1.Text = "MenuStrip1"
'
'mnuFile
'
Me.mnuFile.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.mnuFileNew, Me.mnuFileOpen, Me.mnuFileSave, Me.mnuFileSaveAs, Me.ToolStripSeparator1, Me.mnuFileExit})
Me.mnuFile.Name = "mnuFile"
Me.mnuFile.Size = New System.Drawing.Size(44, 24)
Me.mnuFile.Text = "&File"
'
'mnuFileNew
'
Me.mnuFileNew.Name = "mnuFileNew"
Me.mnuFileNew.ShortcutKeys = CType((System.Windows.Forms.Keys.Control Or System.Windows.Forms.Keys.N), System.Windows.Forms.Keys)
Me.mnuFileNew.Size = New System.Drawing.Size(176, 24)
Me.mnuFileNew.Text = "&New"
'
'mnuFileOpen
'
Me.mnuFileOpen.Name = "mnuFileOpen"
Me.mnuFileOpen.ShortcutKeys = CType((System.Windows.Forms.Keys.Control Or System.Windows.Forms.Keys.O), System.Windows.Forms.Keys)
Me.mnuFileOpen.Size = New System.Drawing.Size(176, 24)
Me.mnuFileOpen.Text = "&Open..."
'
'mnuFileSave
'
Me.mnuFileSave.Name = "mnuFileSave"
Me.mnuFileSave.ShortcutKeys = CType((System.Windows.Forms.Keys.Control Or System.Windows.Forms.Keys.S), System.Windows.Forms.Keys)
Me.mnuFileSave.Size = New System.Drawing.Size(176, 24)
Me.mnuFileSave.Text = "&Save"
'
'mnuFileSaveAs
'
Me.mnuFileSaveAs.Name = "mnuFileSaveAs"
Me.mnuFileSaveAs.Size = New System.Drawing.Size(176, 24)
Me.mnuFileSaveAs.Text = "Save &As..."
'
'ToolStripSeparator1
'
Me.ToolStripSeparator1.Name = "ToolStripSeparator1"
Me.ToolStripSeparator1.Size = New System.Drawing.Size(173, 6)
'
'mnuFileExit
'
Me.mnuFileExit.Name = "mnuFileExit"
Me.mnuFileExit.ShortcutKeys = CType((System.Windows.Forms.Keys.Control Or System.Windows.Forms.Keys.Q), System.Windows.Forms.Keys)
Me.mnuFileExit.Size = New System.Drawing.Size(176, 24)
Me.mnuFileExit.Text = "E&xit"
'
'mnuHelp
'
Me.mnuHelp.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.mnuHelpAbout})
Me.mnuHelp.Name = "mnuHelp"
Me.mnuHelp.Size = New System.Drawing.Size(53, 24)
Me.mnuHelp.Text = "&Help"
'
'mnuHelpAbout
'
Me.mnuHelpAbout.Name = "mnuHelpAbout"
Me.mnuHelpAbout.Size = New System.Drawing.Size(152, 24)
Me.mnuHelpAbout.Text = "&About"
'
'txtDocument
'
Me.txtDocument.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.txtDocument.Location = New System.Drawing.Point(13, 32)
Me.txtDocument.Multiline = True
Me.txtDocument.Name = "txtDocument"
Me.txtDocument.ScrollBars = System.Windows.Forms.ScrollBars.Vertical
Me.txtDocument.Size = New System.Drawing.Size(685, 370)
Me.txtDocument.TabIndex = 1
'
'sfdSaveFile
'
Me.sfdSaveFile.Filter = "Text Files (*.txt) | *.txt"
Me.sfdSaveFile.Title = "Save File As"
'
'ofdOpenFile
'
Me.ofdOpenFile.FileName = "OpenFileDialog1"
Me.ofdOpenFile.Filter = "Text Files (*.txt) | *.txt"
Me.ofdOpenFile.Title = "Open File"
'
'StatusStrip1
'
Me.StatusStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.stsLabel})
Me.StatusStrip1.Location = New System.Drawing.Point(0, 405)
Me.StatusStrip1.Name = "StatusStrip1"
Me.StatusStrip1.Size = New System.Drawing.Size(710, 25)
Me.StatusStrip1.TabIndex = 2
Me.StatusStrip1.Text = "StatusStrip1"
'
'stsLabel
'
Me.stsLabel.Name = "stsLabel"
Me.stsLabel.Size = New System.Drawing.Size(352, 20)
Me.stsLabel.Text = "Your document text has not changed since last save."
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(8.0!, 16.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(710, 430)
Me.Controls.Add(Me.StatusStrip1)
Me.Controls.Add(Me.txtDocument)
Me.Controls.Add(Me.MenuStrip1)
Me.MainMenuStrip = Me.MenuStrip1
Me.Name = "Form1"
Me.Text = "Michael Kellar Simple Text Editor"
Me.MenuStrip1.ResumeLayout(False)
Me.MenuStrip1.PerformLayout()
Me.StatusStrip1.ResumeLayout(False)
Me.StatusStrip1.PerformLayout()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents MenuStrip1 As System.Windows.Forms.MenuStrip
Friend WithEvents mnuFile As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents mnuFileNew As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents mnuFileOpen As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents mnuFileSave As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents mnuFileSaveAs As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents ToolStripSeparator1 As System.Windows.Forms.ToolStripSeparator
Friend WithEvents mnuFileExit As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents mnuHelp As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents mnuHelpAbout As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents txtDocument As System.Windows.Forms.TextBox
Friend WithEvents sfdSaveFile As System.Windows.Forms.SaveFileDialog
Friend WithEvents ofdOpenFile As System.Windows.Forms.OpenFileDialog
Friend WithEvents StatusStrip1 As System.Windows.Forms.StatusStrip
Friend WithEvents stsLabel As System.Windows.Forms.ToolStripStatusLabel
End Class
|
Shadorunce/MiniProjects
|
Text Editor/TextEditor/Form1.Designer.vb
|
Visual Basic
|
mit
| 8,518
|
Partial Friend Class Deque(Of T)
#Region "SynchronizedDeque Class"
<Serializable>
Private NotInheritable Class SynchronizedDeque
Inherits Deque(Of T)
Implements IEnumerable
#Region "SynchronziedDeque Members"
#Region "Fields"
Private ReadOnly myDeque As Deque(Of T)
Private ReadOnly myRoot As Object
#End Region
#Region "Construction"
Friend Sub New(deque As Deque(Of T))
If deque Is Nothing Then
Throw New ArgumentNullException("deque")
End If
myDeque = deque
myRoot = deque.SyncRoot
End Sub
#End Region
#Region "Methods"
Friend Overrides Sub Clear()
SyncLock myRoot
myDeque.Clear()
End SyncLock
End Sub
Friend Overrides Function Contains(item As T) As Boolean
SyncLock myRoot
Return myDeque.Contains(item)
End SyncLock
End Function
Friend Overrides Sub PushFront(item As T)
SyncLock myRoot
myDeque.PushFront(item)
End SyncLock
End Sub
Friend Overrides Sub PushBack(item As T)
SyncLock myRoot
myDeque.PushBack(item)
End SyncLock
End Sub
Friend Overrides Function PopFront() As T
SyncLock myRoot
Return myDeque.PopFront()
End SyncLock
End Function
Friend Overrides Function PopBack() As T
SyncLock myRoot
Return myDeque.PopBack()
End SyncLock
End Function
Friend Overrides Function PeekFront() As T
SyncLock myRoot
Return myDeque.PeekFront()
End SyncLock
End Function
Friend Overrides Function PeekBack() As T
SyncLock myRoot
Return myDeque.PeekBack()
End SyncLock
End Function
Friend Overrides Function ToArray() As T()
SyncLock myRoot
Return myDeque.ToArray()
End SyncLock
End Function
Friend Overrides Function Clone() As Object
SyncLock myRoot
Return myDeque.Clone()
End SyncLock
End Function
Friend Overrides Sub CopyTo(array As Array, index As Integer)
SyncLock myRoot
myDeque.CopyTo(array, index)
End SyncLock
End Sub
Friend Overrides Function GetEnumerator() As IEnumerator(Of T)
SyncLock myRoot
Return myDeque.GetEnumerator()
End SyncLock
End Function
#End Region
#Region "Properties"
Friend Overrides ReadOnly Property Count As Integer
Get
SyncLock myRoot
Return myDeque.Count
End SyncLock
End Get
End Property
Friend Overrides ReadOnly Property IsSynchronized As Boolean
Get
Return True
End Get
End Property
#End Region
#End Region
End Class
#End Region
End Class
|
TeamEEDev/EECloud
|
EECloud.Host/Deque/Deque.Synchronized.vb
|
Visual Basic
|
mit
| 3,153
|
Public Class ChartScaleBounds
' Calculates nice-looking values for chart scale bounds and number of intervals
' Final number of intervals will be closest to the requested (optimal) number
' Input parameters
Private _lower_data_bound As Double
Private _upper_data_bound As Double
Private _optimal_num As Integer
' Results
Private _min As Double
Private _max As Double
Private _n As Integer
Private _interval As Double
''' <summary>
''' Constructor
''' </summary>
''' <param name="lower_data_bound">Lower data bound</param>
''' <param name="upper_data_bound">Upper data bound</param>
''' <param name="optimal_num">Optimal number of intervals</param>
Public Sub New(lower_data_bound As Double, upper_data_bound As Double, optimal_num As Integer)
_lower_data_bound = lower_data_bound
_upper_data_bound = upper_data_bound
_optimal_num = optimal_num
Call Calc()
End Sub
''' <summary>
''' Minimum value of data range (input)
''' </summary>
Public Property LowerDataBound As Double
Get
Return _lower_data_bound
End Get
Set(value As Double)
_lower_data_bound = value
Call Calc()
End Set
End Property
''' <summary>
''' Maximum value of data range (input)
''' </summary>
Public Property UpperDataBound As Double
Get
Return _upper_data_bound
End Get
Set(value As Double)
_upper_data_bound = value
Call Calc()
End Set
End Property
''' <summary>
''' Desired number of intervals (input)
''' </summary>
Public Property OptimalN As Integer
Get
Return _optimal_num
End Get
Set(value As Integer)
_optimal_num = value
Call Calc()
End Set
End Property
''' <summary>
''' Lower scale bound (output)
''' </summary>
Public ReadOnly Property Min As Double
Get
Return _min
End Get
End Property
''' <summary>
''' Upper scale bound (output)
''' </summary>
Public ReadOnly Property Max As Double
Get
Return _max
End Get
End Property
''' <summary>
''' Number of intervals (output)
''' </summary>
Public ReadOnly Property N As Integer
Get
Return _n
End Get
End Property
''' <summary>
''' Size of the interval (output)
''' </summary>
Public ReadOnly Property Interval As Double
Get
Return _interval
End Get
End Property
Private Sub Calc()
Dim MinStep, s(4), tmp_num(4), tmp_min(4), tmp_max(4) As Double
MinStep = (_upper_data_bound - _lower_data_bound) / _optimal_num
s(0) = 10 ^ (Math.Ceiling(Math.Log10(MinStep)))
s(1) = 10 ^ (Math.Ceiling(Math.Log10(MinStep))) / 2
s(2) = 10 ^ (Math.Ceiling(Math.Log10(MinStep))) / 4
s(3) = 10 ^ (Math.Ceiling(Math.Log10(MinStep))) / 5
s(4) = 10 ^ (Math.Ceiling(Math.Log10(MinStep))) / 10
For i As Integer = 0 To 4
tmp_min(i) = s(i) * Math.Floor(_lower_data_bound / s(i))
tmp_max(i) = s(i) * Math.Ceiling(_upper_data_bound / s(i))
tmp_num(i) = (tmp_max(i) - tmp_min(i)) / s(i)
Next
Dim best, diff As Integer
best = 0
diff = Math.Abs(_optimal_num - tmp_num(0))
For i As Integer = 1 To 4
If Math.Abs(_optimal_num - tmp_num(i)) < diff Then
diff = Math.Abs(_optimal_num - tmp_num(i))
best = i
ElseIf (Math.Abs(_optimal_num - tmp_num(i)) = diff) And (tmp_num(i) < _optimal_num) Then '// choose smaller number of intevals
diff = Math.Abs(_optimal_num - tmp_num(i))
best = i
End If
Next
_n = tmp_num(best)
_min = tmp_min(best)
_max = tmp_max(best)
_interval = (_max - _min) / _n
End Sub
End Class
|
RiSearcher/VB.Net-snippets
|
ChartScaleClass.vb
|
Visual Basic
|
mit
| 4,070
|
Imports Transporter_AEHF.Objects.EmcFunctions.Math
'Imports NationalInstruments.Analysis.Math
Imports MathNet.Numerics.LinearAlgebra
Imports Keysight.Visa
Imports Ivi.Visa
Imports Transporter_AEHF.Objects.Enumerations
Public Class DataController
'Private CurrentTraceData As Double(,) = New Double(,) {}
Private _tempCalArray As Double(,) = New Double(,) {}
Private _tempAntArray As Double(,) = New Double(,) {}
'Private EMC As Transporter.EMC.Math
Public Sub New()
End Sub
Function GetMarkerValue(ByVal traceNum As Integer, ByVal azrSession As TcpipSession, ByVal azrModel As PumaEnums.AnalyzerModels, ByVal findPeak As Boolean) As String()
Dim valueY As String = ""
Dim valueX As String = ""
Dim localArray(1) As String
Try
If findPeak = True Then
Select Case azrModel
Case PumaEnums.AnalyzerModels.AgilentFieldFox
azrSession.FormattedIO.WriteLine(":CALC:MARK" & traceNum & ":FUNC:MAX")
Case Else
azrSession.FormattedIO.WriteLine(":CALC:MARK" & traceNum & ":MAX")
End Select
End If
azrSession.FormattedIO.WriteLine(":CALC:MARK" & traceNum & ":X?")
valueX = azrSession.FormattedIO.ReadString
azrSession.FormattedIO.WriteLine(":CALC:MARK" & traceNum & ":Y?")
valueY = azrSession.FormattedIO.ReadString
localArray(0) = valueX
localArray(1) = valueY
Catch ex As Exception
MsgBox("error! Unable to grab marker " & traceNum & "value: " & ex.Message)
End Try
Return localArray
End Function
Public Sub SetMarker(ByVal traceNum As Integer, ByVal azrSession As TcpipSession, ByVal azrModel As PumaEnums.AnalyzerModels, ByVal onPeak As Boolean, Optional ByVal freq As String = "")
Try
If onPeak = False Then
Dim centerFreq As String = freq
If azrModel = PumaEnums.AnalyzerModels.AgilentFieldFox Then
azrSession.FormattedIO.WriteLine(":CALC:MARK" & traceNum & ":TRACE " & traceNum)
azrSession.FormattedIO.WriteLine(":CALC:MARK" & traceNum & ":FUNC:MAX")
azrSession.FormattedIO.WriteLine(":CALC:MARK" & traceNum & ":X " & centerFreq)
Else
azrSession.FormattedIO.WriteLine(":CALC:MARK" & traceNum & ":MODE POSITION")
azrSession.FormattedIO.WriteLine(":CALC:MARK" & traceNum & ":TRACE " & traceNum)
azrSession.FormattedIO.WriteLine(":CALC:MARK" & (traceNum) & ":X " & centerFreq)
End If
Else
Select Case azrModel
Case PumaEnums.AnalyzerModels.AgilentFieldFox
azrSession.FormattedIO.WriteLine(":CALC:MARK" & traceNum & ":FUNC:MAX")
Case Else
azrSession.FormattedIO.WriteLine(":CALC:MARK" & traceNum & ":MAX")
End Select
End If
Catch ex As Exception
MsgBox("Unable to set up marker: " & ex.Message)
End Try
End Sub
Function GetTraceBinary(ByVal azr As Integer, ByVal traceNum As Integer, ByVal azrSession As TcpipSession, ByVal azrType As PumaEnums.AnalyzerModels) As Trace
Dim newTrace As New Trace
' step 1. Get the traces
With newTrace
azrSession.FormattedIO.WriteLine("POWer:ATTenuation?")
.Attenuation = azrSession.FormattedIO.ReadString
azrSession.FormattedIO.WriteLine("DISPlay:WINDow:TRACe:Y:RLEVel?")
.ReferenceLevel = azrSession.FormattedIO.ReadString()
azrSession.FormattedIO.WriteLine("Bandwidth:Resolution?")
.ResolutionBandwidth = azrSession.FormattedIO.ReadString()
azrSession.FormattedIO.WriteLine("Bandwidth:video?")
.VideoBandwidth = azrSession.FormattedIO.ReadString()
azrSession.FormattedIO.WriteLine("Sweep:Time?")
.SweepTime = azrSession.FormattedIO.ReadString()
azrSession.FormattedIO.WriteLine("FREQuency:STARt?")
.StartFrequency = azrSession.FormattedIO.ReadString()
azrSession.FormattedIO.WriteLine("FREQuency:STOP?")
.StopFrequency = azrSession.FormattedIO.ReadString()
.Errorcode = ""
End With
'change some default values
'azrSession.SetBufferSize(IOBuffers.ReadWrite, 200000) ' value on bytes
'azrSession.TimeoutMilliseconds = 60000 ' time in milliseconds
'trace formatting stuff
'Dim format As String = azrSession.Query(":Format:Data?") 'just for debugging to see what it is '2/3/14: got rid of the word TRACE to support FieldFox
'If azrType <> PumaEnums.AnalyzerModels.AgilentFieldFox Then
'End If
'format = azrSession.Query(":Format:Data?") 'just for debugging to ensure that it changed '2/3/14: got rid of the word TRACE to support FieldFox
' get trace
If azrType = PumaEnums.AnalyzerModels.AgilentFieldFox Then
azrSession.FormattedIO.WriteLine("FORM REAL,32")
azrSession.FormattedIO.WriteLine(":Format:Border SWAPped") ' get the bytes LSB first
azrSession.FormattedIO.WriteLine("INIT:CONT OFF") 'initiate continuous off
azrSession.FormattedIO.WriteLine("INIT:IMM;*OPC?")
azrSession.FormattedIO.ReadString() 'initiate immediate and wait for op complete
azrSession.FormattedIO.WriteLine(":TRACE" & traceNum & ":DATA?")
Else
azrSession.FormattedIO.WriteLine(":Format:Data REAL,32") 'get the trace data y axis values as 32 bit real numbers '2/3/14: got rid of the word TRACE to support FieldFox
azrSession.FormattedIO.WriteLine(":Format:Border SWAPped") ' get the bytes LSB first
azrSession.FormattedIO.WriteLine(":TRAC:DATA? TRACE" & traceNum) 'request trace values
End If
Dim traceByte() As Byte = azrSession.FormattedIO.ReadBinaryBlockOfByte() ' store the values into a byte array
azrSession.Clear()
' step 2. Convert the trace data to display it
'get the start and stop frequencies and number of data points
azrSession.FormattedIO.WriteLine(":Sense:Freq:Start?")
Dim startFreq As String = azrSession.FormattedIO.ReadString()
azrSession.FormattedIO.WriteLine(":Sense:Freq:Stop?")
Dim stopFreq As String = azrSession.FormattedIO.ReadString()
azrSession.FormattedIO.WriteLine(":Sense:Sweep:Points?")
Dim numDataPoints As String = azrSession.FormattedIO.ReadString()
'set-up the output arrays
Dim dataPoints As Double = CDbl(numDataPoints)
Dim span As Double = CDbl(startFreq) - CDbl(stopFreq)
Dim fPoint(dataPoints - 1) As Double
Dim ampAarray(dataPoints - 1) As Single
'get some temporary loop variables
Dim ii As Integer = 0
Dim jj As Integer = 0
Dim idx As Integer = 0
Dim fPt As Double = 0
'determine how at which point we need to start at in the byte arrays to leap over some header
'bytes and get into the amplitude bytes
'The need for this has been eliminated with the use of NI-VISA
'NI-VISA provides a function that reads block data and removes the header
'If traceByte.Length < 1000000 Then
' jj = 8
'End If
'If traceByte.Length < 100000 Then
' jj = 7
'End If
'If traceByte.Length < 10000 Then ' if the byte array length is less than 10,000 bytes
' jj = 6
'End If
'If traceByte.Length < 1000 Then
' jj = 5
'End If
'If traceByte.Length < 100 Then
' jj = 4
'End If
'If traceByte.Length < 10 Then
' jj = 3
'End If
Try
'loop through and build the arrays
ReDim newTrace.DataSingles(dataPoints - 1)
For ii = 0 To (dataPoints - 1)
fPt = CDbl(startFreq) + (span * idx / (dataPoints)) 'calc freq of this point
fPoint(idx) = fPt / (10 ^ 6) ' convert to MHz
If azrType = PumaEnums.AnalyzerModels.AgilentFieldFox Then 'field fox uses little endian and must be swapped here
Dim tmparr(3) As Byte
tmparr(3) = traceByte(jj)
tmparr(2) = traceByte(jj + 1)
tmparr(1) = traceByte(jj + 2)
tmparr(0) = traceByte(jj + 3)
ampAarray(idx) = System.BitConverter.ToSingle(tmparr, 0)
Else
Dim tmparr As Byte = System.BitConverter.ToSingle(traceByte, jj)
ampAarray(idx) = tmparr
End If
newTrace.DataSingles(idx) = System.Math.Round(ampAarray(idx), 3)
idx += 1 ' increment the freq and amplitude arrays by 1
jj += 4 ' advance the byte arrays by 4 (4 bytes to one single)
Next
Catch ex As Exception
Dim test = 0
End Try
Return newTrace
End Function
''' <summary>
''' takes a Trace and generates the Frequency column for the TraceData. This is used to Plot the data in a graph
''' </summary>
''' <param name="tracedata"></param>
''' <returns>A 2 by datapoints array of Doubles</returns>
''' <remarks></remarks>
Function DataArrayConverterDoubles(ByVal tracedata As Trace) As Double(,)
Dim mDataArray As Double(,)
Dim x As Integer = tracedata.DataSingles.Length - 1
ReDim mDataArray(1, x) ' resize array
Dim I As Integer = 0, fpoint As Double, span As Double = CDbl(tracedata.StopFrequency) - CDbl(tracedata.StartFrequency), dataPoints As Double = tracedata.DataSingles.Length
For Each ss In tracedata.DataSingles() 'convert to mDataArray
If dataPoints <> 1 Then
fpoint = CDbl(tracedata.StartFrequency) + span * (I) / (dataPoints - 1) 'calc freq of point
Else
fpoint = CDbl(tracedata.StartFrequency)
End If
mDataArray(0, I) = CDbl(fpoint / 1000000) 'Freq in Mhz
mDataArray(1, I) = ss
If tracedata.DataSingles.Length <> dataPoints Then
Dim tmpStr As String = ("datapoint mismatch " & tracedata.Name)
'Me.ErrorLogFile(tmpStr)
Exit For
End If
I += 1
Next
Return mDataArray
End Function
Function ScaleData(ByVal currentTrace As Trace, ByVal mCurrentTraceData As Double(,), ByVal mCalData As Double(,), ByVal mAntData As Double(,), ByVal unitsStr As String, Optional ByVal interpdArrays As Boolean = False) As Double(,)
Control.CheckForIllegalCrossThreadCalls = False
Dim traces As Integer = 0
Dim points As Integer = 0
Dim freq As Double = Nothing
Dim gain As Double = Nothing
Dim af As Double = Nothing
Dim dataPoints As Integer = mCurrentTraceData.Length ' determine number of Data Points in Trace
Dim mScaleData As Double(,)
Dim arraySize As Integer = dataPoints - 1
ReDim mScaleData(1, arraySize)
Dim currentFile As String = ""
Dim ss As String = "" 's As String
dataPoints = currentTrace.DataSingles.Length.ToString
If currentTrace.Azimuth <> "" Then currentTrace.Azimuth = currentTrace.Azimuth.Replace(" ", "") 'remove blank space in legacy data files
'If DataScatterGraph.Caption <> "" Then DataScatterGraph.Caption = CStr(CurrentTrace.Name)
Dim span As Double = CDbl(currentTrace.StopFrequency) - CDbl(currentTrace.StartFrequency)
Dim fpoint As Double
Dim I As Integer = 0
'MsgBox(CurrentTrace.Data().Length.ToString)
If currentTrace.DataSingles.Length < 20 Then
For Each ss In currentTrace.Data() 'convert to CurrentTraceData
fpoint = CDbl(currentTrace.StartFrequency) + span * (I) / (dataPoints - 1) 'calc freq of point
mCurrentTraceData(0, I) = fpoint / 1000000 'Freq in Mhz
mCurrentTraceData(1, I) = CDbl(ss)
If currentTrace.Data.Length <> dataPoints Then
Dim tmpStr As String = ("datapoint mismatch " & currentTrace.Name)
'Me.ErrorLogFile(tmpStr)
Exit For
End If
I += 1
Next
Else
For Each ss In currentTrace.DataSingles() 'convert to CurrentTraceData
fpoint = CDbl(currentTrace.StartFrequency) + span * (I) / (dataPoints - 1) 'calc freq of point
mCurrentTraceData(0, I) = fpoint / 1000000 'Freq in Mhz
mCurrentTraceData(1, I) = currentTrace.DataSingles(I)
If currentTrace.DataSingles.Length <> dataPoints Then
Dim tmpStr As String = ("datapoint mismatch " & currentTrace.Name)
'Me.ErrorLogFile(tmpStr)
Exit For
End If
I += 1
Next
End If
'return an interpolated array for the cable cal file that will match the frequency points in the trace data
If interpdArrays = False Then
Dim xTempCalArray(,) As Double = MyLinearDataInterpelator(mCalData, mCurrentTraceData) 'spline Cal Data to match data
_tempCalArray = xTempCalArray
Else
_tempCalArray = mCalData
End If
'correct the trace data for the cable losses
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, _tempCalArray, PumaEnums.Operatortype.SubTract)
'return an interpolated array for the antenna cal file that will match the frequency points in the trace data
If interpdArrays = False Then
Dim tempAntennaData As Double(,) = New Double(,) {}, element As Double, jj As Integer = 0
Select Case unitsStr
Case "V/m"
jj = 2 'AF' ss = CStr(System.Math.Pow(10, (Val(ss) + AntennaFactorData(points) + 107 + 1 - 120) / 20)) ' dBuV conversion
Case "dBuV"
jj = 1 'Gain ' ss = CStr(Val(ss) + 107)
Case "dBuV/m"
jj = 2 'AF ' ss = CStr(Val(ss) + AntennaFactorData(points)+ 107)
Case "dBm"
jj = 1 'Gain ' ss = CStr(Val(ss) - AntennaGainData(points)) 'dBm'subtract gain
Case "dBm/Hz"
jj = 1 'Gain ' ss = CStr(Val(ss) - AntennaGainData(points)) 'dBm'subtract gain
Case "W/m2"
jj = 2 'AF ss = CStr(System.Math.Pow(10, ( E(dBuV/m) - 120 - 25.76) /10)
Case "mW/cm2"
jj = 2 'AF ss = W/m2 / 10
End Select
'Dim II As Integer = 0
'ReDim TempAntennaData(1, ArrayOperation.CopyRow(mANTData, 0).Length - 1)
'For Each Element In ArrayOperation.CopyRow(mANTData, 1) ' make 2D Array to pass to MyLinearDataInterpelator
' TempAntennaData(0, II) = Element
' TempAntennaData(1, II) = mANTData(JJ, II)
' II += 1
'Next
Dim elIdx = 0
Dim frqs = Matrix(Of Double).Build.DenseOfArray(mAntData).Row(0).ToArray()
ReDim tempAntennaData(1, frqs.Length - 1)
For Each element In frqs
tempAntennaData(0, elIdx) = element
tempAntennaData(1, elIdx) = mAntData(jj, elIdx)
elIdx += 1
Next
_tempAntArray = MyLinearDataInterpelator(tempAntennaData, mCurrentTraceData)
Else
_tempAntArray = mAntData
End If
' Dim AntennaDataIndex As Integer = 0, Fa As Double, Fb As Double, Ga As Double, Gb As Double, AFa As Double, AFb As Double
Select Case unitsStr
Case "V/m"
'note: was all CurrentTraceData
'CurrentTraceData = EMC.Math.MyDataArrayAddingMachine(CurrentTraceData, TempAntArray, operatortype.ADD) ' add Antenna Factors
'CurrentTraceData = EMC.Math.MyDataArrayAddingMachine(CurrentTraceData, 107, operatortype.ADD) 'dBm/m to dBuV/m
'CurrentTraceData = EMC.Math.MyDataArrayAddingMachine(CurrentTraceData, 120, operatortype.SubTract) 'dBuV/m to dBV/m
'CurrentTraceData = EMC.Math.MyDataArrayAddingMachine(CurrentTraceData, 20, operatortype.ToThePower) 'dBV/m to V/m
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, _tempAntArray, PumaEnums.Operatortype.Add) ' add Antenna Factors
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, 107, PumaEnums.Operatortype.Add) 'dBm/m to dBuV/m
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, 120, PumaEnums.Operatortype.SubTract) 'dBuV/m to dBV/m
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, 20, PumaEnums.Operatortype.ToThePower) 'dBV/m to V/m
Case "dBuV/m"
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, _tempAntArray, PumaEnums.Operatortype.Add) ' add Antenna Factors
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, 107, PumaEnums.Operatortype.Add) 'dBm/m to dBuV/m
Case "dBuV"
'note: was all CurrentTraceData
'CurrentTraceData = EMC.Math.MyDataArrayAddingMachine(CurrentTraceData, TempAntArray, operatortype.SubTract) ' subtract Antenna Gains
'CurrentTraceData = EMC.Math.MyDataArrayAddingMachine(CurrentTraceData, 107, operatortype.ADD) 'dBm to dBuV
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, _tempAntArray, PumaEnums.Operatortype.SubTract) ' subtract Antenna Gains
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, 107, PumaEnums.Operatortype.Add) 'dBm to dBuV
Case "dBm"
'note: was all CurrentTraceData
'CurrentTraceData = EMC.Math.MyDataArrayAddingMachine(CurrentTraceData, TempAntArray, operatortype.SubTract) ' subtract Antenna Gains
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, _tempAntArray, PumaEnums.Operatortype.SubTract)
Case "dBm/Hz"
'note: was all CurrentTraceData
'CurrentTraceData = EMC.Math.MyDataArrayAddingMachine(CurrentTraceData, TempAntArray, operatortype.SubTract) ' subtract Antenna Gains
'CurrentTraceData = EMC.Math.MyDataArrayAddingMachine(CurrentTraceData, 10 * System.Math.Log10(CDbl(CurrentTrace.ResolutionBandwidth)), operatortype.SubTract)
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, _tempAntArray, PumaEnums.Operatortype.SubTract) ' subtract Antenna Gains
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, 10 * System.Math.Log10(CDbl(currentTrace.ResolutionBandwidth)), PumaEnums.Operatortype.SubTract)
Case "W/m2"
' ss = CStr(System.Math.Pow(10, ( E(dBuV/m) - 120 - 25.76) /10)
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, _tempAntArray, PumaEnums.Operatortype.Add) ' add Antenna Factors
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, 107, PumaEnums.Operatortype.Add) 'dBm/m to dBuV/m
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, 120, PumaEnums.Operatortype.SubTract) 'dBuV/m to dBV/m
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, 25.76, PumaEnums.Operatortype.SubTract) 'dBV/m to dBW/m2
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, 10, PumaEnums.Operatortype.ToThePower) 'dBW/m2 to W/m2
Case "mW/cm2"
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, _tempAntArray, PumaEnums.Operatortype.Add) ' add Antenna Factors
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, 107, PumaEnums.Operatortype.Add) 'dBm/m to dBuV/m
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, 120, PumaEnums.Operatortype.SubTract) 'dBuV/m to dBV/m
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, 25.76, PumaEnums.Operatortype.SubTract) 'dBV/m to dBW/m2
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, 10, PumaEnums.Operatortype.ToThePower) 'dBW/m2 to W/m2
mCurrentTraceData = MyDataArrayAddingMachine(mCurrentTraceData, 10, PumaEnums.Operatortype.Divide) 'W/m2 to mW/cm2
End Select
points = 0
Dim maxElement As Double = 0
Dim currentAzimuth As Double = 0
traces += 1
Return mCurrentTraceData
End Function
End Class
|
wboxx1/85-EIS-PUMA
|
puma/src/Supporting Controllers/Data/DataController.vb
|
Visual Basic
|
mit
| 21,066
|
Public Class Cliente
Inherits Persona
Private _tipo As String
Public Property Tipo() As String
Get
Return _tipo
End Get
Set(ByVal value As String)
_tipo = value
End Set
End Property
Public Sub New()
End Sub
Public Sub New(nombre As String, apellido As String)
Me.Nombre = nombre
Me.Apellido = apellido
End Sub
Public Sub New(nombre As String, apellido As String, edad As Short, email As String, telefono As String, genero As String, cedula As String, tipo As String)
MyBase.New(nombre, apellido, edad, email, telefono, genero, cedula)
Me.Tipo = tipo
End Sub
End Class
|
Mikamocha/ProyctoVisualPrimerParcial
|
Proyecto/Proyecto/Cliente.vb
|
Visual Basic
|
mit
| 703
|
Partial Class TemplateList
Inherits System.Web.UI.Page
Public Property DirectoryName() As String
Get
Return ViewState("DirectoryName")
End Get
Set(ByVal value As String)
ViewState("DirectoryName") = value
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
DirectoryName = DirectoryService.GetTemplatesDirectory
Directory1.Path = DirectoryName
End If
End Sub
Protected Sub lnkNewSubdirectory_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkNewSubdirectory.Click
Context.Items("DirectoryName") = DirectoryName
Server.Transfer("~/DirectoryNew.aspx")
End Sub
Protected Sub lnkNewFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkNewFile.Click
Context.Items("DirectoryName") = DirectoryName
Server.Transfer("~/FileNew.aspx")
End Sub
Protected Sub lnkUploadFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkUploadFile.Click
Context.Items("DirectoryName") = DirectoryName
Server.Transfer("~/FileUpload.aspx")
End Sub
Protected Sub lnkDownload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkDownload.Click
Dim zipfilename As String
zipfilename = ZipService.ZipDirectory(DirectoryName, "")
Response.Redirect(zipfilename)
End Sub
Protected Sub lnkUploadZip_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkUploadZip.Click
Context.Items("DirectoryName") = DirectoryName
Server.Transfer("~/ZipUpload.aspx")
End Sub
End Class
|
ajlopez/AjGenesis
|
src/AjGenesis.WebStudio/TemplateList.aspx.vb
|
Visual Basic
|
mit
| 1,817
|
' 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.Linq
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend NotInheritable Class OverloadResolution
Private Sub New()
Throw ExceptionUtilities.Unreachable
End Sub
''' <summary>
''' Information about a candidate from a group.
''' Will have different implementation for methods, extension methods and properties.
''' </summary>
''' <remarks></remarks>
Public MustInherit Class Candidate
Public MustOverride ReadOnly Property UnderlyingSymbol As Symbol
Friend MustOverride Function Construct(typeArguments As ImmutableArray(Of TypeSymbol)) As Candidate
''' <summary>
''' Whether the method is used as extension method vs. called as a static method.
''' </summary>
Public Overridable ReadOnly Property IsExtensionMethod As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Whether the method is used as an operator.
''' </summary>
Public Overridable ReadOnly Property IsOperator As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Whether the method is used in a lifted to nullable form.
''' </summary>
Public Overridable ReadOnly Property IsLifted As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Precedence level for an extension method.
''' </summary>
Public Overridable ReadOnly Property PrecedenceLevel As Integer
Get
Return 0
End Get
End Property
''' <summary>
''' Extension method type parameters that were fixed during currying, if any.
''' If none were fixed, BitArray.Null should be returned.
''' </summary>
Public Overridable ReadOnly Property FixedTypeParameters As BitVector
Get
Return BitVector.Null
End Get
End Property
Public MustOverride ReadOnly Property IsGeneric As Boolean
Public MustOverride ReadOnly Property ParameterCount As Integer
Public MustOverride Function Parameters(index As Integer) As ParameterSymbol
Public MustOverride ReadOnly Property ReturnType As TypeSymbol
Public MustOverride ReadOnly Property Arity As Integer
Public MustOverride ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Friend Sub GetAllParameterCounts(
ByRef requiredCount As Integer,
ByRef maxCount As Integer,
ByRef hasParamArray As Boolean
)
maxCount = Me.ParameterCount
hasParamArray = False
requiredCount = -1
Dim last = maxCount - 1
For i As Integer = 0 To last Step 1
Dim param As ParameterSymbol = Me.Parameters(i)
If i = last AndAlso param.IsParamArray Then
hasParamArray = True
ElseIf Not param.IsOptional Then
requiredCount = i
End If
Next
requiredCount += 1
End Sub
Friend Function TryGetNamedParamIndex(name As String, ByRef index As Integer) As Boolean
For i As Integer = 0 To Me.ParameterCount - 1 Step 1
Dim param As ParameterSymbol = Me.Parameters(i)
If IdentifierComparison.Equals(name, param.Name) Then
index = i
Return True
End If
Next
index = -1
Return False
End Function
''' <summary>
''' Receiver type for extension method. Otherwise, containing type.
''' </summary>
Public MustOverride ReadOnly Property ReceiverType As TypeSymbol
''' <summary>
''' For extension methods, the type of the fist parameter in method's definition (i.e. before type parameters are substituted).
''' Otherwise, same as the ReceiverType.
''' </summary>
Public MustOverride ReadOnly Property ReceiverTypeDefinition As TypeSymbol
Friend MustOverride Function IsOverriddenBy(otherSymbol As Symbol) As Boolean
End Class
''' <summary>
''' Implementation for an ordinary method (based on usage).
''' </summary>
Public Class MethodCandidate
Inherits Candidate
Protected ReadOnly m_Method As MethodSymbol
Public Sub New(method As MethodSymbol)
Debug.Assert(method IsNot Nothing)
Debug.Assert(method.ReducedFrom Is Nothing OrElse Me.IsExtensionMethod)
m_Method = method
End Sub
Friend Overrides Function Construct(typeArguments As ImmutableArray(Of TypeSymbol)) As Candidate
Return New MethodCandidate(m_Method.Construct(typeArguments))
End Function
Public Overrides ReadOnly Property IsGeneric As Boolean
Get
Return m_Method.IsGenericMethod
End Get
End Property
Public Overrides ReadOnly Property ParameterCount As Integer
Get
Return m_Method.ParameterCount
End Get
End Property
Public Overrides Function Parameters(index As Integer) As ParameterSymbol
Return m_Method.Parameters(index)
End Function
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return m_Method.ReturnType
End Get
End Property
Public Overrides ReadOnly Property ReceiverType As TypeSymbol
Get
Return m_Method.ContainingType
End Get
End Property
Public Overrides ReadOnly Property ReceiverTypeDefinition As TypeSymbol
Get
Return m_Method.ContainingType
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return m_Method.Arity
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return m_Method.TypeParameters
End Get
End Property
Public Overrides ReadOnly Property UnderlyingSymbol As Symbol
Get
Return m_Method
End Get
End Property
Friend Overrides Function IsOverriddenBy(otherSymbol As Symbol) As Boolean
Dim definition As MethodSymbol = m_Method.OriginalDefinition
If definition.IsOverridable OrElse definition.IsOverrides OrElse definition.IsMustOverride Then
Dim otherMethod As MethodSymbol = DirectCast(otherSymbol, MethodSymbol).OverriddenMethod
While otherMethod IsNot Nothing
If otherMethod.OriginalDefinition.Equals(definition) Then
Return True
End If
otherMethod = otherMethod.OverriddenMethod
End While
End If
Return False
End Function
End Class
''' <summary>
''' Implementation for an extension method, i.e. it is used as an extension method.
''' </summary>
Public NotInheritable Class ExtensionMethodCandidate
Inherits MethodCandidate
Private _fixedTypeParameters As BitVector
Public Sub New(method As MethodSymbol)
Me.New(method, GetFixedTypeParameters(method))
End Sub
' TODO: Consider building this bitmap lazily, on demand.
Private Shared Function GetFixedTypeParameters(method As MethodSymbol) As BitVector
If method.FixedTypeParameters.Length > 0 Then
Dim fixedTypeParameters = BitVector.Create(method.ReducedFrom.Arity)
For Each fixed As KeyValuePair(Of TypeParameterSymbol, TypeSymbol) In method.FixedTypeParameters
fixedTypeParameters(fixed.Key.Ordinal) = True
Next
Return fixedTypeParameters
End If
Return Nothing
End Function
Private Sub New(method As MethodSymbol, fixedTypeParameters As BitVector)
MyBase.New(method)
Debug.Assert(method.ReducedFrom IsNot Nothing)
_fixedTypeParameters = fixedTypeParameters
End Sub
Public Overrides ReadOnly Property IsExtensionMethod As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property PrecedenceLevel As Integer
Get
Return m_Method.Proximity
End Get
End Property
Public Overrides ReadOnly Property FixedTypeParameters As BitVector
Get
Return _fixedTypeParameters
End Get
End Property
Friend Overrides Function Construct(typeArguments As ImmutableArray(Of TypeSymbol)) As Candidate
Return New ExtensionMethodCandidate(m_Method.Construct(typeArguments), _fixedTypeParameters)
End Function
Public Overrides ReadOnly Property ReceiverType As TypeSymbol
Get
Return m_Method.ReceiverType
End Get
End Property
Public Overrides ReadOnly Property ReceiverTypeDefinition As TypeSymbol
Get
Return m_Method.ReducedFrom.Parameters(0).Type
End Get
End Property
Friend Overrides Function IsOverriddenBy(otherSymbol As Symbol) As Boolean
Return False ' Extension methods never override/overridden
End Function
End Class
''' <summary>
''' Implementation for an operator
''' </summary>
Public Class OperatorCandidate
Inherits MethodCandidate
Public Sub New(method As MethodSymbol)
MyBase.New(method)
End Sub
Public NotOverridable Overrides ReadOnly Property IsOperator As Boolean
Get
Return True
End Get
End Property
End Class
''' <summary>
''' Implementation for a lifted operator.
''' </summary>
Public Class LiftedOperatorCandidate
Inherits OperatorCandidate
Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol)
Private ReadOnly _returnType As TypeSymbol
Public Sub New(method As MethodSymbol, parameters As ImmutableArray(Of ParameterSymbol), returnType As TypeSymbol)
MyBase.New(method)
Debug.Assert(parameters.Length = method.ParameterCount)
_parameters = parameters
_returnType = returnType
End Sub
Public Overrides ReadOnly Property ParameterCount As Integer
Get
Return _parameters.Length
End Get
End Property
Public Overrides Function Parameters(index As Integer) As ParameterSymbol
Return _parameters(index)
End Function
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return _returnType
End Get
End Property
Public Overrides ReadOnly Property IsLifted As Boolean
Get
Return True
End Get
End Property
End Class
''' <summary>
''' Implementation for a property.
''' </summary>
Public NotInheritable Class PropertyCandidate
Inherits Candidate
Private ReadOnly _property As PropertySymbol
Public Sub New([property] As PropertySymbol)
Debug.Assert([property] IsNot Nothing)
_property = [property]
End Sub
Friend Overrides Function Construct(typeArguments As ImmutableArray(Of TypeSymbol)) As Candidate
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides ReadOnly Property IsGeneric As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property ParameterCount As Integer
Get
Return _property.Parameters.Length
End Get
End Property
Public Overrides Function Parameters(index As Integer) As ParameterSymbol
Return _property.Parameters(index)
End Function
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return _property.Type
End Get
End Property
Public Overrides ReadOnly Property ReceiverType As TypeSymbol
Get
Return _property.ContainingType
End Get
End Property
Public Overrides ReadOnly Property ReceiverTypeDefinition As TypeSymbol
Get
Return _property.ContainingType
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return 0
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return ImmutableArray(Of TypeParameterSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property UnderlyingSymbol As Symbol
Get
Return _property
End Get
End Property
Friend Overrides Function IsOverriddenBy(otherSymbol As Symbol) As Boolean
Dim definition As PropertySymbol = _property.OriginalDefinition
If definition.IsOverridable OrElse definition.IsOverrides OrElse definition.IsMustOverride Then
Dim otherProperty As PropertySymbol = DirectCast(otherSymbol, PropertySymbol).OverriddenProperty
While otherProperty IsNot Nothing
If otherProperty.OriginalDefinition.Equals(definition) Then
Return True
End If
otherProperty = otherProperty.OverriddenProperty
End While
End If
Return False
End Function
End Class
Private Const s_stateSize = 8 ' bit size of the following enum
Public Enum CandidateAnalysisResultState As Byte
Applicable
' All following states are to indicate inapplicability
HasUnsupportedMetadata
HasUseSiteError
Ambiguous
BadGenericArity
ArgumentCountMismatch
TypeInferenceFailed
ArgumentMismatch
GenericConstraintsViolated
RequiresNarrowing
RequiresNarrowingNotFromObject
ExtensionMethodVsInstanceMethod
Shadowed
LessApplicable
ExtensionMethodVsLateBinding
Count
End Enum
<Flags()>
Private Enum SmallFieldMask As Integer
State = (1 << s_stateSize) - 1
IsExpandedParamArrayForm = 1 << (s_stateSize + 0)
InferenceLevelShift = (s_stateSize + 1)
InferenceLevelMask = 3 << InferenceLevelShift ' 2 bits are used
ArgumentMatchingDone = 1 << (s_stateSize + 3)
RequiresNarrowingConversion = 1 << (s_stateSize + 4)
RequiresNarrowingNotFromObject = 1 << (s_stateSize + 5)
RequiresNarrowingNotFromNumericConstant = 1 << (s_stateSize + 6)
' Must be equal to ConversionKind.DelegateRelaxationLevelMask
' Compile time "asserts" below enforce it by reporting a compilation error in case of a violation.
' I am not using the form of
' DelegateRelaxationLevelMask = ConversionKind.DelegateRelaxationLevelMask
' to make it easier to reason about bits used relative to other values in this enum.
DelegateRelaxationLevelMask = 7 << (s_stateSize + 7) ' 3 bits used!
SomeInferenceFailed = 1 << (s_stateSize + 10)
AllFailedInferenceIsDueToObject = 1 << (s_stateSize + 11)
InferenceErrorReasonsShift = (s_stateSize + 12)
InferenceErrorReasonsMask = 3 << InferenceErrorReasonsShift
IgnoreExtensionMethods = 1 << (s_stateSize + 14)
IllegalInAttribute = 1 << (s_stateSize + 15)
End Enum
#If DEBUG Then
' Compile time asserts.
Private Const s_delegateRelaxationLevelMask_AssertZero = SmallFieldMask.DelegateRelaxationLevelMask - ConversionKind.DelegateRelaxationLevelMask
Private _delegateRelaxationLevelMask_Assert1(s_delegateRelaxationLevelMask_AssertZero) As Boolean
Private _delegateRelaxationLevelMask_Assert2(-s_delegateRelaxationLevelMask_AssertZero) As Boolean
Private Const s_inferenceLevelMask_AssertZero = CByte((SmallFieldMask.InferenceLevelMask >> SmallFieldMask.InferenceLevelShift) <> ((TypeArgumentInference.InferenceLevel.Invalid << 1) - 1))
Private _inferenceLevelMask_Assert1(s_inferenceLevelMask_AssertZero) As Boolean
Private _inferenceLevelMask_Assert2(-s_inferenceLevelMask_AssertZero) As Boolean
#End If
Public Structure OptionalArgument
Public ReadOnly DefaultValue As BoundExpression
Public ReadOnly Conversion As KeyValuePair(Of ConversionKind, MethodSymbol)
Public Sub New(value As BoundExpression, conversion As KeyValuePair(Of ConversionKind, MethodSymbol))
Me.DefaultValue = value
Me.Conversion = conversion
End Sub
End Structure
Public Structure CandidateAnalysisResult
Public ReadOnly Property IsExpandedParamArrayForm As Boolean
Get
Return (_smallFields And SmallFieldMask.IsExpandedParamArrayForm) <> 0
End Get
End Property
Public Sub SetIsExpandedParamArrayForm()
_smallFields = _smallFields Or SmallFieldMask.IsExpandedParamArrayForm
End Sub
Public ReadOnly Property InferenceLevel As TypeArgumentInference.InferenceLevel
Get
Return CType((_smallFields And SmallFieldMask.InferenceLevelMask) >> SmallFieldMask.InferenceLevelShift, TypeArgumentInference.InferenceLevel)
End Get
End Property
Public Sub SetInferenceLevel(level As TypeArgumentInference.InferenceLevel)
Dim value As Integer = CInt(level) << SmallFieldMask.InferenceLevelShift
Debug.Assert((value And SmallFieldMask.InferenceLevelMask) = value)
_smallFields = (_smallFields And (Not SmallFieldMask.InferenceLevelMask)) Or (value And SmallFieldMask.InferenceLevelMask)
End Sub
Public ReadOnly Property ArgumentMatchingDone As Boolean
Get
Return (_smallFields And SmallFieldMask.ArgumentMatchingDone) <> 0
End Get
End Property
Public Sub SetArgumentMatchingDone()
_smallFields = _smallFields Or SmallFieldMask.ArgumentMatchingDone
End Sub
Public ReadOnly Property RequiresNarrowingConversion As Boolean
Get
Return (_smallFields And SmallFieldMask.RequiresNarrowingConversion) <> 0
End Get
End Property
Public Sub SetRequiresNarrowingConversion()
_smallFields = _smallFields Or SmallFieldMask.RequiresNarrowingConversion
End Sub
Public ReadOnly Property RequiresNarrowingNotFromObject As Boolean
Get
Return (_smallFields And SmallFieldMask.RequiresNarrowingNotFromObject) <> 0
End Get
End Property
Public Sub SetRequiresNarrowingNotFromObject()
_smallFields = _smallFields Or SmallFieldMask.RequiresNarrowingNotFromObject
End Sub
Public ReadOnly Property RequiresNarrowingNotFromNumericConstant As Boolean
Get
Return (_smallFields And SmallFieldMask.RequiresNarrowingNotFromNumericConstant) <> 0
End Get
End Property
Public Sub SetRequiresNarrowingNotFromNumericConstant()
Debug.Assert(RequiresNarrowingConversion)
IgnoreExtensionMethods = False
_smallFields = _smallFields Or SmallFieldMask.RequiresNarrowingNotFromNumericConstant
End Sub
''' <summary>
''' Only bits specific to delegate relaxation level are returned.
''' </summary>
Public ReadOnly Property MaxDelegateRelaxationLevel As ConversionKind
Get
Return CType(_smallFields And SmallFieldMask.DelegateRelaxationLevelMask, ConversionKind)
End Get
End Property
Public Sub RegisterDelegateRelaxationLevel(conversionKind As ConversionKind)
Dim relaxationLevel As Integer = (conversionKind And SmallFieldMask.DelegateRelaxationLevelMask)
If relaxationLevel > (_smallFields And SmallFieldMask.DelegateRelaxationLevelMask) Then
Debug.Assert(relaxationLevel <= ConversionKind.DelegateRelaxationLevelNarrowing)
If relaxationLevel = ConversionKind.DelegateRelaxationLevelNarrowing Then
IgnoreExtensionMethods = False
End If
_smallFields = (_smallFields And (Not SmallFieldMask.DelegateRelaxationLevelMask)) Or relaxationLevel
End If
End Sub
Public Sub SetSomeInferenceFailed()
_smallFields = _smallFields Or SmallFieldMask.SomeInferenceFailed
End Sub
Public ReadOnly Property SomeInferenceFailed As Boolean
Get
Return (_smallFields And SmallFieldMask.SomeInferenceFailed) <> 0
End Get
End Property
Public Sub SetIllegalInAttribute()
_smallFields = _smallFields Or SmallFieldMask.IllegalInAttribute
End Sub
Public ReadOnly Property IsIllegalInAttribute As Boolean
Get
Return (_smallFields And SmallFieldMask.IllegalInAttribute) <> 0
End Get
End Property
Public Sub SetAllFailedInferenceIsDueToObject()
_smallFields = _smallFields Or SmallFieldMask.AllFailedInferenceIsDueToObject
End Sub
Public ReadOnly Property AllFailedInferenceIsDueToObject As Boolean
Get
Return (_smallFields And SmallFieldMask.AllFailedInferenceIsDueToObject) <> 0
End Get
End Property
Public Sub SetInferenceErrorReasons(reasons As InferenceErrorReasons)
Dim value As Integer = CInt(reasons) << SmallFieldMask.InferenceErrorReasonsShift
Debug.Assert((value And SmallFieldMask.InferenceErrorReasonsMask) = value)
_smallFields = (_smallFields And (Not SmallFieldMask.InferenceErrorReasonsMask)) Or (value And SmallFieldMask.InferenceErrorReasonsMask)
End Sub
Public ReadOnly Property InferenceErrorReasons As InferenceErrorReasons
Get
Return CType((_smallFields And SmallFieldMask.InferenceErrorReasonsMask) >> SmallFieldMask.InferenceErrorReasonsShift, InferenceErrorReasons)
End Get
End Property
Public Property State As CandidateAnalysisResultState
Get
Return CType(_smallFields And SmallFieldMask.State, CandidateAnalysisResultState)
End Get
Set(value As CandidateAnalysisResultState)
Debug.Assert((value And (Not SmallFieldMask.State)) = 0)
Dim newFields = _smallFields And (Not SmallFieldMask.State)
newFields = newFields Or value
_smallFields = newFields
End Set
End Property
Public Property IgnoreExtensionMethods As Boolean
Get
Return (_smallFields And SmallFieldMask.IgnoreExtensionMethods) <> 0
End Get
Set(value As Boolean)
If value Then
_smallFields = _smallFields Or SmallFieldMask.IgnoreExtensionMethods
Else
_smallFields = _smallFields And (Not SmallFieldMask.IgnoreExtensionMethods)
End If
End Set
End Property
Private _smallFields As Integer
Public Candidate As Candidate
Public ExpandedParamArrayArgumentsUsed As Integer
Public EquallyApplicableCandidatesBucket As Integer
' When this is null, it means that arguments map to parameters sequentially
Public ArgsToParamsOpt As ImmutableArray(Of Integer)
' When these are null, it means that all conversions are identity conversions
Public ConversionsOpt As ImmutableArray(Of KeyValuePair(Of ConversionKind, MethodSymbol))
Public ConversionsBackOpt As ImmutableArray(Of KeyValuePair(Of ConversionKind, MethodSymbol))
' When this is null, it means that there aren't any optional arguments
' This array is indexed by parameter index, not the argument index.
Public OptionalArguments As ImmutableArray(Of OptionalArgument)
Public ReadOnly Property UsedOptionalParameterDefaultValue As Boolean
Get
Return Not OptionalArguments.IsDefault
End Get
End Property
Public NotInferredTypeArguments As BitVector
Public TypeArgumentInferenceDiagnosticsOpt As DiagnosticBag
Public Sub New(candidate As Candidate, state As CandidateAnalysisResultState)
Me.Candidate = candidate
Me.State = state
End Sub
Public Sub New(candidate As Candidate)
Me.Candidate = candidate
Me.State = CandidateAnalysisResultState.Applicable
End Sub
End Structure
' Represents a simple overload resolution result
Friend Structure OverloadResolutionResult
Private ReadOnly _bestResult As CandidateAnalysisResult?
Private ReadOnly _allResults As ImmutableArray(Of CandidateAnalysisResult)
Private ReadOnly _resolutionIsLateBound As Boolean
Private ReadOnly _remainingCandidatesRequireNarrowingConversion As Boolean
Public ReadOnly AsyncLambdaSubToFunctionMismatch As ImmutableArray(Of BoundExpression)
' Create an overload resolution result from a full set of results.
Public Sub New(allResults As ImmutableArray(Of CandidateAnalysisResult), resolutionIsLateBound As Boolean,
remainingCandidatesRequireNarrowingConversion As Boolean,
asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression))
Me._allResults = allResults
Me._resolutionIsLateBound = resolutionIsLateBound
Me._remainingCandidatesRequireNarrowingConversion = remainingCandidatesRequireNarrowingConversion
Me.AsyncLambdaSubToFunctionMismatch = If(asyncLambdaSubToFunctionMismatch Is Nothing,
ImmutableArray(Of BoundExpression).Empty,
asyncLambdaSubToFunctionMismatch.ToArray().AsImmutableOrNull())
If Not resolutionIsLateBound Then
Me._bestResult = GetBestResult(allResults)
End If
End Sub
Public ReadOnly Property Candidates As ImmutableArray(Of CandidateAnalysisResult)
Get
Return _allResults
End Get
End Property
' Returns the best method. Note that if overload resolution succeeded, the set of conversion kinds will NOT be returned.
Public ReadOnly Property BestResult As CandidateAnalysisResult?
Get
Return _bestResult
End Get
End Property
Public ReadOnly Property ResolutionIsLateBound As Boolean
Get
Return _resolutionIsLateBound
End Get
End Property
''' <summary>
''' This might simplify error reporting. If not, consider getting rid of this property.
''' </summary>
Public ReadOnly Property RemainingCandidatesRequireNarrowingConversion As Boolean
Get
Return _remainingCandidatesRequireNarrowingConversion
End Get
End Property
Private Shared Function GetBestResult(allResults As ImmutableArray(Of CandidateAnalysisResult)) As CandidateAnalysisResult?
Dim best As CandidateAnalysisResult? = Nothing
Dim i As Integer = 0
While i < allResults.Length
Dim current = allResults(i)
If current.State = CandidateAnalysisResultState.Applicable Then
If best IsNot Nothing Then
Return Nothing
End If
best = current
End If
i = i + 1
End While
Return best
End Function
End Structure
''' <summary>
''' Perform overload resolution on the given method or property group, with the given arguments and names.
''' The names can be null if no names were supplied to any arguments.
''' </summary>
Public Shared Function MethodOrPropertyInvocationOverloadResolution(
group As BoundMethodOrPropertyGroup,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
binder As Binder,
callerInfoOpt As SyntaxNode,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo),
Optional includeEliminatedCandidates As Boolean = False,
Optional forceExpandedForm As Boolean = False
) As OverloadResolutionResult
If group.Kind = BoundKind.MethodGroup Then
Dim methodGroup = DirectCast(group, BoundMethodGroup)
Return MethodInvocationOverloadResolution(
methodGroup,
arguments,
argumentNames,
binder,
callerInfoOpt,
useSiteDiagnostics,
includeEliminatedCandidates,
forceExpandedForm:=forceExpandedForm)
Else
Dim propertyGroup = DirectCast(group, BoundPropertyGroup)
Return PropertyInvocationOverloadResolution(
propertyGroup,
arguments,
argumentNames,
binder,
callerInfoOpt,
useSiteDiagnostics,
includeEliminatedCandidates)
End If
End Function
''' <summary>
''' Perform overload resolution on the given method group, with the given arguments.
''' </summary>
Public Shared Function QueryOperatorInvocationOverloadResolution(
methodGroup As BoundMethodGroup,
arguments As ImmutableArray(Of BoundExpression),
binder As Binder,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo),
Optional includeEliminatedCandidates As Boolean = False
) As OverloadResolutionResult
Return MethodInvocationOverloadResolution(
methodGroup,
arguments,
Nothing,
binder,
callerInfoOpt:=Nothing,
useSiteDiagnostics:=useSiteDiagnostics,
includeEliminatedCandidates:=includeEliminatedCandidates,
lateBindingIsAllowed:=False,
isQueryOperatorInvocation:=True)
End Function
''' <summary>
''' Perform overload resolution on the given method group, with the given arguments and names.
''' The names can be null if no names were supplied to any arguments.
''' </summary>
Public Shared Function MethodInvocationOverloadResolution(
methodGroup As BoundMethodGroup,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
binder As Binder,
callerInfoOpt As SyntaxNode,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo),
Optional includeEliminatedCandidates As Boolean = False,
Optional delegateReturnType As TypeSymbol = Nothing,
Optional delegateReturnTypeReferenceBoundNode As BoundNode = Nothing,
Optional lateBindingIsAllowed As Boolean = True,
Optional isQueryOperatorInvocation As Boolean = False,
Optional forceExpandedForm As Boolean = False
) As OverloadResolutionResult
Debug.Assert(methodGroup.ResultKind = LookupResultKind.Good OrElse methodGroup.ResultKind = LookupResultKind.Inaccessible)
Dim typeArguments = If(methodGroup.TypeArgumentsOpt IsNot Nothing, methodGroup.TypeArgumentsOpt.Arguments, ImmutableArray(Of TypeSymbol).Empty)
' To simplify code later
If typeArguments.IsDefault Then
typeArguments = ImmutableArray(Of TypeSymbol).Empty
End If
If arguments.IsDefault Then
arguments = ImmutableArray(Of BoundExpression).Empty
End If
Dim candidates = ArrayBuilder(Of CandidateAnalysisResult).GetInstance()
Dim instanceCandidates As ArrayBuilder(Of Candidate) = ArrayBuilder(Of Candidate).GetInstance()
Dim curriedCandidates As ArrayBuilder(Of Candidate) = ArrayBuilder(Of Candidate).GetInstance()
Dim methods As ImmutableArray(Of MethodSymbol) = methodGroup.Methods
If Not methods.IsDefault Then
' Create MethodCandidates for ordinary methods and ExtensionMethodCandidates
' for curried methods, separating them.
For Each method As MethodSymbol In methods
If method.ReducedFrom Is Nothing Then
instanceCandidates.Add(New MethodCandidate(method))
Else
curriedCandidates.Add(New ExtensionMethodCandidate(method))
End If
Next
End If
Dim asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression) = Nothing
Dim applicableNarrowingCandidateCount As Integer = 0
Dim applicableInstanceCandidateCount As Integer = 0
' First collect instance methods.
If instanceCandidates.Count > 0 Then
CollectOverloadedCandidates(
binder, candidates, instanceCandidates, typeArguments,
arguments, argumentNames, delegateReturnType, delegateReturnTypeReferenceBoundNode,
includeEliminatedCandidates, isQueryOperatorInvocation, forceExpandedForm, asyncLambdaSubToFunctionMismatch,
useSiteDiagnostics)
applicableInstanceCandidateCount = EliminateNotApplicableToArguments(methodGroup, candidates, arguments, argumentNames, binder,
applicableNarrowingCandidateCount, asyncLambdaSubToFunctionMismatch,
callerInfoOpt,
forceExpandedForm,
useSiteDiagnostics)
End If
instanceCandidates.Free()
instanceCandidates = Nothing
' Now add extension methods if they should be considered.
Dim addedExtensionMethods As Boolean = False
If ShouldConsiderExtensionMethods(candidates) Then
' Request additional extension methods, if any available.
If methodGroup.ResultKind = LookupResultKind.Good Then
methods = methodGroup.AdditionalExtensionMethods(useSiteDiagnostics)
For Each method As MethodSymbol In methods
curriedCandidates.Add(New ExtensionMethodCandidate(method))
Next
End If
If curriedCandidates.Count > 0 Then
addedExtensionMethods = True
CollectOverloadedCandidates(
binder, candidates, curriedCandidates, typeArguments,
arguments, argumentNames, delegateReturnType, delegateReturnTypeReferenceBoundNode,
includeEliminatedCandidates, isQueryOperatorInvocation, forceExpandedForm, asyncLambdaSubToFunctionMismatch,
useSiteDiagnostics)
End If
End If
curriedCandidates.Free()
Dim result As OverloadResolutionResult
If applicableInstanceCandidateCount = 0 AndAlso Not addedExtensionMethods Then
result = ReportOverloadResolutionFailedOrLateBound(candidates, applicableInstanceCandidateCount, lateBindingIsAllowed AndAlso binder.OptionStrict <> OptionStrict.On, asyncLambdaSubToFunctionMismatch)
Else
result = ResolveOverloading(methodGroup, candidates, arguments, argumentNames, delegateReturnType, lateBindingIsAllowed, binder, asyncLambdaSubToFunctionMismatch, callerInfoOpt, forceExpandedForm,
useSiteDiagnostics)
End If
candidates.Free()
Return result
End Function
Private Shared Function ReportOverloadResolutionFailedOrLateBound(candidates As ArrayBuilder(Of CandidateAnalysisResult),
applicableNarrowingCandidateCount As Integer,
lateBindingIsAllowed As Boolean,
asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression)) As OverloadResolutionResult
Dim isLateBound As Boolean = False
If lateBindingIsAllowed Then
For Each candidate In candidates
If candidate.State = CandidateAnalysisResultState.TypeInferenceFailed Then
If candidate.AllFailedInferenceIsDueToObject AndAlso Not candidate.Candidate.IsExtensionMethod Then
isLateBound = True
Exit For
End If
End If
Next
End If
Return New OverloadResolutionResult(candidates.ToImmutable, isLateBound, applicableNarrowingCandidateCount > 0, asyncLambdaSubToFunctionMismatch)
End Function
''' <summary>
''' Perform overload resolution on the given array of property symbols.
''' </summary>
Public Shared Function PropertyInvocationOverloadResolution(
propertyGroup As BoundPropertyGroup,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
binder As Binder,
callerInfoOpt As SyntaxNode,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo),
Optional includeEliminatedCandidates As Boolean = False
) As OverloadResolutionResult
Debug.Assert(propertyGroup.ResultKind = LookupResultKind.Good OrElse propertyGroup.ResultKind = LookupResultKind.Inaccessible)
Dim properties As ImmutableArray(Of PropertySymbol) = propertyGroup.Properties
' To simplify code later
If arguments.IsDefault Then
arguments = ImmutableArray(Of BoundExpression).Empty
End If
Dim results = ArrayBuilder(Of CandidateAnalysisResult).GetInstance()
Dim candidates = ArrayBuilder(Of Candidate).GetInstance(properties.Length - 1)
For i As Integer = 0 To properties.Length - 1 Step 1
candidates.Add(New PropertyCandidate(properties(i)))
Next
Dim asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression) = Nothing
CollectOverloadedCandidates(binder, results, candidates, ImmutableArray(Of TypeSymbol).Empty,
arguments, argumentNames, Nothing, Nothing, includeEliminatedCandidates,
isQueryOperatorInvocation:=False, forceExpandedForm:=False, asyncLambdaSubToFunctionMismatch:=asyncLambdaSubToFunctionMismatch,
useSiteDiagnostics:=useSiteDiagnostics)
Debug.Assert(asyncLambdaSubToFunctionMismatch Is Nothing)
candidates.Free()
Dim result = ResolveOverloading(propertyGroup, results, arguments, argumentNames, delegateReturnType:=Nothing, lateBindingIsAllowed:=True, binder:=binder,
asyncLambdaSubToFunctionMismatch:=asyncLambdaSubToFunctionMismatch, callerInfoOpt:=callerInfoOpt, forceExpandedForm:=False,
useSiteDiagnostics:=useSiteDiagnostics)
results.Free()
Return result
End Function
''' <summary>
''' Given instance method candidates gone through applicability analysis,
''' figure out if we should consider extension methods, if any.
''' </summary>
Private Shared Function ShouldConsiderExtensionMethods(
candidates As ArrayBuilder(Of CandidateAnalysisResult)
) As Boolean
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim candidate = candidates(i)
Debug.Assert(Not candidate.Candidate.IsExtensionMethod)
If candidate.IgnoreExtensionMethods Then
Return False
End If
Next
Return True
End Function
Private Shared Function ResolveOverloading(
methodOrPropertyGroup As BoundMethodOrPropertyGroup,
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
delegateReturnType As TypeSymbol,
lateBindingIsAllowed As Boolean,
binder As Binder,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
callerInfoOpt As SyntaxNode,
forceExpandedForm As Boolean,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As OverloadResolutionResult
Debug.Assert(argumentNames.IsDefault OrElse argumentNames.Length = arguments.Length)
Dim applicableCandidates As Integer
Dim resolutionIsLateBound As Boolean = False
Dim narrowingCandidatesRemainInTheSet As Boolean = False
Dim applicableNarrowingCandidates As Integer = 0
'TODO: Where does this fit?
'Semantics::ResolveOverloading
'// See if type inference failed for all candidates and it failed from
'// Object. For this scenario, in non-strict mode, treat the call
'// as latebound.
'§11.8.1 Overloaded Method Resolution
'2. Next, eliminate all members from the set that are inaccessible or not applicable to the argument list.
' Note, similar to Dev10 compiler this process will eliminate candidates requiring narrowing conversions
' if strict semantics is used, exception are candidates that require narrowing only from numeric constants.
applicableCandidates = EliminateNotApplicableToArguments(methodOrPropertyGroup, candidates, arguments, argumentNames, binder,
applicableNarrowingCandidates, asyncLambdaSubToFunctionMismatch,
callerInfoOpt,
forceExpandedForm,
useSiteDiagnostics)
If applicableCandidates < 2 Then
narrowingCandidatesRemainInTheSet = (applicableNarrowingCandidates > 0)
GoTo ResolutionComplete
End If
' §11.8.1 Overloaded Method Resolution.
' 7.8. If one or more arguments are AddressOf or lambda expressions, and all of the corresponding
' delegate types in M match exactly, but not all do in N, eliminate N from the set.
' 7.9. If one or more arguments are AddressOf or lambda expressions, and all of the corresponding
' delegate types in M are widening conversions, but not all are in N, eliminate N from the set.
'
' The spec implies that this rule is applied to the set of most applicable candidate as one of the tie breaking rules.
' However, doing it there wouldn't have any effect because all candidates in the set of most applicable candidates
' are equally applicable, therefore, have the same types for corresponding parameters. Thus all the candidates
' have exactly the same delegate relaxation level and none would be eliminated.
' Dev10 applies this rule much earlier, even before eliminating narrowing candidates, and it does it across the board.
' I am going to do the same.
applicableCandidates = ShadowBasedOnDelegateRelaxation(candidates, applicableNarrowingCandidates)
If applicableCandidates < 2 Then
narrowingCandidatesRemainInTheSet = (applicableNarrowingCandidates > 0)
GoTo ResolutionComplete
End If
' §11.8.1 Overloaded Method Resolution.
'7.7. If M and N both required type inference to produce type arguments, and M did not
' require determining the dominant type for any of its type arguments (i.e. each the
' type arguments inferred to a single type), but N did, eliminate N from the set.
' Despite what the spec says, this rule is applied after shadowing based on delegate relaxation
' level, however it needs other tie breaking rules applied to equally applicable candidates prior
' to figuring out the minimal inference level to use as the filter.
ShadowBasedOnInferenceLevel(candidates, arguments, Not argumentNames.IsDefault, delegateReturnType, binder,
applicableCandidates, applicableNarrowingCandidates, useSiteDiagnostics)
If applicableCandidates < 2 Then
narrowingCandidatesRemainInTheSet = (applicableNarrowingCandidates > 0)
GoTo ResolutionComplete
End If
'3. Next, eliminate all members from the set that require narrowing conversions
' to be applicable to the argument list, except for the case where the argument
' expression type is Object.
'4. Next, eliminate all remaining members from the set that require narrowing coercions
' to be applicable to the argument list. If the set is empty, the type containing the
' method group is not an interface, and strict semantics are not being used, the
' invocation target expression is reclassified as a late-bound method access.
' Otherwise, the normal rules apply.
If applicableCandidates = applicableNarrowingCandidates Then
' All remaining candidates are narrowing, deal with them.
narrowingCandidatesRemainInTheSet = True
applicableCandidates = AnalyzeNarrowingCandidates(candidates, arguments, delegateReturnType,
lateBindingIsAllowed AndAlso binder.OptionStrict <> OptionStrict.On, binder,
resolutionIsLateBound,
useSiteDiagnostics)
Else
If applicableNarrowingCandidates > 0 Then
Debug.Assert(applicableNarrowingCandidates < applicableCandidates)
applicableCandidates = EliminateNarrowingCandidates(candidates)
Debug.Assert(applicableCandidates > 0)
If applicableCandidates < 2 Then
GoTo ResolutionComplete
End If
End If
'5. Next, if any instance methods remain in the set,
' eliminate all extension methods from the set.
' !!! I don't think we need to do this explicitly. ResolveMethodOverloading doesn't add
' !!! extension methods in the list if we need to remove them here.
'applicableCandidates = EliminateExtensionMethodsInPresenceOfInstanceMethods(candidates)
'If applicableCandidates < 2 Then
' GoTo ResolutionComplete
'End If
'6. Next, if, given any two members of the set, M and N, M is more applicable than N
' to the argument list, eliminate N from the set. If more than one member remains
' in the set and the remaining members are not equally applicable to the argument
' list, a compile-time error results.
'7. Otherwise, given any two members of the set, M and N, apply the following tie-breaking rules, in order.
applicableCandidates = EliminateLessApplicableToTheArguments(candidates, arguments, delegateReturnType,
False, ' appliedTieBreakingRules
binder, useSiteDiagnostics)
End If
ResolutionComplete:
If Not resolutionIsLateBound AndAlso applicableCandidates = 0 Then
Return ReportOverloadResolutionFailedOrLateBound(candidates, applicableCandidates, lateBindingIsAllowed AndAlso binder.OptionStrict <> OptionStrict.On, asyncLambdaSubToFunctionMismatch)
End If
Return New OverloadResolutionResult(candidates.ToImmutable(), resolutionIsLateBound, narrowingCandidatesRemainInTheSet, asyncLambdaSubToFunctionMismatch)
End Function
Private Shared Function EliminateNarrowingCandidates(
candidates As ArrayBuilder(Of CandidateAnalysisResult)
) As Integer
Dim applicableCandidates As Integer = 0
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable Then
If current.RequiresNarrowingConversion Then
current.State = CandidateAnalysisResultState.RequiresNarrowing
candidates(i) = current
Else
applicableCandidates += 1
End If
End If
Next
Return applicableCandidates
End Function
''' <summary>
''' §11.8.1 Overloaded Method Resolution
''' 6. Next, if, given any two members of the set, M and N, M is more applicable than N
''' to the argument list, eliminate N from the set. If more than one member remains
''' in the set and the remaining members are not equally applicable to the argument
''' list, a compile-time error results.
''' 7. Otherwise, given any two members of the set, M and N, apply the following tie-breaking rules, in order.
'''
''' Returns amount of applicable candidates left.
'''
''' Note that less applicable candidates are going to be eliminated if and only if there are most applicable
''' candidates.
''' </summary>
Private Shared Function EliminateLessApplicableToTheArguments(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
delegateReturnType As TypeSymbol,
appliedTieBreakingRules As Boolean,
binder As Binder,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo),
Optional mostApplicableMustNarrowOnlyFromNumericConstants As Boolean = False
) As Integer
Dim applicableCandidates As Integer
Dim indexesOfEqualMostApplicableCandidates As ArrayBuilder(Of Integer) = ArrayBuilder(Of Integer).GetInstance()
If FastFindMostApplicableCandidates(candidates, arguments, indexesOfEqualMostApplicableCandidates, binder, useSiteDiagnostics) AndAlso
(mostApplicableMustNarrowOnlyFromNumericConstants = False OrElse
candidates(indexesOfEqualMostApplicableCandidates(0)).RequiresNarrowingNotFromNumericConstant = False OrElse
indexesOfEqualMostApplicableCandidates.Count = CountApplicableCandidates(candidates)) Then
' We have most applicable candidates.
' Mark those that lost applicability comparison.
' Applicable candidates with indexes before the first value in indexesOfEqualMostApplicableCandidates,
' after the last value in indexesOfEqualMostApplicableCandidates and in between consecutive values in
' indexesOfEqualMostApplicableCandidates are less applicable.
Debug.Assert(indexesOfEqualMostApplicableCandidates.Count > 0)
Dim nextMostApplicable As Integer = 0 ' and index into indexesOfEqualMostApplicableCandidates
Dim indexOfNextMostApplicable As Integer = indexesOfEqualMostApplicableCandidates(nextMostApplicable)
For i As Integer = 0 To candidates.Count - 1 Step 1
If i = indexOfNextMostApplicable Then
nextMostApplicable += 1
If nextMostApplicable < indexesOfEqualMostApplicableCandidates.Count Then
indexOfNextMostApplicable = indexesOfEqualMostApplicableCandidates(nextMostApplicable)
Else
indexOfNextMostApplicable = candidates.Count
End If
Continue For
End If
Dim contender As CandidateAnalysisResult = candidates(i)
If contender.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
contender.State = CandidateAnalysisResultState.LessApplicable
candidates(i) = contender
Next
' Apply tie-breaking rules
If Not appliedTieBreakingRules Then
applicableCandidates = ApplyTieBreakingRules(candidates, indexesOfEqualMostApplicableCandidates, arguments, delegateReturnType, binder, useSiteDiagnostics)
Else
applicableCandidates = indexesOfEqualMostApplicableCandidates.Count
End If
ElseIf Not appliedTieBreakingRules Then
' Overload resolution failed, we couldn't find most applicable candidates.
' We still need to apply shadowing rules to the sets of equally applicable candidates,
' this will provide better error reporting experience. As we are doing this, we will redo
' applicability comparisons that we've done earlier in FastFindMostApplicableCandidates, but we are willing to
' pay the price for erroneous code.
applicableCandidates = ApplyTieBreakingRulesToEquallyApplicableCandidates(candidates, arguments, delegateReturnType, binder, useSiteDiagnostics)
Else
applicableCandidates = CountApplicableCandidates(candidates)
End If
indexesOfEqualMostApplicableCandidates.Free()
Return applicableCandidates
End Function
Private Shared Function CountApplicableCandidates(candidates As ArrayBuilder(Of CandidateAnalysisResult)) As Integer
Dim applicableCandidates As Integer = 0
For i As Integer = 0 To candidates.Count - 1 Step 1
If candidates(i).State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
applicableCandidates += 1
Next
Return applicableCandidates
End Function
''' <summary>
''' Returns amount of applicable candidates left.
''' </summary>
Private Shared Function ApplyTieBreakingRulesToEquallyApplicableCandidates(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
delegateReturnType As TypeSymbol,
binder As Binder,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As Integer
' First, let's break all remaining candidates into buckets of equally applicable candidates
Dim buckets = GroupEquallyApplicableCandidates(candidates, arguments, binder)
Debug.Assert(buckets.Count > 0)
Dim applicableCandidates As Integer = 0
' Apply tie-breaking rules
For i As Integer = 0 To buckets.Count - 1 Step 1
applicableCandidates += ApplyTieBreakingRules(candidates, buckets(i), arguments, delegateReturnType, binder, useSiteDiagnostics)
Next
' Release memory we no longer need.
For i As Integer = 0 To buckets.Count - 1 Step 1
buckets(i).Free()
Next
buckets.Free()
Return applicableCandidates
End Function
''' <summary>
''' Returns True if there are most applicable candidates.
'''
''' indexesOfMostApplicableCandidates will contain indexes of equally applicable candidates, which are most applicable
''' by comparison to the other (non-equal) candidates. The indexes will be in ascending order.
''' </summary>
Private Shared Function FastFindMostApplicableCandidates(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
indexesOfMostApplicableCandidates As ArrayBuilder(Of Integer),
binder As Binder,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As Boolean
Dim mightBeTheMostApplicableIndex As Integer = -1
Dim mightBeTheMostApplicable As CandidateAnalysisResult = Nothing
indexesOfMostApplicableCandidates.Clear()
' Use linear complexity algorithm to find the first most applicable candidate.
' We are saying "the first" because there could be a number of candidates equally applicable
' by comparison to the one we find, their indexes are collected in indexesOfMostApplicableCandidates.
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim contender As CandidateAnalysisResult = candidates(i)
If contender.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
If mightBeTheMostApplicableIndex = -1 Then
mightBeTheMostApplicableIndex = i
mightBeTheMostApplicable = contender
indexesOfMostApplicableCandidates.Add(i)
Else
Dim cmp As ApplicabilityComparisonResult = CompareApplicabilityToTheArguments(mightBeTheMostApplicable, contender, arguments, binder, useSiteDiagnostics)
If cmp = ApplicabilityComparisonResult.RightIsMoreApplicable Then
mightBeTheMostApplicableIndex = i
mightBeTheMostApplicable = contender
indexesOfMostApplicableCandidates.Clear()
indexesOfMostApplicableCandidates.Add(i)
ElseIf cmp = ApplicabilityComparisonResult.Undefined Then
mightBeTheMostApplicableIndex = -1
indexesOfMostApplicableCandidates.Clear()
ElseIf cmp = ApplicabilityComparisonResult.EquallyApplicable Then
indexesOfMostApplicableCandidates.Add(i)
Else
Debug.Assert(cmp = ApplicabilityComparisonResult.LeftIsMoreApplicable)
End If
End If
Next
For i As Integer = 0 To mightBeTheMostApplicableIndex - 1 Step 1
Dim contender As CandidateAnalysisResult = candidates(i)
If contender.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
Dim cmp As ApplicabilityComparisonResult = CompareApplicabilityToTheArguments(mightBeTheMostApplicable, contender, arguments, binder, useSiteDiagnostics)
If cmp = ApplicabilityComparisonResult.RightIsMoreApplicable OrElse
cmp = ApplicabilityComparisonResult.Undefined OrElse
cmp = ApplicabilityComparisonResult.EquallyApplicable Then
' We do this for equal applicability too because this contender was dropped during the first loop, so,
' if we continue, the mightBeTheMostApplicable candidate will be definitely dropped too.
mightBeTheMostApplicableIndex = -1
Exit For
Else
Debug.Assert(cmp = ApplicabilityComparisonResult.LeftIsMoreApplicable)
End If
Next
Return (mightBeTheMostApplicableIndex > -1)
End Function
''' <summary>
''' §11.8.1 Overloaded Method Resolution
''' 7. Otherwise, given any two members of the set, M and N, apply the following tie-breaking rules, in order.
''' </summary>
Private Shared Function ApplyTieBreakingRules(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
bucket As ArrayBuilder(Of Integer),
arguments As ImmutableArray(Of BoundExpression),
delegateReturnType As TypeSymbol,
binder As Binder,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As Integer
Dim leftWins As Boolean
Dim rightWins As Boolean
Dim applicableCandidates As Integer = bucket.Count
For i = 0 To bucket.Count - 1 Step 1
Dim left = candidates(bucket(i))
If left.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
For j = i + 1 To bucket.Count - 1 Step 1
Dim right = candidates(bucket(j))
If right.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
If ShadowBasedOnTieBreakingRules(left, right, arguments, delegateReturnType, leftWins, rightWins, binder, useSiteDiagnostics) Then
Debug.Assert(Not (leftWins AndAlso rightWins))
If leftWins Then
right.State = CandidateAnalysisResultState.Shadowed
candidates(bucket(j)) = right
applicableCandidates -= 1
Else
Debug.Assert(rightWins)
left.State = CandidateAnalysisResultState.Shadowed
candidates(bucket(i)) = left
applicableCandidates -= 1
Exit For
End If
End If
Next
Next
Debug.Assert(applicableCandidates >= 0)
Return applicableCandidates
End Function
''' <summary>
''' §11.8.1 Overloaded Method Resolution
''' 7. Otherwise, given any two members of the set, M and N, apply the following tie-breaking rules, in order.
''' </summary>
Private Shared Function ShadowBasedOnTieBreakingRules(
left As CandidateAnalysisResult,
right As CandidateAnalysisResult,
arguments As ImmutableArray(Of BoundExpression),
delegateReturnType As TypeSymbol,
ByRef leftWins As Boolean,
ByRef rightWins As Boolean,
binder As Binder,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As Boolean
' Let's apply various shadowing and tie-breaking rules
' from section 7 of §11.8.1 Overloaded Method Resolution.
leftWins = False
rightWins = False
'• If M has fewer parameters from an expanded paramarray than N, eliminate N from the set.
If ShadowBasedOnParamArrayUsage(left, right, leftWins, rightWins) Then
Return True
End If
'7.1. If M is defined in a more derived type than N, eliminate N from the set.
' This rule also applies to the types that extension methods are defined on.
'7.2. If M and N are extension methods and the target type of M is a class or
' structure and the target type of N is an interface, eliminate N from the set.
If ShadowBasedOnReceiverType(left, right, leftWins, rightWins, useSiteDiagnostics) Then
Return True ' I believe we can get here only in presence of named arguments and optional parameters. Otherwise, CombineCandidates takes care of this shadowing.
End If
'7.3. If M and N are extension methods and the target type of M has fewer type
' parameters than the target type of N, eliminate N from the set.
' !!! Note that spec talks about "fewer type parameters", but it is not really about count.
' !!! It is about one refers to a type parameter and the other one doesn't.
If ShadowBasedOnExtensionMethodTargetTypeGenericity(left, right, leftWins, rightWins) Then
Return True ' I believe we can get here only in presence of named arguments and optional parameters. Otherwise, CombineCandidates takes care of this shadowing.
End If
'7.4. If M is less generic than N, eliminate N from the set.
If ShadowBasedOnGenericity(left, right, leftWins, rightWins, arguments, binder) Then
Return True
End If
'7.5. If M is not an extension method and N is, eliminate N from the set.
'7.6. If M and N are extension methods and M was found before N, eliminate N from the set.
If ShadowBasedOnExtensionVsInstanceAndPrecedence(left, right, leftWins, rightWins) Then
Return True
End If
'7.7. If M and N both required type inference to produce type arguments, and M did not
' require determining the dominant type for any of its type arguments (i.e. each the
' type arguments inferred to a single type), but N did, eliminate N from the set.
' The spec is incorrect, this shadowing doesn't belong here, it is applied across the board
' after these tie breaking rules. For more information, see comment in ResolveOverloading.
'7.8. If one or more arguments are AddressOf or lambda expressions, and all of the corresponding delegate types in M match exactly, but not all do in N, eliminate N from the set.
'7.9. If one or more arguments are AddressOf or lambda expressions, and all of the corresponding delegate types in M are widening conversions, but not all are in N, eliminate N from the set.
' The spec is incorrect, this shadowing doesn't belong here, it is applied much earlier.
' For more information, see comment in ResolveOverloading.
' 7.9. If M did not use any optional parameter defaults in place of explicit
' arguments, but N did, then eliminate N from the set.
'
' !!!WARNING!!! The index (7.9) is based on "VB11 spec [draft 3]" version of documentation rather
' than Dev10 documentation.
If ShadowBasedOnOptionalParametersDefaultsUsed(left, right, leftWins, rightWins) Then
Return True
End If
'7.10. If the overload resolution is being done to resolve the target of a delegate-creation expression from an AddressOf expression and M is a function, while N is a subroutine, eliminate N from the set.
If ShadowBasedOnSubOrFunction(left, right, delegateReturnType, leftWins, rightWins) Then
Return True
End If
' 7.10. Before type arguments have been substituted, if M has greater depth of
' genericity (Section 11.8.1.3) than N, then eliminate N from the set.
'
' !!!WARNING!!! The index (7.10) is based on "VB11 spec [draft 3]" version of documentation
' rather than Dev10 documentation.
'
' NOTE: Dev11 puts this analysis in a second phase with the first phase
' performing analysis of { $11.8.1:6 + 7.9/7.10/7.11/7.8 }, see comments in
' OverloadResolution.cpp: bool Semantics::AreProceduresEquallySpecific(...)
'
' Placing this analysis here seems to be more natural than
' matching Dev11 implementation
If ShadowBasedOnDepthOfGenericity(left, right, leftWins, rightWins, arguments, binder) Then
Return True
End If
Return False
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.10. If the overload resolution is being done to resolve the target of a
''' delegate-creation expression from an AddressOf expression and M is a
''' function, while N is a subroutine, eliminate N from the set.
''' </summary>
Private Shared Function ShadowBasedOnSubOrFunction(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
delegateReturnType As TypeSymbol,
ByRef leftWins As Boolean, ByRef rightWins As Boolean
) As Boolean
' !!! Actually, the spec isn't accurate here. If the target delegate is a Sub, we prefer a Sub. !!!
' !!! If the target delegate is a Function, we prefer a Function. !!!
If delegateReturnType Is Nothing Then
Return False
End If
Dim leftReturnsVoid As Boolean = left.Candidate.ReturnType.IsVoidType()
Dim rightReturnsVoid As Boolean = right.Candidate.ReturnType.IsVoidType()
If leftReturnsVoid = rightReturnsVoid Then
Return False
End If
If delegateReturnType.IsVoidType() = leftReturnsVoid Then
leftWins = True
Return True
End If
Debug.Assert(delegateReturnType.IsVoidType() = rightReturnsVoid)
rightWins = True
Return True
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.8. If one or more arguments are AddressOf or lambda expressions, and all of the corresponding
''' delegate types in M match exactly, but not all do in N, eliminate N from the set.
''' 7.9. If one or more arguments are AddressOf or lambda expressions, and all of the corresponding
''' delegate types in M are widening conversions, but not all are in N, eliminate N from the set.
''' </summary>
Private Shared Function ShadowBasedOnDelegateRelaxation(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
ByRef applicableNarrowingCandidates As Integer
) As Integer
' Find the minimal MaxDelegateRelaxationLevel
Dim minMaxRelaxation As ConversionKind = ConversionKind.DelegateRelaxationLevelInvalid
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable Then
Dim relaxation As ConversionKind = current.MaxDelegateRelaxationLevel
If relaxation < minMaxRelaxation Then
minMaxRelaxation = relaxation
End If
End If
Next
' Now eliminate all candidates with relaxation level bigger than the minimal.
Dim applicableCandidates As Integer = 0
applicableNarrowingCandidates = 0
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
Dim relaxation As ConversionKind = current.MaxDelegateRelaxationLevel
If relaxation > minMaxRelaxation Then
current.State = CandidateAnalysisResultState.Shadowed
candidates(i) = current
Else
applicableCandidates += 1
If current.RequiresNarrowingConversion Then
applicableNarrowingCandidates += 1
End If
End If
Next
Return applicableCandidates
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.9. If M did not use any optional parameter defaults in place of explicit
''' arguments, but N did, then eliminate N from the set.
'''
''' !!!WARNING!!! The index (7.9) is based on "VB11 spec [draft 3]" version of documentation rather
''' than Dev10 documentation.
''' TODO: Update indexes of other overload method resolution rules
''' </summary>
Private Shared Function ShadowBasedOnOptionalParametersDefaultsUsed(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean
) As Boolean
Dim leftUsesOptionalParameterDefaults As Boolean = left.UsedOptionalParameterDefaultValue
If leftUsesOptionalParameterDefaults = right.UsedOptionalParameterDefaultValue Then
Return False ' No winner
End If
If Not leftUsesOptionalParameterDefaults Then
leftWins = True
Else
rightWins = True
End If
Return True
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.7. If M and N both required type inference to produce type arguments, and M did not
''' require determining the dominant type for any of its type arguments (i.e. each the
''' type arguments inferred to a single type), but N did, eliminate N from the set.
''' </summary>
Private Shared Sub ShadowBasedOnInferenceLevel(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
haveNamedArguments As Boolean,
delegateReturnType As TypeSymbol,
binder As Binder,
ByRef applicableCandidates As Integer,
ByRef applicableNarrowingCandidates As Integer,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
)
Debug.Assert(Not haveNamedArguments OrElse Not candidates(0).Candidate.IsOperator)
' See if there are candidates with different InferenceLevel
Dim haveDifferentInferenceLevel As Boolean = False
Dim theOnlyInferenceLevel As TypeArgumentInference.InferenceLevel = CType(Byte.MaxValue, TypeArgumentInference.InferenceLevel)
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable Then
Dim inferenceLevel As TypeArgumentInference.InferenceLevel = current.InferenceLevel
If theOnlyInferenceLevel = Byte.MaxValue Then
theOnlyInferenceLevel = inferenceLevel
ElseIf inferenceLevel <> theOnlyInferenceLevel Then
haveDifferentInferenceLevel = True
Exit For
End If
End If
Next
If Not haveDifferentInferenceLevel Then
' Nothing to do.
Return
End If
' Native compiler used to have a bug where CombineCandidates was applying shadowing in presence of named arguments
' before figuring out whether candidates are applicable. We fixed that. However, in cases when candidates were applicable
' after all, that shadowing had impact on the shadowing based on the inference level by affecting minimal inference level.
' To compensate, we will perform the CombineCandidates-style shadowing here. Note that we cannot simply call
' ApplyTieBreakingRulesToEquallyApplicableCandidates to do this because shadowing performed by CombineCandidates is more
' constrained.
If haveNamedArguments Then
Debug.Assert(Not candidates(0).Candidate.IsOperator)
Dim indexesOfApplicableCandidates = ArrayBuilder(Of Integer).GetInstance(applicableCandidates)
For i As Integer = 0 To candidates.Count - 1 Step 1
If candidates(i).State = CandidateAnalysisResultState.Applicable Then
indexesOfApplicableCandidates.Add(i)
End If
Next
Debug.Assert(indexesOfApplicableCandidates.Count = applicableCandidates)
' Sort indexes by inference level
indexesOfApplicableCandidates.Sort(New InferenceLevelComparer(candidates))
#If DEBUG Then
Dim level As TypeArgumentInference.InferenceLevel = TypeArgumentInference.InferenceLevel.None
For Each index As Integer In indexesOfApplicableCandidates
Debug.Assert(level <= candidates(index).InferenceLevel)
level = candidates(index).InferenceLevel
Next
#End If
' In order of sorted indexes, apply constrained shadowing rules looking for the first one survived.
' This will be sufficient to calculate "correct" minimal inference level. We don't have to apply
' shadowing to each pair of candidates.
For i As Integer = 0 To indexesOfApplicableCandidates.Count - 2
Dim left As CandidateAnalysisResult = candidates(indexesOfApplicableCandidates(i))
If left.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
For j As Integer = i + 1 To indexesOfApplicableCandidates.Count - 1
Dim right As CandidateAnalysisResult = candidates(indexesOfApplicableCandidates(j))
If right.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
' Shadowing is applied only to candidates that have the same types for corresponding parameters
' in virtual signatures
Dim equallyApplicable As Boolean = True
For k = 0 To arguments.Length - 1 Step 1
Dim leftParamType As TypeSymbol = GetParameterTypeFromVirtualSignature(left, left.ArgsToParamsOpt(k))
Dim rightParamType As TypeSymbol = GetParameterTypeFromVirtualSignature(right, right.ArgsToParamsOpt(k))
If Not leftParamType.IsSameTypeIgnoringAll(rightParamType) Then
' Signatures are different, shadowing rules do not apply
equallyApplicable = False
Exit For
End If
Next
If Not equallyApplicable Then
Continue For
End If
Dim signatureMatch As Boolean = True
' Compare complete signature, with no regard to arguments
If left.Candidate.ParameterCount <> right.Candidate.ParameterCount Then
signatureMatch = False
Else
For k As Integer = 0 To left.Candidate.ParameterCount - 1 Step 1
Dim leftType As TypeSymbol = left.Candidate.Parameters(k).Type
Dim rightType As TypeSymbol = right.Candidate.Parameters(k).Type
If Not leftType.IsSameTypeIgnoringAll(rightType) Then
signatureMatch = False
Exit For
End If
Next
End If
Dim leftWins As Boolean = False
Dim rightWins As Boolean = False
If (Not signatureMatch AndAlso ShadowBasedOnParamArrayUsage(left, right, leftWins, rightWins)) OrElse
ShadowBasedOnReceiverType(left, right, leftWins, rightWins, useSiteDiagnostics) OrElse
ShadowBasedOnExtensionMethodTargetTypeGenericity(left, right, leftWins, rightWins) Then
Debug.Assert(leftWins Xor rightWins)
If leftWins Then
right.State = CandidateAnalysisResultState.Shadowed
candidates(indexesOfApplicableCandidates(j)) = right
ElseIf rightWins Then
left.State = CandidateAnalysisResultState.Shadowed
candidates(indexesOfApplicableCandidates(i)) = left
Exit For ' advance to the next left
End If
End If
Next
If left.State = CandidateAnalysisResultState.Applicable Then
' left has survived
Exit For
End If
Next
End If
' Find the minimal InferenceLevel
Dim minInferenceLevel = TypeArgumentInference.InferenceLevel.Invalid
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable Then
Dim inferenceLevel As TypeArgumentInference.InferenceLevel = current.InferenceLevel
If inferenceLevel < minInferenceLevel Then
minInferenceLevel = inferenceLevel
End If
End If
Next
' Now eliminate all candidates with inference level bigger than the minimal.
applicableCandidates = 0
applicableNarrowingCandidates = 0
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
Dim inferenceLevel As TypeArgumentInference.InferenceLevel = current.InferenceLevel
If inferenceLevel > minInferenceLevel Then
current.State = CandidateAnalysisResultState.Shadowed
candidates(i) = current
Else
applicableCandidates += 1
If current.RequiresNarrowingConversion Then
applicableNarrowingCandidates += 1
End If
End If
Next
' Done.
End Sub
Private Class InferenceLevelComparer
Implements IComparer(Of Integer)
Private ReadOnly _candidates As ArrayBuilder(Of CandidateAnalysisResult)
Public Sub New(candidates As ArrayBuilder(Of CandidateAnalysisResult))
_candidates = candidates
End Sub
Public Function Compare(indexX As Integer, indexY As Integer) As Integer Implements IComparer(Of Integer).Compare
Return CInt(_candidates(indexX).InferenceLevel).CompareTo(_candidates(indexY).InferenceLevel)
End Function
End Class
''' <summary>
''' §11.8.1.1 Applicability
''' </summary>
Private Shared Function CompareApplicabilityToTheArguments(
ByRef left As CandidateAnalysisResult,
ByRef right As CandidateAnalysisResult,
arguments As ImmutableArray(Of BoundExpression),
binder As Binder,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As ApplicabilityComparisonResult
' §11.8.1.1 Applicability
'A member M is considered more applicable than N if their signatures are different and at least one
'parameter type in M is more applicable than a parameter type in N, and no parameter type in N is more
'applicable than a parameter type in M.
Dim equallyApplicable As Boolean = True
Dim leftHasMoreApplicableParameterType As Boolean = False
Dim rightHasMoreApplicableParameterType As Boolean = False
Dim leftParamIndex As Integer = 0
Dim rightParamIndex As Integer = 0
For i = 0 To arguments.Length - 1 Step 1
Dim leftParamType As TypeSymbol
Debug.Assert(left.ArgsToParamsOpt.IsDefault = right.ArgsToParamsOpt.IsDefault)
If left.ArgsToParamsOpt.IsDefault Then
leftParamType = GetParameterTypeFromVirtualSignature(left, leftParamIndex)
AdvanceParameterInVirtualSignature(left, leftParamIndex)
Else
leftParamType = GetParameterTypeFromVirtualSignature(left, left.ArgsToParamsOpt(i))
End If
Dim rightParamType As TypeSymbol
If right.ArgsToParamsOpt.IsDefault Then
rightParamType = GetParameterTypeFromVirtualSignature(right, rightParamIndex)
AdvanceParameterInVirtualSignature(right, rightParamIndex)
Else
rightParamType = GetParameterTypeFromVirtualSignature(right, right.ArgsToParamsOpt(i))
End If
' Parameters matching omitted arguments do not participate.
If arguments(i).Kind = BoundKind.OmittedArgument Then
Continue For
End If
Dim cmp = CompareParameterTypeApplicability(leftParamType, rightParamType, arguments(i), binder, useSiteDiagnostics)
If cmp = ApplicabilityComparisonResult.LeftIsMoreApplicable Then
leftHasMoreApplicableParameterType = True
If rightHasMoreApplicableParameterType Then
Return ApplicabilityComparisonResult.Undefined ' Neither is more applicable
End If
equallyApplicable = False
ElseIf cmp = ApplicabilityComparisonResult.RightIsMoreApplicable Then
rightHasMoreApplicableParameterType = True
If leftHasMoreApplicableParameterType Then
Return ApplicabilityComparisonResult.Undefined ' Neither is more applicable
End If
equallyApplicable = False
ElseIf cmp = ApplicabilityComparisonResult.Undefined Then
equallyApplicable = False
Else
Debug.Assert(cmp = ApplicabilityComparisonResult.EquallyApplicable)
End If
Next
Debug.Assert(Not (leftHasMoreApplicableParameterType AndAlso rightHasMoreApplicableParameterType))
If leftHasMoreApplicableParameterType Then
Return ApplicabilityComparisonResult.LeftIsMoreApplicable
End If
If rightHasMoreApplicableParameterType Then
Return ApplicabilityComparisonResult.RightIsMoreApplicable
End If
Return If(equallyApplicable, ApplicabilityComparisonResult.EquallyApplicable, ApplicabilityComparisonResult.Undefined)
End Function
Private Enum ApplicabilityComparisonResult
Undefined
EquallyApplicable
LeftIsMoreApplicable
RightIsMoreApplicable
End Enum
''' <summary>
''' §11.8.1.1 Applicability
''' </summary>
Private Shared Function CompareParameterTypeApplicability(
left As TypeSymbol,
right As TypeSymbol,
argument As BoundExpression,
binder As Binder,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As ApplicabilityComparisonResult
Debug.Assert(argument Is Nothing OrElse argument.Kind <> BoundKind.OmittedArgument)
' §11.8.1.1 Applicability
'Given a pair of parameters Mj and Nj that matches an argument Aj,
'the type of Mj is considered more applicable than the type of Nj if one of the following conditions is true:
Dim leftToRightConversion = Conversions.ClassifyConversion(left, right, useSiteDiagnostics)
'1. Mj and Nj have identical types, or
' !!! Does this rule make sense? Not implementing it for now.
If Conversions.IsIdentityConversion(leftToRightConversion.Key) Then
Return ApplicabilityComparisonResult.EquallyApplicable
End If
'2. There exists a widening conversion from the type of Mj to the type Nj, or
If Conversions.IsWideningConversion(leftToRightConversion.Key) Then
' !!! For user defined conversions that widen in both directions there is a tie-breaking rule
' !!! not mentioned in the spec. The type that matches argument's type is more applicable.
' !!! Otherwise neither is more applicable.
If Conversions.IsWideningConversion(Conversions.ClassifyConversion(right, left, useSiteDiagnostics).Key) Then
GoTo BreakTheTie
End If
' !!! Spec makes it look like rule #3 is a separate rule applied after the second, but this isn't the case
' !!! because enumerated type widens to its underlying type, however, if argument is a zero literal,
' !!! underlying type should win.
' !!! Also, based on Dev10 implementation, Mj doesn't have to be a numeric type, it is enough if it is not
' !!! an enumerated type.
'3. Aj is the literal 0, Mj is a numeric type and Nj is an enumerated type, or
If argument IsNot Nothing AndAlso argument.IsIntegerZeroLiteral AndAlso
left.TypeKind = TypeKind.Enum AndAlso right.TypeKind <> TypeKind.Enum Then
Return ApplicabilityComparisonResult.RightIsMoreApplicable
End If
Return ApplicabilityComparisonResult.LeftIsMoreApplicable
End If
If Conversions.IsWideningConversion(Conversions.ClassifyConversion(right, left, useSiteDiagnostics).Key) Then
' !!! Spec makes it look like rule #3 is a separate rule applied after the second, but this isn't the case
' !!! because enumerated type widens to its underlying type, however, if argument is a zero literal,
' !!! underlying type should win.
' !!! Also, based on Dev10 implementation, Mj doesn't have to be a numeric type, it is enough if it is not
' !!! an enumerated type.
'3. Aj is the literal 0, Mj is a numeric type and Nj is an enumerated type, or
If argument IsNot Nothing AndAlso argument.IsIntegerZeroLiteral AndAlso
right.TypeKind = TypeKind.Enum AndAlso left.TypeKind <> TypeKind.Enum Then
Return ApplicabilityComparisonResult.LeftIsMoreApplicable
End If
Return ApplicabilityComparisonResult.RightIsMoreApplicable
End If
''3. Aj is the literal 0, Mj is a numeric type and Nj is an enumerated type, or
'If argument IsNot Nothing AndAlso argument.IsIntegerZeroLiteral Then
' If left.IsNumericType() Then
' If right.TypeKind = TypeKind.Enum Then
' leftIsMoreApplicable = True
' Return
' End If
' ElseIf right.IsNumericType() Then
' If left.TypeKind = TypeKind.Enum Then
' rightIsMoreApplicable = True
' Return
' End If
' End If
'End If
'4. Mj is Byte and Nj is SByte, or
'5. Mj is Short and Nj is UShort, or
'6. Mj is Integer and Nj is UInteger, or
'7. Mj is Long and Nj is ULong.
'!!! Plus rules not mentioned in the spec
If left.IsNumericType() AndAlso right.IsNumericType() Then
Dim leftSpecialType = left.SpecialType
Dim rightSpecialType = right.SpecialType
If leftSpecialType = SpecialType.System_Byte AndAlso rightSpecialType = SpecialType.System_SByte Then
Return ApplicabilityComparisonResult.LeftIsMoreApplicable
End If
If leftSpecialType = SpecialType.System_SByte AndAlso rightSpecialType = SpecialType.System_Byte Then
Return ApplicabilityComparisonResult.RightIsMoreApplicable
End If
' This comparison depends on the ordering of the SpecialType enum. There is a unit-test that verifies the ordering.
If leftSpecialType < rightSpecialType Then
Return ApplicabilityComparisonResult.LeftIsMoreApplicable
Else
Debug.Assert(rightSpecialType < leftSpecialType)
Return ApplicabilityComparisonResult.RightIsMoreApplicable
End If
End If
'8. Mj and Nj are delegate function types and the return type of Mj is more specific than the return type of Nj.
' If Aj is classified as a lambda method, and Mj or Nj is System.Linq.Expressions.Expression(Of T), then the
' type argument of the type (assuming it is a delegate type) is substituted for the type being compared.
If argument IsNot Nothing Then
Dim leftIsExpressionTree As Boolean, rightIsExpressionTree As Boolean
Dim leftDelegateType As NamedTypeSymbol = left.DelegateOrExpressionDelegate(binder, leftIsExpressionTree)
Dim rightDelegateType As NamedTypeSymbol = right.DelegateOrExpressionDelegate(binder, rightIsExpressionTree)
' Native compiler will only compare D1 and D2 for Expression(Of D1) and D2 if the argument is a lambda. It will compare
' Expression(Of D1) and Expression (Of D2) regardless of the argument.
If leftDelegateType IsNot Nothing AndAlso rightDelegateType IsNot Nothing AndAlso
((leftIsExpressionTree = rightIsExpressionTree) OrElse argument.IsAnyLambda()) Then
Dim leftInvoke As MethodSymbol = leftDelegateType.DelegateInvokeMethod
Dim rightInvoke As MethodSymbol = rightDelegateType.DelegateInvokeMethod
If leftInvoke IsNot Nothing AndAlso Not leftInvoke.IsSub AndAlso rightInvoke IsNot Nothing AndAlso Not rightInvoke.IsSub Then
Dim newArgument As BoundExpression = Nothing
' TODO: Should probably handle GroupTypeInferenceLambda too.
If argument.Kind = BoundKind.QueryLambda Then
newArgument = DirectCast(argument, BoundQueryLambda).Expression
End If
Return CompareParameterTypeApplicability(leftInvoke.ReturnType, rightInvoke.ReturnType, newArgument, binder, useSiteDiagnostics)
End If
End If
End If
BreakTheTie:
' !!! There is a tie-breaking rule not mentioned in the spec. The type that matches argument's type is more applicable.
' !!! Otherwise neither is more applicable.
If argument IsNot Nothing Then
Dim argType As TypeSymbol = If(argument.Kind <> BoundKind.ArrayLiteral, argument.Type, DirectCast(argument, BoundArrayLiteral).InferredType)
If argType IsNot Nothing Then
If left.IsSameTypeIgnoringAll(argType) Then
Return ApplicabilityComparisonResult.LeftIsMoreApplicable
End If
If right.IsSameTypeIgnoringAll(argType) Then
Return ApplicabilityComparisonResult.RightIsMoreApplicable
End If
End If
End If
' Neither is more applicable
Return ApplicabilityComparisonResult.Undefined
End Function
''' <summary>
''' This method groups equally applicable (§11.8.1.1 Applicability) candidates into buckets.
'''
''' Returns an ArrayBuilder of buckets. Each bucket is represented by an ArrayBuilder(Of Integer),
''' which contains indexes of equally applicable candidates from input parameter 'candidates'.
''' </summary>
Private Shared Function GroupEquallyApplicableCandidates(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
binder As Binder
) As ArrayBuilder(Of ArrayBuilder(Of Integer))
Dim buckets = ArrayBuilder(Of ArrayBuilder(Of Integer)).GetInstance()
Dim i As Integer
Dim j As Integer
' §11.8.1.1 Applicability
' A member M is considered equally applicable as N if their signatures are the same or
' if each parameter type in M is the same as the corresponding parameter type in N.
For i = 0 To candidates.Count - 1 Step 1
Dim left As CandidateAnalysisResult = candidates(i)
If left.State <> CandidateAnalysisResultState.Applicable OrElse
left.EquallyApplicableCandidatesBucket > 0 Then
Continue For
End If
left.EquallyApplicableCandidatesBucket = buckets.Count + 1
candidates(i) = left
Dim b = ArrayBuilder(Of Integer).GetInstance()
b.Add(i)
buckets.Add(b)
For j = i + 1 To candidates.Count - 1 Step 1
Dim right As CandidateAnalysisResult = candidates(j)
If right.State <> CandidateAnalysisResultState.Applicable OrElse
right.EquallyApplicableCandidatesBucket > 0 OrElse
right.Candidate Is left.Candidate Then
Continue For
End If
If CandidatesAreEquallyApplicableToArguments(left, right, arguments, binder) Then
right.EquallyApplicableCandidatesBucket = left.EquallyApplicableCandidatesBucket
candidates(j) = right
b.Add(j)
End If
Next
Next
Return buckets
End Function
Private Shared Function CandidatesAreEquallyApplicableToArguments(
ByRef left As CandidateAnalysisResult,
ByRef right As CandidateAnalysisResult,
arguments As ImmutableArray(Of BoundExpression),
binder As Binder
) As Boolean
' §11.8.1.1 Applicability
' A member M is considered equally applicable as N if their signatures are the same or
' if each parameter type in M is the same as the corresponding parameter type in N.
' Compare types of corresponding parameters
Dim k As Integer
Dim leftParamIndex As Integer = 0
Dim rightParamIndex As Integer = 0
For k = 0 To arguments.Length - 1 Step 1
Dim leftParamType As TypeSymbol
Debug.Assert(left.ArgsToParamsOpt.IsDefault = right.ArgsToParamsOpt.IsDefault)
If left.ArgsToParamsOpt.IsDefault Then
leftParamType = GetParameterTypeFromVirtualSignature(left, leftParamIndex)
AdvanceParameterInVirtualSignature(left, leftParamIndex)
Else
leftParamType = GetParameterTypeFromVirtualSignature(left, left.ArgsToParamsOpt(k))
End If
Dim rightParamType As TypeSymbol
If right.ArgsToParamsOpt.IsDefault Then
rightParamType = GetParameterTypeFromVirtualSignature(right, rightParamIndex)
AdvanceParameterInVirtualSignature(right, rightParamIndex)
Else
rightParamType = GetParameterTypeFromVirtualSignature(right, right.ArgsToParamsOpt(k))
End If
' Parameters matching omitted arguments do not participate.
If arguments(k).Kind <> BoundKind.OmittedArgument AndAlso
Not ParametersAreEquallyApplicableToArgument(leftParamType, rightParamType, arguments(k), binder) Then
' Signatures are different
Exit For
End If
Next
Return k >= arguments.Length
End Function
Private Shared Function ParametersAreEquallyApplicableToArgument(
leftParamType As TypeSymbol,
rightParamType As TypeSymbol,
argument As BoundExpression,
binder As Binder
) As Boolean
Debug.Assert(argument Is Nothing OrElse argument.Kind <> BoundKind.OmittedArgument)
If Not leftParamType.IsSameTypeIgnoringAll(rightParamType) Then
If argument IsNot Nothing Then
Dim leftIsExpressionTree As Boolean, rightIsExpressionTree As Boolean
Dim leftDelegateType As NamedTypeSymbol = leftParamType.DelegateOrExpressionDelegate(binder, leftIsExpressionTree)
Dim rightDelegateType As NamedTypeSymbol = rightParamType.DelegateOrExpressionDelegate(binder, rightIsExpressionTree)
' Native compiler will only compare D1 and D2 for Expression(Of D1) and D2 if the argument is a lambda. It will compare
' Expression(Of D1) and Expression (Of D2) regardless of the argument.
If leftDelegateType IsNot Nothing AndAlso rightDelegateType IsNot Nothing AndAlso
((leftIsExpressionTree = rightIsExpressionTree) OrElse argument.IsAnyLambda()) Then
Dim leftInvoke As MethodSymbol = leftDelegateType.DelegateInvokeMethod
Dim rightInvoke As MethodSymbol = rightDelegateType.DelegateInvokeMethod
If leftInvoke IsNot Nothing AndAlso Not leftInvoke.IsSub AndAlso rightInvoke IsNot Nothing AndAlso Not rightInvoke.IsSub Then
Dim newArgument As BoundExpression = Nothing
' TODO: Should probably handle GroupTypeInferenceLambda too.
If argument.Kind = BoundKind.QueryLambda Then
newArgument = DirectCast(argument, BoundQueryLambda).Expression
End If
Return ParametersAreEquallyApplicableToArgument(leftInvoke.ReturnType, rightInvoke.ReturnType, newArgument, binder)
End If
End If
End If
' Signatures are different
Return False
End If
Return True
End Function
''' <summary>
''' §11.8.1 Overloaded Method Resolution
''' 3. Next, eliminate all members from the set that require narrowing conversions
''' to be applicable to the argument list, except for the case where the argument
''' expression type is Object.
''' 4. Next, eliminate all remaining members from the set that require narrowing coercions
''' to be applicable to the argument list. If the set is empty, the type containing the
''' method group is not an interface, and strict semantics are not being used, the
''' invocation target expression is reclassified as a late-bound method access.
''' Otherwise, the normal rules apply.
'''
''' Returns amount of applicable candidates left.
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Private Shared Function AnalyzeNarrowingCandidates(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
delegateReturnType As TypeSymbol,
lateBindingIsAllowed As Boolean,
binder As Binder,
ByRef resolutionIsLateBound As Boolean,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As Integer
Dim applicableCandidates As Integer = 0
Dim appliedTieBreakingRules As Boolean = False
' Look through the candidate set for lifted operators that require narrowing conversions whose
' source operators also require narrowing conversions. In that case, we only want to keep one method in
' the set. If the source operator requires nullables to be unwrapped, then we discard it and keep the lifted operator.
' If it does not, then we discard the lifted operator and keep the source operator. This will prevent the presence of
' lifted operators from causing overload resolution conflicts where there otherwise wouldn't be one. However,
' if the source operator only requires narrowing conversions from numeric literals, then we keep both in the set,
' because the conversion in that case is not really narrowing.
If candidates(0).Candidate.IsOperator Then
' As an optimization, we can rely on the fact that lifted operator, if added, immediately
' follows source operator.
Dim i As Integer
For i = 0 To candidates.Count - 2 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
Debug.Assert(current.Candidate.IsOperator)
If current.State = CandidateAnalysisResultState.Applicable AndAlso
Not current.Candidate.IsLifted AndAlso
current.RequiresNarrowingNotFromNumericConstant Then
Dim contender As CandidateAnalysisResult = candidates(i + 1)
Debug.Assert(contender.Candidate.IsOperator)
If contender.State = CandidateAnalysisResultState.Applicable AndAlso
contender.Candidate.IsLifted AndAlso
current.Candidate.UnderlyingSymbol Is contender.Candidate.UnderlyingSymbol Then
Exit For
End If
End If
Next
If i < candidates.Count - 1 Then
' [i] is the index of the first "interesting" pair of source/lifted operators.
If Not appliedTieBreakingRules Then
' Apply shadowing rules, Dev10 compiler does that for narrowing candidates too.
applicableCandidates = ApplyTieBreakingRulesToEquallyApplicableCandidates(candidates, arguments, delegateReturnType, binder, useSiteDiagnostics)
appliedTieBreakingRules = True
Debug.Assert(applicableCandidates > 1) ' source and lifted operators are not equally applicable.
End If
' Let's do the elimination pass now.
For i = i To candidates.Count - 2 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
Debug.Assert(current.Candidate.IsOperator)
If current.State = CandidateAnalysisResultState.Applicable AndAlso
Not current.Candidate.IsLifted AndAlso
current.RequiresNarrowingNotFromNumericConstant Then
Dim contender As CandidateAnalysisResult = candidates(i + 1)
Debug.Assert(contender.Candidate.IsOperator)
If contender.State = CandidateAnalysisResultState.Applicable AndAlso
contender.Candidate.IsLifted AndAlso
current.Candidate.UnderlyingSymbol Is contender.Candidate.UnderlyingSymbol Then
For j As Integer = 0 To arguments.Length - 1
Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = current.ConversionsOpt(j)
If Conversions.IsNarrowingConversion(conv.Key) Then
Dim lost As Boolean = False
If (conv.Key And ConversionKind.UserDefined) = 0 Then
If IsUnwrappingNullable(conv.Key, arguments(j).Type, current.Candidate.Parameters(j).Type) Then
lost = True
End If
Else
' Lifted user-defined conversions don't unwrap nullables, they are marked with Nullable bit.
If (conv.Key And ConversionKind.Nullable) = 0 Then
If IsUnwrappingNullable(arguments(j).Type, conv.Value.Parameters(0).Type, useSiteDiagnostics) Then
lost = True
ElseIf IsUnwrappingNullable(conv.Value.ReturnType, current.Candidate.Parameters(j).Type, useSiteDiagnostics) Then
lost = True
End If
End If
End If
If lost Then
' unwrapping nullable, current lost
current.State = CandidateAnalysisResultState.Shadowed
candidates(i) = current
i = i + 1
GoTo Next_i
End If
End If
Next
' contender lost
contender.State = CandidateAnalysisResultState.Shadowed
candidates(i + 1) = contender
i = i + 1
GoTo Next_i
End If
End If
Next_i:
Next
End If
End If
If lateBindingIsAllowed Then
' Are there all narrowing from object candidates?
Dim haveAllNarrowingFromObject As Boolean = HaveNarrowingOnlyFromObjectCandidates(candidates)
If haveAllNarrowingFromObject AndAlso Not appliedTieBreakingRules Then
' Apply shadowing rules, Dev10 compiler does that for narrowing candidates too.
applicableCandidates = ApplyTieBreakingRulesToEquallyApplicableCandidates(candidates, arguments, delegateReturnType, binder, useSiteDiagnostics)
appliedTieBreakingRules = True
If applicableCandidates < 2 Then
Return applicableCandidates
End If
haveAllNarrowingFromObject = HaveNarrowingOnlyFromObjectCandidates(candidates)
End If
If haveAllNarrowingFromObject Then
' Get rid of candidates that require narrowing from something other than Object
applicableCandidates = 0
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable Then
If (current.RequiresNarrowingNotFromObject OrElse current.Candidate.IsExtensionMethod) Then
current.State = CandidateAnalysisResultState.ExtensionMethodVsLateBinding
candidates(i) = current
Else
applicableCandidates += 1
End If
End If
Next
Debug.Assert(applicableCandidates > 0)
If applicableCandidates > 1 Then
resolutionIsLateBound = True
End If
Return applicableCandidates
End If
End If
' Although all candidates narrow, there may be a best choice when factoring in narrowing of numeric constants.
' Note that EliminateLessApplicableToTheArguments applies shadowing rules, Dev10 compiler does that for narrowing candidates too.
applicableCandidates = EliminateLessApplicableToTheArguments(candidates, arguments, delegateReturnType, appliedTieBreakingRules, binder,
mostApplicableMustNarrowOnlyFromNumericConstants:=True, useSiteDiagnostics:=useSiteDiagnostics)
' If we ended up with 2 applicable candidates, make sure it is not the same method in
' ParamArray expanded and non-expanded form. The non-expanded form should win in this case.
If applicableCandidates = 2 Then
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim first As CandidateAnalysisResult = candidates(i)
If first.State = CandidateAnalysisResultState.Applicable Then
For j As Integer = i + 1 To candidates.Count - 1 Step 1
Dim second As CandidateAnalysisResult = candidates(j)
If second.State = CandidateAnalysisResultState.Applicable Then
If first.Candidate.UnderlyingSymbol.Equals(second.Candidate.UnderlyingSymbol) Then
Dim firstWins As Boolean = False
Dim secondWins As Boolean = False
If ShadowBasedOnParamArrayUsage(first, second, firstWins, secondWins) Then
If firstWins Then
second.State = CandidateAnalysisResultState.Shadowed
candidates(j) = second
applicableCandidates = 1
ElseIf secondWins Then
first.State = CandidateAnalysisResultState.Shadowed
candidates(i) = first
applicableCandidates = 1
End If
Debug.Assert(applicableCandidates = 1)
End If
End If
GoTo Done
End If
Next
Debug.Assert(False, "Should not reach this line.")
End If
Next
End If
Done:
Return applicableCandidates
End Function
Private Shared Function IsUnwrappingNullable(
conv As ConversionKind,
sourceType As TypeSymbol,
targetType As TypeSymbol
) As Boolean
Debug.Assert((conv And ConversionKind.UserDefined) = 0)
Return (conv And ConversionKind.Nullable) <> 0 AndAlso
sourceType IsNot Nothing AndAlso
sourceType.IsNullableType() AndAlso
Not targetType.IsNullableType()
End Function
Private Shared Function IsUnwrappingNullable(
sourceType As TypeSymbol,
targetType As TypeSymbol,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As Boolean
Return sourceType IsNot Nothing AndAlso
IsUnwrappingNullable(Conversions.ClassifyPredefinedConversion(sourceType, targetType, useSiteDiagnostics), sourceType, targetType)
End Function
Private Shared Function HaveNarrowingOnlyFromObjectCandidates(
candidates As ArrayBuilder(Of CandidateAnalysisResult)
) As Boolean
Dim haveAllNarrowingFromObject As Boolean = False
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable AndAlso
Not current.RequiresNarrowingNotFromObject AndAlso
Not current.Candidate.IsExtensionMethod Then
haveAllNarrowingFromObject = True
Exit For
End If
Next
Return haveAllNarrowingFromObject
End Function
''' <summary>
''' §11.8.1 Overloaded Method Resolution
''' 2. Next, eliminate all members from the set that are inaccessible or not applicable to the argument list.
'''
''' Note, similar to Dev10 compiler this process will eliminate candidates requiring narrowing conversions
''' if strict semantics is used, exception are candidates that require narrowing only from numeric constants.
'''
''' Returns amount of applicable candidates left.
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Private Shared Function EliminateNotApplicableToArguments(
methodOrPropertyGroup As BoundMethodOrPropertyGroup,
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
binder As Binder,
<Out()> ByRef applicableNarrowingCandidates As Integer,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
callerInfoOpt As SyntaxNode,
forceExpandedForm As Boolean,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As Integer
Dim applicableCandidates As Integer = 0
Dim illegalInAttribute As Integer = 0
applicableNarrowingCandidates = 0
' Filter out inapplicable candidates
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
If Not current.ArgumentMatchingDone Then
MatchArguments(methodOrPropertyGroup, current, arguments, argumentNames, binder, asyncLambdaSubToFunctionMismatch, callerInfoOpt, forceExpandedForm, useSiteDiagnostics)
current.SetArgumentMatchingDone()
candidates(i) = current
End If
If current.State = CandidateAnalysisResultState.Applicable Then
applicableCandidates += 1
If current.RequiresNarrowingConversion Then
applicableNarrowingCandidates += 1
End If
If current.IsIllegalInAttribute Then
illegalInAttribute += 1
End If
End If
Next
' Filter out candidates with IsIllegalInAttribute if there are other applicable candidates
If illegalInAttribute > 0 AndAlso applicableCandidates > illegalInAttribute Then
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable AndAlso current.IsIllegalInAttribute Then
applicableCandidates -= 1
If current.RequiresNarrowingConversion Then
applicableNarrowingCandidates -= 1
End If
current.State = CandidateAnalysisResultState.ArgumentMismatch
candidates(i) = current
End If
Next
Debug.Assert(applicableCandidates > 0)
End If
Return applicableCandidates
End Function
''' <summary>
''' Figure out corresponding arguments for parameters §11.8.2 Applicable Methods.
'''
''' Note, this function mutates the candidate structure.
'''
''' If non-Nothing ArrayBuilders are returned through parameterToArgumentMap and paramArrayItems
''' parameters, the caller is responsible fo returning them into the pool.
'''
''' Assumptions:
''' 1) This function is never called for a candidate that should be rejected due to parameter count.
''' 2) Omitted arguments [ Call Goo(a, , b) ] are represented by OmittedArgumentExpression node in the arguments array.
''' 3) Omitted argument never has name.
''' 4) argumentNames contains Nothing for all positional arguments.
'''
''' !!! Should keep this function in sync with Binder.PassArguments, which uses data this function populates. !!!
''' !!! Should keep this function in sync with Binder.ReportOverloadResolutionFailureForASingleCandidate. !!!
''' !!! Everything we flag as an error here, Binder.ReportOverloadResolutionFailureForASingleCandidate should detect as well. !!!
''' </summary>
Private Shared Sub BuildParameterToArgumentMap(
ByRef candidate As CandidateAnalysisResult,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
ByRef parameterToArgumentMap As ArrayBuilder(Of Integer),
ByRef paramArrayItems As ArrayBuilder(Of Integer)
)
Debug.Assert(Not arguments.IsDefault)
Debug.Assert(argumentNames.IsDefault OrElse (argumentNames.Length > 0 AndAlso argumentNames.Length = arguments.Length))
Debug.Assert(Not candidate.ArgumentMatchingDone)
Debug.Assert(candidate.State = CandidateAnalysisResultState.Applicable)
parameterToArgumentMap = ArrayBuilder(Of Integer).GetInstance(candidate.Candidate.ParameterCount, -1)
Dim argsToParams As ArrayBuilder(Of Integer) = Nothing
If Not argumentNames.IsDefault Then
argsToParams = ArrayBuilder(Of Integer).GetInstance(arguments.Length, -1)
End If
paramArrayItems = Nothing
If candidate.IsExpandedParamArrayForm Then
paramArrayItems = ArrayBuilder(Of Integer).GetInstance()
End If
'§11.8.2 Applicable Methods
'1. First, match each positional argument in order to the list of method parameters.
'If there are more positional arguments than parameters and the last parameter is not a paramarray, the method is not applicable.
'Otherwise, the paramarray parameter is expanded with parameters of the paramarray element type to match the number of positional arguments.
'If a positional argument is omitted, the method is not applicable.
' !!! Not sure about the last sentence: "If a positional argument is omitted, the method is not applicable."
' !!! Dev10 allows omitting positional argument as long as the corresponding parameter is optional.
Dim positionalArguments As Integer = 0
Dim paramIndex = 0
For i As Integer = 0 To arguments.Length - 1 Step 1
If Not argumentNames.IsDefault AndAlso argumentNames(i) IsNot Nothing Then
' First named argument
Exit For
End If
positionalArguments += 1
If argsToParams IsNot Nothing Then
argsToParams(i) = paramIndex
End If
If arguments(i).Kind = BoundKind.OmittedArgument Then
If paramIndex = candidate.Candidate.ParameterCount - 1 AndAlso
candidate.Candidate.Parameters(paramIndex).IsParamArray Then
' Omitted ParamArray argument at the call site
' ERRID_OmittedParamArrayArgument
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
Else
paramIndex += 1
End If
ElseIf (candidate.IsExpandedParamArrayForm AndAlso
paramIndex = candidate.Candidate.ParameterCount - 1) Then
paramArrayItems.Add(i)
Else
parameterToArgumentMap(paramIndex) = i
paramIndex += 1
End If
Next
Debug.Assert(argumentNames.IsDefault OrElse positionalArguments < arguments.Length)
'§11.8.2 Applicable Methods
'2. Next, match each named argument to a parameter with the given name.
'If one of the named arguments fails to match, matches a paramarray parameter,
'or matches an argument already matched with another positional or named argument,
'the method is not applicable.
For i As Integer = positionalArguments To arguments.Length - 1 Step 1
Debug.Assert(argumentNames(i) Is Nothing OrElse argumentNames(i).Length > 0)
If argumentNames(i) Is Nothing Then
' Unnamed argument follows named arguments, parser should have detected an error.
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
'Continue For
End If
If Not candidate.Candidate.TryGetNamedParamIndex(argumentNames(i), paramIndex) Then
' ERRID_NamedParamNotFound1
' ERRID_NamedParamNotFound2
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
'Continue For
End If
If argsToParams IsNot Nothing Then
argsToParams(i) = paramIndex
End If
If paramIndex = candidate.Candidate.ParameterCount - 1 AndAlso
candidate.Candidate.Parameters(paramIndex).IsParamArray Then
' ERRID_NamedParamArrayArgument
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
'Continue For
End If
If parameterToArgumentMap(paramIndex) <> -1 Then
' ERRID_NamedArgUsedTwice1
' ERRID_NamedArgUsedTwice2
' ERRID_NamedArgUsedTwice3
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
'Continue For
End If
' It is an error for a named argument to specify
' a value for an explicitly omitted positional argument.
If paramIndex < positionalArguments Then
'ERRID_NamedArgAlsoOmitted1
'ERRID_NamedArgAlsoOmitted2
'ERRID_NamedArgAlsoOmitted3
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
'Continue For
End If
parameterToArgumentMap(paramIndex) = i
Next
If argsToParams IsNot Nothing Then
candidate.ArgsToParamsOpt = argsToParams.ToImmutableAndFree()
argsToParams = Nothing
End If
Bailout:
If argsToParams IsNot Nothing Then
argsToParams.Free()
argsToParams = Nothing
End If
End Sub
''' <summary>
''' Match candidate's parameters to arguments §11.8.2 Applicable Methods.
'''
''' Note, similar to Dev10 compiler this process will eliminate candidate requiring narrowing conversions
''' if strict semantics is used, exception are candidates that require narrowing only from numeric constants.
'''
''' Assumptions:
''' 1) This function is never called for a candidate that should be rejected due to parameter count.
''' 2) Omitted arguments [ Call Goo(a, , b) ] are represented by OmittedArgumentExpression node in the arguments array.
''' 3) Omitted argument never has name.
''' 4) argumentNames contains Nothing for all positional arguments.
'''
''' !!! Should keep this function in sync with Binder.PassArguments, which uses data this function populates. !!!
''' !!! Should keep this function in sync with Binder.ReportOverloadResolutionFailureForASingleCandidate. !!!
''' !!! Should keep this function in sync with InferenceGraph.PopulateGraph. !!!
''' !!! Everything we flag as an error here, Binder.ReportOverloadResolutionFailureForASingleCandidate should detect as well. !!!
''' </summary>
Private Shared Sub MatchArguments(
methodOrPropertyGroup As BoundMethodOrPropertyGroup,
ByRef candidate As CandidateAnalysisResult,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
binder As Binder,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
callerInfoOpt As SyntaxNode,
forceExpandedForm As Boolean,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
)
Debug.Assert(Not arguments.IsDefault)
Debug.Assert(argumentNames.IsDefault OrElse (argumentNames.Length > 0 AndAlso argumentNames.Length = arguments.Length))
Debug.Assert(Not candidate.ArgumentMatchingDone)
Debug.Assert(candidate.State = CandidateAnalysisResultState.Applicable)
Dim parameterToArgumentMap As ArrayBuilder(Of Integer) = Nothing
Dim paramArrayItems As ArrayBuilder(Of Integer) = Nothing
Dim conversionKinds As KeyValuePair(Of ConversionKind, MethodSymbol)() = Nothing
Dim conversionBackKinds As KeyValuePair(Of ConversionKind, MethodSymbol)() = Nothing
Dim optionalArguments As OptionalArgument() = Nothing
Dim diagnostics As DiagnosticBag = Nothing
BuildParameterToArgumentMap(candidate, arguments, argumentNames, parameterToArgumentMap, paramArrayItems)
If candidate.State <> CandidateAnalysisResultState.Applicable Then
Debug.Assert(Not candidate.IgnoreExtensionMethods)
GoTo Bailout
End If
' At this point we will set IgnoreExtensionMethods to true and will
' clear it when appropriate because not every failure should allow
' us to consider extension methods.
If Not candidate.Candidate.IsExtensionMethod Then
candidate.IgnoreExtensionMethods = True
End If
'§11.8.2 Applicable Methods
'The type arguments, if any, must satisfy the constraints, if any, on the matching type parameters.
Dim candidateSymbol = candidate.Candidate.UnderlyingSymbol
If candidateSymbol.Kind = SymbolKind.Method Then
Dim method = DirectCast(candidateSymbol, MethodSymbol)
If method.IsGenericMethod Then
Dim diagnosticsBuilder = ArrayBuilder(Of TypeParameterDiagnosticInfo).GetInstance()
Dim useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo) = Nothing
Dim satisfiedConstraints = method.CheckConstraints(diagnosticsBuilder, useSiteDiagnosticsBuilder)
diagnosticsBuilder.Free()
If useSiteDiagnosticsBuilder IsNot Nothing AndAlso useSiteDiagnosticsBuilder.Count > 0 Then
If useSiteDiagnostics Is Nothing Then
useSiteDiagnostics = New HashSet(Of DiagnosticInfo)()
End If
For Each diag In useSiteDiagnosticsBuilder
useSiteDiagnostics.Add(diag.DiagnosticInfo)
Next
End If
If Not satisfiedConstraints Then
' Do not clear IgnoreExtensionMethods flag if constraints are violated.
candidate.State = CandidateAnalysisResultState.GenericConstraintsViolated
GoTo Bailout
End If
End If
End If
' Traverse the parameters, converting corresponding arguments
' as appropriate.
Dim argIndex As Integer
Dim candidateIsAProperty As Boolean = (candidate.Candidate.UnderlyingSymbol.Kind = SymbolKind.Property)
For paramIndex = 0 To candidate.Candidate.ParameterCount - 1 Step 1
If candidate.State <> CandidateAnalysisResultState.Applicable AndAlso
Not candidate.IgnoreExtensionMethods Then
' There is no reason to continue. We will not learn anything new.
GoTo Bailout
End If
Dim param As ParameterSymbol = candidate.Candidate.Parameters(paramIndex)
Dim isByRef As Boolean = param.IsByRef
Dim targetType As TypeSymbol = param.Type
If param.IsParamArray AndAlso paramIndex = candidate.Candidate.ParameterCount - 1 Then
If targetType.Kind <> SymbolKind.ArrayType Then
' ERRID_ParamArrayWrongType
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
GoTo Bailout
'Continue For
End If
If Not candidate.IsExpandedParamArrayForm Then
argIndex = parameterToArgumentMap(paramIndex)
Dim paramArrayArgument = If(argIndex = -1, Nothing, arguments(argIndex))
Debug.Assert(paramArrayArgument Is Nothing OrElse paramArrayArgument.Kind <> BoundKind.OmittedArgument)
'§11.8.2 Applicable Methods
'If the conversion from the type of the argument expression to the paramarray type is narrowing,
'then the method is only applicable in its expanded form.
'!!! However, there is an exception to that rule - narrowing conversion from semantical Nothing literal is Ok. !!!
Dim arrayConversion As KeyValuePair(Of ConversionKind, MethodSymbol) = Nothing
If Not (paramArrayArgument IsNot Nothing AndAlso
Not paramArrayArgument.HasErrors AndAlso CanPassToParamArray(paramArrayArgument, targetType, arrayConversion, binder, useSiteDiagnostics)) Then
' It doesn't look like native compiler reports any errors in this case.
' Probably due to assumption that either errors were already reported for bad argument expression or
' we will report errors for expanded version of the same candidate.
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
GoTo Bailout
'Continue For
ElseIf Conversions.IsNarrowingConversion(arrayConversion.Key) Then
' We can get here only for Object with constant value == Nothing.
Debug.Assert(paramArrayArgument.IsNothingLiteral())
' Unlike for other arguments, Dev10 doesn't make a note of this narrowing.
' However, should this narrowing cause a conversion error, the error must be noted.
If binder.OptionStrict = OptionStrict.On Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
' Note, this doesn't clear IgnoreExtensionMethods flag.
Continue For
End If
Else
Debug.Assert(Conversions.IsWideningConversion(arrayConversion.Key))
End If
' Since CanPassToParamArray succeeded, there is no need to check conversions for this argument again
If Not Conversions.IsIdentityConversion(arrayConversion.Key) Then
If conversionKinds Is Nothing Then
conversionKinds = New KeyValuePair(Of ConversionKind, MethodSymbol)(arguments.Length - 1) {}
For i As Integer = 0 To conversionKinds.Length - 1
conversionKinds(i) = Conversions.Identity
Next
End If
conversionKinds(argIndex) = arrayConversion
End If
Else
Debug.Assert(candidate.IsExpandedParamArrayForm)
'§11.8.2 Applicable Methods
' If the argument expression is the literal Nothing, then the method is only applicable in its unexpanded form.
' Note, that explicitly converted NOTHING is treated the same way by Dev10.
' But, for the purpose of interpolated string lowering the method is applicable even if the argument expression
' is the literal Nothing. This is because for interpolated string lowering we want to always call methods
' in their expanded form. E.g. $"{Nothing}" should be lowered to String.Format("{0}", New Object() {Nothing}) not
' String.Format("{0}", CType(Nothing, Object())).
If paramArrayItems.Count = 1 AndAlso arguments(paramArrayItems(0)).IsNothingLiteral() AndAlso Not forceExpandedForm Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
GoTo Bailout
'Continue For
End If
' Otherwise, for a ParamArray parameter, all the matching arguments are passed
' ByVal as instances of the element type of the ParamArray.
' Perform the conversions to the element type of the ParamArray here.
Dim arrayType = DirectCast(targetType, ArrayTypeSymbol)
If Not arrayType.IsSZArray Then
' ERRID_ParamArrayWrongType
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
GoTo Bailout
'Continue For
End If
targetType = arrayType.ElementType
If targetType.Kind = SymbolKind.ErrorType Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
' Note, IgnoreExtensionMethods is not cleared.
Continue For
End If
For j As Integer = 0 To paramArrayItems.Count - 1 Step 1
Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = Nothing
If arguments(paramArrayItems(j)).HasErrors Then ' UNDONE: should HasErrors really always cause argument mismatch [petergo, 3/9/2011]
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
GoTo Bailout
'Continue For
End If
If Not MatchArgumentToByValParameter(methodOrPropertyGroup, candidate, arguments(paramArrayItems(j)), targetType, binder, conv, asyncLambdaSubToFunctionMismatch, useSiteDiagnostics) Then
' Note, IgnoreExtensionMethods is not cleared here, MatchArgumentToByValParameter makes required changes.
Continue For
End If
' typically all conversions in otherwise acceptable candidate are identity conversions
If Not Conversions.IsIdentityConversion(conv.Key) Then
If conversionKinds Is Nothing Then
conversionKinds = New KeyValuePair(Of ConversionKind, MethodSymbol)(arguments.Length - 1) {}
For i As Integer = 0 To conversionKinds.Length - 1
conversionKinds(i) = Conversions.Identity
Next
End If
conversionKinds(paramArrayItems(j)) = conv
End If
Next
End If
Continue For
End If
argIndex = parameterToArgumentMap(paramIndex)
Dim argument = If(argIndex = -1, Nothing, arguments(argIndex))
Dim defaultArgument As BoundExpression = Nothing
If argument Is Nothing Then
' Deal with Optional arguments.
If diagnostics Is Nothing Then
diagnostics = DiagnosticBag.GetInstance()
End If
defaultArgument = binder.GetArgumentForParameterDefaultValue(param, methodOrPropertyGroup.Syntax, diagnostics, callerInfoOpt)
If defaultArgument IsNot Nothing AndAlso Not diagnostics.HasAnyErrors Then
Debug.Assert(Not diagnostics.AsEnumerable().Any())
' Mark these as compiler generated so they are ignored by later phases. For example,
' these bound nodes will mess up the incremental binder cache, because they use the
' the same syntax node as the method identifier from the invocation / AddressOf if they
' are not marked.
defaultArgument.SetWasCompilerGenerated()
argument = defaultArgument
Else
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
'Note, IgnoreExtensionMethods flag should not be cleared due to a badness of default value.
candidate.IgnoreExtensionMethods = False
GoTo Bailout
End If
End If
If targetType.Kind = SymbolKind.ErrorType Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
' Note, IgnoreExtensionMethods is not cleared.
Continue For
End If
If argument.HasErrors Then ' UNDONE: should HasErrors really always cause argument mismatch [petergo, 3/9/2011]
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
GoTo Bailout
End If
Dim conversion As KeyValuePair(Of ConversionKind, MethodSymbol) = Nothing
Dim conversionBack As KeyValuePair(Of ConversionKind, MethodSymbol) = Nothing
Debug.Assert(Not isByRef OrElse param.IsExplicitByRef OrElse targetType.IsStringType())
' Arguments for properties are always passed with ByVal semantics. Even if
' parameter in metadata is defined ByRef, we always pass corresponding argument
' through a temp without copy-back.
' Non-string arguments for implicitly ByRef string parameters of Declare functions
' are passed through a temp without copy-back.
If isByRef AndAlso Not candidateIsAProperty AndAlso defaultArgument Is Nothing AndAlso
(param.IsExplicitByRef OrElse (argument.Type IsNot Nothing AndAlso argument.Type.IsStringType())) Then
MatchArgumentToByRefParameter(methodOrPropertyGroup, candidate, argument, targetType, binder, conversion, conversionBack, asyncLambdaSubToFunctionMismatch, useSiteDiagnostics)
Else
conversionBack = Conversions.Identity
MatchArgumentToByValParameter(methodOrPropertyGroup, candidate, argument, targetType, binder, conversion, asyncLambdaSubToFunctionMismatch, useSiteDiagnostics, defaultArgument IsNot Nothing)
End If
' typically all conversions in otherwise acceptable candidate are identity conversions
If Not Conversions.IsIdentityConversion(conversion.Key) Then
If conversionKinds Is Nothing Then
conversionKinds = New KeyValuePair(Of ConversionKind, MethodSymbol)(arguments.Length - 1) {}
For i As Integer = 0 To conversionKinds.Length - 1
conversionKinds(i) = Conversions.Identity
Next
End If
' If this is not a default argument then store the conversion in the conversionKinds.
' For default arguments the conversion is stored below.
If defaultArgument Is Nothing Then
conversionKinds(argIndex) = conversion
End If
End If
' If this is a default argument then add it to the candidate result default arguments.
' Note these arguments are stored by parameter index. Default arguments are missing so they
' may not have an argument index.
If defaultArgument IsNot Nothing Then
If optionalArguments Is Nothing Then
optionalArguments = New OptionalArgument(candidate.Candidate.ParameterCount - 1) {}
End If
optionalArguments(paramIndex) = New OptionalArgument(defaultArgument, conversion)
End If
If Not Conversions.IsIdentityConversion(conversionBack.Key) Then
If conversionBackKinds Is Nothing Then
' There should never be a copy back conversion with a default argument.
Debug.Assert(defaultArgument Is Nothing)
conversionBackKinds = New KeyValuePair(Of ConversionKind, MethodSymbol)(arguments.Length - 1) {}
For i As Integer = 0 To conversionBackKinds.Length - 1
conversionBackKinds(i) = Conversions.Identity
Next
End If
conversionBackKinds(argIndex) = conversionBack
End If
Next
Bailout:
If diagnostics IsNot Nothing Then
diagnostics.Free()
End If
If paramArrayItems IsNot Nothing Then
paramArrayItems.Free()
End If
If conversionKinds IsNot Nothing Then
candidate.ConversionsOpt = conversionKinds.AsImmutableOrNull()
End If
If conversionBackKinds IsNot Nothing Then
candidate.ConversionsBackOpt = conversionBackKinds.AsImmutableOrNull()
End If
If optionalArguments IsNot Nothing Then
candidate.OptionalArguments = optionalArguments.AsImmutableOrNull()
End If
If parameterToArgumentMap IsNot Nothing Then
parameterToArgumentMap.Free()
End If
End Sub
''' <summary>
''' Should be in sync with Binder.ReportByRefConversionErrors.
''' </summary>
Private Shared Sub MatchArgumentToByRefParameter(
methodOrPropertyGroup As BoundMethodOrPropertyGroup,
ByRef candidate As CandidateAnalysisResult,
argument As BoundExpression,
targetType As TypeSymbol,
binder As Binder,
<Out()> ByRef outConversionKind As KeyValuePair(Of ConversionKind, MethodSymbol),
<Out()> ByRef outConversionBackKind As KeyValuePair(Of ConversionKind, MethodSymbol),
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
)
If argument.IsSupportingAssignment() Then
If argument.IsLValue() AndAlso targetType.IsSameTypeIgnoringAll(argument.Type) Then
outConversionKind = Conversions.Identity
outConversionBackKind = Conversions.Identity
Else
outConversionBackKind = Conversions.Identity
If MatchArgumentToByValParameter(methodOrPropertyGroup, candidate, argument, targetType, binder, outConversionKind, asyncLambdaSubToFunctionMismatch, useSiteDiagnostics) Then
' Check copy back conversion
Dim copyBackType = argument.GetTypeOfAssignmentTarget()
Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(targetType, copyBackType, useSiteDiagnostics)
outConversionBackKind = conv
If Conversions.NoConversion(conv.Key) Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch ' Possible only with user-defined conversions, I think.
candidate.IgnoreExtensionMethods = False
Else
If Conversions.IsNarrowingConversion(conv.Key) Then
' Similar to Dev10 compiler, we will eliminate candidate requiring narrowing conversions
' if strict semantics is used, exception are candidates that require narrowing only from
' numeric(Constants.
candidate.SetRequiresNarrowingConversion()
Debug.Assert((conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) = 0)
candidate.SetRequiresNarrowingNotFromNumericConstant()
If binder.OptionStrict = OptionStrict.On Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
Return
End If
If targetType.SpecialType <> SpecialType.System_Object Then
candidate.SetRequiresNarrowingNotFromObject()
End If
End If
candidate.RegisterDelegateRelaxationLevel(conv.Key)
End If
End If
End If
Else
' No copy back needed
' If we are inside a lambda in a constructor and are passing ByRef a non-LValue field, which
' would be an LValue field, if it were referred to in the constructor outside of a lambda,
' we need to report an error because the operation will result in a simulated pass by
' ref (through a temp, without a copy back), which might be not the intent.
If binder.Report_ERRID_ReadOnlyInClosure(argument) Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
' Note, we do not change IgnoreExtensionMethods flag here.
End If
outConversionBackKind = Conversions.Identity
MatchArgumentToByValParameter(methodOrPropertyGroup, candidate, argument, targetType, binder, outConversionKind, asyncLambdaSubToFunctionMismatch, useSiteDiagnostics)
End If
End Sub
''' <summary>
''' Should be in sync with Binder.ReportByValConversionErrors.
''' </summary>
Private Shared Function MatchArgumentToByValParameter(
methodOrPropertyGroup As BoundMethodOrPropertyGroup,
ByRef candidate As CandidateAnalysisResult,
argument As BoundExpression,
targetType As TypeSymbol,
binder As Binder,
<Out()> ByRef outConversionKind As KeyValuePair(Of ConversionKind, MethodSymbol),
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo),
Optional isDefaultValueArgument As Boolean = False
) As Boolean
outConversionKind = Nothing 'VBConversions.NoConversion
' TODO: Do we need to do more thorough check for error types here, i.e. dig into generics,
' arrays, etc., detect types from unreferenced assemblies, ... ?
If targetType.IsErrorType() Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
' Note, IgnoreExtensionMethods is not cleared.
Return False
End If
Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(argument, targetType, binder, useSiteDiagnostics)
outConversionKind = conv
If Conversions.NoConversion(conv.Key) Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
If (conv.Key And (ConversionKind.DelegateRelaxationLevelMask Or ConversionKind.Lambda)) = (ConversionKind.DelegateRelaxationLevelInvalid Or ConversionKind.Lambda) Then
' Dig through parenthesized
Dim underlying As BoundExpression = argument
While underlying.Kind = BoundKind.Parenthesized AndAlso underlying.Type Is Nothing
underlying = DirectCast(underlying, BoundParenthesized).Expression
End While
Dim unbound = If(underlying.Kind = BoundKind.UnboundLambda, DirectCast(underlying, UnboundLambda), Nothing)
If unbound IsNot Nothing AndAlso Not unbound.IsFunctionLambda AndAlso
(unbound.Flags And SourceMemberFlags.Async) <> 0 AndAlso
targetType.IsDelegateType Then
Dim delegateInvoke As MethodSymbol = DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod
Debug.Assert(delegateInvoke IsNot Nothing)
If delegateInvoke IsNot Nothing Then
Dim bound As BoundLambda = unbound.GetBoundLambda(New UnboundLambda.TargetSignature(delegateInvoke))
Debug.Assert(bound IsNot Nothing)
If bound IsNot Nothing AndAlso (bound.MethodConversionKind And MethodConversionKind.AllErrorReasons) = MethodConversionKind.Error_SubToFunction AndAlso
(Not bound.Diagnostics.HasAnyErrors) Then
If asyncLambdaSubToFunctionMismatch Is Nothing Then
asyncLambdaSubToFunctionMismatch = New HashSet(Of BoundExpression)(ReferenceEqualityComparer.Instance)
End If
asyncLambdaSubToFunctionMismatch.Add(unbound)
End If
End If
End If
End If
Return False
End If
' Characteristics of conversion applied to a default value for an optional parameter shouldn't be used to disambiguate
' between two candidates.
If Conversions.IsNarrowingConversion(conv.Key) Then
' Similar to Dev10 compiler, we will eliminate candidate requiring narrowing conversions
' if strict semantics is used, exception are candidates that require narrowing only from
' numeric constants.
If Not isDefaultValueArgument Then
candidate.SetRequiresNarrowingConversion()
End If
If (conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) = 0 Then
If Not isDefaultValueArgument Then
candidate.SetRequiresNarrowingNotFromNumericConstant()
End If
If binder.OptionStrict = OptionStrict.On Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
Return False
End If
End If
Dim argumentType = argument.Type
If argumentType Is Nothing OrElse
argumentType.SpecialType <> SpecialType.System_Object Then
If Not isDefaultValueArgument Then
candidate.SetRequiresNarrowingNotFromObject()
End If
End If
ElseIf (conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) <> 0 Then
' Dev10 overload resolution treats conversions that involve narrowing from numeric constant type
' as narrowing.
If Not isDefaultValueArgument Then
candidate.SetRequiresNarrowingConversion()
candidate.SetRequiresNarrowingNotFromObject()
End If
End If
If Not isDefaultValueArgument Then
candidate.RegisterDelegateRelaxationLevel(conv.Key)
End If
' If we are in attribute context, keep track of candidates that will result in illegal arguments.
' They should be dismissed in favor of other applicable candidates.
If binder.BindingLocation = BindingLocation.Attribute AndAlso
Not candidate.IsIllegalInAttribute AndAlso
Not methodOrPropertyGroup.WasCompilerGenerated AndAlso
methodOrPropertyGroup.Kind = BoundKind.MethodGroup AndAlso
IsWithinAppliedAttributeName(methodOrPropertyGroup.Syntax) AndAlso
DirectCast(candidate.Candidate.UnderlyingSymbol, MethodSymbol).MethodKind = MethodKind.Constructor AndAlso
binder.Compilation.GetWellKnownType(WellKnownType.System_Attribute).IsBaseTypeOf(candidate.Candidate.UnderlyingSymbol.ContainingType, useSiteDiagnostics) Then
Debug.Assert(Not argument.HasErrors)
Dim diagnostics = DiagnosticBag.GetInstance()
Dim passedExpression As BoundExpression = binder.PassArgumentByVal(argument, conv, targetType, diagnostics)
If Not passedExpression.IsConstant Then ' Trying to match native compiler behavior in Semantics::IsValidAttributeConstant
Dim visitor As New Binder.AttributeExpressionVisitor(binder, passedExpression.HasErrors)
visitor.VisitExpression(passedExpression, diagnostics)
If visitor.HasErrors Then
candidate.SetIllegalInAttribute()
End If
End If
diagnostics.Free()
End If
Return True
End Function
Private Shared Function IsWithinAppliedAttributeName(syntax As SyntaxNode) As Boolean
Dim parent As SyntaxNode = syntax.Parent
While parent IsNot Nothing
If parent.Kind = SyntaxKind.Attribute Then
Return DirectCast(parent, AttributeSyntax).Name.Span.Contains(syntax.Position)
ElseIf TypeOf parent Is ExpressionSyntax OrElse TypeOf parent Is StatementSyntax Then
Exit While
End If
parent = parent.Parent
End While
Return False
End Function
Public Shared Function CanPassToParamArray(
expression As BoundExpression,
targetType As TypeSymbol,
<Out()> ByRef outConvKind As KeyValuePair(Of ConversionKind, MethodSymbol),
binder As Binder,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As Boolean
'§11.8.2 Applicable Methods
'If the conversion from the type of the argument expression to the paramarray type is narrowing,
'then the method is only applicable in its expanded form.
outConvKind = Conversions.ClassifyConversion(expression, targetType, binder, useSiteDiagnostics)
' Note, user-defined conversions are acceptable here.
If Conversions.IsWideningConversion(outConvKind.Key) Then
Return True
End If
' Dev10 allows explicitly converted NOTHING as an argument for a ParamArray parameter,
' even if conversion to the array type is narrowing.
If IsNothingLiteral(expression) Then
Debug.Assert(Conversions.IsNarrowingConversion(outConvKind.Key))
Return True
End If
Return False
End Function
''' <summary>
''' Performs an initial pass through the group of candidates and does
''' the following in the process.
''' 1) Eliminates candidates based on the number of supplied arguments and number of supplied generic type arguments.
''' 2) Adds additional entries for expanded ParamArray forms when applicable.
''' 3) Infers method's generic type arguments if needed.
''' 4) Substitutes method's generic type arguments.
''' 5) Eliminates candidates based on shadowing by signature.
''' This partially takes care of §11.8.1 Overloaded Method Resolution, section 7.1.
''' If M is defined in a more derived type than N, eliminate N from the set.
''' 6) Eliminates candidates with identical virtual signatures by applying various shadowing and
''' tie-breaking rules from §11.8.1 Overloaded Method Resolution, section 7.0
''' • If M has fewer parameters from an expanded paramarray than N, eliminate N from the set.
''' 7) Takes care of unsupported overloading within the same type for instance methods/properties.
'''
''' Assumptions:
''' 1) Shadowing by name has been already applied.
''' 2) group can include extension methods.
''' 3) group contains original definitions, i.e. method type arguments have not been substituted yet.
''' Exception are extension methods with type parameters substituted based on receiver type rather
''' than based on type arguments supplied at the call site.
''' 4) group contains only accessible candidates.
''' 5) group doesn't contain members involved into unsupported overloading, i.e. differ by casing or custom modifiers only.
''' 6) group does not contain duplicates.
''' 7) All elements of arguments array are Not Nothing, omitted arguments are represented by OmittedArgumentExpression node.
''' </summary>
''' <remarks>
''' This method is destructive to content of the [group] parameter.
''' </remarks>
Private Shared Sub CollectOverloadedCandidates(
binder As Binder,
results As ArrayBuilder(Of CandidateAnalysisResult),
group As ArrayBuilder(Of Candidate),
typeArguments As ImmutableArray(Of TypeSymbol),
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
delegateReturnType As TypeSymbol,
delegateReturnTypeReferenceBoundNode As BoundNode,
includeEliminatedCandidates As Boolean,
isQueryOperatorInvocation As Boolean,
forceExpandedForm As Boolean,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
)
Debug.Assert(results IsNot Nothing)
Debug.Assert(argumentNames.IsDefault OrElse (argumentNames.Length > 0 AndAlso argumentNames.Length = arguments.Length))
Dim quickInfo = ArrayBuilder(Of QuickApplicabilityInfo).GetInstance()
Dim sourceModule As ModuleSymbol = binder.SourceModule
For i As Integer = 0 To group.Count - 1
If group(i) Is Nothing Then
Continue For
End If
Dim info As QuickApplicabilityInfo = DoQuickApplicabilityCheck(group(i), typeArguments, arguments, isQueryOperatorInvocation, forceExpandedForm, useSiteDiagnostics)
If info.Candidate Is Nothing Then
Continue For
End If
If info.Candidate.UnderlyingSymbol.ContainingModule Is sourceModule OrElse
info.Candidate.IsExtensionMethod Then
CollectOverloadedCandidate(results, info, typeArguments, arguments, argumentNames,
delegateReturnType, delegateReturnTypeReferenceBoundNode,
includeEliminatedCandidates, binder, asyncLambdaSubToFunctionMismatch,
useSiteDiagnostics)
Continue For
End If
' Deal with VB-illegal overloading in imported types.
' We are trying to avoid doing signature comparison as much as possible and limit them to
' cases when at least one candidate is applicable based on the quick applicability check.
' Similar code exists in overriding checks in OverrideHidingHelper.RemoveMembersWithConflictingAccessibility.
Dim container As Symbol = info.Candidate.UnderlyingSymbol.ContainingSymbol
' If there are more candidates from this type, collect all of them in quickInfo array,
' but keep the applicable candidates at the beginning
quickInfo.Clear()
quickInfo.Add(info)
Dim applicableCount As Integer = If(info.State = CandidateAnalysisResultState.Applicable, 1, 0)
For j As Integer = i + 1 To group.Count - 1
If group(j) Is Nothing OrElse
group(j).IsExtensionMethod Then ' VS2013 ignores illegal overloading for extension methods
Continue For
End If
If container = group(j).UnderlyingSymbol.ContainingSymbol Then
info = DoQuickApplicabilityCheck(group(j), typeArguments, arguments, isQueryOperatorInvocation, forceExpandedForm, useSiteDiagnostics)
group(j) = Nothing
If info.Candidate Is Nothing Then
Continue For
End If
' Keep applicable candidates at the beginning.
If info.State <> CandidateAnalysisResultState.Applicable Then
quickInfo.Add(info)
ElseIf applicableCount = quickInfo.Count Then
quickInfo.Add(info)
applicableCount += 1
Else
quickInfo.Add(quickInfo(applicableCount))
quickInfo(applicableCount) = info
applicableCount += 1
End If
End If
Next
' Now see if any candidates are ambiguous or lose against other candidates in the quickInfo array.
' This loop is destructive to the content of the quickInfo, some applicable candidates could be replaced with
' a "better" candidate, even though that candidate is not applicable, "losers" are deleted, etc.
For k As Integer = 0 To If(applicableCount > 0 OrElse Not includeEliminatedCandidates, applicableCount, quickInfo.Count) - 1
info = quickInfo(k)
If info.Candidate Is Nothing OrElse info.State = CandidateAnalysisResultState.Ambiguous Then
Continue For
End If
#If DEBUG Then
Dim isExtensionMethod As Boolean = info.Candidate.IsExtensionMethod
#End If
Dim firstSymbol As Symbol = info.Candidate.UnderlyingSymbol.OriginalDefinition
If firstSymbol.IsReducedExtensionMethod() Then
firstSymbol = DirectCast(firstSymbol, MethodSymbol).ReducedFrom
End If
For l As Integer = k + 1 To quickInfo.Count - 1
Dim info2 As QuickApplicabilityInfo = quickInfo(l)
If info2.Candidate Is Nothing OrElse info2.State = CandidateAnalysisResultState.Ambiguous Then
Continue For
End If
#If DEBUG Then
Debug.Assert(isExtensionMethod = info2.Candidate.IsExtensionMethod)
#End If
Dim secondSymbol As Symbol = info2.Candidate.UnderlyingSymbol.OriginalDefinition
If secondSymbol.IsReducedExtensionMethod() Then
secondSymbol = DirectCast(secondSymbol, MethodSymbol).ReducedFrom
End If
' The following check should be similar to the one performed by SourceNamedTypeSymbol.CheckForOverloadsErrors
' However, we explicitly ignore custom modifiers here, since this part is NYI for SourceNamedTypeSymbol.
Const significantDifferences As SymbolComparisonResults = SymbolComparisonResults.AllMismatches And
Not SymbolComparisonResults.MismatchesForConflictingMethods
Dim comparisonResults As SymbolComparisonResults = OverrideHidingHelper.DetailedSignatureCompare(
firstSymbol,
secondSymbol,
significantDifferences,
significantDifferences)
' Signature must be considered equal following VB rules.
If comparisonResults = 0 Then
Dim accessibilityCmp As Integer = LookupResult.CompareAccessibilityOfSymbolsConflictingInSameContainer(firstSymbol, secondSymbol)
If accessibilityCmp > 0 Then
' first wins
quickInfo(l) = Nothing
ElseIf accessibilityCmp < 0 Then
' second wins
quickInfo(k) = info2
quickInfo(l) = Nothing
firstSymbol = secondSymbol
info = info2
Else
Debug.Assert(accessibilityCmp = 0)
info = New QuickApplicabilityInfo(info.Candidate, CandidateAnalysisResultState.Ambiguous)
quickInfo(k) = info
quickInfo(l) = New QuickApplicabilityInfo(info2.Candidate, CandidateAnalysisResultState.Ambiguous)
End If
End If
Next
If info.State <> CandidateAnalysisResultState.Ambiguous Then
CollectOverloadedCandidate(results, info, typeArguments, arguments, argumentNames,
delegateReturnType, delegateReturnTypeReferenceBoundNode,
includeEliminatedCandidates, binder, asyncLambdaSubToFunctionMismatch,
useSiteDiagnostics)
ElseIf includeEliminatedCandidates Then
CollectOverloadedCandidate(results, info, typeArguments, arguments, argumentNames,
delegateReturnType, delegateReturnTypeReferenceBoundNode,
includeEliminatedCandidates, binder, asyncLambdaSubToFunctionMismatch,
useSiteDiagnostics)
For l As Integer = k + 1 To quickInfo.Count - 1
Dim info2 As QuickApplicabilityInfo = quickInfo(l)
If info2.Candidate IsNot Nothing AndAlso info2.State = CandidateAnalysisResultState.Ambiguous Then
quickInfo(l) = Nothing
CollectOverloadedCandidate(results, info2, typeArguments, arguments, argumentNames,
delegateReturnType, delegateReturnTypeReferenceBoundNode,
includeEliminatedCandidates, binder, asyncLambdaSubToFunctionMismatch,
useSiteDiagnostics)
End If
Next
End If
Next
Next
quickInfo.Free()
#If DEBUG Then
group.Clear()
#End If
End Sub
Private Structure QuickApplicabilityInfo
Public ReadOnly Candidate As Candidate
Public ReadOnly State As CandidateAnalysisResultState
Public ReadOnly AppliesToNormalForm As Boolean
Public ReadOnly AppliesToParamArrayForm As Boolean
Public Sub New(
candidate As Candidate,
state As CandidateAnalysisResultState,
Optional appliesToNormalForm As Boolean = True,
Optional appliesToParamArrayForm As Boolean = True
)
Debug.Assert(candidate IsNot Nothing)
Debug.Assert(appliesToNormalForm OrElse appliesToParamArrayForm)
Me.Candidate = candidate
Me.State = state
Me.AppliesToNormalForm = appliesToNormalForm
Me.AppliesToParamArrayForm = appliesToParamArrayForm
End Sub
End Structure
Private Shared Function DoQuickApplicabilityCheck(
candidate As Candidate,
typeArguments As ImmutableArray(Of TypeSymbol),
arguments As ImmutableArray(Of BoundExpression),
isQueryOperatorInvocation As Boolean,
forceExpandedForm As Boolean,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As QuickApplicabilityInfo
If isQueryOperatorInvocation AndAlso DirectCast(candidate.UnderlyingSymbol, MethodSymbol).IsSub Then
' Subs are never considered as candidates for Query Operators, but method group might have subs in it.
Return Nothing
End If
If candidate.UnderlyingSymbol.HasUnsupportedMetadata Then
Return New QuickApplicabilityInfo(candidate, CandidateAnalysisResultState.HasUnsupportedMetadata)
End If
' If type arguments have been supplied, eliminate procedures that don't have an
' appropriate number of type parameters.
'§11.8.2 Applicable Methods
'Section 4.
' If type arguments have been specified, they are matched against the type parameter list.
' If the two lists do not have the same number of elements, the method is not applicable,
' unless the type argument list is empty.
If typeArguments.Length > 0 AndAlso candidate.Arity <> typeArguments.Length Then
Return New QuickApplicabilityInfo(candidate, CandidateAnalysisResultState.BadGenericArity)
End If
' Eliminate procedures that cannot accept the number of supplied arguments.
Dim requiredCount As Integer
Dim maxCount As Integer
Dim hasParamArray As Boolean
candidate.GetAllParameterCounts(requiredCount, maxCount, hasParamArray)
'§11.8.2 Applicable Methods
'If there are more positional arguments than parameters and the last parameter is not a paramarray,
'the method is not applicable. Otherwise, the paramarray parameter is expanded with parameters of
'the paramarray element type to match the number of positional arguments. If a single argument expression
'matches a paramarray parameter and the type of the argument expression is convertible to both the type of
'the paramarray parameter and the paramarray element type, the method is applicable in both its expanded
'and unexpanded forms, with two exceptions. If the conversion from the type of the argument expression to
'the paramarray type is narrowing, then the method is only applicable in its expanded form. If the argument
'expression is the literal Nothing, then the method is only applicable in its unexpanded form.
If isQueryOperatorInvocation Then
' Query operators require exact match for argument count.
If arguments.Length <> maxCount Then
Return New QuickApplicabilityInfo(candidate, CandidateAnalysisResultState.ArgumentCountMismatch, True, False)
End If
ElseIf arguments.Length < requiredCount OrElse
(Not hasParamArray AndAlso arguments.Length > maxCount) Then
Return New QuickApplicabilityInfo(candidate, CandidateAnalysisResultState.ArgumentCountMismatch, Not hasParamArray, hasParamArray)
End If
Dim useSiteErrorInfo As DiagnosticInfo = candidate.UnderlyingSymbol.GetUseSiteErrorInfo()
If useSiteErrorInfo IsNot Nothing Then
If useSiteDiagnostics Is Nothing Then
useSiteDiagnostics = New HashSet(Of DiagnosticInfo)()
End If
useSiteDiagnostics.Add(useSiteErrorInfo)
Return New QuickApplicabilityInfo(candidate, CandidateAnalysisResultState.HasUseSiteError)
End If
' A method with a paramarray can be considered in two forms: in an
' expanded form or in an unexpanded form (i.e. as if the paramarray
' decoration was not specified). It can apply in both forms, as
' in the case of passing Object() to ParamArray x As Object() (because
' Object() converts to both Object() and Object).
' Does the method apply in its unexpanded form? This can only happen if
' either there is no paramarray or if the argument count matches exactly
' (if it's less, then the paramarray is expanded to nothing, if it's more,
' it's expanded to one or more parameters).
Dim applicableInNormalForm As Boolean = False
Dim applicableInParamArrayForm As Boolean = False
If Not hasParamArray OrElse (arguments.Length = maxCount AndAlso Not forceExpandedForm) Then
applicableInNormalForm = True
End If
' How about it's expanded form? It always applies if there's a paramarray.
If hasParamArray AndAlso Not isQueryOperatorInvocation Then
applicableInParamArrayForm = True
End If
Return New QuickApplicabilityInfo(candidate, CandidateAnalysisResultState.Applicable, applicableInNormalForm, applicableInParamArrayForm)
End Function
Private Shared Sub CollectOverloadedCandidate(
results As ArrayBuilder(Of CandidateAnalysisResult),
candidate As QuickApplicabilityInfo,
typeArguments As ImmutableArray(Of TypeSymbol),
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
delegateReturnType As TypeSymbol,
delegateReturnTypeReferenceBoundNode As BoundNode,
includeEliminatedCandidates As Boolean,
binder As Binder,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
)
Select Case candidate.State
Case CandidateAnalysisResultState.HasUnsupportedMetadata
If includeEliminatedCandidates Then
results.Add(New CandidateAnalysisResult(candidate.Candidate, CandidateAnalysisResultState.HasUnsupportedMetadata))
End If
Case CandidateAnalysisResultState.HasUseSiteError
If includeEliminatedCandidates Then
results.Add(New CandidateAnalysisResult(candidate.Candidate, CandidateAnalysisResultState.HasUseSiteError))
End If
Case CandidateAnalysisResultState.BadGenericArity
If includeEliminatedCandidates Then
results.Add(New CandidateAnalysisResult(candidate.Candidate, CandidateAnalysisResultState.BadGenericArity))
End If
Case CandidateAnalysisResultState.ArgumentCountMismatch
Debug.Assert(candidate.AppliesToNormalForm <> candidate.AppliesToParamArrayForm)
If includeEliminatedCandidates Then
Dim candidateAnalysis As New CandidateAnalysisResult(ConstructIfNeedTo(candidate.Candidate, typeArguments), CandidateAnalysisResultState.ArgumentCountMismatch)
If candidate.AppliesToParamArrayForm Then
candidateAnalysis.SetIsExpandedParamArrayForm()
End If
results.Add(candidateAnalysis)
End If
Case CandidateAnalysisResultState.Applicable
Dim candidateAnalysis As CandidateAnalysisResult
If typeArguments.Length > 0 Then
candidateAnalysis = New CandidateAnalysisResult(candidate.Candidate.Construct(typeArguments))
Else
candidateAnalysis = New CandidateAnalysisResult(candidate.Candidate)
End If
#If DEBUG Then
Dim triedToAddSomething As Boolean = False
#End If
If candidate.AppliesToNormalForm Then
#If DEBUG Then
triedToAddSomething = True
#End If
InferTypeArgumentsIfNeedToAndCombineWithExistingCandidates(results, candidateAnalysis, typeArguments,
arguments, argumentNames,
delegateReturnType, delegateReturnTypeReferenceBoundNode,
binder, asyncLambdaSubToFunctionMismatch,
useSiteDiagnostics)
End If
' How about it's expanded form? It always applies if there's a paramarray.
If candidate.AppliesToParamArrayForm Then
#If DEBUG Then
triedToAddSomething = True
#End If
candidateAnalysis.SetIsExpandedParamArrayForm()
candidateAnalysis.ExpandedParamArrayArgumentsUsed = Math.Max(arguments.Length - candidate.Candidate.ParameterCount + 1, 0)
InferTypeArgumentsIfNeedToAndCombineWithExistingCandidates(results, candidateAnalysis, typeArguments,
arguments, argumentNames,
delegateReturnType, delegateReturnTypeReferenceBoundNode,
binder, asyncLambdaSubToFunctionMismatch,
useSiteDiagnostics)
End If
#If DEBUG Then
Debug.Assert(triedToAddSomething)
#End If
Case CandidateAnalysisResultState.Ambiguous
If includeEliminatedCandidates Then
results.Add(New CandidateAnalysisResult(candidate.Candidate, CandidateAnalysisResultState.Ambiguous))
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(candidate.State)
End Select
End Sub
Private Shared Sub InferTypeArgumentsIfNeedToAndCombineWithExistingCandidates(
results As ArrayBuilder(Of CandidateAnalysisResult),
newCandidate As CandidateAnalysisResult,
typeArguments As ImmutableArray(Of TypeSymbol),
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
delegateReturnType As TypeSymbol,
delegateReturnTypeReferenceBoundNode As BoundNode,
binder As Binder,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
)
If typeArguments.Length = 0 AndAlso newCandidate.Candidate.Arity > 0 Then
'§11.8.2 Applicable Methods
'Section 4.
'If the type argument list is empty, type inferencing is used to try and infer the type argument list.
'If type inferencing fails, the method is not applicable. Otherwise, the type arguments are filled
'in the place of the type parameters in the signature.
If Not InferTypeArguments(newCandidate, arguments, argumentNames, delegateReturnType, delegateReturnTypeReferenceBoundNode,
asyncLambdaSubToFunctionMismatch, binder, useSiteDiagnostics) Then
Debug.Assert(newCandidate.State <> CandidateAnalysisResultState.Applicable)
results.Add(newCandidate)
Return
End If
End If
CombineCandidates(results, newCandidate, arguments.Length, argumentNames, useSiteDiagnostics)
End Sub
''' <summary>
''' Combine new candidate with the list of existing candidates, applying various shadowing and
''' tie-breaking rules. New candidate may or may not be added to the result, some
''' existing candidates may be removed from the result.
''' </summary>
Private Shared Sub CombineCandidates(
results As ArrayBuilder(Of CandidateAnalysisResult),
newCandidate As CandidateAnalysisResult,
argumentCount As Integer,
argumentNames As ImmutableArray(Of String),
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
)
Debug.Assert(newCandidate.State = CandidateAnalysisResultState.Applicable)
Dim operatorResolution As Boolean = newCandidate.Candidate.IsOperator
Debug.Assert(newCandidate.Candidate.ParameterCount >= argumentCount OrElse newCandidate.IsExpandedParamArrayForm)
Debug.Assert(argumentNames.IsDefault OrElse argumentNames.Length > 0)
Debug.Assert(Not operatorResolution OrElse argumentNames.IsDefault)
Dim i As Integer = 0
While i < results.Count
Dim existingCandidate As CandidateAnalysisResult = results(i)
' Skip over some eliminated candidates, which we will be unable to match signature against.
If existingCandidate.State = CandidateAnalysisResultState.ArgumentCountMismatch OrElse
existingCandidate.State = CandidateAnalysisResultState.BadGenericArity OrElse
existingCandidate.State = CandidateAnalysisResultState.Ambiguous Then
GoTo ContinueCandidatesLoop
End If
' Candidate can't hide another form of itself
If existingCandidate.Candidate Is newCandidate.Candidate Then
Debug.Assert(Not operatorResolution)
GoTo ContinueCandidatesLoop
End If
Dim existingWins As Boolean = False
Dim newWins As Boolean = False
' An overriding method hides the methods it overrides.
' In particular, this rule takes care of bug VSWhidbey #385900. Where type argument inference fails
' for an overriding method due to named argument name mismatch, but succeeds for the overridden method
' from base (the overridden method uses parameter name matching the named argument name). At the end,
' however, the overriding method is called, even though it doesn't have parameter with matching name.
' Also helps with methods overridden by restricted types (TypedReference, etc.), ShadowBasedOnReceiverType
' doesn't do the job for them because it relies on Conversions.ClassifyDirectCastConversion, which
' disallows boxing conversion for restricted types.
If Not operatorResolution AndAlso ShadowBasedOnOverriding(existingCandidate, newCandidate, existingWins, newWins) Then
GoTo DeterminedTheWinner
End If
If existingCandidate.State = CandidateAnalysisResultState.TypeInferenceFailed OrElse existingCandidate.SomeInferenceFailed OrElse
existingCandidate.State = CandidateAnalysisResultState.HasUseSiteError OrElse
existingCandidate.State = CandidateAnalysisResultState.HasUnsupportedMetadata Then
' Won't be able to match signature.
GoTo ContinueCandidatesLoop
End If
' It looks like the following code is applying some tie-breaking rules from section 7 of
' §11.8.1 Overloaded Method Resolution, but not all of them and even skips ParamArrays tie-breaking
' rule in some scenarios. I couldn't find an explanation of this behavior in the spec and
' simply tried to keep this code close to Dev10.
' Spec says that the tie-breaking rules should be applied only for members equally applicable to the argument list.
' [§11.8.1.1 Applicability] defines equally applicable members as follows:
' A member M is considered equally applicable as N if
' 1) their signatures are the same or
' 2) if each parameter type in M is the same as the corresponding parameter type in N.
' We can always check if signature is the same, but we cannot check the second condition in presence
' of named arguments because for them we don't know yet which parameter in M corresponds to which
' parameter in N.
Debug.Assert(existingCandidate.Candidate.ParameterCount >= argumentCount OrElse existingCandidate.IsExpandedParamArrayForm)
If argumentNames.IsDefault Then
Dim existingParamIndex As Integer = 0
Dim newParamIndex As Integer = 0
'CONSIDER: Can we somehow merge this with the complete signature comparison?
For j As Integer = 0 To argumentCount - 1 Step 1
Dim existingType As TypeSymbol = GetParameterTypeFromVirtualSignature(existingCandidate, existingParamIndex)
Dim newType As TypeSymbol = GetParameterTypeFromVirtualSignature(newCandidate, newParamIndex)
If Not existingType.IsSameTypeIgnoringAll(newType) Then
' Signatures are different, shadowing rules do not apply
GoTo ContinueCandidatesLoop
End If
' Advance to the next parameter in the existing candidate,
' unless we are on the expanded ParamArray parameter.
AdvanceParameterInVirtualSignature(existingCandidate, existingParamIndex)
' Advance to the next parameter in the new candidate,
' unless we are on the expanded ParamArray parameter.
AdvanceParameterInVirtualSignature(newCandidate, newParamIndex)
Next
Else
Debug.Assert(Not operatorResolution)
End If
Dim signatureMatch As Boolean = True
' Compare complete signature, with no regard to arguments
If existingCandidate.Candidate.ParameterCount <> newCandidate.Candidate.ParameterCount Then
Debug.Assert(Not operatorResolution)
signatureMatch = False
ElseIf operatorResolution Then
Debug.Assert(argumentCount = existingCandidate.Candidate.ParameterCount)
Debug.Assert(signatureMatch)
' Not lifted operators are preferred over lifted.
If existingCandidate.Candidate.IsLifted Then
If Not newCandidate.Candidate.IsLifted Then
newWins = True
GoTo DeterminedTheWinner
End If
ElseIf newCandidate.Candidate.IsLifted Then
Debug.Assert(Not existingCandidate.Candidate.IsLifted)
existingWins = True
GoTo DeterminedTheWinner
End If
Else
For j As Integer = 0 To existingCandidate.Candidate.ParameterCount - 1 Step 1
Dim existingType As TypeSymbol = existingCandidate.Candidate.Parameters(j).Type
Dim newType As TypeSymbol = newCandidate.Candidate.Parameters(j).Type
If Not existingType.IsSameTypeIgnoringAll(newType) Then
signatureMatch = False
Exit For
End If
Next
End If
If Not argumentNames.IsDefault AndAlso Not signatureMatch Then
' Signatures are different, shadowing rules do not apply
GoTo ContinueCandidatesLoop
End If
If Not signatureMatch Then
Debug.Assert(argumentNames.IsDefault)
' If we have gotten to this point it means that the 2 procedures have equal specificity,
' but signatures that do not match exactly (after generic substitution). This
' implies that we are dealing with differences in shape due to param arrays
' or optional arguments.
' So we look and see if one procedure maps fewer arguments to the
' param array than the other. The one using more, is then shadowed by the one using less.
'• If M has fewer parameters from an expanded paramarray than N, eliminate N from the set.
If ShadowBasedOnParamArrayUsage(existingCandidate, newCandidate, existingWins, newWins) Then
GoTo DeterminedTheWinner
End If
Else
' The signatures of the two methods match (after generic parameter substitution).
' This means that param array shadowing doesn't come into play.
' !!! Why? Where is this mentioned in the spec?
End If
Debug.Assert(argumentNames.IsDefault OrElse signatureMatch)
' In presence of named arguments, the following shadowing rules
' cannot be applied if any candidate is extension method because
' full signature match doesn't guarantee equal applicability (in presence of named arguments)
' and instance methods hide by signature regardless applicability rules do not apply to extension methods.
If argumentNames.IsDefault OrElse
Not (existingCandidate.Candidate.IsExtensionMethod OrElse newCandidate.Candidate.IsExtensionMethod) Then
'7.1. If M is defined in a more derived type than N, eliminate N from the set.
' This rule also applies to the types that extension methods are defined on.
'7.2. If M and N are extension methods and the target type of M is a class or
' structure and the target type of N is an interface, eliminate N from the set.
If ShadowBasedOnReceiverType(existingCandidate, newCandidate, existingWins, newWins, useSiteDiagnostics) Then
GoTo DeterminedTheWinner
End If
'7.3. If M and N are extension methods and the target type of M has fewer type
' parameters than the target type of N, eliminate N from the set.
' !!! Note that spec talks about "fewer type parameters", but it is not really about count.
' !!! It is about one refers to a type parameter and the other one doesn't.
If ShadowBasedOnExtensionMethodTargetTypeGenericity(existingCandidate, newCandidate, existingWins, newWins) Then
GoTo DeterminedTheWinner
End If
End If
DeterminedTheWinner:
Debug.Assert(Not existingWins OrElse Not newWins) ' Both cannot win!
If newWins Then
' Remove existing
results.RemoveAt(i)
' We should continue the loop because at least with
' extension methods in the picture, there could be other
' winners and losers in the results.
' Since we removed the element, we should bypass index increment.
Continue While
ElseIf existingWins Then
' New candidate lost, shouldn't add it.
Return
End If
ContinueCandidatesLoop:
i += 1
End While
results.Add(newCandidate)
End Sub
Private Shared Function ShadowBasedOnOverriding(
existingCandidate As CandidateAnalysisResult, newCandidate As CandidateAnalysisResult,
ByRef existingWins As Boolean, ByRef newWins As Boolean
) As Boolean
Dim existingSymbol As Symbol = existingCandidate.Candidate.UnderlyingSymbol
Dim newSymbol As Symbol = newCandidate.Candidate.UnderlyingSymbol
Dim existingType As NamedTypeSymbol = existingSymbol.ContainingType
Dim newType As NamedTypeSymbol = newSymbol.ContainingType
' Optimization: We will rely on ShadowBasedOnReceiverType to give us the
' same effect later on for cases when existingCandidate is
' applicable and neither candidate is from restricted type.
Dim existingIsApplicable As Boolean = (existingCandidate.State = CandidateAnalysisResultState.Applicable)
If existingIsApplicable AndAlso Not existingType.IsRestrictedType() AndAlso Not newType.IsRestrictedType() Then
Return False
End If
' Optimization: symbols from the same type can't override each other.
' ShadowBasedOnReceiverType
If existingType.OriginalDefinition IsNot newType.OriginalDefinition Then
If newCandidate.Candidate.IsOverriddenBy(existingSymbol) Then
existingWins = True
Return True
ElseIf existingIsApplicable AndAlso existingCandidate.Candidate.IsOverriddenBy(newSymbol) Then
newWins = True
Return True
End If
End If
Return False
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.5. If M is not an extension method and N is, eliminate N from the set.
''' 7.6. If M and N are extension methods and M was found before N, eliminate N from the set.
''' </summary>
Private Shared Function ShadowBasedOnExtensionVsInstanceAndPrecedence(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean
) As Boolean
If left.Candidate.IsExtensionMethod Then
If Not right.Candidate.IsExtensionMethod Then
'7.5.
rightWins = True
Return True
Else
' Both are extensions
If left.Candidate.PrecedenceLevel < right.Candidate.PrecedenceLevel Then
'7.6.
leftWins = True
Return True
ElseIf left.Candidate.PrecedenceLevel > right.Candidate.PrecedenceLevel Then
'7.6.
rightWins = True
Return True
End If
End If
ElseIf right.Candidate.IsExtensionMethod Then
'7.5.
leftWins = True
Return True
End If
Return False
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.4. If M is less generic than N, eliminate N from the set.
''' </summary>
Private Shared Function ShadowBasedOnGenericity(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean,
arguments As ImmutableArray(Of BoundExpression),
binder As Binder
) As Boolean
' §11.8.1.2 Genericity
' A member M is determined to be less generic than a member N as follows:
'
' 1. If, for each pair of matching parameters Mj and Nj, Mj is less or equally generic than Nj
' with respect to type parameters on the method, and at least one Mj is less generic with
' respect to type parameters on the method.
' 2. Otherwise, if for each pair of matching parameters Mj and Nj, Mj is less or equally generic
' than Nj with respect to type parameters on the type, and at least one Mj is less generic with
' respect to type parameters on the type, then M is less generic than N.
'
' A parameter M is considered to be equally generic to a parameter N if their types Mt and Nt
' both refer to type parameters or both don't refer to type parameters. M is considered to be less
' generic than N if Mt does not refer to a type parameter and Nt does.
'
' Extension method type parameters that were fixed during currying are considered type parameters on the type,
' not type parameters on the method.
' At the beginning we will track both method and type type parameters.
Dim track As TypeParameterKind = TypeParameterKind.Both
If Not (left.Candidate.IsGeneric OrElse right.Candidate.IsGeneric) Then
track = track And (Not TypeParameterKind.Method)
End If
If Not ((left.Candidate.UnderlyingSymbol.ContainingType.IsOrInGenericType() OrElse
(left.Candidate.IsExtensionMethod AndAlso Not left.Candidate.FixedTypeParameters.IsNull)) OrElse
(right.Candidate.UnderlyingSymbol.ContainingType.IsOrInGenericType() OrElse
(right.Candidate.IsExtensionMethod AndAlso Not right.Candidate.FixedTypeParameters.IsNull))) Then
track = track And (Not TypeParameterKind.Type)
End If
If track = TypeParameterKind.None Then
Return False ' There is no winner.
End If
#If DEBUG Then
Dim saveTrack = track
#End If
Dim leftHasLeastGenericParameterAgainstMethod As Boolean = False
Dim leftHasLeastGenericParameterAgainstType As Boolean = False
Dim rightHasLeastGenericParameterAgainstMethod As Boolean = False
Dim rightHasLeastGenericParameterAgainstType As Boolean = False
Dim leftParamIndex As Integer = 0
Dim rightParamIndex As Integer = 0
For i = 0 To arguments.Length - 1 Step 1
Dim leftParamType As TypeSymbol
Dim leftParamTypeForGenericityCheck As TypeSymbol = Nothing
Debug.Assert(left.ArgsToParamsOpt.IsDefault = right.ArgsToParamsOpt.IsDefault)
If left.ArgsToParamsOpt.IsDefault Then
leftParamType = GetParameterTypeFromVirtualSignature(left, leftParamIndex, leftParamTypeForGenericityCheck)
AdvanceParameterInVirtualSignature(left, leftParamIndex)
Else
leftParamType = GetParameterTypeFromVirtualSignature(left, left.ArgsToParamsOpt(i), leftParamTypeForGenericityCheck)
End If
Dim rightParamType As TypeSymbol
Dim rightParamTypeForGenericityCheck As TypeSymbol = Nothing
If right.ArgsToParamsOpt.IsDefault Then
rightParamType = GetParameterTypeFromVirtualSignature(right, rightParamIndex, rightParamTypeForGenericityCheck)
AdvanceParameterInVirtualSignature(right, rightParamIndex)
Else
rightParamType = GetParameterTypeFromVirtualSignature(right, right.ArgsToParamsOpt(i), rightParamTypeForGenericityCheck)
End If
' Parameters matching omitted arguments do not participate.
If arguments(i).Kind = BoundKind.OmittedArgument Then
Continue For
End If
If SignatureMismatchForThePurposeOfShadowingBasedOnGenericity(leftParamType, rightParamType, arguments(i), binder) Then
Return False
End If
Dim leftRefersTo As TypeParameterKind = DetectReferencesToGenericParameters(leftParamTypeForGenericityCheck, track, left.Candidate.FixedTypeParameters)
Dim rightRefersTo As TypeParameterKind = DetectReferencesToGenericParameters(rightParamTypeForGenericityCheck, track, right.Candidate.FixedTypeParameters)
' Still looking for less generic with respect to type parameters on the method.
If (track And TypeParameterKind.Method) <> 0 Then
If (leftRefersTo And TypeParameterKind.Method) = 0 Then
If (rightRefersTo And TypeParameterKind.Method) <> 0 Then
leftHasLeastGenericParameterAgainstMethod = True
End If
ElseIf (rightRefersTo And TypeParameterKind.Method) = 0 Then
rightHasLeastGenericParameterAgainstMethod = True
End If
' If both won at least once, neither candidate is less generic with respect to type parameters on the method.
' Stop checking for this.
If leftHasLeastGenericParameterAgainstMethod AndAlso rightHasLeastGenericParameterAgainstMethod Then
track = track And (Not TypeParameterKind.Method)
End If
End If
' Still looking for less generic with respect to type parameters on the type.
If (track And TypeParameterKind.Type) <> 0 Then
If (leftRefersTo And TypeParameterKind.Type) = 0 Then
If (rightRefersTo And TypeParameterKind.Type) <> 0 Then
leftHasLeastGenericParameterAgainstType = True
End If
ElseIf (rightRefersTo And TypeParameterKind.Type) = 0 Then
rightHasLeastGenericParameterAgainstType = True
End If
' If both won at least once, neither candidate is less generic with respect to type parameters on the type.
' Stop checking for this.
If leftHasLeastGenericParameterAgainstType AndAlso rightHasLeastGenericParameterAgainstType Then
track = track And (Not TypeParameterKind.Type)
End If
End If
' Are we still looking for a winner?
If track = TypeParameterKind.None Then
#If DEBUG Then
Debug.Assert((saveTrack And TypeParameterKind.Method) = 0 OrElse (leftHasLeastGenericParameterAgainstMethod AndAlso rightHasLeastGenericParameterAgainstMethod))
Debug.Assert((saveTrack And TypeParameterKind.Type) = 0 OrElse (leftHasLeastGenericParameterAgainstType AndAlso rightHasLeastGenericParameterAgainstType))
#End If
Return False ' There is no winner.
End If
Next
If leftHasLeastGenericParameterAgainstMethod Then
If Not rightHasLeastGenericParameterAgainstMethod Then
leftWins = True
Return True
End If
ElseIf rightHasLeastGenericParameterAgainstMethod Then
rightWins = True
Return True
End If
If leftHasLeastGenericParameterAgainstType Then
If Not rightHasLeastGenericParameterAgainstType Then
leftWins = True
Return True
End If
ElseIf rightHasLeastGenericParameterAgainstType Then
rightWins = True
Return True
End If
Return False
End Function
Private Shared Function SignatureMismatchForThePurposeOfShadowingBasedOnGenericity(
leftParamType As TypeSymbol,
rightParamType As TypeSymbol,
argument As BoundExpression,
binder As Binder
) As Boolean
Debug.Assert(argument.Kind <> BoundKind.OmittedArgument)
' See Semantics::CompareGenericityIsSignatureMismatch in native compiler.
If leftParamType.IsSameTypeIgnoringAll(rightParamType) Then
Return False
Else
' Note: Undocumented rule.
' Different types. We still consider them the same if they are delegates with
' equivalent signatures, after possibly unwrapping Expression(Of D).
Dim leftIsExpressionTree As Boolean, rightIsExpressionTree As Boolean
Dim leftDelegateType As NamedTypeSymbol = leftParamType.DelegateOrExpressionDelegate(binder, leftIsExpressionTree)
Dim rightDelegateType As NamedTypeSymbol = rightParamType.DelegateOrExpressionDelegate(binder, rightIsExpressionTree)
' Native compiler will only compare D1 and D2 for Expression(Of D1) and D2 if the argument is a lambda. It will compare
' Expression(Of D1) and Expression (Of D2) regardless of the argument.
If leftDelegateType IsNot Nothing AndAlso rightDelegateType IsNot Nothing AndAlso
((leftIsExpressionTree = rightIsExpressionTree) OrElse argument.IsAnyLambda()) Then
Dim leftInvoke = leftDelegateType.DelegateInvokeMethod
Dim rightInvoke = rightDelegateType.DelegateInvokeMethod
If leftInvoke IsNot Nothing AndAlso rightInvoke IsNot Nothing AndAlso
MethodSignatureComparer.ParametersAndReturnTypeSignatureComparer.Equals(leftInvoke, rightInvoke) Then
Return False
End If
End If
End If
Return True
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1.3 Depth of genericity
''' </summary>
Private Shared Function ShadowBasedOnDepthOfGenericity(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean,
arguments As ImmutableArray(Of BoundExpression),
binder As Binder
) As Boolean
' §11.8.1.3 Depth of Genericity
' A member M is determined to have greater depth of genericity than a member N if, for each pair
' of matching parameters Mj and Nj, Mj has greater or equal depth of genericity than Nj, and at
' least one Mj is has greater depth of genericity. Depth of genericity is defined as follows:
'
' 1. Anything other than a type parameter has greater depth of genericity than a type parameter;
' 2. Recursively, a constructed type has greater depth of genericity than another constructed type
' (with the same number of type arguments) if at least one type argument has greater depth
' of genericity and no type argument has less depth than the corresponding type argument in the other.
' 3. An array type has greater depth of genericity than another array type (with the same number
' of dimensions) if the element type of the first has greater depth of genericity than the
' element type of the second.
'
' For example:
'
' Module Test
' Sub f(Of T)(x As Task(Of T))
' End Sub
' Sub f(Of T)(x As T)
' End Sub
' Sub Main()
' Dim x As Task(Of Integer) = Nothing
' f(x) ' Calls the first overload
' End Sub
' End Module
Dim leftParamIndex As Integer = 0
Dim rightParamIndex As Integer = 0
For i = 0 To arguments.Length - 1 Step 1
Dim leftParamType As TypeSymbol
Dim leftParamTypeForGenericityCheck As TypeSymbol = Nothing
Debug.Assert(left.ArgsToParamsOpt.IsDefault = right.ArgsToParamsOpt.IsDefault)
If left.ArgsToParamsOpt.IsDefault Then
leftParamType = GetParameterTypeFromVirtualSignature(left, leftParamIndex, leftParamTypeForGenericityCheck)
AdvanceParameterInVirtualSignature(left, leftParamIndex)
Else
leftParamType = GetParameterTypeFromVirtualSignature(left, left.ArgsToParamsOpt(i), leftParamTypeForGenericityCheck)
End If
Dim rightParamType As TypeSymbol
Dim rightParamTypeForGenericityCheck As TypeSymbol = Nothing
If right.ArgsToParamsOpt.IsDefault Then
rightParamType = GetParameterTypeFromVirtualSignature(right, rightParamIndex, rightParamTypeForGenericityCheck)
AdvanceParameterInVirtualSignature(right, rightParamIndex)
Else
rightParamType = GetParameterTypeFromVirtualSignature(right, right.ArgsToParamsOpt(i), rightParamTypeForGenericityCheck)
End If
' Parameters matching omitted arguments do not participate.
If arguments(i).Kind = BoundKind.OmittedArgument Then
Continue For
End If
If SignatureMismatchForThePurposeOfShadowingBasedOnGenericity(leftParamType, rightParamType, arguments(i), binder) Then
Return False ' no winner if the types of the parameter are different
End If
Dim leftParamWins As Boolean = False
Dim rightParamWins As Boolean = False
If CompareParameterTypeGenericDepth(leftParamTypeForGenericityCheck, rightParamTypeForGenericityCheck, leftParamWins, rightParamWins) Then
Debug.Assert(leftParamWins <> rightParamWins)
If leftParamWins Then
If rightWins Then
rightWins = False
Return False ' both won
Else
leftWins = True
End If
Else
If leftWins Then
leftWins = False
Return False ' both won
Else
rightWins = True
End If
End If
End If
Next
Debug.Assert(Not leftWins OrElse Not rightWins)
Return leftWins OrElse rightWins
End Function
''' <summary>
'''
''' </summary>
''' <returns>False if node of candidates wins</returns>
Private Shared Function CompareParameterTypeGenericDepth(leftType As TypeSymbol, rightType As TypeSymbol,
ByRef leftWins As Boolean, ByRef rightWins As Boolean) As Boolean
' Depth of genericity is defined as follows:
' 1. Anything other than a type parameter has greater depth of genericity than a type parameter;
' 2. Recursively, a constructed type has greater depth of genericity than another constructed
' type (with the same number of type arguments) if at least one type argument has greater
' depth of genericity and no type argument has less depth than the corresponding type
' argument in the other.
' 3. An array type has greater depth of genericity than another array type (with the same number
' of dimensions) if the element type of the first has greater depth of genericity than the
' element type of the second.
'
' For exact rules see Dev11 OverloadResolution.cpp: void Semantics::CompareParameterTypeGenericDepth(...)
If leftType Is rightType Then
Return False
End If
If leftType.IsTypeParameter Then
If rightType.IsTypeParameter Then
' Both type parameters => no winner
Return False
Else
' Left is a type parameter, but right is not
rightWins = True
Return True
End If
ElseIf rightType.IsTypeParameter Then
' Right is a type parameter, but left is not
leftWins = True
Return True
End If
' None of the two is a type parameter
If leftType.IsArrayType AndAlso rightType.IsArrayType Then
' Both are arrays
Dim leftArray = DirectCast(leftType, ArrayTypeSymbol)
Dim rightArray = DirectCast(rightType, ArrayTypeSymbol)
If leftArray.HasSameShapeAs(rightArray) Then
Return CompareParameterTypeGenericDepth(leftArray.ElementType, rightArray.ElementType, leftWins, rightWins)
End If
End If
' Both are generics
If leftType.Kind = SymbolKind.NamedType AndAlso rightType.Kind = SymbolKind.NamedType Then
Dim leftNamedType = DirectCast(leftType.GetTupleUnderlyingTypeOrSelf(), NamedTypeSymbol)
Dim rightNamedType = DirectCast(rightType.GetTupleUnderlyingTypeOrSelf(), NamedTypeSymbol)
' If their arities are equal
If leftNamedType.Arity = rightNamedType.Arity Then
Dim leftTypeArguments As ImmutableArray(Of TypeSymbol) = leftNamedType.TypeArgumentsNoUseSiteDiagnostics
Dim rightTypeArguments As ImmutableArray(Of TypeSymbol) = rightNamedType.TypeArgumentsNoUseSiteDiagnostics
For i = 0 To leftTypeArguments.Length - 1
Dim leftArgWins As Boolean = False
Dim rightArgWins As Boolean = False
If CompareParameterTypeGenericDepth(leftTypeArguments(i), rightTypeArguments(i), leftArgWins, rightArgWins) Then
Debug.Assert(leftArgWins <> rightArgWins)
If leftArgWins Then
If rightWins Then
rightWins = False
Return False
Else
leftWins = True
End If
Else
If leftWins Then
leftWins = False
Return False
Else
rightWins = True
End If
End If
End If
Next
Debug.Assert(Not leftWins OrElse Not rightWins)
Return leftWins OrElse rightWins
End If
End If
Return False
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.3. If M and N are extension methods and the target type of M has fewer type
''' parameters than the target type of N, eliminate N from the set.
''' !!! Note that spec talks about "fewer type parameters", but it is not really about count.
''' !!! It is about one refers to a type parameter and the other one doesn't.
''' </summary>
Private Shared Function ShadowBasedOnExtensionMethodTargetTypeGenericity(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean
) As Boolean
If Not left.Candidate.IsExtensionMethod OrElse Not right.Candidate.IsExtensionMethod Then
Return False
End If
'!!! Note, the spec does not mention this explicitly, but this rule applies only if receiver type
'!!! is the same for both methods.
If Not left.Candidate.ReceiverType.IsSameTypeIgnoringAll(right.Candidate.ReceiverType) Then
Return False
End If
' Only interested in method type parameters.
Dim leftRefersToATypeParameter = DetectReferencesToGenericParameters(left.Candidate.ReceiverTypeDefinition,
TypeParameterKind.Method,
BitVector.Null)
' Only interested in method type parameters.
Dim rightRefersToATypeParameter = DetectReferencesToGenericParameters(right.Candidate.ReceiverTypeDefinition,
TypeParameterKind.Method,
BitVector.Null)
If (leftRefersToATypeParameter And TypeParameterKind.Method) <> 0 Then
If (rightRefersToATypeParameter And TypeParameterKind.Method) = 0 Then
rightWins = True
Return True
End If
ElseIf (rightRefersToATypeParameter And TypeParameterKind.Method) <> 0 Then
leftWins = True
Return True
End If
Return False
End Function
<Flags()>
Private Enum TypeParameterKind
None = 0
Method = 1 << 0
Type = 1 << 1
Both = Method Or Type
End Enum
Private Shared Function DetectReferencesToGenericParameters(
symbol As NamedTypeSymbol,
track As TypeParameterKind,
methodTypeParametersToTreatAsTypeTypeParameters As BitVector
) As TypeParameterKind
Dim result As TypeParameterKind = TypeParameterKind.None
Do
If symbol Is symbol.OriginalDefinition Then
If (track And TypeParameterKind.Type) = 0 Then
Return result
End If
If symbol.Arity > 0 Then
Return result Or TypeParameterKind.Type
End If
Else
For Each argument As TypeSymbol In symbol.TypeArgumentsNoUseSiteDiagnostics
result = result Or DetectReferencesToGenericParameters(argument, track,
methodTypeParametersToTreatAsTypeTypeParameters)
If (result And track) = track Then
Return result
End If
Next
End If
symbol = symbol.ContainingType
Loop While symbol IsNot Nothing
Return result
End Function
Private Shared Function DetectReferencesToGenericParameters(
symbol As TypeParameterSymbol,
track As TypeParameterKind,
methodTypeParametersToTreatAsTypeTypeParameters As BitVector
) As TypeParameterKind
If symbol.ContainingSymbol.Kind = SymbolKind.NamedType Then
If (track And TypeParameterKind.Type) <> 0 Then
Return TypeParameterKind.Type
End If
Else
If methodTypeParametersToTreatAsTypeTypeParameters.IsNull OrElse Not methodTypeParametersToTreatAsTypeTypeParameters(symbol.Ordinal) Then
If (track And TypeParameterKind.Method) <> 0 Then
Return TypeParameterKind.Method
End If
Else
If (track And TypeParameterKind.Type) <> 0 Then
Return TypeParameterKind.Type
End If
End If
End If
Return TypeParameterKind.None
End Function
Private Shared Function DetectReferencesToGenericParameters(
this As TypeSymbol,
track As TypeParameterKind,
methodTypeParametersToTreatAsTypeTypeParameters As BitVector
) As TypeParameterKind
Select Case this.Kind
Case SymbolKind.TypeParameter
Return DetectReferencesToGenericParameters(DirectCast(this, TypeParameterSymbol), track,
methodTypeParametersToTreatAsTypeTypeParameters)
Case SymbolKind.ArrayType
Return DetectReferencesToGenericParameters(DirectCast(this, ArrayTypeSymbol).ElementType, track,
methodTypeParametersToTreatAsTypeTypeParameters)
Case SymbolKind.NamedType, SymbolKind.ErrorType
Return DetectReferencesToGenericParameters(DirectCast(this, NamedTypeSymbol), track,
methodTypeParametersToTreatAsTypeTypeParameters)
Case Else
Throw ExceptionUtilities.UnexpectedValue(this.Kind)
End Select
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.1. If M is defined in a more derived type than N, eliminate N from the set.
''' This rule also applies to the types that extension methods are defined on.
''' 7.2. If M and N are extension methods and the target type of M is a class or
''' structure and the target type of N is an interface, eliminate N from the set.
''' </summary>
Private Shared Function ShadowBasedOnReceiverType(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As Boolean
Dim leftType = left.Candidate.ReceiverType
Dim rightType = right.Candidate.ReceiverType
If Not leftType.IsSameTypeIgnoringAll(rightType) Then
If DoesReceiverMatchInstance(leftType, rightType, useSiteDiagnostics) Then
leftWins = True
Return True
ElseIf DoesReceiverMatchInstance(rightType, leftType, useSiteDiagnostics) Then
rightWins = True
Return True
End If
End If
Return False
End Function
''' <summary>
''' For a receiver to match an instance, more or less, the type of that instance has to be convertible
''' to the type of the receiver with the same bit-representation (i.e. identity on value-types
''' and reference-convertibility on reference types).
''' Actually, we don't include the reference-convertibilities that seem nonsensical, e.g. enum() to underlyingtype()
''' We do include inheritance, implements and variance conversions amongst others.
''' </summary>
Public Shared Function DoesReceiverMatchInstance(instanceType As TypeSymbol, receiverType As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As Boolean
Return Conversions.HasWideningDirectCastConversionButNotEnumTypeConversion(instanceType, receiverType, useSiteDiagnostics)
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' • If M has fewer parameters from an expanded paramarray than N, eliminate N from the set.
''' </summary>
Private Shared Function ShadowBasedOnParamArrayUsage(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean
) As Boolean
If left.IsExpandedParamArrayForm Then
If right.IsExpandedParamArrayForm Then
If left.ExpandedParamArrayArgumentsUsed > right.ExpandedParamArrayArgumentsUsed Then
rightWins = True
Return True
ElseIf left.ExpandedParamArrayArgumentsUsed < right.ExpandedParamArrayArgumentsUsed Then
leftWins = True
Return True
End If
Else
rightWins = True
Return True
End If
ElseIf right.IsExpandedParamArrayForm Then
leftWins = True
Return True
End If
Return False
End Function
Friend Shared Function GetParameterTypeFromVirtualSignature(
ByRef candidate As CandidateAnalysisResult,
paramIndex As Integer
) As TypeSymbol
Dim paramType As TypeSymbol = candidate.Candidate.Parameters(paramIndex).Type
If candidate.IsExpandedParamArrayForm AndAlso
paramIndex = candidate.Candidate.ParameterCount - 1 AndAlso
paramType.Kind = SymbolKind.ArrayType Then
paramType = DirectCast(paramType, ArrayTypeSymbol).ElementType
End If
Return paramType
End Function
Private Shared Function GetParameterTypeFromVirtualSignature(
ByRef candidate As CandidateAnalysisResult,
paramIndex As Integer,
ByRef typeForGenericityCheck As TypeSymbol
) As TypeSymbol
Dim param As ParameterSymbol = candidate.Candidate.Parameters(paramIndex)
Dim paramForGenericityCheck = param.OriginalDefinition
If paramForGenericityCheck.ContainingSymbol.Kind = SymbolKind.Method Then
Dim method = DirectCast(paramForGenericityCheck.ContainingSymbol, MethodSymbol)
If method.IsReducedExtensionMethod Then
paramForGenericityCheck = method.ReducedFrom.Parameters(paramIndex + 1)
End If
End If
Dim paramType As TypeSymbol = param.Type
typeForGenericityCheck = paramForGenericityCheck.Type
If candidate.IsExpandedParamArrayForm AndAlso
paramIndex = candidate.Candidate.ParameterCount - 1 AndAlso
paramType.Kind = SymbolKind.ArrayType Then
paramType = DirectCast(paramType, ArrayTypeSymbol).ElementType
typeForGenericityCheck = DirectCast(typeForGenericityCheck, ArrayTypeSymbol).ElementType
End If
Return paramType
End Function
Friend Shared Sub AdvanceParameterInVirtualSignature(
ByRef candidate As CandidateAnalysisResult,
ByRef paramIndex As Integer
)
If Not (candidate.IsExpandedParamArrayForm AndAlso
paramIndex = candidate.Candidate.ParameterCount - 1) Then
paramIndex += 1
End If
End Sub
Private Shared Function InferTypeArguments(
ByRef candidate As CandidateAnalysisResult,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
delegateReturnType As TypeSymbol,
delegateReturnTypeReferenceBoundNode As BoundNode,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
binder As Binder,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As Boolean
Dim parameterToArgumentMap As ArrayBuilder(Of Integer) = Nothing
Dim paramArrayItems As ArrayBuilder(Of Integer) = Nothing
BuildParameterToArgumentMap(candidate, arguments, argumentNames, parameterToArgumentMap, paramArrayItems)
If candidate.State = CandidateAnalysisResultState.Applicable Then
Dim typeArguments As ImmutableArray(Of TypeSymbol) = Nothing
Dim inferenceLevel As TypeArgumentInference.InferenceLevel = TypeArgumentInference.InferenceLevel.None
Dim allFailedInferenceIsDueToObject As Boolean = False
Dim someInferenceFailed As Boolean = False
Dim inferenceErrorReasons As InferenceErrorReasons = InferenceErrorReasons.Other
Dim inferredTypeByAssumption As BitVector = Nothing
Dim typeArgumentsLocation As ImmutableArray(Of SyntaxNodeOrToken) = Nothing
If TypeArgumentInference.Infer(DirectCast(candidate.Candidate.UnderlyingSymbol, MethodSymbol),
arguments, parameterToArgumentMap, paramArrayItems,
delegateReturnType:=delegateReturnType,
delegateReturnTypeReferenceBoundNode:=delegateReturnTypeReferenceBoundNode,
typeArguments:=typeArguments,
inferenceLevel:=inferenceLevel,
someInferenceFailed:=someInferenceFailed,
allFailedInferenceIsDueToObject:=allFailedInferenceIsDueToObject,
inferenceErrorReasons:=inferenceErrorReasons,
inferredTypeByAssumption:=inferredTypeByAssumption,
typeArgumentsLocation:=typeArgumentsLocation,
asyncLambdaSubToFunctionMismatch:=asyncLambdaSubToFunctionMismatch,
useSiteDiagnostics:=useSiteDiagnostics,
diagnostic:=candidate.TypeArgumentInferenceDiagnosticsOpt) Then
candidate.SetInferenceLevel(inferenceLevel)
candidate.Candidate = candidate.Candidate.Construct(typeArguments)
' Need check for Option Strict and warn if parameter type is an assumed inferred type.
If binder.OptionStrict = OptionStrict.On AndAlso Not inferredTypeByAssumption.IsNull Then
For i As Integer = 0 To typeArguments.Length - 1 Step 1
If inferredTypeByAssumption(i) Then
Dim diagnostics = candidate.TypeArgumentInferenceDiagnosticsOpt
If diagnostics Is Nothing Then
diagnostics = New DiagnosticBag()
candidate.TypeArgumentInferenceDiagnosticsOpt = diagnostics
End If
Binder.ReportDiagnostic(diagnostics,
typeArgumentsLocation(i),
ERRID.WRN_TypeInferenceAssumed3,
candidate.Candidate.TypeParameters(i),
DirectCast(candidate.Candidate.UnderlyingSymbol, MethodSymbol).OriginalDefinition,
typeArguments(i))
End If
Next
End If
Else
candidate.State = CandidateAnalysisResultState.TypeInferenceFailed
If someInferenceFailed Then
candidate.SetSomeInferenceFailed()
End If
If allFailedInferenceIsDueToObject Then
candidate.SetAllFailedInferenceIsDueToObject()
If Not candidate.Candidate.IsExtensionMethod Then
candidate.IgnoreExtensionMethods = True
End If
End If
candidate.SetInferenceErrorReasons(inferenceErrorReasons)
candidate.NotInferredTypeArguments = BitVector.Create(typeArguments.Length)
For i As Integer = 0 To typeArguments.Length - 1 Step 1
If typeArguments(i) Is Nothing Then
candidate.NotInferredTypeArguments(i) = True
End If
Next
End If
Else
candidate.SetSomeInferenceFailed()
End If
If paramArrayItems IsNot Nothing Then
paramArrayItems.Free()
End If
If parameterToArgumentMap IsNot Nothing Then
parameterToArgumentMap.Free()
End If
Return (candidate.State = CandidateAnalysisResultState.Applicable)
End Function
Private Shared Function ConstructIfNeedTo(candidate As Candidate, typeArguments As ImmutableArray(Of TypeSymbol)) As Candidate
If typeArguments.Length > 0 Then
Return candidate.Construct(typeArguments)
End If
Return candidate
End Function
End Class
End Namespace
|
kelltrick/roslyn
|
src/Compilers/VisualBasic/Portable/Semantics/OverloadResolution.vb
|
Visual Basic
|
apache-2.0
| 249,174
|
Imports System
Imports Microsoft.VisualBasic
Imports ChartDirector
Public Class vbarmeter
Implements DemoModule
'Name of demo module
Public Function getName() As String Implements DemoModule.getName
Return "Vertical Bar Meter"
End Function
'Number of charts produced in this demo module
Public Function getNoOfCharts() As Integer Implements DemoModule.getNoOfCharts
Return 1
End Function
'Main code for creating chart.
'Note: the argument chartIndex is unused because this demo only has 1 chart.
Public Sub createChart(viewer As WinChartViewer, chartIndex As Integer) _
Implements DemoModule.createChart
' The value to display on the meter
Dim value As Double = 66.77
' Create an LinearMeter object of size 70 x 240 pixels with a very light grey (0xeeeeee)
' background, and a rounded 3-pixel thick light grey (0xbbbbbb) border
Dim m As LinearMeter = New LinearMeter(70, 240, &Heeeeee, &Hbbbbbb)
m.setRoundedFrame(Chart.Transparent)
m.setThickFrame(3)
' Set the scale region top-left corner at (28, 18), with size of 20 x 205 pixels. The scale
' labels are located on the left (default - implies vertical meter).
m.setMeter(28, 18, 20, 205)
' Set meter scale from 0 - 100, with a tick every 10 units
m.setScale(0, 100, 10)
' Add a 5-pixel thick smooth color scale to the meter at x = 54 (right of meter scale)
Dim smoothColorScale() As Double = {0, &H0000ff, 25, &H0088ff, 50, &H00ff00, 75, &Hffff00, _
100, &Hff0000}
m.addColorScale(smoothColorScale, 54, 5)
' Add a light blue (0x0088ff) bar from 0 to the data value with glass effect and 4 pixel
' rounded corners
m.addBar(0, value, &H0088ff, Chart.glassEffect(Chart.NormalGlare, Chart.Left), 4)
' Output the chart
viewer.Chart = m
End Sub
End Class
|
jojogreen/Orbital-Mechanix-Suite
|
NetWinCharts/VBNetWinCharts/vbarmeter.vb
|
Visual Basic
|
apache-2.0
| 1,956
|
' 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.ReplacePropertyWithMethods
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings.ReplaceMethodWithProperty
Partial Friend Class VisualBasicReplacePropertyWithMethods
Inherits AbstractReplacePropertyWithMethodsService(Of IdentifierNameSyntax, ExpressionSyntax, CrefReferenceSyntax, StatementSyntax, PropertyStatementSyntax)
Private Class ConvertValueToReturnsRewriter
Inherits VisualBasicSyntaxRewriter
Public Shared ReadOnly instance As New ConvertValueToReturnsRewriter()
Private Sub New()
End Sub
Private Function ConvertToReturns(name As XmlNodeSyntax) As SyntaxNode
Return name.ReplaceToken(DirectCast(name, XmlNameSyntax).LocalName,
SyntaxFactory.XmlNameToken("returns", SyntaxKind.IdentifierToken))
End Function
Public Overrides Function VisitXmlElementStartTag(node As XmlElementStartTagSyntax) As SyntaxNode
Return If(IsValueName(node.Name),
node.ReplaceNode(node.Name, ConvertToReturns(node.Name)),
MyBase.VisitXmlElementStartTag(node))
End Function
Public Overrides Function VisitXmlElementEndTag(node As XmlElementEndTagSyntax) As SyntaxNode
Return If(IsValueName(node.Name),
node.ReplaceNode(node.Name, ConvertToReturns(node.Name)),
MyBase.VisitXmlElementEndTag(node))
End Function
End Class
End Class
End Namespace
|
aelij/roslyn
|
src/Features/VisualBasic/Portable/ReplacePropertyWithMethods/VisualBasicReplacePropertyWithMethods.ConvertValueToReturnsRewriter.vb
|
Visual Basic
|
apache-2.0
| 1,833
|
' Licensed to the .NET Foundation under one or more 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.Statements
Public Class EachKeywordRecommenderTests
Inherits RecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub EachNotInMethodBodyTest()
VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Each")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub EachAfterForKeywordTest()
VerifyRecommendationsContain(<MethodBody>For |</MethodBody>, "Each")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub EachNotAfterTouchingForTest()
VerifyRecommendationsMissing(<MethodBody>For|</MethodBody>, "Each")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub EachTouchingLoopIdentifierTest()
VerifyRecommendationsContain(<MethodBody>For i|</MethodBody>, "Each")
End Sub
<WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotAfterEolTest()
VerifyRecommendationsMissing(
<MethodBody>For
|</MethodBody>, "Each")
End Sub
<WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterExplicitLineContinuationTest()
VerifyRecommendationsContain(
<MethodBody>For _
|</MethodBody>, "Each")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation()
VerifyRecommendationsContain(
<MethodBody>For _ ' Test
|</MethodBody>, "Each")
End Sub
<WorkItem(4946, "http://github.com/dotnet/roslyn/issues/4946")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInForLoop()
VerifyNoRecommendations(
<MethodBody>For | = 1 To 100
Next</MethodBody>)
End Sub
End Class
End Namespace
|
CyrusNajmabadi/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/Statements/EachKeywordRecommenderTests.vb
|
Visual Basic
|
mit
| 2,490
|
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Style
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=NameOf(TernaryOperatorWithReturnCodeFixProvider)), Composition.Shared>
Public Class TernaryOperatorWithReturnCodeFixProvider
Inherits CodeFixProvider
Public Overrides Async Function RegisterCodeFixesAsync(context As CodeFixContext) As Task
Dim root = Await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(False)
Dim diagnostic = context.Diagnostics.First
Dim span = diagnostic.Location.SourceSpan
Dim declaration = root.FindToken(span.Start).Parent.FirstAncestorOrSelf(Of MultiLineIfBlockSyntax)
If declaration Is Nothing Then Exit Function
context.RegisterCodeFix(CodeAction.Create("Change to ternary operator", Function(c) MakeTernaryAsync(context.Document, declaration, c), NameOf(TernaryOperatorWithReturnCodeFixProvider)), diagnostic)
End Function
Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) =
ImmutableArray.Create(DiagnosticId.TernaryOperator_Return.ToDiagnosticId())
Public Overrides Function GetFixAllProvider() As FixAllProvider
Return WellKnownFixAllProviders.BatchFixer
End Function
Private Async Function MakeTernaryAsync(document As Document, ifBlock As MultiLineIfBlockSyntax, cancellationToken As CancellationToken) As Task(Of Document)
Dim ifReturn = TryCast(ifBlock.Statements.FirstOrDefault(), ReturnStatementSyntax)
Dim elseReturn = TryCast(ifBlock.ElseBlock?.Statements.FirstOrDefault(), ReturnStatementSyntax)
Dim ternary = SyntaxFactory.TernaryConditionalExpression(ifBlock.IfStatement.Condition.WithoutTrailingTrivia(),
ifReturn.Expression.WithoutTrailingTrivia(),
elseReturn.Expression.WithoutTrailingTrivia()).
WithLeadingTrivia(ifBlock.GetLeadingTrivia()).
WithTrailingTrivia(ifBlock.GetTrailingTrivia()).
WithAdditionalAnnotations(Formatter.Annotation)
Dim returnStatement = SyntaxFactory.ReturnStatement(ternary)
Dim root = Await document.GetSyntaxRootAsync(cancellationToken)
Dim newRoot = root.ReplaceNode(ifBlock, returnStatement)
Dim newDocument = document.WithSyntaxRoot(newRoot)
Return newDocument
End Function
End Class
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=NameOf(TernaryOperatorWithAssignmentCodeFixProvider)), Composition.Shared>
Public Class TernaryOperatorWithAssignmentCodeFixProvider
Inherits CodeFixProvider
Public Overrides Async Function RegisterCodeFixesAsync(context As CodeFixContext) As Task
Dim root = Await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(False)
Dim diagnostic = context.Diagnostics.First
Dim span = diagnostic.Location.SourceSpan
Dim declaration = root.FindToken(span.Start).Parent.FirstAncestorOrSelf(Of MultiLineIfBlockSyntax)
If declaration Is Nothing Then Exit Function
context.RegisterCodeFix(CodeAction.Create("Change to ternary operator", Function(c) MakeTernaryAsync(context.Document, declaration, c), NameOf(TernaryOperatorWithAssignmentCodeFixProvider)), diagnostic)
End Function
Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) =
ImmutableArray.Create(DiagnosticId.TernaryOperator_Assignment.ToDiagnosticId())
Public Overrides Function GetFixAllProvider() As FixAllProvider
Return WellKnownFixAllProviders.BatchFixer
End Function
Private Async Function MakeTernaryAsync(document As Document, ifBlock As MultiLineIfBlockSyntax, cancellationToken As CancellationToken) As Task(Of Document)
Dim ifAssign = TryCast(ifBlock.Statements.FirstOrDefault(), AssignmentStatementSyntax)
Dim elseAssign = TryCast(ifBlock.ElseBlock?.Statements.FirstOrDefault(), AssignmentStatementSyntax)
Dim variableIdentifier = TryCast(ifAssign.Left, IdentifierNameSyntax)
Dim ternary = SyntaxFactory.TernaryConditionalExpression(
ifBlock.IfStatement.Condition,
ifAssign.Right.WithoutTrailingTrivia(),
elseAssign.Right.WithoutTrailingTrivia())
Dim assignment = SyntaxFactory.SimpleAssignmentStatement(variableIdentifier, ternary).
WithLeadingTrivia(ifBlock.GetLeadingTrivia()).
WithTrailingTrivia(ifBlock.GetTrailingTrivia()).
WithAdditionalAnnotations(Formatter.Annotation)
Dim root = Await document.GetSyntaxRootAsync(cancellationToken)
Dim newRoot = root.ReplaceNode(ifBlock, assignment)
Dim newDocument = document.WithSyntaxRoot(newRoot)
Return newDocument
End Function
End Class
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=NameOf(TernaryOperatorFromIifCodeFixProvider)), Composition.Shared>
Public Class TernaryOperatorFromIifCodeFixProvider
Inherits CodeFixProvider
Public Overrides Async Function RegisterCodeFixesAsync(context As CodeFixContext) As Task
Dim root = Await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(False)
Dim diagnostic = context.Diagnostics.First
Dim span = diagnostic.Location.SourceSpan
Dim declaration = root.FindToken(span.Start).Parent.FirstAncestorOrSelf(Of InvocationExpressionSyntax)
If declaration Is Nothing Then Exit Function
context.RegisterCodeFix(CodeAction.Create("Change IIF to If to short circuit evaulations", Function(c) MakeTernaryAsync(context.Document, declaration, c), NameOf(TernaryOperatorFromIifCodeFixProvider)), diagnostic)
End Function
Public Overrides ReadOnly Property FixableDiagnosticIds() As ImmutableArray(Of String) =
ImmutableArray.Create(DiagnosticId.TernaryOperator_Iif.ToDiagnosticId())
Public Overrides Function GetFixAllProvider() As FixAllProvider
Return WellKnownFixAllProviders.BatchFixer
End Function
Private Async Function MakeTernaryAsync(document As Document, iifAssignment As InvocationExpressionSyntax, cancellationToken As CancellationToken) As Task(Of Document)
Dim ternary = SyntaxFactory.TernaryConditionalExpression(
iifAssignment.ArgumentList.Arguments(0).GetExpression(),
iifAssignment.ArgumentList.Arguments(1).GetExpression(),
iifAssignment.ArgumentList.Arguments(2).GetExpression()).
WithLeadingTrivia(iifAssignment.GetLeadingTrivia()).
WithTrailingTrivia(iifAssignment.GetTrailingTrivia()).
WithAdditionalAnnotations(Formatter.Annotation)
Dim root = Await document.GetSyntaxRootAsync(cancellationToken)
Dim newRoot = root.ReplaceNode(iifAssignment, ternary)
Dim newDocument = document.WithSyntaxRoot(newRoot)
Return newDocument
End Function
End Class
End Namespace
|
dmgandini/code-cracker
|
src/VisualBasic/CodeCracker/Style/TernaryOperatorCodeFixProviders.vb
|
Visual Basic
|
apache-2.0
| 7,672
|
' 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.UnitTests.FindReferences
Partial Public Class FindReferencesTests
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestParameterInMethod1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Foo(int {|Definition:$$i|})
{
Console.WriteLine([|i|]);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestParameterInMethod2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Foo(int {|Definition:$$i|})
{
Console.WriteLine([|i|]);
}
void Bar(int i)
{
Console.WriteLine(i);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestParameterInMethod3() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Foo(int {|Definition:$$i|})
{
Console.WriteLine([|i|]);
}
void Bar()
{
Foo([|i|]: 0);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestParameterCaseSensitivity1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Foo(int {|Definition:$$i|})
{
Console.WriteLine([|i|]);
Console.WriteLine(I);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestParameterCaseSensitivity2() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class C
sub Foo(byval {|Definition:$$i|} as Integer)
Console.WriteLine([|i|])
Console.WriteLine([|I|])
end sub
end class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(542475, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542475")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestPartialParameter1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class program
{
static partial void foo(string {|Definition:$$name|}, int age, bool sex, int index1 = 1) { }
}
partial class program
{
static partial void foo(string {|Definition:name|}, int age, bool sex, int index1 = 1);
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(542475, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542475")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestPartialParameter2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class program
{
static partial void foo(string {|Definition:name|}, int age, bool sex, int index1 = 1) { }
}
partial class program
{
static partial void foo(string {|Definition:$$name|}, int age, bool sex, int index1 = 1);
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
#Region "FAR on partial methods"
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestParameter_CSharpWithSignaturesMatchFARParameterOnDefDecl() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class C
{
partial void PM(int {|Definition:$$x|}, int y);
partial void PM(int {|Definition:x|}, int y)
{
int s = [|x|];
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestParameter_VBWithSignaturesMatchFARParameterOnDefDecl() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
partial sub PM({|Definition:x|} as Integer, y as Integer)
End Sub
sub PM({|Definition:x|} as Integer, y as Integer)
Dim y as Integer = [|$$x|];;
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
#End Region
<WorkItem(543276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543276")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousFunctionParameter1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module Program
Sub Main
Foo(Sub({|Definition:$$x|} As Integer) Return, Sub({|Definition:x|} As Integer) Return)
End Sub
Sub Foo(Of T)(x As T, y As T)
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(624310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624310")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousFunctionParameter3() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module Program
Dim field As Object = If(True, Function({|Definition:$$x|} As String) [|x|].ToUpper(), Function({|Definition:x|} As String) [|x|].ToLower())
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(624310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624310")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousFunctionParameter4() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class Program
{
public object O = true ? (Func<string, string>)((string {|Definition:$$x|}) => {return [|x|].ToUpper(); }) : (Func<string, string>)((string x) => {return x.ToLower(); });
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(543276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543276")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousFunctionParameter2() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module Program
Sub Main
Foo(Sub({|Definition:x|} As Integer) Return, Sub({|Definition:$$x|} As Integer) Return)
End Sub
Sub Foo(Of T)(x As T, y As T)
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(529688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529688")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAnonymousFunctionParameter5() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Module M
Sub Main()
Dim s = Sub({|Definition:$$x|}) Return
s([|x|]:=1)
End Sub
End Module
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(545654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545654")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestReducedExtensionNamedParameter1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Strict On
Imports System
Imports System.Collections.Generic
Imports System.Runtime.CompilerServices
Module M
Sub Main()
Dim x As New Stack(Of String)
Dim y = x.Foo(0, $$[|defaultValue|]:="")
End Sub
<Extension>
Function Foo(x As Stack(Of String), index As Integer, {|Definition:defaultValue|} As String) As String
End Function
End Module
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(545654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545654")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestReducedExtensionNamedParameter2() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Strict On
Imports System
Imports System.Collections.Generic
Imports System.Runtime.CompilerServices
Module M
Sub Main()
Dim x As New Stack(Of String)
Dim y = x.Foo(0, [|defaultValue|]:="")
End Sub
<Extension>
Function Foo(x As Stack(Of String), index As Integer, {|Definition:$$defaultValue|} As String) As String
End Function
End Module
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(545618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545618")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_TestAnonymousMethodParameter1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class X
{
void Main()
{
Func<int, int> f = {|Definition:$$a|} => [|a|];
Converter<int, int> c = a => a;
}
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(545618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545618")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_TestAnonymousMethodParameter2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class X
{
void Main()
{
Func<int, int> f = {|Definition:a|} => [|$$a|];
Converter<int, int> c = a => a;
}
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(545618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545618")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_TestAnonymousMethodParameter3() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class X
{
void Main()
{
Func<int, int> f = a => a;
Converter<int, int> c = {|Definition:$$a|} => [|a|];
}
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(545618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545618")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_TestAnonymousMethodParameter4() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class X
{
void Main()
{
Func<int, int> f = a => a;
Converter<int, int> c = {|Definition:a|} => [|$$a|];
}
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(545618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545618")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVB_TestAnonymousMethodParameter1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
class X
sub Main()
dim f as Func(of integer, integer) = Function({|Definition:$$a|}) [|a|]
dim c as Converter(of integer, integer) = Function(a) a
end sub
end class
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(545618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545618")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVB_TestAnonymousMethodParameter2() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
class X
sub Main()
dim f as Func(of integer, integer) = Function({|Definition:a|}) [|$$a|]
dim c as Converter(of integer, integer) = Function(a) a
end sub
end class
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(545618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545618")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVB_TestAnonymousMethodParameter3() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
class X
sub Main()
dim f as Func(of integer, integer) = Function(a) a
dim c as Converter(of integer, integer) = Function({|Definition:$$a|}) [|a|]
end sub
end class
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(545618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545618")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestVB_TestAnonymousMethodParameter4() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System
class X
sub Main()
dim f as Func(of integer, integer) = Function(a) a
dim c as Converter(of integer, integer) = Function({|Definition:a|}) [|$$a|]
end sub
end class
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(16757, "https://github.com/dotnet/roslyn/issues/16757")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
<Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.LocalFunctions)>
Public Async Function TestParameterInLocalFunction1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Main()
{
void Local(int {|Definition:$$i|})
{
Console.WriteLine([|i|]);
}
Local(1);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(16757, "https://github.com/dotnet/roslyn/issues/16757")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
<Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.LocalFunctions)>
Public Async Function TestParameterInLocalFunction2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Main()
{
void Local(int {|Definition:$$i|})
{
}
Local([|i|]:1);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(16757, "https://github.com/dotnet/roslyn/issues/16757")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
<Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.LocalFunctions)>
Public Async Function TestParameterInLocalFunction3() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Main()
{
void Local(int {|Definition:i|})
{
Console.WriteLine([|$$i|]);
}
Local(1);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(16757, "https://github.com/dotnet/roslyn/issues/16757")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
<Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.LocalFunctions)>
Public Async Function TestParameterInLocalFunction4() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Main()
{
void Local(int {|Definition:i|})
{
}
Local([|$$i|]:1);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
End Class
End Namespace
|
jeffanders/roslyn
|
src/EditorFeatures/Test2/FindReferences/FindReferencesTests.ParameterSymbol.vb
|
Visual Basic
|
apache-2.0
| 19,160
|
' 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.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IConditionalAccessExpression_SimpleMethodAccess()
Dim source = <![CDATA[
Option Strict On
Public Class C1
Public Sub M1()
Dim o As New Object
o?.ToString()'BIND:"o?.ToString()"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IConditionalAccessOperation (OperationKind.ConditionalAccess, Type: System.Void) (Syntax: 'o?.ToString()')
Operation:
ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o')
WhenNotNull:
IInvocationOperation (virtual Function System.Object.ToString() As System.String) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()')
Instance Receiver:
IConditionalAccessInstanceOperation (OperationKind.ConditionalAccessInstance, Type: System.Object, IsImplicit) (Syntax: 'o')
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ConditionalAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IConditionalAccessExpression_SimplePropertyAccess()
Dim source = <![CDATA[
Option Strict On
Public Class C1
Public ReadOnly Property Prop1 As Integer
Public Sub M1()
Dim c1 As C1 = Nothing
Dim propValue = c1?.Prop1'BIND:"c1?.Prop1"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IConditionalAccessOperation (OperationKind.ConditionalAccess, Type: System.Nullable(Of System.Int32)) (Syntax: 'c1?.Prop1')
Operation:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C1) (Syntax: 'c1')
WhenNotNull:
IPropertyReferenceOperation: ReadOnly Property C1.Prop1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: '.Prop1')
Instance Receiver:
IConditionalAccessInstanceOperation (OperationKind.ConditionalAccessInstance, Type: C1, IsImplicit) (Syntax: 'c1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ConditionalAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
<WorkItem(23009, "https://github.com/dotnet/roslyn/issues/23009")>
Public Sub IConditionalAccessExpression_ErrorReceiver()
Dim source = <![CDATA[
Option Strict On
Public Class C1
Public Sub M1()
MyBase?.ToString()'BIND:"MyBase?.ToString()"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IConditionalAccessOperation (OperationKind.ConditionalAccess, Type: System.Void, IsInvalid) (Syntax: 'MyBase?.ToString()')
Operation:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsInvalid) (Syntax: 'MyBase')
WhenNotNull:
IInvocationOperation (virtual Function System.Object.ToString() As System.String) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()')
Instance Receiver:
IConditionalAccessInstanceOperation (OperationKind.ConditionalAccessInstance, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'MyBase')
Arguments(0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC32027: 'MyBase' must be followed by '.' and an identifier.
MyBase?.ToString()'BIND:"MyBase?.ToString()"
~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ConditionalAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ConditionalAccessFlow_06()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As S1?) 'BIND:"Sub M"
x?.P1() = Nothing
End Sub
End Class
Public Structure S1
Property P1() As Integer
End Structure
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30068: Expression is a value and therefore cannot be the target of an assignment.
x?.P1() = Nothing
~~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Nullable(Of S1), IsInvalid) (Syntax: 'x')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'x')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of S1), IsInvalid, IsImplicit) (Syntax: 'x')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '.P1()')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsInvalid, IsImplicit) (Syntax: '.P1()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNullable)
Operand:
IPropertyReferenceOperation: Property S1.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: '.P1()')
Instance Receiver:
IInvocationOperation ( Function System.Nullable(Of S1).GetValueOrDefault() As S1) (OperationKind.Invocation, Type: S1, IsInvalid, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of S1), IsInvalid, IsImplicit) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
Value:
IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of System.Int32), IsInvalid, IsImplicit) (Syntax: 'x')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'x?.P1() = Nothing')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'x?.P1() = Nothing')
Left:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'x?.P1()')
Children(1):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsInvalid, IsImplicit) (Syntax: 'x?.P1()')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNothingLiteral)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ConditionalAccessFlow_07()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As S1?) 'BIND:"Sub M"
x?.P1 = Nothing
End Sub
End Class
Public Structure S1
Property P1() As Integer
End Structure
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30068: Expression is a value and therefore cannot be the target of an assignment.
x?.P1 = Nothing
~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Nullable(Of S1), IsInvalid) (Syntax: 'x')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'x')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of S1), IsInvalid, IsImplicit) (Syntax: 'x')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '.P1')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsInvalid, IsImplicit) (Syntax: '.P1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNullable)
Operand:
IPropertyReferenceOperation: Property S1.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: '.P1')
Instance Receiver:
IInvocationOperation ( Function System.Nullable(Of S1).GetValueOrDefault() As S1) (OperationKind.Invocation, Type: S1, IsInvalid, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of S1), IsInvalid, IsImplicit) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
Value:
IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of System.Int32), IsInvalid, IsImplicit) (Syntax: 'x')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'x?.P1 = Nothing')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'x?.P1 = Nothing')
Left:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'x?.P1')
Children(1):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsInvalid, IsImplicit) (Syntax: 'x?.P1')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNothingLiteral)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ConditionalAccessFlow_08()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As S1?) 'BIND:"Sub M"
x?.F1 = Nothing
End Sub
End Class
Public Structure S1
Public F1 As Integer
End Structure
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30068: Expression is a value and therefore cannot be the target of an assignment.
x?.F1 = Nothing
~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Nullable(Of S1), IsInvalid) (Syntax: 'x')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'x')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of S1), IsInvalid, IsImplicit) (Syntax: 'x')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '.F1')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsInvalid, IsImplicit) (Syntax: '.F1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNullable)
Operand:
IFieldReferenceOperation: S1.F1 As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: '.F1')
Instance Receiver:
IInvocationOperation ( Function System.Nullable(Of S1).GetValueOrDefault() As S1) (OperationKind.Invocation, Type: S1, IsInvalid, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of S1), IsInvalid, IsImplicit) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
Value:
IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of System.Int32), IsInvalid, IsImplicit) (Syntax: 'x')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'x?.F1 = Nothing')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'x?.F1 = Nothing')
Left:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'x?.F1')
Children(1):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsInvalid, IsImplicit) (Syntax: 'x?.F1')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNothingLiteral)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
End Class
End Namespace
|
VSadov/roslyn
|
src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IConditionalAccessExpression.vb
|
Visual Basic
|
apache-2.0
| 18,876
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports CompilationCreationTestHelpers
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE
Public Class LoadingWithEvents : Inherits BasicTestBase
<Fact>
Public Sub LoadingSimpleWithEvents1()
Dim source =
<compilation name="LoadingSimpleWithEvents1">
<file name="a.vb">
</file>
</compilation>
Dim simpleWithEvents = MetadataReference.CreateFromImage(TestResources.SymbolsTests.WithEvents.SimpleWithEvents.AsImmutableOrNull())
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, {simpleWithEvents}, TestOptions.ReleaseExe)
Dim ns = DirectCast(c1.GlobalNamespace.GetMembers("SimpleWithEvents").Single, NamespaceSymbol)
Dim Class1 = ns.GetTypeMembers("Class1").Single
Dim Class1_WE1 = DirectCast(Class1.GetMember("WE1"), PropertySymbol)
Dim Class1_WE2 = DirectCast(Class1.GetMember("WE2"), PropertySymbol)
Assert.True(Class1_WE1.IsWithEvents)
Assert.True(Class1_WE2.IsWithEvents)
End Sub
<Fact>
Public Sub LoadingSimpleWithEventsDerived()
Dim source =
<compilation name="LoadingSimpleWithEvents1">
<file name="a.vb">
</file>
</compilation>
Dim ref = MetadataReference.CreateFromImage(TestResources.SymbolsTests.WithEvents.SimpleWithEvents.AsImmutableOrNull())
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, {ref}, TestOptions.ReleaseExe)
Dim ns = DirectCast(c1.GlobalNamespace.GetMembers("SimpleWithEvents").Single, NamespaceSymbol)
Dim Derived = ns.GetTypeMembers("Derived").Single
Dim Derived_WE1 = DirectCast(Derived.GetMember("WE1"), PropertySymbol)
Assert.True(Derived_WE1.IsWithEvents)
Assert.True(Derived_WE1.IsOverrides)
Assert.True(Derived_WE1.OverriddenProperty.IsWithEvents)
End Sub
End Class
End Namespace
|
CyrusNajmabadi/roslyn
|
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadingWithEvents.vb
|
Visual Basic
|
mit
| 2,566
|
' 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.UnitTests.FindReferences
Partial Public Class FindReferencesTests
<WorkItem(529629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529629")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_Indexer1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public int {|Definition:$$this|}[int y] { get { } }
}
class D
{
void Goo()
{
var q = new C();
var b = q[||][4];
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(529629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529629")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_Indexer1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class C
public default readonly property {|Definition:$$Item|}(y as Integer) as Integer
get
return 0
end get
end property
end class
class D
sub Goo()
dim q = new C()
dim b = q[||](4)
end sub
end class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(545577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545577")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_Indexer2() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class A
Default ReadOnly Property {|Definition:$$Goo|}(ByVal x As Integer) As Integer
Get
End Get
End Property
Shared Sub Main()
Dim x As New A
Dim y = x[||](1)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(650779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/650779")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_Indexer3() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class C
Default Public Property {|Definition:$$Item|}(index As Integer) As C
Get
Return Nothing
End Get
Set(value As C)
End Set
End Property
Public Sub Goo(c As C)
c = c.[|Item|](2)
c[||](1) = c
c.[|Item|](1) = c
c[||](1).[|Item|](1) = c
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
<WorkItem(661362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/661362")>
<WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_Indexer4() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Default Public Property {|Definition:$$Hello|}(x As String) As String
Get
Return Nothing
End Get
Set(value As String)
End Set
End Property
End Class
Module Program
Sub Main(args As String())
Dim x As New C
Dim y = x![||]HELLO
Dim z = x![||]HI
x[||]("HELLO") = ""
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input)
End Function
End Class
End Namespace
|
mmitche/roslyn
|
src/EditorFeatures/Test2/FindReferences/FindReferencesTests.IndexerSymbols.vb
|
Visual Basic
|
apache-2.0
| 3,979
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Globalization
Imports System.Reflection
Imports Microsoft.CodeAnalysis.Collections
Namespace Microsoft.CodeAnalysis.VisualBasic.ObjectDisplay
#Disable Warning RS0010
''' <summary>
''' Displays a value in the VisualBasic style.
''' </summary>
''' <seealso cref="T:Microsoft.CodeAnalysis.CSharp.Symbols.ObjectDisplay"/>
#Enable Warning RS0010
Friend Module ObjectDisplay
Private Const s_nullChar As Char = ChrW(0)
Private Const s_back As Char = ChrW(8)
Private Const s_Cr As Char = ChrW(13)
Private Const s_formFeed As Char = ChrW(12)
Private Const s_Lf As Char = ChrW(10)
Private Const s_tab As Char = ChrW(9)
Private Const s_verticalTab As Char = ChrW(11)
''' <summary>
''' Returns a string representation of an object of primitive type.
''' </summary>
''' <param name="obj">A value to display as a string.</param>
''' <param name="options">Options used to customize formatting of an Object value.</param>
''' <returns>A string representation of an object of primitive type (or null if the type is not supported).</returns>
''' <remarks>
''' Handles <see cref="Boolean"/>, <see cref="String"/>, <see cref="Char"/>, <see cref="SByte"/>
''' <see cref="Byte"/>, <see cref="Short"/>, <see cref="UShort"/>, <see cref="Integer"/>, <see cref="UInteger"/>,
''' <see cref="Long"/>, <see cref="ULong"/>, <see cref="Double"/>, <see cref="Single"/>, <see cref="Decimal"/>,
''' <see cref="Date"/>, and <c>Nothing</c>.
''' </remarks>
Public Function FormatPrimitive(obj As Object, options As ObjectDisplayOptions) As String
If obj Is Nothing Then
Return NullLiteral
End If
Dim type = obj.GetType()
If type.GetTypeInfo().IsEnum Then
type = [Enum].GetUnderlyingType(type)
End If
If type Is GetType(Integer) Then
Return FormatLiteral(DirectCast(obj, Integer), options)
End If
If type Is GetType(String) Then
Return FormatLiteral(DirectCast(obj, String), options)
End If
If type Is GetType(Boolean) Then
Return FormatLiteral(DirectCast(obj, Boolean))
End If
If type Is GetType(Char) Then
Return FormatLiteral(DirectCast(obj, Char), options)
End If
If type Is GetType(Byte) Then
Return FormatLiteral(DirectCast(obj, Byte), options)
End If
If type Is GetType(Short) Then
Return FormatLiteral(DirectCast(obj, Short), options)
End If
If type Is GetType(Long) Then
Return FormatLiteral(DirectCast(obj, Long), options)
End If
If type Is GetType(Double) Then
Return FormatLiteral(DirectCast(obj, Double), options)
End If
If type Is GetType(ULong) Then
Return FormatLiteral(DirectCast(obj, ULong), options)
End If
If type Is GetType(UInteger) Then
Return FormatLiteral(DirectCast(obj, UInteger), options)
End If
If type Is GetType(UShort) Then
Return FormatLiteral(DirectCast(obj, UShort), options)
End If
If type Is GetType(SByte) Then
Return FormatLiteral(DirectCast(obj, SByte), options)
End If
If type Is GetType(Single) Then
Return FormatLiteral(DirectCast(obj, Single), options)
End If
If type Is GetType(Decimal) Then
Return FormatLiteral(DirectCast(obj, Decimal), options)
End If
If type Is GetType(Date) Then
Return FormatLiteral(DirectCast(obj, Date))
End If
Return Nothing
End Function
Friend ReadOnly Property NullLiteral As String
Get
Return "Nothing"
End Get
End Property
Friend Function FormatLiteral(value As Boolean) As String
Return If(value, "True", "False")
End Function
''' <summary>
''' Formats string literal.
''' </summary>
''' <param name="value">Literal value.</param>
''' <param name="options">Options used to customize formatting of a literal value.</param>
Friend Function FormatLiteral(value As String, options As ObjectDisplayOptions) As String
ValidateOptions(options)
If value Is Nothing Then
Throw New ArgumentNullException()
End If
Dim pooledBuilder = PooledStringBuilder.GetInstance()
Dim sb = pooledBuilder.Builder
Dim useQuotes = options.IncludesOption(ObjectDisplayOptions.UseQuotes)
Dim useHex = options.IncludesOption(ObjectDisplayOptions.UseHexadecimalNumbers)
For Each token As Integer In TokenizeString(value, useQuotes, useHex)
sb.Append(ChrW(token And &HFFFF)) ' lower 16 bits of token contains the Unicode char value
Next
Return pooledBuilder.ToStringAndFree()
End Function
Friend Function FormatLiteral(c As Char, options As ObjectDisplayOptions) As String
ValidateOptions(options)
If Not options.IncludesOption(ObjectDisplayOptions.UseQuotes) Then
Return c.ToString()
End If
Dim wellKnown = GetWellKnownCharacterName(c)
If wellKnown IsNot Nothing Then
Return wellKnown
End If
If Not IsPrintable(c) Then
Dim codepoint = AscW(c)
Return If(options.IncludesOption(ObjectDisplayOptions.UseHexadecimalNumbers), "ChrW(&H" & codepoint.ToString("X"), "ChrW(" & codepoint.ToString()) & ")"
End If
Return """"c & EscapeQuote(c) & """"c & "c"
End Function
Private Function EscapeQuote(c As Char) As String
Return If(c = """", """""", c)
End Function
Friend Function FormatLiteral(value As SByte, options As ObjectDisplayOptions) As String
ValidateOptions(options)
If options.IncludesOption(ObjectDisplayOptions.UseHexadecimalNumbers) Then
Return "&H" & If(value >= 0, value.ToString("X2"), CInt(value).ToString("X8"))
Else
Return value.ToString(CultureInfo.InvariantCulture)
End If
End Function
Friend Function FormatLiteral(value As Byte, options As ObjectDisplayOptions) As String
ValidateOptions(options)
If options.IncludesOption(ObjectDisplayOptions.UseHexadecimalNumbers) Then
Return "&H" & value.ToString("X2")
Else
Return value.ToString(CultureInfo.InvariantCulture)
End If
End Function
Friend Function FormatLiteral(value As Short, options As ObjectDisplayOptions) As String
ValidateOptions(options)
Dim pooledBuilder = PooledStringBuilder.GetInstance()
Dim sb = pooledBuilder.Builder
If options.IncludesOption(ObjectDisplayOptions.UseHexadecimalNumbers) Then
sb.Append("&H")
sb.Append(If(value >= 0, value.ToString("X4"), CInt(value).ToString("X8")))
Else
sb.Append(value.ToString(CultureInfo.InvariantCulture))
End If
If options.IncludesOption(ObjectDisplayOptions.IncludeTypeSuffix) Then
sb.Append("S"c)
End If
Return pooledBuilder.ToStringAndFree()
End Function
Friend Function FormatLiteral(value As UShort, options As ObjectDisplayOptions) As String
ValidateOptions(options)
Dim pooledBuilder = PooledStringBuilder.GetInstance()
Dim sb = pooledBuilder.Builder
If options.IncludesOption(ObjectDisplayOptions.UseHexadecimalNumbers) Then
sb.Append("&H")
sb.Append(value.ToString("X4"))
Else
sb.Append(value.ToString(CultureInfo.InvariantCulture))
End If
If options.IncludesOption(ObjectDisplayOptions.IncludeTypeSuffix) Then
sb.Append("US")
End If
Return pooledBuilder.ToStringAndFree()
End Function
Friend Function FormatLiteral(value As Integer, options As ObjectDisplayOptions) As String
ValidateOptions(options)
Dim pooledBuilder = PooledStringBuilder.GetInstance()
Dim sb = pooledBuilder.Builder
If options.IncludesOption(ObjectDisplayOptions.UseHexadecimalNumbers) Then
sb.Append("&H")
sb.Append(value.ToString("X8"))
Else
sb.Append(value.ToString(CultureInfo.InvariantCulture))
End If
If options.IncludesOption(ObjectDisplayOptions.IncludeTypeSuffix) Then
sb.Append("I"c)
End If
Return pooledBuilder.ToStringAndFree()
End Function
Friend Function FormatLiteral(value As UInteger, options As ObjectDisplayOptions) As String
ValidateOptions(options)
Dim pooledBuilder = PooledStringBuilder.GetInstance()
Dim sb = pooledBuilder.Builder
If options.IncludesOption(ObjectDisplayOptions.UseHexadecimalNumbers) Then
sb.Append("&H")
sb.Append(value.ToString("X8"))
Else
sb.Append(value.ToString(CultureInfo.InvariantCulture))
End If
If options.IncludesOption(ObjectDisplayOptions.IncludeTypeSuffix) Then
sb.Append("UI")
End If
Return pooledBuilder.ToStringAndFree()
End Function
Friend Function FormatLiteral(value As Long, options As ObjectDisplayOptions) As String
ValidateOptions(options)
Dim pooledBuilder = PooledStringBuilder.GetInstance()
Dim sb = pooledBuilder.Builder
If options.IncludesOption(ObjectDisplayOptions.UseHexadecimalNumbers) Then
sb.Append("&H")
sb.Append(value.ToString("X16"))
Else
sb.Append(value.ToString(CultureInfo.InvariantCulture))
End If
If options.IncludesOption(ObjectDisplayOptions.IncludeTypeSuffix) Then
sb.Append("L"c)
End If
Return pooledBuilder.ToStringAndFree()
End Function
Friend Function FormatLiteral(value As ULong, options As ObjectDisplayOptions) As String
ValidateOptions(options)
Dim pooledBuilder = PooledStringBuilder.GetInstance()
Dim sb = pooledBuilder.Builder
If options.IncludesOption(ObjectDisplayOptions.UseHexadecimalNumbers) Then
sb.Append("&H")
sb.Append(value.ToString("X16"))
Else
sb.Append(value.ToString(CultureInfo.InvariantCulture))
End If
If options.IncludesOption(ObjectDisplayOptions.IncludeTypeSuffix) Then
sb.Append("UL")
End If
Return pooledBuilder.ToStringAndFree()
End Function
Friend Function FormatLiteral(value As Double, options As ObjectDisplayOptions) As String
ValidateOptions(options)
Dim result = value.ToString("R", CultureInfo.InvariantCulture)
Return If(options.IncludesOption(ObjectDisplayOptions.IncludeTypeSuffix), result & "R", result)
End Function
Friend Function FormatLiteral(value As Single, options As ObjectDisplayOptions) As String
ValidateOptions(options)
Dim result = value.ToString("R", CultureInfo.InvariantCulture)
Return If(options.IncludesOption(ObjectDisplayOptions.IncludeTypeSuffix), result & "F", result)
End Function
Friend Function FormatLiteral(value As Decimal, options As ObjectDisplayOptions) As String
ValidateOptions(options)
Dim result = value.ToString(CultureInfo.InvariantCulture)
Return If(options.IncludesOption(ObjectDisplayOptions.IncludeTypeSuffix), result & "D", result)
End Function
Friend Function FormatLiteral(value As Date) As String
Return value.ToString("#M/d/yyyy hh:mm:ss tt#", CultureInfo.InvariantCulture)
End Function
Private Function Character(c As Char) As Integer
Return (SymbolDisplayPartKind.StringLiteral << 16) Or AscW(c)
End Function
Private Function Identifier(c As Char) As Integer
Return (SymbolDisplayPartKind.MethodName << 16) Or AscW(c)
End Function
Private Function Number(c As Char) As Integer
Return (SymbolDisplayPartKind.NumericLiteral << 16) Or AscW(c)
End Function
Private Function Punctuation(c As Char) As Integer
Return (SymbolDisplayPartKind.Punctuation << 16) Or AscW(c)
End Function
Private Function [Operator](c As Char) As Integer
Return (SymbolDisplayPartKind.Operator << 16) Or AscW(c)
End Function
Private Function Space() As Integer
Return (SymbolDisplayPartKind.Space << 16) Or AscW(" "c)
End Function
Private Function Quotes() As Integer
Return (SymbolDisplayPartKind.StringLiteral << 16) Or AscW("""")
End Function
' TODO: consider making "token" returned by this function a structure to abstract bit masking operations
Friend Iterator Function TokenizeString(str As String, quote As Boolean, useHexadecimalNumbers As Boolean) As IEnumerable(Of Integer)
If str.Length = 0 Then
If quote Then
Yield Quotes()
Yield Quotes()
End If
Return
End If
Dim startNewConcatenand = False
Dim lastConcatenandWasQuoted = False
Dim i = 0
While i < str.Length
Dim isFirst = (i = 0)
Dim c = str(i)
i += 1
Dim wellKnown As String
Dim isNonPrintable As Boolean
Dim isCrLf As Boolean
' vbCrLf
If c = s_Cr AndAlso i < str.Length AndAlso str(i) = s_Lf Then
wellKnown = "vbCrLf"
isNonPrintable = True
isCrLf = True
i += 1
Else
wellKnown = GetWellKnownCharacterName(c)
isNonPrintable = wellKnown IsNot Nothing OrElse Not IsPrintable(c)
isCrLf = False
End If
If isNonPrintable Then
If quote Then
If lastConcatenandWasQuoted Then
Yield Quotes()
lastConcatenandWasQuoted = False
End If
If Not isFirst Then
Yield Space()
Yield [Operator]("&"c)
Yield Space()
End If
If wellKnown IsNot Nothing Then
For Each e In wellKnown
Yield Identifier(e)
Next
Else
Yield Identifier("C"c)
Yield Identifier("h"c)
Yield Identifier("r"c)
Yield Identifier("W"c)
Yield Punctuation("("c)
If useHexadecimalNumbers Then
Yield Number("&"c)
Yield Number("H"c)
End If
Dim codepoint = AscW(c)
For Each digit In If(useHexadecimalNumbers, codepoint.ToString("X"), codepoint.ToString())
Yield Number(digit)
Next
Yield Punctuation(")"c)
End If
startNewConcatenand = True
ElseIf (isCrLf) Then
Yield Character(s_Cr)
Yield Character(s_Lf)
Else
Yield Character(c)
End If
Else
If isFirst AndAlso quote Then
Yield Quotes()
End If
If startNewConcatenand Then
Yield Space()
Yield [Operator]("&"c)
Yield Space()
Yield Quotes()
startNewConcatenand = False
End If
lastConcatenandWasQuoted = True
If c = """"c AndAlso quote Then
Yield Quotes()
Yield Quotes()
Else
Yield Character(c)
End If
End If
End While
If quote AndAlso lastConcatenandWasQuoted Then
Yield Quotes()
End If
End Function
Friend Function IsPrintable(c As Char) As Boolean
Dim category = CharUnicodeInfo.GetUnicodeCategory(c)
Return category <> UnicodeCategory.OtherNotAssigned AndAlso category <> UnicodeCategory.ParagraphSeparator AndAlso category <> UnicodeCategory.Control
End Function
Friend Function GetWellKnownCharacterName(c As Char) As String
Select Case c
Case s_nullChar
Return "vbNullChar"
Case s_back
Return "vbBack"
Case s_Cr
Return "vbCr"
Case s_formFeed
Return "vbFormFeed"
Case s_Lf
Return "vbLf"
Case s_tab
Return "vbTab"
Case s_verticalTab
Return "vbVerticalTab"
End Select
Return Nothing
End Function
<Conditional("DEBUG")>
Private Sub ValidateOptions(options As ObjectDisplayOptions)
' This option is not supported and has no meaning in Visual Basic...should not be passed...
Debug.Assert(Not options.IncludesOption(ObjectDisplayOptions.IncludeCodePoints))
End Sub
End Module
End Namespace
|
v-codeel/roslyn
|
src/Compilers/VisualBasic/Portable/SymbolDisplay/ObjectDisplay.vb
|
Visual Basic
|
apache-2.0
| 19,116
|
''' <summary>General Device Type</summary>
''' <autogenerated>Generated from a T4 template. Modifications will be lost, if applicable use a partial class instead.</autogenerated>
''' <generator-date>08/02/2014 17:48:42</generator-date>
''' <generator-functions>1</generator-functions>
''' <generator-source>Caerus\General\Generated\GeneralDevice.tt</generator-source>
''' <generator-template>Text-Templates\Classes\VB_Object.tt</generator-template>
''' <generator-version>1</generator-version>
<System.CodeDom.Compiler.GeneratedCode("Caerus\General\Generated\GeneralDevice.tt", "1")> _
Partial Public Class GeneralDevice
Inherits System.Object
Implements System.IComparable
Implements System.IFormattable
#Region " Public Constructors "
''' <summary>Default Constructor</summary>
Public Sub New()
MyBase.New()
End Sub
''' <summary>Parametered Constructor (1 Parameters)</summary>
Public Sub New( _
ByVal _Index As System.Int32 _
)
MyBase.New()
Index = _Index
End Sub
''' <summary>Parametered Constructor (2 Parameters)</summary>
Public Sub New( _
ByVal _Index As System.Int32, _
ByVal _Name As System.String _
)
MyBase.New()
Index = _Index
Name = _Name
End Sub
''' <summary>Parametered Constructor (3 Parameters)</summary>
Public Sub New( _
ByVal _Index As System.Int32, _
ByVal _Name As System.String, _
ByVal _Type As DeviceType _
)
MyBase.New()
Index = _Index
Name = _Name
[Type] = _Type
End Sub
''' <summary>Parametered Constructor (4 Parameters)</summary>
Public Sub New( _
ByVal _Index As System.Int32, _
ByVal _Name As System.String, _
ByVal _Type As DeviceType, _
ByVal _Status As DeviceStatus _
)
MyBase.New()
Index = _Index
Name = _Name
[Type] = _Type
Status = _Status
End Sub
#End Region
#Region " Class Plumbing/Interface Code "
#Region " IComparable Implementation "
#Region " Public Methods "
''' <summary>Comparison Method</summary>
Public Overridable Function IComparable_CompareTo( _
ByVal value As System.Object _
) As System.Int32 Implements System.IComparable.CompareTo
Dim typed_Value As GeneralDevice = TryCast(value, GeneralDevice)
If typed_Value Is Nothing Then
Throw New ArgumentException(String.Format("Value is not of comparable type: {0}", value.GetType.Name), "Value")
Else
Dim return_Value As Integer = 0
If Not Name Is Nothing Then return_Value = Name.CompareTo(typed_Value.Name)
If return_Value <> 0 Then Return return_Value
Return return_Value
End If
End Function
#End Region
#End Region
#Region " IFormattable Implementation "
#Region " Public Constants "
''' <summary>Public Shared Reference to the Name of the Property: AsString</summary>
''' <remarks></remarks>
Public Const PROPERTY_ASSTRING As String = "AsString"
#End Region
#Region " Public Properties "
''' <summary></summary>
''' <remarks></remarks>
Public ReadOnly Property AsString() As System.String
Get
Return Me.ToString()
End Get
End Property
#End Region
#Region " Public Shared Methods "
#End Region
#Region " Public Methods "
Public Overloads Overrides Function ToString() As String
Return Me.ToString(String.Empty, Nothing)
End Function
Public Overloads Function ToString( _
ByVal format As String _
) As String
Return String.Empty
End Function
Public Overloads Function ToString( _
ByVal format As String, _
ByVal formatProvider As System.IFormatProvider _
) As String Implements System.IFormattable.ToString
Return String.Empty
End Function
#End Region
#End Region
#End Region
#Region " Public Constants "
''' <summary>Public Shared Reference to the Name of the Property: Index</summary>
''' <remarks></remarks>
Public Const PROPERTY_INDEX As String = "Index"
''' <summary>Public Shared Reference to the Name of the Property: Name</summary>
''' <remarks></remarks>
Public Const PROPERTY_NAME As String = "Name"
''' <summary>Public Shared Reference to the Name of the Property: Type</summary>
''' <remarks></remarks>
Public Const PROPERTY_TYPE As String = "Type"
''' <summary>Public Shared Reference to the Name of the Property: Status</summary>
''' <remarks></remarks>
Public Const PROPERTY_STATUS As String = "Status"
#End Region
#Region " Private Variables "
''' <summary>Private Data Storage Variable for Property: Index</summary>
''' <remarks></remarks>
Private m_Index As System.Int32
''' <summary>Private Data Storage Variable for Property: Name</summary>
''' <remarks></remarks>
Private m_Name As System.String
''' <summary>Private Data Storage Variable for Property: Type</summary>
''' <remarks></remarks>
Private m_Type As DeviceType
''' <summary>Private Data Storage Variable for Property: Status</summary>
''' <remarks></remarks>
Private m_Status As DeviceStatus
#End Region
#Region " Public Properties "
''' <summary>Provides Access to the Property: Index</summary>
''' <remarks></remarks>
Public Property Index() As System.Int32
Get
Return m_Index
End Get
Set(value As System.Int32)
m_Index = value
End Set
End Property
''' <summary>Provides Access to the Property: Name</summary>
''' <remarks></remarks>
Public Property Name() As System.String
Get
Return m_Name
End Get
Set(value As System.String)
m_Name = value
End Set
End Property
''' <summary>Provides Access to the Property: Type</summary>
''' <remarks></remarks>
Public Property [Type]() As DeviceType
Get
Return m_Type
End Get
Set(value As DeviceType)
m_Type = value
End Set
End Property
''' <summary>Provides Access to the Property: Status</summary>
''' <remarks></remarks>
Public Property Status() As DeviceStatus
Get
Return m_Status
End Get
Set(value As DeviceStatus)
m_Status = value
End Set
End Property
#End Region
End Class
|
thiscouldbejd/Caerus
|
General/Generated/GeneralDevice.vb
|
Visual Basic
|
mit
| 6,083
|
Module ParallelLife
Sub Main()
Application.Run(New Life())
End Sub
End Module
Class LifePCA
Inherits GenericPCA(Of Cell)
Enum Cell As Byte
Dead = 0
Alive = 1
Random = 2
End Enum
Public Overrides Function NextState(ByVal u As Cell()(), ByVal i As Integer, ByVal j As Integer, ByVal r As System.Random) As Cell
Dim Living As Integer = u(i - 1)(j - 1) + u(i - 1)(j) + u(i - 1)(j + 1) + _
u(i)(j - 1) + u(i)(j + 1) + _
u(i + 1)(j - 1) + u(i + 1)(j) + u(i + 1)(j + 1)
Select Case u(i)(j)
Case Cell.Alive
If Living = 2 Or Living = 3 Then
Return Cell.Alive
Else
Return Cell.Dead
End If
Case Cell.Dead
If Living = 3 Then
Return Cell.Alive
Else
Return Cell.Dead
End If
Case Cell.Random
If r.Next(0, 10) = 0 Then
Return Cell.Alive
Else
Return Cell.Dead
End If
End Select
End Function
Sub New(ByVal q As Integer, ByVal m As Integer, ByVal CellSize As Integer)
MyBase.New(q, m, CellSize, Cell.Dead, Cell.Dead, Cell.Dead, Cell.Dead, Cell.Random)
End Sub
Public Overrides Function GetColor(ByVal S As Cell) As Color
Select Case S
Case Cell.Alive
Return Color.Red
Case Cell.Dead
Return Color.Black
Case Cell.Random
Return Color.Blue
End Select
End Function
End Class
|
JoinPatterns/ScalableJoins
|
Demos/Life/ParallelLife.vb
|
Visual Basic
|
mit
| 1,725
|
Namespace Excel
''' <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:50</generator-date>
''' <generator-functions>1</generator-functions>
''' <generator-source>Deimos\_Excel\Enums\HorizontalAlignment.tt</generator-source>
''' <generator-version>1</generator-version>
<System.CodeDom.Compiler.GeneratedCode("Deimos\_Excel\Enums\HorizontalAlignment.tt", "1")> _
Public Enum HorizontalAlignment As System.Int32
''' <summary>Horizontal Align the Element on the Left</summary>
Left = 1
''' <summary>Horizontal Align the Element in the Center</summary>
Center = 2
''' <summary>Horizontal Align the Element on the Right</summary>
Right = 3
End Enum
End Namespace
|
thiscouldbejd/Deimos
|
_Excel/Enums/HorizontalAlignment.vb
|
Visual Basic
|
mit
| 826
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class substract
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.btnBack = New System.Windows.Forms.Button()
Me.txtResult = New System.Windows.Forms.TextBox()
Me.Label1 = New System.Windows.Forms.Label()
Me.btnCMD = New System.Windows.Forms.Button()
Me.lblAdd = New System.Windows.Forms.Label()
Me.txtNum2 = New System.Windows.Forms.TextBox()
Me.txtNum1 = New System.Windows.Forms.TextBox()
Me.lblNum2 = New System.Windows.Forms.Label()
Me.lblNum1 = New System.Windows.Forms.Label()
Me.SuspendLayout()
'
'btnBack
'
Me.btnBack.Font = New System.Drawing.Font("Microsoft Sans Serif", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.btnBack.Location = New System.Drawing.Point(76, 279)
Me.btnBack.Name = "btnBack"
Me.btnBack.Size = New System.Drawing.Size(197, 44)
Me.btnBack.TabIndex = 17
Me.btnBack.Text = "Go Back to Main"
Me.btnBack.UseVisualStyleBackColor = True
'
'txtResult
'
Me.txtResult.Location = New System.Drawing.Point(173, 231)
Me.txtResult.Name = "txtResult"
Me.txtResult.Size = New System.Drawing.Size(100, 20)
Me.txtResult.TabIndex = 16
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label1.Location = New System.Drawing.Point(72, 231)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(61, 20)
Me.Label1.TabIndex = 15
Me.Label1.Text = "Result"
'
'btnCMD
'
Me.btnCMD.Font = New System.Drawing.Font("Microsoft Sans Serif", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.btnCMD.Location = New System.Drawing.Point(142, 171)
Me.btnCMD.Name = "btnCMD"
Me.btnCMD.Size = New System.Drawing.Size(131, 44)
Me.btnCMD.TabIndex = 14
Me.btnCMD.Text = "Compute"
Me.btnCMD.UseVisualStyleBackColor = True
'
'lblAdd
'
Me.lblAdd.AutoSize = True
Me.lblAdd.Font = New System.Drawing.Font("Matura MT Script Capitals", 15.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.lblAdd.Location = New System.Drawing.Point(119, 38)
Me.lblAdd.Name = "lblAdd"
Me.lblAdd.Size = New System.Drawing.Size(144, 28)
Me.lblAdd.TabIndex = 13
Me.lblAdd.Text = "Substraction"
'
'txtNum2
'
Me.txtNum2.Location = New System.Drawing.Point(173, 127)
Me.txtNum2.Name = "txtNum2"
Me.txtNum2.Size = New System.Drawing.Size(100, 20)
Me.txtNum2.TabIndex = 12
'
'txtNum1
'
Me.txtNum1.Location = New System.Drawing.Point(173, 87)
Me.txtNum1.Name = "txtNum1"
Me.txtNum1.Size = New System.Drawing.Size(100, 20)
Me.txtNum1.TabIndex = 11
'
'lblNum2
'
Me.lblNum2.AutoSize = True
Me.lblNum2.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.lblNum2.Location = New System.Drawing.Point(72, 127)
Me.lblNum2.Name = "lblNum2"
Me.lblNum2.Size = New System.Drawing.Size(86, 20)
Me.lblNum2.TabIndex = 10
Me.lblNum2.Text = "Number 2"
'
'lblNum1
'
Me.lblNum1.AutoSize = True
Me.lblNum1.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.lblNum1.Location = New System.Drawing.Point(72, 87)
Me.lblNum1.Name = "lblNum1"
Me.lblNum1.Size = New System.Drawing.Size(86, 20)
Me.lblNum1.TabIndex = 9
Me.lblNum1.Text = "Number 1"
'
'substract
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(345, 361)
Me.Controls.Add(Me.btnBack)
Me.Controls.Add(Me.txtResult)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.btnCMD)
Me.Controls.Add(Me.lblAdd)
Me.Controls.Add(Me.txtNum2)
Me.Controls.Add(Me.txtNum1)
Me.Controls.Add(Me.lblNum2)
Me.Controls.Add(Me.lblNum1)
Me.Name = "substract"
Me.Text = "substract"
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents btnBack As System.Windows.Forms.Button
Friend WithEvents txtResult As System.Windows.Forms.TextBox
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents btnCMD As System.Windows.Forms.Button
Friend WithEvents lblAdd As System.Windows.Forms.Label
Friend WithEvents txtNum2 As System.Windows.Forms.TextBox
Friend WithEvents txtNum1 As System.Windows.Forms.TextBox
Friend WithEvents lblNum2 As System.Windows.Forms.Label
Friend WithEvents lblNum1 As System.Windows.Forms.Label
End Class
|
miguel2192/CSC-162
|
Rodriguez_MathMultForms/Rodriguez_MathMultForms/substract.Designer.vb
|
Visual Basic
|
mit
| 6,160
|
'------------------------------------------------------------------------------
' <auto-generated>
' Dieser Code wurde von einem Tool generiert.
' Laufzeitversion:4.0.30319.34209
'
' Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
' der Code erneut generiert wird.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Imports System
Namespace My.Resources
'Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert
'-Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert.
'Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen
'mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu.
'''<summary>
''' Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("osu_Sync_UpdatePatcher.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle
''' Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
troke12/osu-Sync
|
osu!Sync UpdatePatcher/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,951
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.IO
Imports System.Threading
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.Implementation.Peek
Imports Microsoft.CodeAnalysis.Editor.Peek
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.VisualStudio.Imaging.Interop
Imports Microsoft.VisualStudio.Language.Intellisense
Imports Microsoft.VisualStudio.Text
Imports Moq
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Peek
Public Class PeekTests
<Fact, WorkItem(820706), Trait(Traits.Feature, Traits.Features.Peek)>
Sub InvokeInEmptyFile()
Dim result = GetPeekResultCollection(<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>$$}</Document>
</Project>
</Workspace>)
Assert.Null(result)
End Sub
<Fact, WorkItem(827025), Trait(Traits.Feature, Traits.Features.Peek)>
Sub WorksAcrossLanguages()
Using workspace = TestWorkspaceFactory.CreateWorkspace(<Workspace>
<Project Language="C#" AssemblyName="Reference" CommonReferences="true">
<Document>public class {|Identifier:TestClass|} { }</Document>
</Project>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>Reference</ProjectReference>
<Document>
Public Class Blah : Inherits $$TestClass : End Class
</Document>
</Project>
</Workspace>)
Dim result = GetPeekResultCollection(workspace)
Assert.Equal(1, result.Items.Count)
result.AssertNavigatesToIdentifier(index:=0, name:="Identifier")
End Using
End Sub
<Fact, WorkItem(824336), Trait(Traits.Feature, Traits.Features.Peek)>
Sub PeekDefinitionWhenInvokedOnLiteral()
Using workspace = TestWorkspaceFactory.CreateWorkspace(<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class C { string s = $$"Foo"; }</Document>
</Project>
</Workspace>)
Dim result = GetPeekResultCollection(workspace)
Assert.Equal(1, result.Items.Count)
Assert.Equal($"String [{EditorFeaturesResources.FromMetadata}]", result(0).DisplayInfo.Label)
Assert.Equal($"String [{EditorFeaturesResources.FromMetadata}]", result(0).DisplayInfo.Title)
Assert.True(result.GetRemainingIdentifierLineTextOnDisk(index:=0).StartsWith("String", StringComparison.Ordinal))
End Using
End Sub
<Fact, WorkItem(824331), WorkItem(820289), Trait(Traits.Feature, Traits.Features.Peek)>
Sub PeekDefinitionWhenExtensionMethodFromMetadata()
Using workspace = TestWorkspaceFactory.CreateWorkspace(<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Linq;
class C { void M() { int[] a; a.$$Distinct(); }</Document>
</Project>
</Workspace>)
Dim result = GetPeekResultCollection(workspace)
Assert.Equal(1, result.Items.Count)
Assert.Equal($"Enumerable [{EditorFeaturesResources.FromMetadata}]", result(0).DisplayInfo.Label)
Assert.Equal($"Enumerable [{EditorFeaturesResources.FromMetadata}]", result(0).DisplayInfo.Title)
Assert.True(result.GetRemainingIdentifierLineTextOnDisk(index:=0).StartsWith("Distinct", StringComparison.Ordinal))
End Using
End Sub
<Fact, WorkItem(819660), Trait(Traits.Feature, Traits.Features.Peek)>
Sub PeekDefinitionFromVisualBasicMetadataAsSource()
Using workspace = TestWorkspaceFactory.CreateWorkspace(<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[<System.$$Serializable()>
Class AA
End Class
</Document>
]]></Document>
</Project>
</Workspace>)
Dim result = GetPeekResultCollection(workspace)
Assert.Equal(1, result.Items.Count)
Assert.Equal($"SerializableAttribute [{EditorFeaturesResources.FromMetadata}]", result(0).DisplayInfo.Label)
Assert.Equal($"SerializableAttribute [{EditorFeaturesResources.FromMetadata}]", result(0).DisplayInfo.Title)
Assert.True(result.GetRemainingIdentifierLineTextOnDisk(index:=0).StartsWith("New()", StringComparison.Ordinal)) ' Navigates to constructor
End Using
End Sub
<Fact, WorkItem(819602), Trait(Traits.Feature, Traits.Features.Peek)>
Sub PeekDefinitionOnParamNameXmlDocComment()
Using workspace = TestWorkspaceFactory.CreateWorkspace(<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Class C
''' <param name="$$exePath"></param>
Public Sub ddd(ByVal {|Identifier:exePath|} As String)
End Sub
End Class
]]></Document>
</Project>
</Workspace>)
Dim result = GetPeekResultCollection(workspace)
Assert.Equal(1, result.Items.Count)
result.AssertNavigatesToIdentifier(0, "Identifier")
End Using
End Sub
<Fact, WorkItem(820363), Trait(Traits.Feature, Traits.Features.Peek)>
Sub PeekDefinitionOnLinqVariable()
Using workspace = TestWorkspaceFactory.CreateWorkspace(<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Module M
Sub S()
Dim arr = {3, 4, 5}
Dim q = From i In arr Select {|Identifier:$$d|} = i.GetType
End Sub
End Module
]]></Document>
</Project>
</Workspace>)
Dim result = GetPeekResultCollection(workspace)
Assert.Equal(1, result.Items.Count)
result.AssertNavigatesToIdentifier(0, "Identifier")
End Using
End Sub
<Fact>
<WorkItem(1091211)>
Public Sub PeekAcrossProjectsInvolvingPortableReferences()
Dim workspaceDefinition =
<Workspace>
<Project Language="C#" AssemblyName="CSharpAssembly" CommonReferencesPortable="true">
<Document>
namespace N
{
public class CSClass
{
public void {|Identifier:M|}(int i) { }
}
}
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true" CommonReferenceFacadeSystemRuntime="true">
<ProjectReference>CSharpAssembly</ProjectReference>
<Document>
Imports N
Public Class VBClass
Sub Test()
Dim x As New CSClass()
x.M$$(5)
End Sub
End Class
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspaceFactory.CreateWorkspace(workspaceDefinition)
Dim result = GetPeekResultCollection(workspace)
Assert.Equal(1, result.Items.Count)
result.AssertNavigatesToIdentifier(0, "Identifier")
End Using
End Sub
Private Function GetPeekResultCollection(workspace As XElement) As PeekResultCollection
Using testWorkspace = TestWorkspaceFactory.CreateWorkspace(workspace)
Return GetPeekResultCollection(testWorkspace)
End Using
End Function
Private Function GetPeekResultCollection(workspace As TestWorkspace) As PeekResultCollection
Dim document = workspace.Documents.FirstOrDefault(Function(d) d.CursorPosition.HasValue)
If document Is Nothing Then
AssertEx.Fail("The test is missing a $$ in the workspace.")
End If
Dim textBuffer = document.GetTextBuffer()
Dim textView = document.GetTextView()
Dim peekableItemSource As New PeekableItemSource(textBuffer,
workspace.GetService(Of IPeekableItemFactory),
New MockPeekResultFactory(workspace.GetService(Of IPersistentSpanFactory)),
workspace.GetService(Of IMetadataAsSourceFileService),
workspace.GetService(Of IWaitIndicator))
Dim peekableSession As New Mock(Of IPeekSession)(MockBehavior.Strict)
Dim triggerPoint = New SnapshotPoint(document.GetTextBuffer().CurrentSnapshot, document.CursorPosition.Value)
peekableSession.Setup(Function(s) s.GetTriggerPoint(It.IsAny(Of ITextSnapshot))).Returns(triggerPoint)
Dim items As New List(Of IPeekableItem)
peekableItemSource.AugmentPeekSession(peekableSession.Object, items)
If Not items.Any Then
Return Nothing
End If
Dim peekResult As New PeekResultCollection(workspace)
Dim item = items.SingleOrDefault()
If item IsNot Nothing Then
Dim resultSource = item.GetOrCreateResultSource(PredefinedPeekRelationships.Definitions.Name)
resultSource.FindResults(PredefinedPeekRelationships.Definitions.Name,
peekResult,
CancellationToken.None,
New Mock(Of IFindPeekResultsCallback)(MockBehavior.Loose).Object)
End If
Return peekResult
End Function
Private Class MockPeekResultFactory
Implements IPeekResultFactory
Private ReadOnly _persistentSpanFactory As IPersistentSpanFactory
Public Sub New(persistentSpanFactory As IPersistentSpanFactory)
_persistentSpanFactory = persistentSpanFactory
End Sub
Public Function Create(displayInfo As IPeekResultDisplayInfo, browseAction As Action) As IExternallyBrowsablePeekResult Implements IPeekResultFactory.Create
Throw New NotImplementedException()
End Function
Public Function Create(displayInfo As IPeekResultDisplayInfo, filePath As String, eoiSpan As Span, idPosition As Integer, isReadOnly As Boolean) As IDocumentPeekResult Implements IPeekResultFactory.Create
Throw New NotImplementedException()
End Function
Public Function Create(displayInfo As IPeekResultDisplayInfo, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idLine As Integer, idIndex As Integer) As IDocumentPeekResult Implements IPeekResultFactory.Create
Throw New NotImplementedException()
End Function
Public Function Create(displayInfo As IPeekResultDisplayInfo, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idLine As Integer, idIndex As Integer, isReadOnly As Boolean) As IDocumentPeekResult Implements IPeekResultFactory.Create
Dim documentResult As New Mock(Of IDocumentPeekResult)(MockBehavior.Strict)
documentResult.SetupGet(Function(d) d.DisplayInfo).Returns(displayInfo)
documentResult.SetupGet(Function(d) d.FilePath).Returns(filePath)
documentResult.SetupGet(Function(d) d.IdentifyingSpan).Returns(_persistentSpanFactory.Create(filePath, idLine, idIndex, idLine, idIndex, SpanTrackingMode.EdgeInclusive))
documentResult.SetupGet(Function(d) d.Span).Returns(_persistentSpanFactory.Create(filePath, idLine, idIndex, idLine, idIndex, SpanTrackingMode.EdgeInclusive))
documentResult.SetupGet(Function(d) d.IsReadOnly).Returns(isReadOnly)
Return documentResult.Object
End Function
Public Function Create(displayInfo As IPeekResultDisplayInfo2, image As ImageMoniker, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idStartLine As Integer, idStartIndex As Integer, idEndLine As Integer, idEndIndex As Integer) As IDocumentPeekResult Implements IPeekResultFactory.Create
Throw New NotImplementedException()
End Function
Public Function Create(displayInfo As IPeekResultDisplayInfo2, image As ImageMoniker, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idStartLine As Integer, idStartIndex As Integer, idEndLine As Integer, idEndIndex As Integer, isReadOnly As Boolean) As IDocumentPeekResult Implements IPeekResultFactory.Create
Throw New NotImplementedException()
End Function
Public Function Create(displayInfo As IPeekResultDisplayInfo2, image As ImageMoniker, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idStartLine As Integer, idStartIndex As Integer, idEndLine As Integer, idEndIndex As Integer, isReadOnly As Boolean, editorDestination As Guid) As IDocumentPeekResult Implements IPeekResultFactory.Create
Throw New NotImplementedException()
End Function
Public Function Create(displayInfo As IPeekResultDisplayInfo2, image As ImageMoniker, filePath As String, startLine As Integer, startIndex As Integer, endLine As Integer, endIndex As Integer, idStartLine As Integer, idStartIndex As Integer, idEndLine As Integer, idEndIndex As Integer, isReadOnly As Boolean, editorDestination As Guid, postNavigationCallback As Action(Of IPeekResult, Object, Object)) As IDocumentPeekResult Implements IPeekResultFactory.Create
Throw New NotImplementedException()
End Function
End Class
Private Class PeekResultCollection
Implements IPeekResultCollection
Public ReadOnly Items As New List(Of IPeekResult)
Private ReadOnly _workspace As TestWorkspace
Public Sub New(workspace As TestWorkspace)
_workspace = workspace
End Sub
Private ReadOnly Property Count As Integer Implements IPeekResultCollection.Count
Get
Return Items.Count
End Get
End Property
Default Property Item(index As Integer) As IPeekResult Implements IPeekResultCollection.Item
Get
Return Items(index)
End Get
Set(value As IPeekResult)
Throw New NotImplementedException()
End Set
End Property
Private Sub Add(peekResult As IPeekResult) Implements IPeekResultCollection.Add
Items.Add(peekResult)
End Sub
Private Sub Clear() Implements IPeekResultCollection.Clear
Throw New NotImplementedException()
End Sub
Private Sub Insert(index As Integer, peekResult As IPeekResult) Implements IPeekResultCollection.Insert
Throw New NotImplementedException()
End Sub
Private Sub Move(oldIndex As Integer, newIndex As Integer) Implements IPeekResultCollection.Move
Throw New NotImplementedException()
End Sub
Private Sub RemoveAt(index As Integer) Implements IPeekResultCollection.RemoveAt
Throw New NotImplementedException()
End Sub
Private Function Contains(peekResult As IPeekResult) As Boolean Implements IPeekResultCollection.Contains
Throw New NotImplementedException()
End Function
Private Function IndexOf(peekResult As IPeekResult, startAt As Integer) As Integer Implements IPeekResultCollection.IndexOf
Throw New NotImplementedException()
End Function
Private Function Remove(item As IPeekResult) As Boolean Implements IPeekResultCollection.Remove
Throw New NotImplementedException()
End Function
''' <summary>
''' Returns the text of the identifier line, starting at the identifier and ending at end of the line.
''' </summary>
''' <param name="index"></param>
''' <returns></returns>
Friend Function GetRemainingIdentifierLineTextOnDisk(index As Integer) As String
Dim documentResult = DirectCast(Items(index), IDocumentPeekResult)
Dim textBufferService = _workspace.GetService(Of ITextBufferFactoryService)
Dim buffer = textBufferService.CreateTextBuffer(New StreamReader(documentResult.FilePath), textBufferService.InertContentType)
Dim startLine As Integer
Dim startIndex As Integer
Assert.True(documentResult.IdentifyingSpan.TryGetStartLineIndex(startLine, startIndex), "Unable to get span for metadata file.")
Dim line = buffer.CurrentSnapshot.GetLineFromLineNumber(startLine)
Return buffer.CurrentSnapshot.GetText(line.Start + startIndex, line.Length - startIndex)
End Function
Friend Sub AssertNavigatesToIdentifier(index As Integer, name As String)
Dim documentResult = DirectCast(Items(index), IDocumentPeekResult)
Dim document = _workspace.Documents.FirstOrDefault(Function(d) d.FilePath = documentResult.FilePath)
AssertEx.NotNull(document, "Peek didn't navigate to a document in source. Navigated to " + documentResult.FilePath + " instead.")
Dim startLine As Integer
Dim startIndex As Integer
Assert.True(documentResult.IdentifyingSpan.TryGetStartLineIndex(startLine, startIndex), "Unable to get span for source file.")
Dim snapshot = document.GetTextBuffer().CurrentSnapshot
Dim expectedPosition = New SnapshotPoint(snapshot, document.AnnotatedSpans(name).Single().Start)
Dim actualPosition = snapshot.GetLineFromLineNumber(startLine).Start + startIndex
Assert.Equal(expectedPosition, actualPosition)
End Sub
End Class
End Class
End Namespace
|
ManishJayaswal/roslyn
|
src/EditorFeatures/Test2/Peek/PeekTests.vb
|
Visual Basic
|
apache-2.0
| 20,938
|
'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.
Imports ESRI.ArcGIS.Carto
Imports ESRI.ArcGIS.Controls
Imports ESRI.ArcGIS.ADF.BaseClasses
Imports ESRI.ArcGIS.SystemUI
Public NotInheritable Class ScaleThresholds
Inherits BaseCommand
Implements ICommandSubType
Private m_pMapControl As IMapControl3
Private m_lSubType As Long
Public Sub New()
MyBase.New()
End Sub
Public Overrides Sub OnCreate(ByVal hook As Object)
m_pMapControl = hook
End Sub
Public Overrides Sub OnClick()
Dim pLayer As ILayer
pLayer = m_pMapControl.CustomProperty
If (m_lSubType = 1) Then pLayer.MaximumScale = m_pMapControl.MapScale
If (m_lSubType = 2) Then pLayer.MinimumScale = m_pMapControl.MapScale
If (m_lSubType = 3) Then
pLayer.MaximumScale = 0
pLayer.MinimumScale = 0
End If
m_pMapControl.Refresh(esriViewDrawPhase.esriViewGeography)
End Sub
Public Function GetCount() As Integer Implements ESRI.ArcGIS.SystemUI.ICommandSubType.GetCount
Return 3
End Function
Public Sub SetSubType(ByVal SubType As Integer) Implements ESRI.ArcGIS.SystemUI.ICommandSubType.SetSubType
m_lSubType = SubType
End Sub
Public Overrides ReadOnly Property Caption() As String
Get
If (m_lSubType = 1) Then
Return "Set Maximum Scale"
ElseIf (m_lSubType = 2) Then
Return "Set Minimum Scale"
Else
Return "Remove Scale Thresholds"
End If
End Get
End Property
Public Overrides ReadOnly Property Enabled() As Boolean
Get
Dim bEnabled As Boolean
bEnabled = True
Dim pLayer As ILayer
pLayer = m_pMapControl.CustomProperty
If (m_lSubType = 3) Then
If (pLayer.MaximumScale = 0) And (pLayer.MinimumScale = 0) Then bEnabled = False
End If
Return bEnabled
End Get
End Property
End Class
|
Esri/arcobjects-sdk-community-samples
|
Net/Controls/TOCControlContextMenu/VBNet/ScaleThresholds.vb
|
Visual Basic
|
apache-2.0
| 2,560
|
Namespace DataMart
Public Class PurchasesPerPersonPerMonthAggregateFact
Private _id As Integer
Private _personId As Integer
Private _monthNumber As Integer
Private _monthName As String
Private _purchasesTotal As Decimal
Public ReadOnly Property Id() As Integer
Get
Return _id
End Get
End Property
Public ReadOnly Property PersonId() As Integer
Get
Return _personId
End Get
End Property
Public ReadOnly Property MonthNumber() As Integer
Get
Return _monthNumber
End Get
End Property
Public ReadOnly Property MonthName() As String
Get
Return _monthName
End Get
End Property
Public ReadOnly Property PurchasesTotal() As Decimal
Get
Return _purchasesTotal
End Get
End Property
Public Sub New(ByVal id As Integer, ByVal personId As Integer, ByVal monthNumber As Integer, ByVal monthName As String, ByVal purchasesTotal As Decimal)
_id = id
_personId = personId
_monthNumber = monthNumber
_monthName = monthName
_purchasesTotal = purchasesTotal
End Sub
Private Sub New()
' for NHibernate
End Sub
End Class
End Namespace
|
ferventcoder/ssis-vs-code
|
WarehouseToDataMart/DataMart/PurchasesPerPersonPerMonthAggregateFact.vb
|
Visual Basic
|
apache-2.0
| 1,509
|
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("FileSupport-SkyCDNativeFormat")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("")>
<Assembly: AssemblyCopyright("")>
<Assembly: AssemblyTrademark("")>
<Assembly: CLSCompliant(True)>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("476f05bc-8a67-460d-9881-f7691a234049")>
' 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.1.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
SkyCD/SkyCD
|
Plugins/FileFormat/SkyCDNativeFormat/My Project/AssemblyInfo.vb
|
Visual Basic
|
bsd-3-clause
| 1,153
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.TextBox1 = New System.Windows.Forms.TextBox()
Me.TextBox2 = New System.Windows.Forms.TextBox()
Me.Label1 = New System.Windows.Forms.Label()
Me.Label2 = New System.Windows.Forms.Label()
Me.Button1 = New System.Windows.Forms.Button()
Me.Button2 = New System.Windows.Forms.Button()
Me.SuspendLayout()
'
'TextBox1
'
Me.TextBox1.Location = New System.Drawing.Point(87, 84)
Me.TextBox1.Name = "TextBox1"
Me.TextBox1.Size = New System.Drawing.Size(100, 20)
Me.TextBox1.TabIndex = 0
'
'TextBox2
'
Me.TextBox2.Location = New System.Drawing.Point(87, 126)
Me.TextBox2.Name = "TextBox2"
Me.TextBox2.PasswordChar = Global.Microsoft.VisualBasic.ChrW(42)
Me.TextBox2.Size = New System.Drawing.Size(100, 20)
Me.TextBox2.TabIndex = 1
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Location = New System.Drawing.Point(12, 87)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(38, 13)
Me.Label1.TabIndex = 2
Me.Label1.Text = "NAME"
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.Location = New System.Drawing.Point(11, 129)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(70, 13)
Me.Label2.TabIndex = 3
Me.Label2.Text = "PASSWORD"
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(36, 179)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(75, 23)
Me.Button1.TabIndex = 4
Me.Button1.Text = "LOGIN"
Me.Button1.UseVisualStyleBackColor = True
'
'Button2
'
Me.Button2.Location = New System.Drawing.Point(150, 179)
Me.Button2.Name = "Button2"
Me.Button2.Size = New System.Drawing.Size(75, 23)
Me.Button2.TabIndex = 5
Me.Button2.Text = "REGISTER"
Me.Button2.UseVisualStyleBackColor = True
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(279, 237)
Me.Controls.Add(Me.Button2)
Me.Controls.Add(Me.Button1)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.TextBox2)
Me.Controls.Add(Me.TextBox1)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
Friend WithEvents TextBox2 As System.Windows.Forms.TextBox
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents Button1 As System.Windows.Forms.Button
Friend WithEvents Button2 As System.Windows.Forms.Button
End Class
|
pepincho/John-Atanasov-Visual-Basic
|
Dodge Balls/Dodge Balls/Form1.Designer.vb
|
Visual Basic
|
mit
| 3,936
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Linq
Imports System.Text
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public MustInherit Class FlowTestBase
Inherits BasicTestBase
Friend Function FlowDiagnostics(compilation As VisualBasicCompilation) As ImmutableArray(Of Diagnostic)
Dim diagnostics = DiagnosticBag.GetInstance()
For Each method In AllMethods(compilation.SourceModule.GlobalNamespace)
Dim sourceSymbol = TryCast(method, SourceMethodSymbol)
If sourceSymbol Is Nothing OrElse method.IsPartialWithoutImplementation Then
Continue For
End If
Dim compilationState As New TypeCompilationState(compilation, Nothing, initializeComponentOpt:=Nothing)
Dim boundBody = sourceSymbol.GetBoundMethodBody(compilationState, New DiagnosticBag())
FlowAnalysisPass.Analyze(sourceSymbol, boundBody, diagnostics)
Debug.Assert(Not compilationState.HasSynthesizedMethods)
Next
Return diagnostics.ToReadOnlyAndFree()
End Function
Private Function AllMethods(symbol As Symbol) As IList(Of MethodSymbol)
Dim symbols As New List(Of MethodSymbol)
Select Case symbol.Kind
Case SymbolKind.Method
symbols.Add(TryCast(symbol, MethodSymbol))
Case SymbolKind.NamedType
For Each m In (TryCast(symbol, NamedTypeSymbol)).GetMembers()
symbols.AddRange(AllMethods(m))
Next
Case SymbolKind.[Namespace]
For Each m In (TryCast(symbol, NamespaceSymbol)).GetMembers()
symbols.AddRange(AllMethods(m))
Next
End Select
Return symbols
End Function
#Region "Utilities"
Protected Function CompileAndAnalyzeControlFlow(program As XElement, Optional ilSource As XCData = Nothing, Optional errors As XElement = Nothing) As ControlFlowAnalysis
Return CompileAndGetModelAndSpan(program, Function(binding, startNodes, endNodes) AnalyzeControlFlow(binding, startNodes, endNodes), ilSource, errors)
End Function
Protected Function CompileAndAnalyzeDataFlow(program As XElement, Optional ilSource As XCData = Nothing, Optional errors As XElement = Nothing) As DataFlowAnalysis
Return CompileAndGetModelAndSpan(program, Function(binding, startNodes, endNodes) AnalyzeDataFlow(binding, startNodes, endNodes), ilSource, errors)
End Function
Protected Function CompileAndAnalyzeControlAndDataFlow(program As XElement, Optional ilSource As XCData = Nothing, Optional errors As XElement = Nothing) As Tuple(Of ControlFlowAnalysis, DataFlowAnalysis)
Return CompileAndGetModelAndSpan(program, Function(binding, startNodes, endNodes) Tuple.Create(AnalyzeControlFlow(binding, startNodes, endNodes), AnalyzeDataFlow(binding, startNodes, endNodes)), ilSource, errors)
End Function
Private Function CompileAndGetModelAndSpan(Of T)(program As XElement, analysisDelegate As Func(Of SemanticModel, List(Of VisualBasicSyntaxNode), List(Of VisualBasicSyntaxNode), T), ilSource As XCData, errors As XElement) As T
Dim startNodes As New List(Of VisualBasicSyntaxNode)
Dim endNodes As New List(Of VisualBasicSyntaxNode)
Dim comp = CompileAndGetModelAndSpan(program, startNodes, endNodes, ilSource, errors)
Return analysisDelegate(comp.GetSemanticModel(comp.SyntaxTrees(0)), startNodes, endNodes)
End Function
Protected Function CompileAndGetModelAndSpan(program As XElement, startNodes As List(Of VisualBasicSyntaxNode), endNodes As List(Of VisualBasicSyntaxNode), ilSource As XCData, errors As XElement, Optional parseOptions As VisualBasicParseOptions = Nothing) As VisualBasicCompilation
Debug.Assert(program.<file>.Count = 1, "Only one file can be in the compilation.")
Dim references = {MscorlibRef, MsvbRef, SystemCoreRef}
If ilSource IsNot Nothing Then
Dim ilImage As ImmutableArray(Of Byte) = Nothing
references = references.Concat(CreateReferenceFromIlCode(ilSource?.Value, appendDefaultHeader:=True, ilImage:=ilImage)).ToArray()
End If
Dim assemblyName As String = Nothing
Dim spans As IEnumerable(Of IEnumerable(Of TextSpan)) = Nothing
Dim trees = ParseSourceXml(program, parseOptions, assemblyName, spans)
Dim comp = CreateEmptyCompilation(trees, references, Nothing, assemblyName)
If errors IsNot Nothing Then
AssertTheseDiagnostics(comp, errors)
End If
Debug.Assert(spans.Count = 1 AndAlso spans(0).Count = 1, "Exactly one region must be selected")
Dim span = spans.Single.Single
FindRegionNodes(comp.SyntaxTrees(0), span, startNodes, endNodes)
Return comp
End Function
Protected Shared Function GetSymbolNamesJoined(Of T As ISymbol)(symbols As IEnumerable(Of T)) As String
Return If(Not symbols.IsEmpty(), String.Join(", ", symbols.Select(Function(symbol) symbol.Name)), Nothing)
End Function
Protected Function AnalyzeControlFlow(model As SemanticModel,
startNodes As List(Of VisualBasicSyntaxNode), endNodes As List(Of VisualBasicSyntaxNode)) As ControlFlowAnalysis
Dim pair = (From s In startNodes From e In endNodes
Where s.Parent Is e.Parent AndAlso TypeOf s Is ExecutableStatementSyntax AndAlso TypeOf e Is ExecutableStatementSyntax
Select New With {.first = DirectCast(s, ExecutableStatementSyntax), .last = DirectCast(e, ExecutableStatementSyntax)}).LastOrDefault()
If pair IsNot Nothing Then
Return model.AnalyzeControlFlow(pair.first, pair.last)
End If
Throw New ArgumentException("Failed to identify statement sequence, maybe the region is invalid")
End Function
Protected Function AnalyzeDataFlow(model As SemanticModel,
startNodes As List(Of VisualBasicSyntaxNode), endNodes As List(Of VisualBasicSyntaxNode)) As DataFlowAnalysis
Dim pair = (From s In startNodes From e In endNodes
Where s.Parent Is e.Parent AndAlso TypeOf s Is ExecutableStatementSyntax AndAlso TypeOf e Is ExecutableStatementSyntax
Select New With {.first = DirectCast(s, ExecutableStatementSyntax), .last = DirectCast(e, ExecutableStatementSyntax)}).LastOrDefault()
If pair IsNot Nothing Then
Return model.AnalyzeDataFlow(pair.first, pair.last)
End If
Dim expr = (From s In startNodes From e In endNodes
Where s Is e AndAlso TypeOf s Is ExpressionSyntax
Select DirectCast(s, ExpressionSyntax)).LastOrDefault()
If expr IsNot Nothing Then
Return model.AnalyzeDataFlow(expr)
End If
Throw New ArgumentException("Failed to identify expression or statement sequence, maybe the region is invalid")
End Function
#Region "Mapping text region into syntax node(s)"
Private Function GetNextToken(token As SyntaxToken) As SyntaxToken
Dim nextToken = token.GetNextToken()
AdjustToken(nextToken)
Return nextToken
End Function
Private Sub AdjustToken(ByRef token As SyntaxToken)
tryAgain:
Select Case token.Kind
Case SyntaxKind.StatementTerminatorToken
token = token.GetNextToken()
GoTo tryAgain
Case SyntaxKind.ColonToken
Dim parent = token.Parent
If TypeOf parent Is StatementSyntax AndAlso parent.Kind <> SyntaxKind.LabelStatement Then
' let's assume this is a statement block, what else can it be?
token = token.GetNextToken()
GoTo tryAgain
End If
End Select
End Sub
Private Sub FindRegionNodes(tree As SyntaxTree, region As TextSpan,
startNodes As List(Of VisualBasicSyntaxNode), endNodes As List(Of VisualBasicSyntaxNode))
Dim startToken As SyntaxToken = tree.GetCompilationUnitRoot().FindToken(region.Start, True)
AdjustToken(startToken)
While startToken.Span.End <= region.Start
startToken = GetNextToken(startToken)
End While
Dim startPosition = startToken.SpanStart
Dim startNode = startToken.Parent
If startPosition <= startNode.SpanStart Then startPosition = startNode.SpanStart
While startNode IsNot Nothing AndAlso startNode.SpanStart = startPosition
startNodes.Add(DirectCast(startNode, VisualBasicSyntaxNode))
startNode = startNode.Parent
End While
Dim endToken As SyntaxToken = Nothing
Do
Dim nextToken = GetNextToken(startToken)
If nextToken.SpanStart >= region.End Then
endToken = startToken
Exit Do
End If
startToken = nextToken
Loop
Dim endPosition = endToken.Span.End
Dim endNode = endToken.Parent
If endPosition >= endNode.Span.End Then endPosition = endNode.Span.End
While endNode IsNot Nothing AndAlso endNode.Span.End = endPosition
endNodes.Add(DirectCast(endNode, VisualBasicSyntaxNode))
endNode = endNode.Parent
End While
End Sub
#End Region
#End Region
Protected Sub VerifyDataFlowAnalysis(
code As XElement,
Optional alwaysAssigned() As String = Nothing,
Optional captured() As String = Nothing,
Optional dataFlowsIn() As String = Nothing,
Optional dataFlowsOut() As String = Nothing,
Optional readInside() As String = Nothing,
Optional readOutside() As String = Nothing,
Optional variablesDeclared() As String = Nothing,
Optional writtenInside() As String = Nothing,
Optional writtenOutside() As String = Nothing,
Optional capturedInside() As String = Nothing,
Optional capturedOutside() As String = Nothing)
Dim analysis = CompileAndAnalyzeDataFlow(code)
Assert.True(analysis.Succeeded)
Assert.Equal(If(alwaysAssigned, {}), analysis.AlwaysAssigned.Select(Function(s) s.Name).ToArray())
Assert.Equal(If(captured, {}), analysis.Captured.Select(Function(s) s.Name).ToArray())
Assert.Equal(If(dataFlowsIn, {}), analysis.DataFlowsIn.Select(Function(s) s.Name).ToArray())
Assert.Equal(If(dataFlowsOut, {}), analysis.DataFlowsOut.Select(Function(s) s.Name).ToArray())
Assert.Equal(If(readInside, {}), analysis.ReadInside.Select(Function(s) s.Name).ToArray())
Assert.Equal(If(readOutside, {}), analysis.ReadOutside.Select(Function(s) s.Name).ToArray())
Assert.Equal(If(variablesDeclared, {}), analysis.VariablesDeclared.Select(Function(s) s.Name).ToArray())
Assert.Equal(If(writtenInside, {}), analysis.WrittenInside.Select(Function(s) s.Name).ToArray())
Assert.Equal(If(writtenOutside, {}), analysis.WrittenOutside.Select(Function(s) s.Name).ToArray())
Assert.Equal(If(capturedInside, {}), analysis.CapturedInside.Select(Function(s) s.Name).ToArray())
Assert.Equal(If(capturedOutside, {}), analysis.CapturedOutside.Select(Function(s) s.Name).ToArray())
End Sub
End Class
End Namespace
|
Hosch250/roslyn
|
src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/FlowTestBase.vb
|
Visual Basic
|
apache-2.0
| 12,575
|
' 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.Diagnostics
Imports Microsoft.CodeAnalysis.Diagnostics.PreferFrameworkType
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Diagnostics.Analyzers
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Friend Class VisualBasicPreferFrameworkTypeDiagnosticAnalyzer
Inherits PreferFrameworkTypeDiagnosticAnalyzerBase(Of SyntaxKind, ExpressionSyntax, PredefinedTypeSyntax)
Protected Overrides ReadOnly Property SyntaxKindsOfInterest As ImmutableArray(Of SyntaxKind) =
ImmutableArray.Create(SyntaxKind.PredefinedType)
Protected Overrides Function IsInMemberAccessOrCrefReferenceContext(node As ExpressionSyntax) As Boolean
Return node.IsInMemberAccessContext() OrElse node.InsideCrefReference()
End Function
Protected Overrides Function IsPredefinedTypeReplaceableWithFrameworkType(node As PredefinedTypeSyntax) As Boolean
' There is nothing to replace if keyword matches type name. For e.g: we don't want to replace `Object`
' Or `String` because we'd essentially be replacing it with the same thing.
Return Not KeywordMatchesTypeName(node.Keyword.Kind())
End Function
Protected Overrides Function GetLanguageName() As String
Return LanguageNames.VisualBasic
End Function
''' <summary>
''' Returns true, if the VB language keyword for predefined type matches its
''' actual framework type name.
''' </summary>
Private Function KeywordMatchesTypeName(kind As SyntaxKind) As Boolean
Select Case kind
Case _
SyntaxKind.BooleanKeyword,
SyntaxKind.ByteKeyword,
SyntaxKind.CharKeyword,
SyntaxKind.ObjectKeyword,
SyntaxKind.SByteKeyword,
SyntaxKind.StringKeyword,
SyntaxKind.SingleKeyword,
SyntaxKind.DecimalKeyword,
SyntaxKind.DoubleKeyword
Return True
End Select
Return False
End Function
End Class
End Namespace
|
OmarTawfik/roslyn
|
src/Features/VisualBasic/Portable/Diagnostics/Analyzers/VisualBasicPreferFrameworkTypeDiagnosticAnalyzer.vb
|
Visual Basic
|
apache-2.0
| 2,395
|
' 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.Hosting
Imports System.Threading
Imports Microsoft.CodeAnalysis.Editor.CSharp.GoToDefinition
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.Implementation.GoToDefinition
Imports Microsoft.CodeAnalysis.Editor.Navigation
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities.GoToHelpers
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Navigation
Imports Microsoft.CodeAnalysis.Notification
Imports Microsoft.CodeAnalysis.Text
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.GoToDefinition
Public Class GoToDefinitionCancellationTests
<WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)>
Public Async Function TestCancellation() As Tasks.Task
' Run without cancelling.
Dim updates As Integer = Await Me.CancelAsync(Integer.MaxValue, False)
Assert.InRange(updates, 0, Integer.MaxValue)
Dim i As Integer = 0
While i < updates
Dim n As Integer = Await Me.CancelAsync(i, True)
Assert.Equal(n, i + 1)
i = i + 1
End While
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)>
Public Async Function TestInLinkedFiles() As Tasks.Task
Dim definition =
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1">
<Document FilePath="C.cs">
class C
{
void M()
{
M1$$(5);
}
#if Proj1
void M1(int x) { }
#endif
#if Proj2
void M1(int x) { }
#endif
}
</Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
</Project>
</Workspace>
Using workspace = Await TestWorkspaceFactory.CreateWorkspaceAsync(
definition,
exportProvider:=MinimalTestExportProvider.CreateExportProvider(GoToTestHelpers.Catalog.WithPart(GetType(CSharpGoToDefinitionService))))
Dim baseDocument = workspace.Documents.First(Function(d) Not d.IsLinkFile)
Dim linkDocument = workspace.Documents.First(Function(d) d.IsLinkFile)
Dim view = baseDocument.GetTextView()
Dim mockDocumentNavigationService =
DirectCast(workspace.Services.GetService(Of IDocumentNavigationService)(), MockDocumentNavigationService)
Dim commandHandler = New GoToDefinitionCommandHandler(New TestWaitIndicator(New TestWaitContext(100)))
commandHandler.TryExecuteCommand(view.TextSnapshot, baseDocument.CursorPosition.Value)
Assert.True(mockDocumentNavigationService._triedNavigationToSpan)
Assert.Equal(New TextSpan(78, 2), mockDocumentNavigationService._span)
workspace.SetDocumentContext(linkDocument.Id)
commandHandler.TryExecuteCommand(view.TextSnapshot, baseDocument.CursorPosition.Value)
Assert.True(mockDocumentNavigationService._triedNavigationToSpan)
Assert.Equal(New TextSpan(121, 2), mockDocumentNavigationService._span)
End Using
End Function
Private Async Function CancelAsync(updatesBeforeCancel As Integer, expectedCancel As Boolean) As Tasks.Task(Of Integer)
Dim definition =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|C|] { $$C c; }"
</Document>
</Project>
</Workspace>
Using workspace = Await TestWorkspaceFactory.CreateWorkspaceAsync(definition, exportProvider:=GoToTestHelpers.ExportProvider)
Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue)
Dim cursorPosition = cursorDocument.CursorPosition.Value
Dim mockDocumentNavigationService = DirectCast(workspace.Services.GetService(Of IDocumentNavigationService)(), MockDocumentNavigationService)
Dim navigatedTo = False
Dim presenter = New MockNavigableItemsPresenter(Sub(i) navigatedTo = True)
Dim presenters = {New Lazy(Of INavigableItemsPresenter)(Function() presenter)}
Dim cursorBuffer = cursorDocument.TextBuffer
Dim document = workspace.CurrentSolution.GetDocument(cursorDocument.Id)
Dim goToDefService = New CSharpGoToDefinitionService(presenters)
Dim waitContext = New TestWaitContext(updatesBeforeCancel)
Dim waitIndicator = New TestWaitIndicator(waitContext)
Dim commandHandler = New GoToDefinitionCommandHandler(waitIndicator)
commandHandler.TryExecuteCommand(document, cursorPosition, goToDefService)
Assert.Equal(navigatedTo OrElse mockDocumentNavigationService._triedNavigationToSpan, Not expectedCancel)
Return waitContext.Updates
End Using
End Function
End Class
End Namespace
|
VPashkov/roslyn
|
src/EditorFeatures/Test2/GoToDefinition/GoToDefinitionCommandHandlerTests.vb
|
Visual Basic
|
apache-2.0
| 5,440
|
' 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
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Public Class ParseXmlDocComments
Inherits BasicTestBase
<Fact()>
Public Sub ParseOneLineText()
ParseAndVerify(<![CDATA[
''' hello doc comments!
Module m1
End Module
]]>)
End Sub
<Fact>
Public Sub ParseImmediateXmlDocText()
ParseAndVerify(<![CDATA['''hello doc comments!
Module m1
End Module
]]>)
End Sub
<Fact>
Public Sub ParseImmediateXmlDocElement()
ParseAndVerify(<![CDATA['''<qqq> blah </qqq>
Module m1
End Module
]]>)
End Sub
<Fact>
Public Sub ParseImmediateXmlDocComment()
ParseAndVerify(<![CDATA['''<!-- qqqqq -->
Module m1
End Module
]]>)
End Sub
<Fact>
Public Sub ParseMultilineXmlDocElement()
ParseAndVerify(<![CDATA[
'''
'''<qqq>
'''<aaa>blah
'''</aaa>
'''</qqq>
Module m1
End Module
]]>)
End Sub
<Fact>
Public Sub ParseMultiLineText()
Dim multiline = ParseAndVerify(<![CDATA[
''' hello doc comments!
''' hello doc comments!
Module m1
End Module
]]>).GetRoot()
Dim comments = multiline.GetFirstToken.LeadingTrivia
Assert.Equal(4, comments.Count)
Dim struct = DirectCast(comments(2).GetStructure, DocumentationCommentTriviaSyntax)
Assert.DoesNotContain(vbCr, struct.GetInteriorXml())
Assert.DoesNotContain(vbLf, struct.GetInteriorXml())
Assert.Equal(" hello doc comments! hello doc comments!", struct.GetInteriorXml)
End Sub
<Fact>
Public Sub ParseOneLineTextAndMarkup()
Dim node = ParseAndVerify(<![CDATA[
''' hello doc comments! <!-- qqqqq --> <qqq> blah </qqq>
Module m1
End Module
]]>)
Dim tk = node.GetRoot().FindToken(25)
Dim docComment = DirectCast(tk.LeadingTrivia(2).GetStructure, DocumentationCommentTriviaSyntax)
Dim txt = docComment.GetInteriorXml
Assert.Equal(" hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> ", txt)
End Sub
<Fact()>
Public Sub ParseTwoLineTextAndMarkup()
Dim node = ParseAndVerify(<![CDATA[
''' hello doc comments! <!-- qqqqq --> <qqq> blah </qqq>
''' hello doc comments! <!-- qqqqq --> <qqq> blah </qqq>
Module m1
End Module
]]>)
Dim tk = node.GetRoot().FindToken(25)
Dim docComment = DirectCast(tk.LeadingTrivia(2).GetStructure, DocumentationCommentTriviaSyntax)
Dim docComment1 = DirectCast(tk.LeadingTrivia(2).GetStructure, DocumentationCommentTriviaSyntax)
Assert.Same(docComment, docComment1)
Dim txt = docComment.GetInteriorXml
Assert.Equal(" hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> " &
" hello doc comments! <!-- qqqqq --> <qqq> blah </qqq>", txt)
End Sub
<Fact>
Public Sub XmlDocCommentsSpanLines()
ParseAndVerify(<![CDATA[
''' hello doc comments! <!-- qqqqq
'''--> <qqq> blah </qqq>
''' hello doc comments! <!--
''' qqqqq --> <qqq> blah </qqq>
Module m1
End Module
]]>)
End Sub
<Fact>
Public Sub XmlDocCommentsAttrSpanLines()
ParseAndVerify(<![CDATA[
''' <qqq a
'''=
'''
'''"
'''h
''' <
''' "
'''> blah </qqq>
Module m1
End Module
]]>)
End Sub
<WorkItem(893656, "DevDiv/Personal")>
<WorkItem(923711, "DevDiv/Personal")>
<Fact>
Public Sub TickTickTickKind()
ParseAndVerify(
" '''<qqq> blah </qqq>" & vbCrLf &
"Module m1" & vbCrLf &
"End Module"
).
FindNodeOrTokenByKind(SyntaxKind.XmlElementStartTag).VerifyPrecedingCommentIsTrivia()
End Sub
<Fact>
Public Sub TickTickTickString()
ParseAndVerify(
"'''<qqq aa=""qq" & vbCrLf &
"'''qqqqqqqqqqqqqqqqqq""> </qqq>" & vbCrLf &
"Module m1" & vbCrLf &
"End Module"
).
FindNodeOrTokenByKind(SyntaxKind.XmlTextLiteralToken, 2).VerifyPrecedingCommentIsTrivia()
End Sub
<Fact>
Public Sub TickTickTickSpaceString()
ParseAndVerify(
"'''<qqq aa=""qq" & vbCrLf &
" '''qqqqqqqqqqqqqqqqqq""> </qqq>" & vbCrLf &
"Module m1" & vbCrLf &
"End Module"
).
FindNodeOrTokenByKind(SyntaxKind.XmlTextLiteralToken, 2).VerifyPrecedingCommentIsTrivia()
End Sub
<Fact>
Public Sub TickTickTickMarkup()
ParseAndVerify(
"'''<qqq " & vbCrLf &
"'''aaaaaaaaaaaaaaa=""qq""> " & vbCrLf &
"'''</qqq>" & vbCrLf &
"Module m1" & vbCrLf &
"End Module"
).
FindNodeOrTokenByKind(SyntaxKind.XmlNameToken, 2).VerifyPrecedingCommentIsTrivia()
End Sub
<Fact>
Public Sub TickTickTickSpaceMarkup()
ParseAndVerify(
"'''<qqq " & vbCrLf &
" '''aaaaaaaaaaaaaaa=""qq""> " & vbCrLf &
"'''</qqq>" & vbCrLf &
"Module m1" & vbCrLf &
"End Module"
).
FindNodeOrTokenByKind(SyntaxKind.XmlNameToken, 2).VerifyPrecedingCommentIsTrivia()
End Sub
<WorkItem(900384, "DevDiv/Personal")>
<Fact>
Public Sub InvalidCastExceptionWithEvent()
ParseAndVerify(<![CDATA[Class Foo
''' <summary>
''' Foo
''' </summary>
Custom Event eventName As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs)
End RaiseEvent
End Event
End Class
]]>)
End Sub
<WorkItem(904414, "DevDiv/Personal")>
<Fact>
Public Sub ParseMalformedDocComments()
ParseAndVerify(<![CDATA[
Module M1
'''<doc>
''' <></>
''' </>
'''</doc>
'''</root>
Sub Main()
End Sub
End Module
Module M2
'''</root>
'''<!--* Missing start tag and no content -->
Sub Foo()
End Sub
End Module
]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose),
<errors>
<error id="42304" warning="True"/>
<error id="42304" warning="True"/>
<error id="42304" warning="True"/>
<error id="42304" warning="True"/>
</errors>)
End Sub
<WorkItem(904903, "DevDiv/Personal")>
<Fact>
Public Sub ParseShortEndTag()
ParseAndVerify(<![CDATA[
'''<qqq>
'''<a><b></></>
'''</>
Module m1
End Module
]]>)
End Sub
<WorkItem(927580, "DevDiv/Personal")>
<WorkItem(927696, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlDocBadNamespacePrefix()
ParseAndVerify(<![CDATA[Module M1
'''<doc xmlns:a:b="abc"/>
Sub Main()
End Sub
End Module]]>)
ParseAndVerify(<![CDATA[Module M1
'''<doc xmlns:a:b="abc"/>
Sub Main()
End Sub
End Module]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose),
<errors>
<error id="42304" warning="True"/>
<error id="42304" warning="True"/>
</errors>)
End Sub
<WorkItem(927781, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlDocCommentMalformedEndTag()
ParseAndVerify(<![CDATA[Module M1
'''<test>
'''</test
Sub Main()
End Sub
'''<doc></doc/>
Sub Foo()
End Sub
End Module
]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose),
<errors>
<error id="42304" warning="True"/>
<error id="42304" warning="True"/>
</errors>)
End Sub
<WorkItem(927785, "DevDiv/Personal")>
<Fact>
Public Sub ParseXmlDocCommentMalformedPI()
ParseAndVerify(<![CDATA[Module M1
'''<doc><? ?></doc>
Sub Main()
End Sub
End Module
'''<?pi
Sub Foo()
End Sub
End Module
]]>,
<errors>
<error id="30622"/>
</errors>)
ParseAndVerify(<![CDATA[Module M1
'''<doc><? ?></doc>
Sub Main()
End Sub
End Module
'''<?pi
Sub Foo()
End Sub
End Module
]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose),
<errors>
<error id="42304" warning="True"/>
<error id="42304" warning="True"/>
<error id="30622"/>
</errors>)
End Sub
<WorkItem(929146, "DevDiv/Personal")>
<WorkItem(929147, "DevDiv/Personal")>
<WorkItem(929684, "DevDiv/Personal")>
<Fact>
Public Sub ParseDTDInXmlDoc()
ParseAndVerify(<![CDATA[Module Module1
'''<!DOCTYPE Foo []>
'''<summary>
'''</summary>
Sub Main()
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[Module Module1
'''<!DOCTYPE Foo []>
'''<summary>
'''</summary>
Sub Main()
End Sub
End Module
]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose),
<errors>
<error id="42304" warning="True"/>
</errors>)
End Sub
<WorkItem(930282, "DevDiv/Personal")>
<Fact>
Public Sub ParseIncorrectCharactersInDocComment()
'!!!!!!!!!!!!!! BELOW TEXT CONTAINS INVISIBLE UNICODE CHARACTERS !!!!!!!!!!!!!!
ParseAndVerify("'''<doc/>" & vbCrLf &
"'''<doc/>" & vbCrLf &
"'''<doc/>" & vbCrLf &
"'''<doc/>")
ParseAndVerify("'''<doc/>" & vbCrLf &
"'''<doc/>" & vbCrLf &
"'''<doc/>" & vbCrLf &
"'''<doc/>", VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose),
<errors>
<error id="42304" warning="True"/>
<error id="42304" warning="True"/>
<error id="42304" warning="True"/>
<error id="42304" warning="True"/>
<error id="42304" warning="True"/>
<error id="42304" warning="True"/>
<error id="42304" warning="True"/>
<error id="42304" warning="True"/>
</errors>)
End Sub
<WorkItem(530663, "DevDiv")>
<Fact()>
Public Sub Bug16663()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Module M
Sub M()
GoTo 1
''' <
1:
End Sub
End Module
]]></file>
</compilation>)
compilation.AssertNoErrors()
compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Module M
Sub M()
GoTo 1
''' </>
1:
End Sub
End Module
]]></file>
</compilation>)
compilation.AssertNoErrors()
compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Module M
Sub M()
GoTo 1
''' <?p
1:
End Sub
End Module
]]></file>
</compilation>)
compilation.AssertNoErrors()
End Sub
<WorkItem(530663, "DevDiv")>
<Fact()>
Public Sub ParseXmlNameWithLeadingSpaces()
ParseAndVerify(<![CDATA[
''' < summary/>
Module M
End Module
]]>)
ParseAndVerify(<![CDATA[
''' < summary/>
Module M
End Module
]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose),
<errors>
<error id="42304" warning="True"/>
</errors>)
ParseAndVerify(<![CDATA[
''' <
''' summary/>
Module M
End Module
]]>)
ParseAndVerify(<![CDATA[
''' <
''' summary/>
Module M
End Module
]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose),
<errors>
<error id="42304" warning="True"/>
<error id="42304" warning="True"/>
<error id="42304" warning="True"/>
</errors>)
End Sub
<WorkItem(530663, "DevDiv")>
<WorkItem(547297, "DevDiv")>
<Fact(Skip:="547297")>
Public Sub ParseOpenBracket()
ParseAndVerify(<![CDATA[
''' <
Module M
End Module
]]>,
<errors>
<error id="42304" warning="True"/>
</errors>)
End Sub
<WorkItem(697115, "DevDiv")>
<Fact()>
Public Sub Bug697115()
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= Function()
''' <summary/>
Sub M()
End Sub
End Module
]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.None),
<errors>
<error id="30625"/>
<error id="31151"/>
<error id="36674"/>
<error id="31159"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <x><%= Function()
''' <summary/>
Sub M()
End Sub
End Module
]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Parse),
<errors>
<error id="30625"/>
<error id="31151"/>
<error id="36674"/>
<error id="31159"/>
<error id="31165"/>
<error id="30636"/>
</errors>)
End Sub
<WorkItem(697269, "DevDiv")>
<Fact()>
Public Sub Bug697269()
ParseAndVerify(<![CDATA[
'''<?a
Module M
End Module
]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose),
<errors>
<error id="42304"/>
</errors>)
ParseAndVerify(<![CDATA[
'''<?a
'''b c<x/>
Module M
End Module
]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose),
<errors>
<error id="42304"/>
</errors>)
ParseAndVerify(<![CDATA[
'''<x><?
Module M
End Module
]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose),
<errors>
<error id="42304"/>
<error id="42304"/>
<error id="42304"/>
<error id="42304"/>
<error id="42304"/>
</errors>)
End Sub
End Class
|
mono/roslyn
|
src/Compilers/VisualBasic/Test/Syntax/Parser/XmlDocComments.vb
|
Visual Basic
|
apache-2.0
| 14,823
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Binder used to bind statements inside With blocks.
''' </summary>
Friend NotInheritable Class WithBlockBinder
Inherits BlockBaseBinder
''' <summary> Reference to a With statement syntax this binder is created for </summary>
Private ReadOnly _withBlockSyntax As WithBlockSyntax
''' <summary> Reference to an expression from With statement </summary>
Private ReadOnly Property Expression As ExpressionSyntax
Get
Return Me._withBlockSyntax.WithStatement.Expression
End Get
End Property
''' <summary>
''' Holds information needed by With block to properly bind
''' references to With block expression placeholder
''' </summary>
Private _withBlockInfo As WithBlockInfo = Nothing
Friend ReadOnly Property Info As WithBlockInfo
Get
Return _withBlockInfo
End Get
End Property
''' <summary>
''' True if there were references to the With statement expression
''' placeholder which prevent ByRef local from being used
''' </summary>
Friend ReadOnly Property ExpressionIsAccessedFromNestedLambda As Boolean
Get
Debug.Assert(Me._withBlockInfo IsNot Nothing)
Return Me._withBlockInfo.ExpressionIsAccessedFromNestedLambda
End Get
End Property
''' <summary>
''' With statement expression placeholder is a bound node being used in initial binding
''' to represent with statement expression. In lowering it is to be replaced with
''' the lowered expression which will actually be emitted.
''' </summary>
Friend ReadOnly Property ExpressionPlaceholder As BoundValuePlaceholderBase
Get
Debug.Assert(Me._withBlockInfo IsNot Nothing)
Return Me._withBlockInfo.ExpressionPlaceholder
End Get
End Property
''' <summary>
''' A draft version of initializers which will be used in this With statement.
''' Initializers are expressions which are used to capture expression in the current
''' With statement; they can be empty in some cases like if the expression is a local
''' variable of value type.
'''
''' Note, the initializers returned by this property are 'draft' because they are
''' generated based on initial bound tree, the real initializers will be generated
''' in lowering based on lowered expression form.
''' </summary>
Friend ReadOnly Property DraftInitializers As ImmutableArray(Of BoundExpression)
Get
Debug.Assert(Me._withBlockInfo IsNot Nothing)
Return Me._withBlockInfo.DraftInitializers
End Get
End Property
''' <summary>
''' A draft version of placeholder substitute which will be used in this With statement.
'''
''' Note, the placeholder substitute returned by this property is 'draft' because it is
''' generated based on initial bound tree, the real substitute will be generated in lowering
''' based on lowered expression form.
''' </summary>
Friend ReadOnly Property DraftPlaceholderSubstitute As BoundExpression
Get
Debug.Assert(Me._withBlockInfo IsNot Nothing)
Return Me._withBlockInfo.DraftSubstitute
End Get
End Property
''' <summary> Holds information needed by With block to properly bind
''' references to With block expression, placeholder, etc... </summary>
Friend Class WithBlockInfo
Public Sub New(originalExpression As BoundExpression,
expressionPlaceholder As BoundValuePlaceholderBase,
draftSubstitute As BoundExpression,
draftInitializers As ImmutableArray(Of BoundExpression),
diagnostics As BindingDiagnosticBag)
Debug.Assert(originalExpression IsNot Nothing)
Debug.Assert(expressionPlaceholder IsNot Nothing AndAlso (expressionPlaceholder.Kind = BoundKind.WithLValueExpressionPlaceholder OrElse expressionPlaceholder.Kind = BoundKind.WithRValueExpressionPlaceholder))
Debug.Assert(draftSubstitute IsNot Nothing)
Debug.Assert(Not draftInitializers.IsDefault)
Debug.Assert(diagnostics IsNot Nothing)
Me.OriginalExpression = originalExpression
Me.ExpressionPlaceholder = expressionPlaceholder
Me.DraftSubstitute = draftSubstitute
Me.DraftInitializers = draftInitializers
Me.Diagnostics = diagnostics
End Sub
''' <summary> Original bound expression from With statement </summary>
Public ReadOnly OriginalExpression As BoundExpression
''' <summary> Bound placeholder expression if used, otherwise Nothing </summary>
Public ReadOnly ExpressionPlaceholder As BoundValuePlaceholderBase
''' <summary> Diagnostics produced while binding the expression </summary>
Public ReadOnly Diagnostics As BindingDiagnosticBag
''' <summary>
''' Draft initializers for With statement, is based on initial binding tree
''' and is only to be used for warnings generation as well as for flow analysis
''' and semantic API; real initializers will be re-calculated in lowering
''' </summary>
Public ReadOnly DraftInitializers As ImmutableArray(Of BoundExpression)
''' <summary>
''' Draft substitute for With expression placeholder, is based on initial
''' binding tree and is only to be used for warnings generation as well as
''' for flow analysis and semantic API; real substitute will be re-calculated
''' in lowering
''' </summary>
Public ReadOnly DraftSubstitute As BoundExpression
Public ReadOnly Property ExpressionIsAccessedFromNestedLambda As Boolean
Get
Return Me._exprAccessedFromNestedLambda = ThreeState.True
End Get
End Property
Public Sub RegisterAccessFromNestedLambda()
If Me._exprAccessedFromNestedLambda <> ThreeState.True Then
Dim oldValue = Interlocked.CompareExchange(Me._exprAccessedFromNestedLambda, ThreeState.True, ThreeState.Unknown)
Debug.Assert(oldValue = ThreeState.Unknown OrElse oldValue = ThreeState.True)
End If
End Sub
Private _exprAccessedFromNestedLambda As Integer = ThreeState.Unknown
''' <summary>
''' If With statement expression is being used from nested lambda there are some restrictions
''' to the usage of Me reference in this expression. As these restrictions are only to be checked
''' in few scenarios, this flag is being calculated lazily.
''' </summary>
Public Function ExpressionHasByRefMeReference(recursionDepth As Integer) As Boolean
If Me._exprHasByRefMeReference = ThreeState.Unknown Then
' Analyze the expression which will be used instead of placeholder
Dim value As Boolean = ValueTypedMeReferenceFinder.HasByRefMeReference(Me.DraftSubstitute, recursionDepth)
Dim newValue As Integer = If(value, ThreeState.True, ThreeState.False)
Dim oldValue = Interlocked.CompareExchange(Me._exprHasByRefMeReference, newValue, ThreeState.Unknown)
Debug.Assert(newValue = oldValue OrElse oldValue = ThreeState.Unknown)
End If
Debug.Assert(Me._exprHasByRefMeReference <> ThreeState.Unknown)
Return Me._exprHasByRefMeReference = ThreeState.True
End Function
Private _exprHasByRefMeReference As Integer = ThreeState.Unknown
End Class
''' <summary> Create a new instance of With statement binder for a statement syntax provided </summary>
Public Sub New(enclosing As Binder, syntax As WithBlockSyntax)
MyBase.New(enclosing)
Debug.Assert(syntax IsNot Nothing)
Debug.Assert(syntax.WithStatement IsNot Nothing)
Debug.Assert(syntax.WithStatement.Expression IsNot Nothing)
Me._withBlockSyntax = syntax
End Sub
#Region "Implementation"
Friend Overrides Function GetWithStatementPlaceholderSubstitute(placeholder As BoundValuePlaceholderBase) As BoundExpression
Me.EnsureExpressionAndPlaceholder()
If placeholder Is Me.ExpressionPlaceholder Then
Return Me.DraftPlaceholderSubstitute
End If
Return MyBase.GetWithStatementPlaceholderSubstitute(placeholder)
End Function
Private Sub EnsureExpressionAndPlaceholder()
If Me._withBlockInfo Is Nothing Then
' Because we cannot guarantee that diagnostics will be freed we
' don't allocate this diagnostics bag from a pool
Dim diagnostics As New BindingDiagnosticBag()
' Bind the expression as a value
Dim boundExpression As BoundExpression = Me.ContainingBinder.BindValue(Me.Expression, diagnostics)
' NOTE: If the expression is not an l-value we should make an r-value of it
If Not boundExpression.IsLValue Then
boundExpression = Me.MakeRValue(boundExpression, diagnostics)
End If
' Prepare draft substitute/initializers for expression placeholder;
' note that those substitute/initializers will be based on initial bound
' form of the original expression captured without using ByRef locals
Dim result As WithExpressionRewriter.Result =
(New WithExpressionRewriter(Me._withBlockSyntax.WithStatement)).AnalyzeWithExpression(Me.ContainingMember, boundExpression,
doNotUseByRefLocal:=True,
binder:=Me.ContainingBinder,
preserveIdentityOfLValues:=True)
' Create a placeholder if needed
Dim placeholder As BoundValuePlaceholderBase = Nothing
If boundExpression.IsLValue OrElse boundExpression.IsMeReference Then
placeholder = New BoundWithLValueExpressionPlaceholder(Me.Expression, boundExpression.Type)
Else
placeholder = New BoundWithRValueExpressionPlaceholder(Me.Expression, boundExpression.Type)
End If
placeholder.SetWasCompilerGenerated()
' It is assumed that the binding result in case of race should still be the same in all racing threads,
' so if the following call fails we can just drop the bound node and diagnostics on the floor
Interlocked.CompareExchange(Me._withBlockInfo,
New WithBlockInfo(boundExpression, placeholder,
result.Expression, result.Initializers, diagnostics),
Nothing)
End If
Debug.Assert(Me._withBlockInfo IsNot Nothing)
End Sub
''' <summary>
''' A bound tree walker which search for a bound Me and MyClass references of value type.
''' Is being only used for calculating the value of 'ExpressionHasByRefMeReference'
''' </summary>
Private Class ValueTypedMeReferenceFinder
Inherits BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
Private Sub New(recursionDepth As Integer)
MyBase.New(recursionDepth)
End Sub
Private _found As Boolean = False
Public Shared Function HasByRefMeReference(expression As BoundExpression, recursionDepth As Integer) As Boolean
Dim walker As New ValueTypedMeReferenceFinder(recursionDepth)
walker.Visit(expression)
Return walker._found
End Function
Public Overrides Function Visit(node As BoundNode) As BoundNode
If Not _found Then
Return MyBase.Visit(node)
End If
Return Nothing
End Function
Public Overrides Function VisitMeReference(node As BoundMeReference) As BoundNode
Dim type As TypeSymbol = node.Type
Debug.Assert(Not type.IsTypeParameter)
Debug.Assert(type.IsValueType)
Me._found = True
Return Nothing
End Function
Public Overrides Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode
Dim type As TypeSymbol = node.Type
Debug.Assert(Not type.IsTypeParameter)
Debug.Assert(type.IsValueType)
Me._found = True
Return Nothing
End Function
End Class
#End Region
#Region "With block binding"
Protected Overrides Function CreateBoundWithBlock(node As WithBlockSyntax, boundBlockBinder As Binder, diagnostics As BindingDiagnosticBag) As BoundStatement
Debug.Assert(node Is Me._withBlockSyntax)
' Bind With statement expression
Me.EnsureExpressionAndPlaceholder()
' We need to take care of possible diagnostics that might be produced
' by EnsureExpressionAndPlaceholder call, note that this call might have
' been before in which case the diagnostics were stored in '_withBlockInfo'
' See also comment in PrepareBindingOfOmittedLeft(...)
diagnostics.AddRange(Me._withBlockInfo.Diagnostics, allowMismatchInDependencyAccumulation:=True)
Return New BoundWithStatement(node,
Me._withBlockInfo.OriginalExpression,
boundBlockBinder.BindBlock(node, node.Statements, diagnostics).MakeCompilerGenerated(),
Me)
End Function
#End Region
#Region "Other Overrides"
''' <summary> Asserts that the node is NOT from With statement expression </summary>
<Conditional("DEBUG")>
Private Sub AssertExpressionIsNotFromStatementExpression(node As SyntaxNode)
While node IsNot Nothing
Debug.Assert(node IsNot Me.Expression)
node = node.Parent
End While
End Sub
#If DEBUG Then
Public Overrides Function BindStatement(node As StatementSyntax, diagnostics As BindingDiagnosticBag) As BoundStatement
AssertExpressionIsNotFromStatementExpression(node)
Return MyBase.BindStatement(node, diagnostics)
End Function
Public Overrides Function GetBinder(node As SyntaxNode) As Binder
AssertExpressionIsNotFromStatementExpression(node)
Return MyBase.GetBinder(node)
End Function
#End If
Private Sub PrepareBindingOfOmittedLeft(node As VisualBasicSyntaxNode, diagnostics As BindingDiagnosticBag, accessingBinder As Binder)
AssertExpressionIsNotFromStatementExpression(node)
Debug.Assert((node.Kind = SyntaxKind.SimpleMemberAccessExpression) OrElse
(node.Kind = SyntaxKind.DictionaryAccessExpression) OrElse
(node.Kind = SyntaxKind.XmlAttributeAccessExpression) OrElse
(node.Kind = SyntaxKind.XmlElementAccessExpression) OrElse
(node.Kind = SyntaxKind.XmlDescendantAccessExpression) OrElse
(node.Kind = SyntaxKind.ConditionalAccessExpression))
Me.EnsureExpressionAndPlaceholder()
' NOTE: In case the call above produced diagnostics they were stored in
' '_withBlockInfo' and will be reported in later call to CreateBoundWithBlock(...)
Dim info As WithBlockInfo = Me._withBlockInfo
If Me.ContainingMember IsNot accessingBinder.ContainingMember Then
' The expression placeholder from With statement may be captured
info.RegisterAccessFromNestedLambda()
End If
End Sub
Protected Friend Overrides Function TryBindOmittedLeftForMemberAccess(node As MemberAccessExpressionSyntax,
diagnostics As BindingDiagnosticBag,
accessingBinder As Binder,
<Out> ByRef wholeMemberAccessExpressionBound As Boolean) As BoundExpression
PrepareBindingOfOmittedLeft(node, diagnostics, accessingBinder)
wholeMemberAccessExpressionBound = False
Return Me._withBlockInfo.ExpressionPlaceholder
End Function
Protected Overrides Function TryBindOmittedLeftForDictionaryAccess(node As MemberAccessExpressionSyntax,
accessingBinder As Binder,
diagnostics As BindingDiagnosticBag) As BoundExpression
PrepareBindingOfOmittedLeft(node, diagnostics, accessingBinder)
Return Me._withBlockInfo.ExpressionPlaceholder
End Function
Protected Overrides Function TryBindOmittedLeftForConditionalAccess(node As ConditionalAccessExpressionSyntax, accessingBinder As Binder, diagnostics As BindingDiagnosticBag) As BoundExpression
PrepareBindingOfOmittedLeft(node, diagnostics, accessingBinder)
Return Me._withBlockInfo.ExpressionPlaceholder
End Function
Protected Friend Overrides Function TryBindOmittedLeftForXmlMemberAccess(node As XmlMemberAccessExpressionSyntax,
diagnostics As BindingDiagnosticBag,
accessingBinder As Binder) As BoundExpression
PrepareBindingOfOmittedLeft(node, diagnostics, accessingBinder)
Return Me._withBlockInfo.ExpressionPlaceholder
End Function
Friend Overrides ReadOnly Property Locals As ImmutableArray(Of LocalSymbol)
Get
Return ImmutableArray(Of LocalSymbol).Empty
End Get
End Property
#End Region
End Class
End Namespace
|
CyrusNajmabadi/roslyn
|
src/Compilers/VisualBasic/Portable/Binding/Binder_WithBlock.vb
|
Visual Basic
|
mit
| 19,728
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Composition
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Navigation
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.GoToDefinition
<ExportWorkspaceServiceFactory(GetType(IDocumentNavigationService), ServiceLayer.Editor), [Shared]>
Friend Class MockDocumentNavigationServiceFactory
Implements IWorkspaceServiceFactory
Public Function CreateService(workspaceServices As HostWorkspaceServices) As IWorkspaceService Implements IWorkspaceServiceFactory.CreateService
Return New MockDocumentNavigationService()
End Function
End Class
End Namespace
|
droyad/roslyn
|
src/EditorFeatures/Test2/GoToDefinition/MockDocumentNavigationServiceFactory.vb
|
Visual Basic
|
apache-2.0
| 832
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> Partial Class frmSerialNumber
#Region "Windows Form Designer generated code "
<System.Diagnostics.DebuggerNonUserCode()> Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
End Sub
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> Protected Overloads Overrides Sub Dispose(ByVal Disposing As Boolean)
If Disposing Then
If Not components Is Nothing Then
components.Dispose()
End If
End If
MyBase.Dispose(Disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
Public ToolTip1 As System.Windows.Forms.ToolTip
Public WithEvents txtRtd As System.Windows.Forms.TextBox
Public WithEvents txtItem As System.Windows.Forms.TextBox
Public WithEvents txtCode As System.Windows.Forms.TextBox
Public WithEvents txtQty As System.Windows.Forms.TextBox
Public WithEvents cmdUpdate As System.Windows.Forms.Button
Public WithEvents cmdRemove As System.Windows.Forms.Button
Public WithEvents lstSerial As System.Windows.Forms.CheckedListBox
Public WithEvents cmdAdd As System.Windows.Forms.Button
Public WithEvents txtSerialNbr As System.Windows.Forms.TextBox
Public WithEvents Label8 As System.Windows.Forms.Label
Public WithEvents Label7 As System.Windows.Forms.Label
Public WithEvents Label6 As System.Windows.Forms.Label
Public WithEvents Label5 As System.Windows.Forms.Label
Public WithEvents Label4 As System.Windows.Forms.Label
Public WithEvents Label3 As System.Windows.Forms.Label
Public WithEvents Line1 As Microsoft.VisualBasic.PowerPacks.LineShape
Public WithEvents Label2 As System.Windows.Forms.Label
Public WithEvents Label1 As System.Windows.Forms.Label
Public WithEvents Frame1 As System.Windows.Forms.GroupBox
Public WithEvents Command1 As System.Windows.Forms.Button
Public WithEvents cmdBack As System.Windows.Forms.Button
Public WithEvents cmdClose As System.Windows.Forms.Button
Public WithEvents picButtons As System.Windows.Forms.Panel
Public WithEvents ShapeContainer1 As Microsoft.VisualBasic.PowerPacks.ShapeContainer
'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.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(frmSerialNumber))
Me.components = New System.ComponentModel.Container()
Me.ToolTip1 = New System.Windows.Forms.ToolTip(components)
Me.ShapeContainer1 = New Microsoft.VisualBasic.PowerPacks.ShapeContainer
Me.Frame1 = New System.Windows.Forms.GroupBox
Me.txtRtd = New System.Windows.Forms.TextBox
Me.txtItem = New System.Windows.Forms.TextBox
Me.txtCode = New System.Windows.Forms.TextBox
Me.txtQty = New System.Windows.Forms.TextBox
Me.cmdUpdate = New System.Windows.Forms.Button
Me.cmdRemove = New System.Windows.Forms.Button
Me.lstSerial = New System.Windows.Forms.CheckedListBox
Me.cmdAdd = New System.Windows.Forms.Button
Me.txtSerialNbr = New System.Windows.Forms.TextBox
Me.Label8 = New System.Windows.Forms.Label
Me.Label7 = New System.Windows.Forms.Label
Me.Label6 = New System.Windows.Forms.Label
Me.Label5 = New System.Windows.Forms.Label
Me.Label4 = New System.Windows.Forms.Label
Me.Label3 = New System.Windows.Forms.Label
Me.Line1 = New Microsoft.VisualBasic.PowerPacks.LineShape
Me.Label2 = New System.Windows.Forms.Label
Me.Label1 = New System.Windows.Forms.Label
Me.picButtons = New System.Windows.Forms.Panel
Me.Command1 = New System.Windows.Forms.Button
Me.cmdBack = New System.Windows.Forms.Button
Me.cmdClose = New System.Windows.Forms.Button
Me.Frame1.SuspendLayout()
Me.picButtons.SuspendLayout()
Me.SuspendLayout()
Me.ToolTip1.Active = True
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
Me.Text = "Serial Number Entry"
Me.ClientSize = New System.Drawing.Size(322, 457)
Me.Location = New System.Drawing.Point(3, 22)
Me.ControlBox = False
Me.MaximizeBox = False
Me.MinimizeBox = False
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.BackColor = System.Drawing.SystemColors.Control
Me.Enabled = True
Me.KeyPreview = False
Me.Cursor = System.Windows.Forms.Cursors.Default
Me.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.ShowInTaskbar = True
Me.HelpButton = False
Me.WindowState = System.Windows.Forms.FormWindowState.Normal
Me.Name = "frmSerialNumber"
Me.Frame1.Size = New System.Drawing.Size(313, 415)
Me.Frame1.Location = New System.Drawing.Point(4, 40)
Me.Frame1.TabIndex = 2
Me.Frame1.BackColor = System.Drawing.SystemColors.Control
Me.Frame1.Enabled = True
Me.Frame1.ForeColor = System.Drawing.SystemColors.ControlText
Me.Frame1.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Frame1.Visible = True
Me.Frame1.Padding = New System.Windows.Forms.Padding(0)
Me.Frame1.Name = "Frame1"
Me.txtRtd.AutoSize = False
Me.txtRtd.TextAlign = System.Windows.Forms.HorizontalAlignment.Right
Me.txtRtd.Enabled = False
Me.txtRtd.Size = New System.Drawing.Size(39, 19)
Me.txtRtd.Location = New System.Drawing.Point(262, 76)
Me.txtRtd.TabIndex = 17
Me.txtRtd.AcceptsReturn = True
Me.txtRtd.BackColor = System.Drawing.SystemColors.Window
Me.txtRtd.CausesValidation = True
Me.txtRtd.ForeColor = System.Drawing.SystemColors.WindowText
Me.txtRtd.HideSelection = True
Me.txtRtd.ReadOnly = False
Me.txtRtd.Maxlength = 0
Me.txtRtd.Cursor = System.Windows.Forms.Cursors.IBeam
Me.txtRtd.MultiLine = False
Me.txtRtd.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.txtRtd.ScrollBars = System.Windows.Forms.ScrollBars.None
Me.txtRtd.TabStop = True
Me.txtRtd.Visible = True
Me.txtRtd.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me.txtRtd.Name = "txtRtd"
Me.txtItem.AutoSize = False
Me.txtItem.Size = New System.Drawing.Size(195, 19)
Me.txtItem.Location = New System.Drawing.Point(106, 16)
Me.txtItem.TabIndex = 15
Me.txtItem.AcceptsReturn = True
Me.txtItem.TextAlign = System.Windows.Forms.HorizontalAlignment.Left
Me.txtItem.BackColor = System.Drawing.SystemColors.Window
Me.txtItem.CausesValidation = True
Me.txtItem.Enabled = True
Me.txtItem.ForeColor = System.Drawing.SystemColors.WindowText
Me.txtItem.HideSelection = True
Me.txtItem.ReadOnly = False
Me.txtItem.Maxlength = 0
Me.txtItem.Cursor = System.Windows.Forms.Cursors.IBeam
Me.txtItem.MultiLine = False
Me.txtItem.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.txtItem.ScrollBars = System.Windows.Forms.ScrollBars.None
Me.txtItem.TabStop = True
Me.txtItem.Visible = True
Me.txtItem.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me.txtItem.Name = "txtItem"
Me.txtCode.AutoSize = False
Me.txtCode.TextAlign = System.Windows.Forms.HorizontalAlignment.Right
Me.txtCode.Enabled = False
Me.txtCode.Size = New System.Drawing.Size(39, 19)
Me.txtCode.Location = New System.Drawing.Point(106, 36)
Me.txtCode.TabIndex = 13
Me.txtCode.AcceptsReturn = True
Me.txtCode.BackColor = System.Drawing.SystemColors.Window
Me.txtCode.CausesValidation = True
Me.txtCode.ForeColor = System.Drawing.SystemColors.WindowText
Me.txtCode.HideSelection = True
Me.txtCode.ReadOnly = False
Me.txtCode.Maxlength = 0
Me.txtCode.Cursor = System.Windows.Forms.Cursors.IBeam
Me.txtCode.MultiLine = False
Me.txtCode.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.txtCode.ScrollBars = System.Windows.Forms.ScrollBars.None
Me.txtCode.TabStop = True
Me.txtCode.Visible = True
Me.txtCode.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me.txtCode.Name = "txtCode"
Me.txtQty.AutoSize = False
Me.txtQty.TextAlign = System.Windows.Forms.HorizontalAlignment.Right
Me.txtQty.Enabled = False
Me.txtQty.Size = New System.Drawing.Size(39, 19)
Me.txtQty.Location = New System.Drawing.Point(106, 76)
Me.txtQty.TabIndex = 10
Me.txtQty.AcceptsReturn = True
Me.txtQty.BackColor = System.Drawing.SystemColors.Window
Me.txtQty.CausesValidation = True
Me.txtQty.ForeColor = System.Drawing.SystemColors.WindowText
Me.txtQty.HideSelection = True
Me.txtQty.ReadOnly = False
Me.txtQty.Maxlength = 0
Me.txtQty.Cursor = System.Windows.Forms.Cursors.IBeam
Me.txtQty.MultiLine = False
Me.txtQty.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.txtQty.ScrollBars = System.Windows.Forms.ScrollBars.None
Me.txtQty.TabStop = True
Me.txtQty.Visible = True
Me.txtQty.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me.txtQty.Name = "txtQty"
Me.cmdUpdate.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me.cmdUpdate.Text = "Update"
Me.cmdUpdate.Size = New System.Drawing.Size(83, 21)
Me.cmdUpdate.Location = New System.Drawing.Point(226, 388)
Me.cmdUpdate.TabIndex = 9
Me.cmdUpdate.BackColor = System.Drawing.SystemColors.Control
Me.cmdUpdate.CausesValidation = True
Me.cmdUpdate.Enabled = True
Me.cmdUpdate.ForeColor = System.Drawing.SystemColors.ControlText
Me.cmdUpdate.Cursor = System.Windows.Forms.Cursors.Default
Me.cmdUpdate.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.cmdUpdate.TabStop = True
Me.cmdUpdate.Name = "cmdUpdate"
Me.cmdRemove.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me.cmdRemove.Text = "Remove"
Me.cmdRemove.Size = New System.Drawing.Size(83, 25)
Me.cmdRemove.Location = New System.Drawing.Point(226, 360)
Me.cmdRemove.TabIndex = 8
Me.cmdRemove.BackColor = System.Drawing.SystemColors.Control
Me.cmdRemove.CausesValidation = True
Me.cmdRemove.Enabled = True
Me.cmdRemove.ForeColor = System.Drawing.SystemColors.ControlText
Me.cmdRemove.Cursor = System.Windows.Forms.Cursors.Default
Me.cmdRemove.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.cmdRemove.TabStop = True
Me.cmdRemove.Name = "cmdRemove"
Me.lstSerial.Size = New System.Drawing.Size(159, 238)
Me.lstSerial.Location = New System.Drawing.Point(4, 170)
Me.lstSerial.TabIndex = 6
Me.lstSerial.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me.lstSerial.BackColor = System.Drawing.SystemColors.Window
Me.lstSerial.CausesValidation = True
Me.lstSerial.Enabled = True
Me.lstSerial.ForeColor = System.Drawing.SystemColors.WindowText
Me.lstSerial.IntegralHeight = True
Me.lstSerial.Cursor = System.Windows.Forms.Cursors.Default
Me.lstSerial.SelectionMode = System.Windows.Forms.SelectionMode.One
Me.lstSerial.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.lstSerial.Sorted = False
Me.lstSerial.TabStop = True
Me.lstSerial.Visible = True
Me.lstSerial.MultiColumn = False
Me.lstSerial.Name = "lstSerial"
Me.cmdAdd.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me.cmdAdd.Text = "Add"
Me.cmdAdd.Size = New System.Drawing.Size(83, 23)
Me.cmdAdd.Location = New System.Drawing.Point(220, 122)
Me.cmdAdd.TabIndex = 5
Me.cmdAdd.BackColor = System.Drawing.SystemColors.Control
Me.cmdAdd.CausesValidation = True
Me.cmdAdd.Enabled = True
Me.cmdAdd.ForeColor = System.Drawing.SystemColors.ControlText
Me.cmdAdd.Cursor = System.Windows.Forms.Cursors.Default
Me.cmdAdd.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.cmdAdd.TabStop = True
Me.cmdAdd.Name = "cmdAdd"
Me.txtSerialNbr.AutoSize = False
Me.txtSerialNbr.Size = New System.Drawing.Size(195, 19)
Me.txtSerialNbr.Location = New System.Drawing.Point(106, 98)
Me.txtSerialNbr.TabIndex = 4
Me.txtSerialNbr.AcceptsReturn = True
Me.txtSerialNbr.TextAlign = System.Windows.Forms.HorizontalAlignment.Left
Me.txtSerialNbr.BackColor = System.Drawing.SystemColors.Window
Me.txtSerialNbr.CausesValidation = True
Me.txtSerialNbr.Enabled = True
Me.txtSerialNbr.ForeColor = System.Drawing.SystemColors.WindowText
Me.txtSerialNbr.HideSelection = True
Me.txtSerialNbr.ReadOnly = False
Me.txtSerialNbr.Maxlength = 0
Me.txtSerialNbr.Cursor = System.Windows.Forms.Cursors.IBeam
Me.txtSerialNbr.MultiLine = False
Me.txtSerialNbr.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.txtSerialNbr.ScrollBars = System.Windows.Forms.ScrollBars.None
Me.txtSerialNbr.TabStop = True
Me.txtSerialNbr.Visible = True
Me.txtSerialNbr.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me.txtSerialNbr.Name = "txtSerialNbr"
Me.Label8.TextAlign = System.Drawing.ContentAlignment.TopCenter
Me.Label8.Text = "All Items that are being returned should be checked"
Me.Label8.Size = New System.Drawing.Size(141, 31)
Me.Label8.Location = New System.Drawing.Point(168, 170)
Me.Label8.TabIndex = 20
Me.Label8.BackColor = System.Drawing.SystemColors.Control
Me.Label8.Enabled = True
Me.Label8.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label8.Cursor = System.Windows.Forms.Cursors.Default
Me.Label8.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label8.UseMnemonic = True
Me.Label8.Visible = True
Me.Label8.AutoSize = False
Me.Label8.BorderStyle = System.Windows.Forms.BorderStyle.None
Me.Label8.Name = "Label8"
Me.Label7.Text = "Returned"
Me.Label7.Size = New System.Drawing.Size(59, 17)
Me.Label7.Location = New System.Drawing.Point(202, 78)
Me.Label7.TabIndex = 19
Me.Label7.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me.Label7.BackColor = System.Drawing.SystemColors.Control
Me.Label7.Enabled = True
Me.Label7.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label7.Cursor = System.Windows.Forms.Cursors.Default
Me.Label7.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label7.UseMnemonic = True
Me.Label7.Visible = True
Me.Label7.AutoSize = False
Me.Label7.BorderStyle = System.Windows.Forms.BorderStyle.None
Me.Label7.Name = "Label7"
Me.Label6.Text = "Recieved"
Me.Label6.Size = New System.Drawing.Size(59, 17)
Me.Label6.Location = New System.Drawing.Point(44, 78)
Me.Label6.TabIndex = 18
Me.Label6.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me.Label6.BackColor = System.Drawing.SystemColors.Control
Me.Label6.Enabled = True
Me.Label6.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label6.Cursor = System.Windows.Forms.Cursors.Default
Me.Label6.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label6.UseMnemonic = True
Me.Label6.Visible = True
Me.Label6.AutoSize = False
Me.Label6.BorderStyle = System.Windows.Forms.BorderStyle.None
Me.Label6.Name = "Label6"
Me.Label5.Text = "Item Name"
Me.Label5.Size = New System.Drawing.Size(83, 17)
Me.Label5.Location = New System.Drawing.Point(4, 18)
Me.Label5.TabIndex = 14
Me.Label5.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me.Label5.BackColor = System.Drawing.SystemColors.Control
Me.Label5.Enabled = True
Me.Label5.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label5.Cursor = System.Windows.Forms.Cursors.Default
Me.Label5.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label5.UseMnemonic = True
Me.Label5.Visible = True
Me.Label5.AutoSize = False
Me.Label5.BorderStyle = System.Windows.Forms.BorderStyle.None
Me.Label5.Name = "Label5"
Me.Label4.Text = "Item Code"
Me.Label4.Size = New System.Drawing.Size(93, 17)
Me.Label4.Location = New System.Drawing.Point(4, 38)
Me.Label4.TabIndex = 12
Me.Label4.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me.Label4.BackColor = System.Drawing.SystemColors.Control
Me.Label4.Enabled = True
Me.Label4.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label4.Cursor = System.Windows.Forms.Cursors.Default
Me.Label4.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label4.UseMnemonic = True
Me.Label4.Visible = True
Me.Label4.AutoSize = False
Me.Label4.BorderStyle = System.Windows.Forms.BorderStyle.None
Me.Label4.Name = "Label4"
Me.Label3.Text = "Quantity"
Me.Label3.Size = New System.Drawing.Size(71, 17)
Me.Label3.Location = New System.Drawing.Point(4, 58)
Me.Label3.TabIndex = 11
Me.Label3.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me.Label3.BackColor = System.Drawing.SystemColors.Control
Me.Label3.Enabled = True
Me.Label3.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label3.Cursor = System.Windows.Forms.Cursors.Default
Me.Label3.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label3.UseMnemonic = True
Me.Label3.Visible = True
Me.Label3.AutoSize = False
Me.Label3.BorderStyle = System.Windows.Forms.BorderStyle.None
Me.Label3.Name = "Label3"
Me.Line1.BorderWidth = 2
Me.Line1.X1 = 4
Me.Line1.X2 = 306
Me.Line1.Y1 = 137
Me.Line1.Y2 = 137
Me.Line1.BorderColor = System.Drawing.SystemColors.WindowText
Me.Line1.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid
Me.Line1.Visible = True
Me.Line1.Name = "Line1"
Me.Label2.Text = "List Of Serial Number"
Me.Label2.Size = New System.Drawing.Size(159, 17)
Me.Label2.Location = New System.Drawing.Point(4, 154)
Me.Label2.TabIndex = 7
Me.Label2.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me.Label2.BackColor = System.Drawing.SystemColors.Control
Me.Label2.Enabled = True
Me.Label2.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label2.Cursor = System.Windows.Forms.Cursors.Default
Me.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label2.UseMnemonic = True
Me.Label2.Visible = True
Me.Label2.AutoSize = False
Me.Label2.BorderStyle = System.Windows.Forms.BorderStyle.None
Me.Label2.Name = "Label2"
Me.Label1.Text = "Serial Number"
Me.Label1.Size = New System.Drawing.Size(91, 17)
Me.Label1.Location = New System.Drawing.Point(4, 100)
Me.Label1.TabIndex = 3
Me.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me.Label1.BackColor = System.Drawing.SystemColors.Control
Me.Label1.Enabled = True
Me.Label1.ForeColor = System.Drawing.SystemColors.ControlText
Me.Label1.Cursor = System.Windows.Forms.Cursors.Default
Me.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Label1.UseMnemonic = True
Me.Label1.Visible = True
Me.Label1.AutoSize = False
Me.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None
Me.Label1.Name = "Label1"
Me.picButtons.Dock = System.Windows.Forms.DockStyle.Top
Me.picButtons.BackColor = System.Drawing.Color.Blue
Me.picButtons.Size = New System.Drawing.Size(322, 38)
Me.picButtons.Location = New System.Drawing.Point(0, 0)
Me.picButtons.TabIndex = 0
Me.picButtons.TabStop = False
Me.picButtons.CausesValidation = True
Me.picButtons.Enabled = True
Me.picButtons.ForeColor = System.Drawing.SystemColors.ControlText
Me.picButtons.Cursor = System.Windows.Forms.Cursors.Default
Me.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.picButtons.Visible = True
Me.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me.picButtons.Name = "picButtons"
Me.Command1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me.Command1.Text = "IMPORT >> "
Me.Command1.Size = New System.Drawing.Size(91, 27)
Me.Command1.Location = New System.Drawing.Point(8, 4)
Me.Command1.TabIndex = 21
Me.Command1.BackColor = System.Drawing.SystemColors.Control
Me.Command1.CausesValidation = True
Me.Command1.Enabled = True
Me.Command1.ForeColor = System.Drawing.SystemColors.ControlText
Me.Command1.Cursor = System.Windows.Forms.Cursors.Default
Me.Command1.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.Command1.TabStop = True
Me.Command1.Name = "Command1"
Me.cmdBack.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me.cmdBack.Text = "<< BACK "
Me.cmdBack.Size = New System.Drawing.Size(91, 27)
Me.cmdBack.Location = New System.Drawing.Point(222, 4)
Me.cmdBack.TabIndex = 16
Me.cmdBack.BackColor = System.Drawing.SystemColors.Control
Me.cmdBack.CausesValidation = True
Me.cmdBack.Enabled = True
Me.cmdBack.ForeColor = System.Drawing.SystemColors.ControlText
Me.cmdBack.Cursor = System.Windows.Forms.Cursors.Default
Me.cmdBack.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.cmdBack.TabStop = True
Me.cmdBack.Name = "cmdBack"
Me.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me.cmdClose.Text = "E&xit"
Me.cmdClose.Size = New System.Drawing.Size(73, 29)
Me.cmdClose.Location = New System.Drawing.Point(576, 3)
Me.cmdClose.TabIndex = 1
Me.cmdClose.TabStop = False
Me.cmdClose.BackColor = System.Drawing.SystemColors.Control
Me.cmdClose.CausesValidation = True
Me.cmdClose.Enabled = True
Me.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText
Me.cmdClose.Cursor = System.Windows.Forms.Cursors.Default
Me.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.cmdClose.Name = "cmdClose"
Me.Controls.Add(Frame1)
Me.Controls.Add(picButtons)
Me.Frame1.Controls.Add(txtRtd)
Me.Frame1.Controls.Add(txtItem)
Me.Frame1.Controls.Add(txtCode)
Me.Frame1.Controls.Add(txtQty)
Me.Frame1.Controls.Add(cmdUpdate)
Me.Frame1.Controls.Add(cmdRemove)
Me.Frame1.Controls.Add(lstSerial)
Me.Frame1.Controls.Add(cmdAdd)
Me.Frame1.Controls.Add(txtSerialNbr)
Me.Frame1.Controls.Add(Label8)
Me.Frame1.Controls.Add(Label7)
Me.Frame1.Controls.Add(Label6)
Me.Frame1.Controls.Add(Label5)
Me.Frame1.Controls.Add(Label4)
Me.Frame1.Controls.Add(Label3)
Me.ShapeContainer1.Shapes.Add(Line1)
Me.Frame1.Controls.Add(Label2)
Me.Frame1.Controls.Add(Label1)
Me.Frame1.Controls.Add(ShapeContainer1)
Me.picButtons.Controls.Add(Command1)
Me.picButtons.Controls.Add(cmdBack)
Me.picButtons.Controls.Add(cmdClose)
Me.Frame1.ResumeLayout(False)
Me.picButtons.ResumeLayout(False)
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
#End Region
End Class
|
nodoid/PointOfSale
|
VB/4PosBackOffice.NET/frmSerialNumber.Designer.vb
|
Visual Basic
|
mit
| 22,314
|
'------------------------------------------------------------------------------
' <auto-generated>
' Dieser Code wurde von einem Tool generiert.
' Laufzeitversion:4.0.30319.42000
'
' Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
' der Code erneut generiert wird.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Imports System
Namespace My.Resources
'Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert
'-Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert.
'Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen
'mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu.
'''<summary>
''' Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Class SchemaFiles
Private Shared resourceMan As Global.System.Resources.ResourceManager
Private Shared resourceCulture As Global.System.Globalization.CultureInfo
<Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _
Friend Sub New()
MyBase.New
End Sub
'''<summary>
''' Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Shared 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("CustomXMLParts.SchemaFiles", GetType(SchemaFiles).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle
''' Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Shared Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set
resourceCulture = value
End Set
End Property
'''<summary>
''' Sucht eine lokalisierte Zeichenfolge, die <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
''' <xs:element name="root">
''' <xs:complexType>
''' <xs:sequence>
''' <xs:choice maxOccurs="unbounded" minOccurs="1">
''' <xs:element name="DBAction">
''' <xs:complexType>
''' <xs:sequence>
''' <xs:choice maxOccurs="unbounded" minOccurs="1">
''' <xs:element type="xs:byte" name="env" minOccurs="0"/>
''' <xs:element type="xs:string" name="database"/>
''' <xs:element ty [Rest der Zeichenfolge wurde abgeschnitten]"; ähnelt.
'''</summary>
Friend Shared ReadOnly Property DBModifDef() As String
Get
Return ResourceManager.GetString("DBModifDef", resourceCulture)
End Get
End Property
End Class
End Namespace
|
Excel-DNA/Samples
|
CustomXMLParts/SchemaFiles.Designer.vb
|
Visual Basic
|
mit
| 4,332
|
'Partial Public Class x8086
' Private Const Size As Integer = 6
' Private mBuffer(Size - 1) As Byte
' Private mAddress As Integer
' Public Sub Prefetch()
' mAddress = SegmentOffetToAbsolute(mRegisters.CS, mRegisters.IP)
' For i As Integer = 0 To Size - 1
' mBuffer(i) = Memory((mAddress + i) Mod MemSize)
' Next
' End Sub
' Public ReadOnly Property Buffer As Byte()
' Get
' Return mBuffer
' End Get
' End Property
' Public ReadOnly Property FromPreftch(testAddress As Integer) As Byte
' Get
' testAddress = testAddress And &HFFFFF ' "Call 5" Legacy Interface: http://www.os2museum.com/wp/?p=734
' If testAddress >= mAddress AndAlso testAddress < mAddress + Size - 1 Then
' Return mBuffer(testAddress - mAddress)
' Else
' Return Memory(testAddress)
' End If
' End Get
' End Property
'End Class
|
morphx666/x8086NetEmu
|
x8086NetEmu/Helpers/Prefetch.vb
|
Visual Basic
|
mit
| 973
|
Imports SolidEdgeCommunity.Extensions ' https://github.com/SolidEdgeCommunity/SolidEdge.Community/wiki/Using-Extension-Methods
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Namespace CreateHoles
Friend Class Program
<STAThread> _
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim documents As SolidEdgeFramework.Documents = Nothing
Dim sheetMetalDocument As SolidEdgePart.SheetMetalDocument = Nothing
Dim refplanes As SolidEdgePart.RefPlanes = Nothing
Dim refplane As SolidEdgePart.RefPlane = Nothing
Dim model As SolidEdgePart.Model = Nothing
Dim holeDataCollection As SolidEdgePart.HoleDataCollection = 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 holes2d As SolidEdgePart.Holes2d = Nothing
Dim hole2d As SolidEdgePart.Hole2d = Nothing
Dim holes As SolidEdgePart.Holes = Nothing
Dim hole As SolidEdgePart.Hole = Nothing
Dim profileStatus As Long = 0
Dim profileList As New List(Of SolidEdgePart.Profile)()
Dim userDefinedPatterns As SolidEdgePart.UserDefinedPatterns = Nothing
Dim userDefinedPattern As SolidEdgePart.UserDefinedPattern = Nothing
Dim selectSet As SolidEdgeFramework.SelectSet = Nothing
Try
' Register with OLE to handle concurrency issues on the current thread.
SolidEdgeCommunity.OleMessageFilter.Register()
' Connect to or start Solid Edge.
application = SolidEdgeCommunity.SolidEdgeUtils.Connect(True, True)
' Get a reference to the Documents collection.
documents = application.Documents
' Create a new sheetmetal document.
sheetMetalDocument = documents.AddSheetMetalDocument()
' Always a good idea to give SE a chance to breathe.
application.DoIdle()
' Call helper method to create the actual geometry.
model = SheetMetalHelper.CreateBaseTabByCircle(sheetMetalDocument)
' Get a reference to the RefPlanes collection.
refplanes = sheetMetalDocument.RefPlanes
' Get a reference to front RefPlane.
refplane = refplanes.GetFrontPlane()
' Get a reference to the ProfileSets collection.
profileSets = sheetMetalDocument.ProfileSets
' Add new ProfileSet.
profileSet = profileSets.Add()
' Get a reference to the Profiles collection.
profiles = profileSet.Profiles
' Add new Profile.
profile = profiles.Add(refplane)
' Get a reference to the Holes2d collection.
holes2d = profile.Holes2d
' This creates a cross pattern of holes.
Dim holeMatrix(,) As Double = { _
{0.00, 0.00}, _
{-0.01, 0.00}, _
{-0.02, 0.00}, _
{-0.03, 0.00}, _
{-0.04, 0.00}, _
{0.01, 0.00}, _
{0.02, 0.00}, _
{0.03, 0.00}, _
{0.04, 0.00}, _
{0.00, -0.01}, _
{0.00, -0.02}, _
{0.00, -0.03}, _
{0.00, -0.04}, _
{0.00, 0.01}, _
{0.00, 0.02}, _
{0.00, 0.03}, _
{0.00, 0.04} _
}
' Draw the Base Profile.
For i As Integer = 0 To holeMatrix.GetUpperBound(0)
' Add new Hole2d.
hole2d = holes2d.Add(XCenter:= holeMatrix(i, 0), YCenter:= holeMatrix(i, 1))
Next i
' Hide the profile.
profile.Visible = False
' Close profile.
profileStatus = profile.End(SolidEdgePart.ProfileValidationType.igProfileClosed)
' Get a reference to the ProfileSet.
profileSet = DirectCast(profile.Parent, SolidEdgePart.ProfileSet)
' Get a reference to the Profiles collection.
profiles = profileSet.Profiles
' Add profiles to list for AddByProfiles().
For i As Integer = 1 To profiles.Count
profileList.Add(profiles.Item(i))
Next i
' Get a reference to the HoleDataCollection collection.
holeDataCollection = sheetMetalDocument.HoleDataCollection
' Add new HoleData.
Dim holeData As SolidEdgePart.HoleData = holeDataCollection.Add(HoleType:= SolidEdgePart.FeaturePropertyConstants.igRegularHole, HoleDiameter:= 0.005, BottomAngle:= 90)
' Get a reference to the Holes collection.
holes = model.Holes
' Add hole.
hole = holes.AddFinite(Profile:= profile, ProfilePlaneSide:= SolidEdgePart.FeaturePropertyConstants.igRight, FiniteDepth:= 0.005, Data:= holeData)
' Get a reference to the UserDefinedPatterns collection.
userDefinedPatterns = model.UserDefinedPatterns
' Create the user defined pattern.
userDefinedPattern = userDefinedPatterns.AddByProfiles(NumberOfProfiles:= profileList.Count, ProfilesArray:= profileList.ToArray(), SeedFeature:= hole)
' Get a reference to the ActiveSelectSet.
selectSet = application.ActiveSelectSet
' Empty ActiveSelectSet.
selectSet.RemoveAll()
' Add new UserDefinedPattern to ActiveSelectSet.
selectSet.Add(userDefinedPattern)
' Switch to ISO view.
application.StartCommand(SolidEdgeConstants.SheetMetalCommandConstants.SheetMetalViewISOView)
Catch ex As System.Exception
Console.WriteLine(ex.Message)
Finally
SolidEdgeCommunity.OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/Samples
|
SheetMetal/CreateHoles/vb/CreateHoles/Program.vb
|
Visual Basic
|
mit
| 6,549
|
Namespace Exterity
''' <summary></summary>
''' <autogenerated>Generated from a T4 template. Modifications will be lost, if applicable use a partial class instead.</autogenerated>
''' <generator-date>08/02/2014 18:20:27</generator-date>
''' <generator-functions>1</generator-functions>
''' <generator-source>Caerus\_Exterity\Generated\TVTunerCollection.tt</generator-source>
''' <generator-template>Text-Templates\Classes\VB_Object.tt</generator-template>
''' <generator-version>1</generator-version>
<System.CodeDom.Compiler.GeneratedCode("Caerus\_Exterity\Generated\TVTunerCollection.tt", "1")> _
<Leviathan.Name(Name:="TV Tuner Cards")> _
<Leviathan.Collections.ElementType(GetType(TVTuner))> _
Partial Public Class TVTunerCollection
Inherits Leviathan.Collections.GeneralCollection
#Region " Public Constructors "
''' <summary>Default Constructor</summary>
Public Sub New()
MyBase.New()
End Sub
#End Region
#Region " Class Plumbing/Interface Code "
#Region " Collection Implementation "
#Region " Public Properties "
''' <summary>Provides A Strongly Typed Index Property</summary>
''' <remarks></remarks>
Default Public Shadows Property Item( _
ByVal index As System.Int32 _
) As TVTuner
Get
Return MyBase.Item(index)
End Get
Set(value As TVTuner)
MyBase.Item(index) = value
End Set
End Property
#End Region
#End Region
#End Region
End Class
End Namespace
|
thiscouldbejd/Caerus
|
_Exterity/Generated/TVTunerCollection.vb
|
Visual Basic
|
mit
| 1,491
|
' Licensed to the .NET Foundation under one or more 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.Reflection.Metadata
Imports Microsoft.CodeAnalysis.Test.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE
Public Class BaseTypeResolution
Inherits BasicTestBase
<Fact()>
Public Sub Test1()
Dim assembly = MetadataTestHelpers.LoadFromBytes(TestResources.NetFX.v4_0_21006.mscorlib)
TestBaseTypeResolutionHelper1(assembly)
Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences(
{TestResources.General.MDTestLib1,
TestResources.General.MDTestLib2,
TestResources.NetFX.v4_0_21006.mscorlib})
TestBaseTypeResolutionHelper2(assemblies)
assemblies = MetadataTestHelpers.GetSymbolsForReferences(
{TestResources.General.MDTestLib1,
TestResources.General.MDTestLib2})
TestBaseTypeResolutionHelper3(assemblies)
assemblies = MetadataTestHelpers.GetSymbolsForReferences(
{
TestReferences.SymbolsTests.MultiModule.Assembly,
TestReferences.SymbolsTests.MultiModule.Consumer
})
TestBaseTypeResolutionHelper4(assemblies)
End Sub
Private Sub TestBaseTypeResolutionHelper1(assembly As AssemblySymbol)
Dim module0 = assembly.Modules(0)
Dim sys = module0.GlobalNamespace.GetMembers("SYSTEM")
Dim collections = DirectCast(sys(0), NamespaceSymbol).GetMembers("CollectionS")
Dim generic = DirectCast(collections(0), NamespaceSymbol).GetMembers("Generic")
Dim dictionary = DirectCast(generic(0), NamespaceSymbol).GetMembers("Dictionary")
Dim base = DirectCast(dictionary(0), NamedTypeSymbol).BaseType
AssertBaseType(base, "System.Object")
Assert.Null(base.BaseType)
Dim concurrent = DirectCast(collections(0), NamespaceSymbol).GetMembers("Concurrent")
Dim orderablePartitioners = DirectCast(concurrent(0), NamespaceSymbol).GetMembers("OrderablePartitioner")
Dim orderablePartitioner As NamedTypeSymbol = Nothing
For Each p In orderablePartitioners
Dim t = TryCast(p, NamedTypeSymbol)
If t IsNot Nothing AndAlso t.Arity = 1 Then
orderablePartitioner = t
Exit For
End If
Next
base = orderablePartitioner.BaseType
AssertBaseType(base, "System.Collections.Concurrent.Partitioner(Of TSource)")
Assert.Same(DirectCast(base, NamedTypeSymbol).TypeArguments(0), orderablePartitioner.TypeParameters(0))
Dim partitioners = DirectCast(concurrent(0), NamespaceSymbol).GetMembers("Partitioner")
Dim partitioner As NamedTypeSymbol = Nothing
For Each p In partitioners
Dim t = TryCast(p, NamedTypeSymbol)
If t IsNot Nothing AndAlso t.Arity = 0 Then
partitioner = t
Exit For
End If
Next
Assert.NotNull(partitioner)
End Sub
Private Sub TestBaseTypeResolutionHelper2(assemblies() As AssemblySymbol)
Dim module1 = assemblies(0).Modules(0)
Dim module2 = assemblies(1).Modules(0)
Dim TC2 = module1.GlobalNamespace.GetTypeMembers("TC2").Single()
Dim TC3 = module1.GlobalNamespace.GetTypeMembers("TC3").Single()
Dim TC4 = module1.GlobalNamespace.GetTypeMembers("TC4").Single()
AssertBaseType(TC2.BaseType, "C1(Of TC2_T1).C2(Of TC2_T2)")
AssertBaseType(TC3.BaseType, "C1(Of TC3_T1).C3")
AssertBaseType(TC4.BaseType, "C1(Of TC4_T1).C3.C4(Of TC4_T2)")
Dim C1 = module1.GlobalNamespace.GetTypeMembers("C1").Single()
AssertBaseType(C1.BaseType, "System.Object")
Assert.Equal(0, C1.Interfaces.Length())
Dim TC5 = module2.GlobalNamespace.GetTypeMembers("TC5").Single()
Dim TC6 = module2.GlobalNamespace.GetTypeMembers("TC6").Single()
Dim TC7 = module2.GlobalNamespace.GetTypeMembers("TC7").Single()
Dim TC8 = module2.GlobalNamespace.GetTypeMembers("TC8").Single()
Dim TC9 = TC6.GetTypeMembers("TC9").Single()
AssertBaseType(TC5.BaseType, "C1(Of TC5_T1).C2(Of TC5_T2)")
AssertBaseType(TC6.BaseType, "C1(Of TC6_T1).C3")
AssertBaseType(TC7.BaseType, "C1(Of TC7_T1).C3.C4(Of TC7_T2)")
AssertBaseType(TC8.BaseType, "C1(Of System.Type)")
AssertBaseType(TC9.BaseType, "TC6(Of TC6_T1)")
Dim CorTypes = module2.GlobalNamespace.GetMembers("CorTypes").OfType(Of NamespaceSymbol)().Single()
Dim CorTypes_Derived = CorTypes.GetTypeMembers("Derived").Single()
AssertBaseType(CorTypes_Derived.BaseType,
"CorTypes.NS.Base(Of System.Boolean, System.SByte, System.Byte, System.Int16, System.UInt16, System.Int32, System.UInt32, System.Int64, System.UInt64, System.Single, System.Double, System.Char, System.String, System.IntPtr, System.UIntPtr, System.Object)")
Dim CorTypes_Derived1 = CorTypes.GetTypeMembers("Derived1").Single()
AssertBaseType(CorTypes_Derived1.BaseType,
"CorTypes.Base(Of System.Int32(), System.Double(,))")
Dim I101 = module1.GlobalNamespace.GetTypeMembers("I101").Single()
Dim I102 = module1.GlobalNamespace.GetTypeMembers("I102").Single()
Dim C203 = module1.GlobalNamespace.GetTypeMembers("C203").Single()
Assert.Equal(1, C203.Interfaces.Length())
Assert.Same(I101, C203.Interfaces(0))
Dim C204 = module1.GlobalNamespace.GetTypeMembers("C204").Single()
Assert.Equal(2, C204.Interfaces.Length())
Assert.Same(I101, C204.Interfaces(0))
Assert.Same(I102, C204.Interfaces(1))
Return
End Sub
Private Sub TestBaseTypeResolutionHelper3(assemblies() As AssemblySymbol)
Dim module1 = assemblies(0).Modules(0)
Dim module2 = assemblies(1).Modules(0)
Dim CorTypes = module2.GlobalNamespace.GetMembers("CorTypes").OfType(Of NamespaceSymbol)().Single()
Dim CorTypes_Derived = CorTypes.GetTypeMembers("Derived").Single()
AssertBaseType(CorTypes_Derived.BaseType,
"CorTypes.NS.Base(Of System.Boolean[missing], System.SByte[missing], System.Byte[missing], System.Int16[missing], System.UInt16[missing], System.Int32[missing], System.UInt32[missing], System.Int64[missing], System.UInt64[missing], System.Single[missing], System.Double[missing], System.Char[missing], System.String[missing], System.IntPtr[missing], System.UIntPtr[missing], System.Object[missing])")
For Each arg In CorTypes_Derived.BaseType.TypeArguments()
Assert.IsAssignableFrom(Of MissingMetadataTypeSymbol)(arg)
Next
Return
End Sub
Private Sub TestBaseTypeResolutionHelper4(assemblies() As AssemblySymbol)
Dim module1 = assemblies(0).Modules(0)
Dim module2 = assemblies(0).Modules(1)
Dim module3 = assemblies(0).Modules(2)
Dim module0 = assemblies(1).Modules(0)
Dim Derived1 = module0.GlobalNamespace.GetTypeMembers("Derived1").Single()
Dim base1 = Derived1.BaseType
Dim Derived2 = module0.GlobalNamespace.GetTypeMembers("Derived2").Single()
Dim base2 = Derived2.BaseType
Dim Derived3 = module0.GlobalNamespace.GetTypeMembers("Derived3").Single()
Dim base3 = Derived3.BaseType
AssertBaseType(base1, "Class1")
AssertBaseType(base2, "Class2")
AssertBaseType(base3, "Class3")
Assert.Same(base1, module1.GlobalNamespace.GetTypeMembers("Class1").Single())
Assert.Same(base2, module2.GlobalNamespace.GetTypeMembers("Class2").Single())
Assert.Same(base3, module3.GlobalNamespace.GetTypeMembers("Class3").Single())
End Sub
Friend Shared Sub AssertBaseType(base As TypeSymbol, name As String)
Assert.NotEqual(SymbolKind.ErrorType, base.Kind)
Assert.Equal(name, base.ToTestDisplayString())
End Sub
<Fact>
Public Sub Test2()
Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences(
{TestResources.SymbolsTests.DifferByCase.Consumer,
TestResources.SymbolsTests.DifferByCase.TypeAndNamespaceDifferByCase})
Dim module0 = TryCast(assemblies(0).Modules(0), PEModuleSymbol)
Dim module1 = TryCast(assemblies(1).Modules(0), PEModuleSymbol)
Dim bases As New HashSet(Of NamedTypeSymbol)()
Dim TC1 = module0.GlobalNamespace.GetTypeMembers("TC1").Single()
Dim base1 = TC1.BaseType
bases.Add(base1)
Assert.NotEqual(SymbolKind.ErrorType, base1.Kind)
Assert.Equal("SomeName.Dummy", base1.ToTestDisplayString())
Dim TC2 = module0.GlobalNamespace.GetTypeMembers("TC2").Single()
Dim base2 = TC2.BaseType
bases.Add(base2)
Assert.NotEqual(SymbolKind.ErrorType, base2.Kind)
Assert.Equal("somEnamE", base2.ToTestDisplayString())
Dim TC3 = module0.GlobalNamespace.GetTypeMembers("TC3").Single()
Dim base3 = TC3.BaseType
bases.Add(base3)
Assert.NotEqual(SymbolKind.ErrorType, base3.Kind)
Assert.Equal("somEnamE1", base3.ToTestDisplayString())
Dim TC4 = module0.GlobalNamespace.GetTypeMembers("TC4").Single()
Dim base4 = TC4.BaseType
bases.Add(base4)
Assert.NotEqual(SymbolKind.ErrorType, base4.Kind)
Assert.Equal("SomeName1", base4.ToTestDisplayString())
Dim TC5 = module0.GlobalNamespace.GetTypeMembers("TC5").Single()
Dim base5 = TC5.BaseType
bases.Add(base5)
Assert.NotEqual(SymbolKind.ErrorType, base5.Kind)
Assert.Equal("somEnamE2.OtherName", base5.ToTestDisplayString())
Dim TC6 = module0.GlobalNamespace.GetTypeMembers("TC6").Single()
Dim base6 = TC6.BaseType
bases.Add(base6)
Assert.NotEqual(SymbolKind.ErrorType, base6.Kind)
Assert.Equal("SomeName2.OtherName", base6.ToTestDisplayString())
Assert.Equal("SomeName2.OtherName", base6.ToTestDisplayString())
Dim TC7 = module0.GlobalNamespace.GetTypeMembers("TC7").Single()
Dim base7 = TC7.BaseType
bases.Add(base7)
Assert.NotEqual(SymbolKind.ErrorType, base7.Kind)
Assert.Equal("NestingClass.somEnamE3", base7.ToTestDisplayString())
Dim TC8 = module0.GlobalNamespace.GetTypeMembers("TC8").Single()
Dim base8 = TC8.BaseType
bases.Add(base8)
Assert.NotEqual(SymbolKind.ErrorType, base8.Kind)
Assert.Equal("NestingClass.SomeName3", base8.ToTestDisplayString())
Assert.Equal(8, bases.Count)
Assert.Equal(base1, module1.TypeHandleToTypeMap(DirectCast(base1, PENamedTypeSymbol).Handle))
Assert.Equal(base2, module1.TypeHandleToTypeMap(DirectCast(base2, PENamedTypeSymbol).Handle))
Assert.Equal(base3, module1.TypeHandleToTypeMap(DirectCast(base3, PENamedTypeSymbol).Handle))
Assert.Equal(base4, module1.TypeHandleToTypeMap(DirectCast(base4, PENamedTypeSymbol).Handle))
Assert.Equal(base5, module1.TypeHandleToTypeMap(DirectCast(base5, PENamedTypeSymbol).Handle))
Assert.Equal(base6, module1.TypeHandleToTypeMap(DirectCast(base6, PENamedTypeSymbol).Handle))
Assert.Equal(base7, module1.TypeHandleToTypeMap(DirectCast(base7, PENamedTypeSymbol).Handle))
Assert.Equal(base8, module1.TypeHandleToTypeMap(DirectCast(base8, PENamedTypeSymbol).Handle))
Assert.Equal(base1, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC1, PENamedTypeSymbol).Handle), TypeReferenceHandle)))
Assert.Equal(base2, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC2, PENamedTypeSymbol).Handle), TypeReferenceHandle)))
Assert.Equal(base3, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC3, PENamedTypeSymbol).Handle), TypeReferenceHandle)))
Assert.Equal(base4, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC4, PENamedTypeSymbol).Handle), TypeReferenceHandle)))
Assert.Equal(base5, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC5, PENamedTypeSymbol).Handle), TypeReferenceHandle)))
Assert.Equal(base6, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC6, PENamedTypeSymbol).Handle), TypeReferenceHandle)))
Assert.Equal(base7, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC7, PENamedTypeSymbol).Handle), TypeReferenceHandle)))
Assert.Equal(base8, module0.TypeRefHandleToTypeMap(CType(module0.Module.GetBaseTypeOfTypeOrThrow(DirectCast(TC8, PENamedTypeSymbol).Handle), TypeReferenceHandle)))
Dim assembly1 = DirectCast(assemblies(1), MetadataOrSourceAssemblySymbol)
Assert.Equal(base1, assembly1.CachedTypeByEmittedName(base1.ToTestDisplayString()))
Assert.Equal(base2, assembly1.CachedTypeByEmittedName(base2.ToTestDisplayString()))
Assert.Equal(base3, assembly1.CachedTypeByEmittedName(base3.ToTestDisplayString()))
Assert.Equal(base4, assembly1.CachedTypeByEmittedName(base4.ToTestDisplayString()))
Assert.Equal(base5, assembly1.CachedTypeByEmittedName(base5.ToTestDisplayString()))
Assert.Equal(base6, assembly1.CachedTypeByEmittedName(base6.ToTestDisplayString()))
Assert.Equal(base7.ContainingType, assembly1.CachedTypeByEmittedName(base7.ContainingType.ToTestDisplayString()))
Assert.Equal(7, assembly1.EmittedNameToTypeMapCount)
End Sub
<Fact()>
Public Sub Test3()
Dim mscorlibRef = TestReferences.NetFx.v4_0_21006.mscorlib
Dim c1 = VisualBasicCompilation.Create("Test", references:={mscorlibRef})
Assert.Equal("System.Object", DirectCast(c1.Assembly.Modules(0), SourceModuleSymbol).GetCorLibType(SpecialType.System_Object).ToTestDisplayString())
Dim MTTestLib1Ref = TestReferences.SymbolsTests.V1.MTTestLib1.dll
Dim c2 = VisualBasicCompilation.Create("Test2", references:={MTTestLib1Ref})
Assert.Equal("System.Object[missing]", DirectCast(c2.Assembly.Modules(0), SourceModuleSymbol).GetCorLibType(SpecialType.System_Object).ToTestDisplayString())
End Sub
<Fact>
Public Sub CrossModuleReferences1()
Dim compilationDef1 =
<compilation name="SimpleTest1">
<file name="a.vb"><![CDATA[
Class Test1
Inherits M3
End Class
Class Test2
Inherits M4
End Class
]]></file>
</compilation>
Dim crossRefModule1 = TestReferences.SymbolsTests.netModule.CrossRefModule1
Dim crossRefModule2 = TestReferences.SymbolsTests.netModule.CrossRefModule2
Dim crossRefLib = TestReferences.SymbolsTests.netModule.CrossRefLib
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(compilationDef1, {crossRefLib}, TestOptions.ReleaseDll)
AssertNoErrors(compilation1)
Dim test1 = compilation1.GetTypeByMetadataName("Test1")
Dim test2 = compilation1.GetTypeByMetadataName("Test2")
Assert.False(test1.BaseType.IsErrorType())
Assert.False(test1.BaseType.BaseType.IsErrorType())
Assert.False(test2.BaseType.IsErrorType())
Assert.False(test2.BaseType.BaseType.IsErrorType())
Assert.False(test2.BaseType.BaseType.BaseType.IsErrorType())
Dim compilationDef2 =
<compilation name="SimpleTest1">
<file name="a.vb"><![CDATA[
Public Class M3
Inherits M1
End Class
Public Class M4
Inherits M2
End Class
]]></file>
</compilation>
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(compilationDef2, {crossRefModule1, crossRefModule2}, TestOptions.ReleaseDll)
AssertNoErrors(compilation2)
Dim m3 = compilation2.GetTypeByMetadataName("M3")
Dim m4 = compilation2.GetTypeByMetadataName("M4")
Assert.False(m3.BaseType.IsErrorType())
Assert.False(m3.BaseType.BaseType.IsErrorType())
Assert.False(m4.BaseType.IsErrorType())
Assert.False(m4.BaseType.BaseType.IsErrorType())
Dim compilation3 = CreateCompilationWithMscorlib40AndReferences(compilationDef2, {crossRefModule2}, TestOptions.ReleaseDll)
m3 = compilation3.GetTypeByMetadataName("M3")
m4 = compilation3.GetTypeByMetadataName("M4")
Assert.True(m3.BaseType.IsErrorType())
Assert.False(m4.BaseType.IsErrorType())
Assert.True(m4.BaseType.BaseType.IsErrorType())
AssertTheseDiagnostics(compilation3,
<expected>
BC37221: Reference to 'CrossRefModule1.netmodule' netmodule missing.
BC30002: Type 'M1' is not defined.
Inherits M1
~~
BC30653: Reference required to module 'CrossRefModule1.netmodule' containing the type 'M1'. Add one to your project.
Inherits M2
~~
</expected>)
End Sub
End Class
End Namespace
|
davkean/roslyn
|
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/BaseTypeResolution.vb
|
Visual Basic
|
apache-2.0
| 18,285
|
Imports System.Security.Cryptography.X509Certificates
Imports Aspose.Email.Mail
'
'This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Email for .NET API reference
'when the project is build. Please check https://Docs.nuget.org/consume/nuget-faq for more information.
'If you do not wish to use NuGet, you can manually download Aspose.Email for .NET API from http://www.aspose.com/downloads,
'install it and then add its reference to this project. For any issues, questions or suggestions
'please feel free to contact us using http://www.aspose.com/community/forums/default.aspx
'
Namespace Aspose.Email.Examples.VisualBasic.Email
Class EncryptAndDecryptMessage
Public Shared Sub Run()
' ExStart:EncryptAndDecryptMessage
' The path to the File directory.
Dim dataDir As String = RunExamples.GetDataDir_Email()
Dim publicCertFile As String = dataDir & Convert.ToString("MartinCertificate.cer")
Dim privateCertFile As String = dataDir & Convert.ToString("MartinCertificate.pfx")
Dim publicCert As New X509Certificate2(publicCertFile)
Dim privateCert As New X509Certificate2(privateCertFile, "anothertestaccount")
' Create a message
Dim msg As New MailMessage("atneostthaecrcount@gmail.com", "atneostthaecrcount@gmail.com", "Test subject", "Test Body")
' Encrypt the message
Dim eMsg As MailMessage = msg.Encrypt(publicCert)
If eMsg.IsEncrypted = True Then
Console.WriteLine("Its encrypted")
Else
Console.WriteLine("Its NOT encrypted")
End If
' Decrypt the message
Dim dMsg As MailMessage = eMsg.Decrypt(privateCert)
If dMsg.IsEncrypted = True Then
Console.WriteLine("Its encrypted")
Else
Console.WriteLine("Its NOT encrypted")
End If
' ExEnd:EncryptAndDecryptMessage
End Sub
End Class
End Namespace
|
maria-shahid-aspose/Aspose.Email-for-.NET
|
Examples/VisualBasic/Email/EncryptAndDecryptMessage.vb
|
Visual Basic
|
mit
| 1,819
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.Shared.Extensions
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities
Imports Microsoft.CodeAnalysis.Formatting.Rules
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.ComponentModelHost
Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus
Imports Microsoft.VisualStudio.Shell.Interop
Imports IVsTextBufferCoordinator = Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferCoordinator
Imports VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Venus
Friend Class VisualBasicContainedLanguage
Inherits ContainedLanguage(Of VisualBasicPackage, VisualBasicLanguageService)
Implements IVsContainedLanguageStaticEventBinding
Public Sub New(bufferCoordinator As IVsTextBufferCoordinator,
componentModel As IComponentModel,
project As AbstractProject,
hierarchy As IVsHierarchy,
itemid As UInteger,
languageService As VisualBasicLanguageService,
sourceCodeKind As SourceCodeKind)
MyBase.New(bufferCoordinator, componentModel, project, hierarchy, itemid, languageService, sourceCodeKind, VisualBasicHelperFormattingRule.Instance)
End Sub
Public Function AddStaticEventBinding(pszClassName As String,
pszUniqueMemberID As String,
pszObjectName As String,
pszNameOfEvent As String) As Integer Implements IVsContainedLanguageStaticEventBinding.AddStaticEventBinding
Me.ComponentModel.GetService(Of IWaitIndicator)().Wait(
BasicVSResources.IntelliSense,
allowCancel:=False,
action:=Sub(c)
Dim visualStudioWorkspace = ComponentModel.GetService(Of VisualStudioWorkspace)()
Dim document = GetThisDocument()
ContainedLanguageStaticEventBinding.AddStaticEventBinding(
document, visualStudioWorkspace, pszClassName, pszUniqueMemberID, pszObjectName, pszNameOfEvent, c.CancellationToken)
End Sub)
Return VSConstants.S_OK
End Function
Public Function EnsureStaticEventHandler(pszClassName As String,
pszObjectTypeName As String,
pszObjectName As String,
pszNameOfEvent As String,
pszEventHandlerName As String,
itemidInsertionPoint As UInteger,
ByRef pbstrUniqueMemberID As String,
ByRef pbstrEventBody As String,
pSpanInsertionPoint() As VsTextSpan) As Integer Implements IVsContainedLanguageStaticEventBinding.EnsureStaticEventHandler
Dim thisDocument = GetThisDocument()
Dim targetDocumentId = Me.ContainedDocument.FindProjectDocumentIdWithItemId(itemidInsertionPoint)
Dim targetDocument = thisDocument.Project.Solution.GetDocument(targetDocumentId)
If targetDocument Is Nothing Then
Throw New InvalidOperationException("Can't generate into that itemid")
End If
Dim idBodyAndInsertionPoint = ContainedLanguageCodeSupport.EnsureEventHandler(
thisDocument,
targetDocument,
pszClassName,
pszObjectName,
pszObjectTypeName,
pszNameOfEvent,
pszEventHandlerName,
itemidInsertionPoint,
useHandlesClause:=True,
additionalFormattingRule:=New LineAdjustmentFormattingRule(),
cancellationToken:=Nothing)
pbstrUniqueMemberID = idBodyAndInsertionPoint.Item1
pbstrEventBody = idBodyAndInsertionPoint.Item2
pSpanInsertionPoint(0) = idBodyAndInsertionPoint.Item3
Return VSConstants.S_OK
End Function
Public Function GetStaticEventBindingsForObject(pszClassName As String,
pszObjectName As String,
ByRef pcMembers As Integer,
ppbstrEventNames As IntPtr,
ppbstrDisplayNames As IntPtr,
ppbstrMemberIDs As IntPtr) As Integer Implements IVsContainedLanguageStaticEventBinding.GetStaticEventBindingsForObject
Dim members As Integer
Me.ComponentModel.GetService(Of IWaitIndicator)().Wait(
BasicVSResources.IntelliSense,
allowCancel:=False,
action:=Sub(c)
Dim eventNamesAndMemberNamesAndIds = ContainedLanguageStaticEventBinding.GetStaticEventBindings(
GetThisDocument(), pszClassName, pszObjectName, c.CancellationToken)
members = eventNamesAndMemberNamesAndIds.Count()
CreateBSTRArray(ppbstrEventNames, eventNamesAndMemberNamesAndIds.Select(Function(e) e.Item1))
CreateBSTRArray(ppbstrDisplayNames, eventNamesAndMemberNamesAndIds.Select(Function(e) e.Item2))
CreateBSTRArray(ppbstrMemberIDs, eventNamesAndMemberNamesAndIds.Select(Function(e) e.Item3))
End Sub)
pcMembers = members
Return VSConstants.S_OK
End Function
Public Function RemoveStaticEventBinding(pszClassName As String,
pszUniqueMemberID As String,
pszObjectName As String,
pszNameOfEvent As String) As Integer Implements IVsContainedLanguageStaticEventBinding.RemoveStaticEventBinding
Me.ComponentModel.GetService(Of IWaitIndicator)().Wait(
BasicVSResources.IntelliSense,
allowCancel:=False,
action:=Sub(c)
Dim visualStudioWorkspace = ComponentModel.GetService(Of VisualStudioWorkspace)()
Dim document = GetThisDocument()
ContainedLanguageStaticEventBinding.RemoveStaticEventBinding(
document, visualStudioWorkspace, pszClassName, pszUniqueMemberID, pszObjectName, pszNameOfEvent, c.CancellationToken)
End Sub)
Return VSConstants.S_OK
End Function
Private Class VisualBasicHelperFormattingRule
Inherits AbstractFormattingRule
Public Shared Shadows Instance As IFormattingRule = New VisualBasicHelperFormattingRule()
Public Overrides Sub AddIndentBlockOperations(list As List(Of IndentBlockOperation), node As SyntaxNode, optionSet As OptionSet, nextOperation As NextAction(Of IndentBlockOperation))
' we need special behavior for VB due to @Helper code generation weird-ness.
' this will looking for code gen specific style to make it not so expansive
If IsEndHelperPattern(node) Then
Return
End If
Dim multiLineLambda = TryCast(node, MultiLineLambdaExpressionSyntax)
If multiLineLambda IsNot Nothing AndAlso IsHelperSubLambda(multiLineLambda) Then
Return
End If
MyBase.AddIndentBlockOperations(list, node, optionSet, nextOperation)
End Sub
Private Shared Function IsHelperSubLambda(multiLineLambda As MultiLineLambdaExpressionSyntax) As Boolean
If multiLineLambda.Kind <> SyntaxKind.MultiLineSubLambdaExpression Then
Return False
End If
If multiLineLambda.SubOrFunctionHeader Is Nothing OrElse
multiLineLambda.SubOrFunctionHeader.ParameterList Is Nothing OrElse
multiLineLambda.SubOrFunctionHeader.ParameterList.Parameters.Count <> 1 OrElse
multiLineLambda.SubOrFunctionHeader.ParameterList.Parameters(0).Identifier.Identifier.Text <> "__razor_helper_writer" Then
Return False
End If
Return True
End Function
Private Shared Function IsEndHelperPattern(node As SyntaxNode) As Boolean
If Not node.HasStructuredTrivia Then
Return False
End If
Dim method = TryCast(node, MethodBlockSyntax)
If method Is Nothing OrElse method.Statements.Count <> 2 Then
Return False
End If
Dim statementWithEndHelper = method.Statements(0)
Dim endToken = statementWithEndHelper.GetFirstToken()
If endToken.Kind <> SyntaxKind.EndKeyword Then
Return False
End If
Dim helperToken = endToken.GetNextToken(includeSkipped:=True)
If helperToken.Kind <> SyntaxKind.IdentifierToken OrElse
Not String.Equals(helperToken.Text, "Helper", StringComparison.OrdinalIgnoreCase) Then
Return False
End If
Dim asToken = helperToken.GetNextToken(includeSkipped:=True)
If asToken.Kind <> SyntaxKind.AsKeyword Then
Return False
End If
Return True
End Function
End Class
End Class
End Namespace
|
mmitche/roslyn
|
src/VisualStudio/VisualBasic/Impl/Venus/VisualBasicContainedLanguage.vb
|
Visual Basic
|
apache-2.0
| 10,499
|
Option Explicit On
Option Strict On
Imports CompuMaster.Data.Information
Namespace CompuMaster.Data
Public Class TextCell
Public Sub New(value As Object)
If value Is Nothing OrElse IsDBNull(value) Then
Me.Text = Nothing
Else
Me.Text = value.ToString
End If
End Sub
'Public Property ParentRow As TextRow
Public Property Text As String
Friend Function LineBreaksCount() As Integer
Dim Result As Integer = 0
For MyCounter As Integer = 0 To Me.Text.Length - 1
If Me.Text(MyCounter) = ControlChars.Cr Then
If Me.Text.Length >= MyCounter + 1 - 1 AndAlso Me.Text(MyCounter + 1) = ControlChars.Lf Then
'Count as 1 NewLine and step over to following char position
MyCounter += 1
End If
Result += 1
ElseIf Me.Text(MyCounter) = ControlChars.Lf Then
Result += 1
End If
Next
Return Result
End Function
''' <summary>
''' The maximum number of chars in a line
''' </summary>
''' <param name="dbNullText">Text representation of DbNull.Value, e.g. empty space or a string like "NULL"</param>
''' <param name="tabText">Text representation of TAB char, e.g. 4 spaces</param>
''' <returns></returns>
Friend Function MaxWidth(dbNullText As String, tabText As String) As Integer
Dim TextLines As String() = Me.TextLines(dbNullText, tabText)
Dim Result As Integer = 0
For MyCounter As Integer = 0 To TextLines.Length - 1
Result = System.Math.Max(Result, TextLines(MyCounter).Length)
Next
Return Result
End Function
''' <summary>
''' Text representation line by line
''' </summary>
''' <param name="dbNullText">Text representation of DbNull.Value, e.g. empty space or a string like "NULL"</param>
''' <param name="tabText">Text representation of TAB char, e.g. 4 spaces</param>
''' <returns></returns>
Friend Function TextLines(dbNullText As String, tabText As String) As String()
If Me.Text Is Nothing Then
Return New String() {Utils.StringNotNothingOrEmpty(dbNullText)}
ElseIf Me.Text = Nothing Then
Return New String() {""}
Else
Dim AllLineBreakStyles As String() = New String() {ControlChars.CrLf, CType(ControlChars.Cr, String), CType(ControlChars.Lf, String)}
Return Me.Text.Replace(ControlChars.Tab, tabText).Split(AllLineBreakStyles, StringSplitOptions.None)
End If
End Function
End Class
End Namespace
|
CompuMasterGmbH/CompuMaster.Data
|
CompuMaster.Data/TextCell.vb
|
Visual Basic
|
mit
| 2,863
|
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 arcs2d As SolidEdgeFrameworkSupport.Arcs2d = Nothing
Dim arc2d As SolidEdgeFrameworkSupport.Arc2d = 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))
arcs2d = profile.Arcs2d
arc2d = arcs2d.AddByCenterStartEnd(0, 0, 0.05, 0, 0, 0.05)
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.Arcs2d.AddByCenterStartEnd.vb
|
Visual Basic
|
mit
| 1,966
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:2.0.50727.3615
'
' 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 NEvoWeb.Modules.NB_Store
Partial Public Class CategoryMenuSettings
'''<summary>
'''plDefaultCategory control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plDefaultCategory As Global.System.Web.UI.UserControl
'''<summary>
'''ddlDefaultCategory control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents ddlDefaultCategory As Global.System.Web.UI.WebControls.DropDownList
'''<summary>
'''plStaticCategory control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plStaticCategory As Global.System.Web.UI.UserControl
'''<summary>
'''chkStaticCategory control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkStaticCategory As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plHideBreadCrumb control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plHideBreadCrumb As Global.System.Web.UI.UserControl
'''<summary>
'''chkHideBreadCrumb control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkHideBreadCrumb As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plHideBreadCrumbRoot control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plHideBreadCrumbRoot As Global.System.Web.UI.UserControl
'''<summary>
'''chkHideBreadCrumbRoot control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkHideBreadCrumbRoot As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plBreadCrumbCSS control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plBreadCrumbCSS As Global.System.Web.UI.UserControl
'''<summary>
'''txtBreadCrumbCSS control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtBreadCrumbCSS As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plBreadCrumbSep control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plBreadCrumbSep As Global.System.Web.UI.UserControl
'''<summary>
'''txtBreadCrumbSep control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtBreadCrumbSep As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plHideRootMenu control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plHideRootMenu As Global.System.Web.UI.UserControl
'''<summary>
'''chkHideRootMenu control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkHideRootMenu As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plPatchWork control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plPatchWork As Global.System.Web.UI.UserControl
'''<summary>
'''chkPatchWork control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkPatchWork As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plRootCSS control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plRootCSS As Global.System.Web.UI.UserControl
'''<summary>
'''txtRootCSS control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtRootCSS As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plRootSelectCSS control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plRootSelectCSS As Global.System.Web.UI.UserControl
'''<summary>
'''txtRootSelectCSS control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtRootSelectCSS As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plRootSep control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plRootSep As Global.System.Web.UI.UserControl
'''<summary>
'''txtRootSep control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtRootSep As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plRootLeftHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plRootLeftHtml As Global.System.Web.UI.UserControl
'''<summary>
'''txtRootLeftHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtRootLeftHtml As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plRootNameTemplate control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plRootNameTemplate As Global.System.Web.UI.UserControl
'''<summary>
'''txtRootNameTemplate control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtRootNameTemplate As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plRootRightHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plRootRightHtml As Global.System.Web.UI.UserControl
'''<summary>
'''txtRootRightHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtRootRightHtml As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plRootHeadHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plRootHeadHtml As Global.System.Web.UI.UserControl
'''<summary>
'''txtRootHeadHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtRootHeadHtml As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plHideSubMenu control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plHideSubMenu As Global.System.Web.UI.UserControl
'''<summary>
'''chkHideSubMenu control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkHideSubMenu As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plHideWhenRoot control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plHideWhenRoot As Global.System.Web.UI.UserControl
'''<summary>
'''chkHideWhenRoot control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkHideWhenRoot As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plCSS control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plCSS As Global.System.Web.UI.UserControl
'''<summary>
'''txtCSS control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtCSS As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plSubSelectCSS control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plSubSelectCSS As Global.System.Web.UI.UserControl
'''<summary>
'''txtSubSelectCSS control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtSubSelectCSS As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plSep control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plSep As Global.System.Web.UI.UserControl
'''<summary>
'''txtSep control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtSep As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plSubLeftHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plSubLeftHtml As Global.System.Web.UI.UserControl
'''<summary>
'''txtSubLeftHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtSubLeftHtml As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plSubNameTemplate control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plSubNameTemplate As Global.System.Web.UI.UserControl
'''<summary>
'''txtSubNameTemplate control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtSubNameTemplate As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plSubRightHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plSubRightHtml As Global.System.Web.UI.UserControl
'''<summary>
'''txtSubRightHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtSubRightHtml As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plSubHeadHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plSubHeadHtml As Global.System.Web.UI.UserControl
'''<summary>
'''txtSubHeadHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtSubHeadHtml As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plShowTreeMenu control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plShowTreeMenu As Global.System.Web.UI.UserControl
'''<summary>
'''chkShowTreeMenu control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkShowTreeMenu As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plTreeCSS control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plTreeCSS As Global.System.Web.UI.UserControl
'''<summary>
'''txtTreeCSS control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtTreeCSS As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plTreeSelectCSS control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plTreeSelectCSS As Global.System.Web.UI.UserControl
'''<summary>
'''txtTreeSelectCSS control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtTreeSelectCSS As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plTreeLeftHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plTreeLeftHtml As Global.System.Web.UI.UserControl
'''<summary>
'''txtTreeLeftHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtTreeLeftHtml As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plTreeNameTemplate control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plTreeNameTemplate As Global.System.Web.UI.UserControl
'''<summary>
'''txtTreeNameTemplate control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtTreeNameTemplate As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plTreeRightHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plTreeRightHtml As Global.System.Web.UI.UserControl
'''<summary>
'''txtTreeRightHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtTreeRightHtml As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plTreeHeadHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plTreeHeadHtml As Global.System.Web.UI.UserControl
'''<summary>
'''txtTreeHeadHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtTreeHeadHtml As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plShowAccordionMenu control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plShowAccordionMenu As Global.System.Web.UI.UserControl
'''<summary>
'''chkShowAccordionMenu control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkShowAccordionMenu As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plAccordionLeftHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plAccordionLeftHtml As Global.System.Web.UI.UserControl
'''<summary>
'''txtAccordionLeftHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtAccordionLeftHtml As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plAccordionNameTemplate control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plAccordionNameTemplate As Global.System.Web.UI.UserControl
'''<summary>
'''txtAccordionNameTemplate control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtAccordionNameTemplate As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plAccordionRightHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plAccordionRightHtml As Global.System.Web.UI.UserControl
'''<summary>
'''txtAccordionRightHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtAccordionRightHtml As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plAccordionHeadHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plAccordionHeadHtml As Global.System.Web.UI.UserControl
'''<summary>
'''txtAccordionHeadHtml control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtAccordionHeadHtml As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plSkipBlankCat control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plSkipBlankCat As Global.System.Web.UI.UserControl
'''<summary>
'''chkSkipBlankCat control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkSkipBlankCat As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plViewProdHide control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plViewProdHide As Global.System.Web.UI.UserControl
'''<summary>
'''chkViewProdHide control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkViewProdHide As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plColumns control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plColumns As Global.System.Web.UI.UserControl
'''<summary>
'''txtColumns control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtColumns As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plThumbnailSize control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plThumbnailSize As Global.System.Web.UI.UserControl
'''<summary>
'''txtThumbnailSize control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtThumbnailSize As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plSectionSep control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plSectionSep As Global.System.Web.UI.UserControl
'''<summary>
'''txtSectionSep control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtSectionSep As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plSectionSep2 control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plSectionSep2 As Global.System.Web.UI.UserControl
'''<summary>
'''txtSectionSep2 control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtSectionSep2 As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plSectionSep3 control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plSectionSep3 As Global.System.Web.UI.UserControl
'''<summary>
'''txtSectionSep3 control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtSectionSep3 As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plProductTabList control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plProductTabList As Global.System.Web.UI.UserControl
'''<summary>
'''lstProductTabs control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents lstProductTabs As Global.System.Web.UI.WebControls.DropDownList
End Class
End Namespace
|
skamphuis/NB_Store
|
CategoryMenuSettings.ascx.designer.vb
|
Visual Basic
|
mit
| 29,936
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.34209
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.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.RasterSyncExtensionReg.My.MySettings
Get
Return Global.RasterSyncExtensionReg.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
Esri/arcobjects-sdk-community-samples
|
Net/Geodatabase/RasterSyncWorkspaceExtension/VBNet/RasterSyncExtensionReg/My Project/Settings.Designer.vb
|
Visual Basic
|
apache-2.0
| 2,934
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:2.0.50727.42
'
' 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("VBPageSettings.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
|
AndreKuzubov/Easy_Report
|
packages/Independentsoft.Office.Word.2.0.400/Tutorial/VBPageSettings/My Project/Resources.Designer.vb
|
Visual Basic
|
apache-2.0
| 2,717
|
Imports Com.Aspose.Barcode.Api
Imports Com.Aspose.Barcode.Model
Namespace GeneratingSaving.WithoutCloudStorage
Class GenerateBarcodeAndGetImageAsStream
Public Shared Sub Run()
'ExStart:1
' Instantiate Aspose BarCode Cloud API SDK
Dim barcodeApi As New BarcodeApi(Common.APP_KEY, Common.APP_SID, Common.BASEPATH)
' Set Filename of image
Dim name As [String] = "sample-barcode"
' Set Text to encode inside barcode
Dim text As [String] = "Aspose.BarCode"
' Set Barcode Symbology
Dim type As [String] = "datamatrix"
' Set Barcode Image Format
Dim format As [String] = "PNG"
' Set optional params (if any)
Dim resolutionX As System.Nullable(Of Single) = Nothing
Dim resolutionY As System.Nullable(Of Single) = Nothing
Dim dimensionX As System.Nullable(Of Single) = Nothing
Dim dimensionY As System.Nullable(Of Single) = Nothing
' Set if checksum will be added to barcode image.
Dim enableChecksum As [String] = Nothing
Try
' Invoke Aspose.BarCode Cloud SDK API to create barcode and save image to a stream
Dim apiResponse As ResponseMessage = barcodeApi.GetBarcodeGenerate(text, type, format, resolutionX, resolutionY, dimensionX, dimensionY, enableChecksum)
If apiResponse IsNot Nothing Then
' Download generated barcode from api response storage
System.IO.File.WriteAllBytes(Common.OUTFOLDER + name + "." + format, apiResponse.ResponseStream)
Console.WriteLine("Generate a Barcode and Get as a Image Stream, Done!")
End If
Catch ex As Exception
Console.WriteLine("error:" + ex.Message + vbLf + ex.StackTrace)
End Try
'ExEnd:1
End Sub
End Class
End Namespace
|
aspose-barcode/Aspose.BarCode-for-Cloud
|
Examples/DotNET/VisualBasic/GeneratingSaving/WithoutCloudStorage/GenerateBarcodeAndGetImageAsStream.vb
|
Visual Basic
|
mit
| 2,000
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports System.Threading
Imports Microsoft.CodeAnalysis.SignatureHelp
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators
Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp
<ExportSignatureHelpProvider("AddRemoveHandlerSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]>
Friend Class AddRemoveHandlerSignatureHelpProvider
Inherits AbstractIntrinsicOperatorSignatureHelpProvider(Of AddRemoveHandlerStatementSyntax)
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Protected Overrides Function GetIntrinsicOperatorDocumentationAsync(node As AddRemoveHandlerStatementSyntax, document As Document, cancellationToken As CancellationToken) As ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))
Select Case node.Kind
Case SyntaxKind.AddHandlerStatement
Return New ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))(SpecializedCollections.SingletonEnumerable(New AddHandlerStatementDocumentation()))
Case SyntaxKind.RemoveHandlerStatement
Return New ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))(SpecializedCollections.SingletonEnumerable(New RemoveHandlerStatementDocumentation()))
End Select
Return New ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))(SpecializedCollections.EmptyEnumerable(Of AbstractIntrinsicOperatorDocumentation)())
End Function
Protected Overrides Function IsTriggerToken(token As SyntaxToken) As Boolean
Return token.IsChildToken(Of AddRemoveHandlerStatementSyntax)(Function(ce) ce.AddHandlerOrRemoveHandlerKeyword) OrElse
token.IsChildToken(Of AddRemoveHandlerStatementSyntax)(Function(ce) ce.CommaToken)
End Function
Public Overrides Function IsTriggerCharacter(ch As Char) As Boolean
Return ch = " "c OrElse ch = ","c
End Function
Public Overrides Function IsRetriggerCharacter(ch As Char) As Boolean
Return False
End Function
Protected Overrides Function IsArgumentListToken(node As AddRemoveHandlerStatementSyntax, token As SyntaxToken) As Boolean
Return True
End Function
End Class
End Namespace
|
reaction1989/roslyn
|
src/Features/VisualBasic/Portable/SignatureHelp/AddRemoveHandlerSignatureHelpProvider.vb
|
Visual Basic
|
apache-2.0
| 2,858
|
Imports NETGeographicLib
Module example_GARS
Sub Main()
Try
' Sample forward calculation
Dim lat As Double = 57.64911, lon = 10.40744
Dim garstring As String
For prec As Integer = 0 To 2
GARS.Forward(lat, lon, prec, garstring)
Console.WriteLine(String.Format("Precision: {0} GARS: {1}", prec, garstring))
Next
' Sample reverse calculation
garstring = "381NH45"
For len As Integer = 5 To garstring.Length
Dim prec As Integer
GARS.Reverse(garstring.Substring(0, len), lat, lon, prec, True)
Console.WriteLine(String.Format("Precision: {0} Latitude: {1} Longitude {2}", prec, lat, lon))
Next
Catch ex As GeographicErr
Console.WriteLine(String.Format("Caught Exception {0}", ex.Message))
End Try
End Sub
End Module
|
geographiclib/geographiclib
|
dotnet/examples/VB/example-GARS.vb
|
Visual Basic
|
mit
| 942
|
'*******************************************************************************************'
' '
' Download Free Evaluation Version From: https://bytescout.com/download/web-installer '
' '
' Also available as Web API! Get free API Key https://app.pdf.co/signup '
' '
' Copyright © 2017-2020 ByteScout, Inc. All rights reserved. '
' https://www.bytescout.com '
' https://www.pdf.co '
'*******************************************************************************************'
Imports System.IO
Imports System.Text.RegularExpressions
Imports Bytescout.PDFExtractor
Module Program
Sub Main()
Try
' Generate CSVExtractor instance
Using extractor As New CSVExtractor("demo", "demo")
' Load PDF document
extractor.LoadDocumentFromFile("sample.pdf")
' Get all data
Dim allData = extractor.GetCSV()
' Regular expressions and replacements
Dim ssnRegex = "\d{3}[-]?\d{2}[-]?\d{4}"
Dim ssnReplace = "***-**-****"
Dim phoneRegex = "\d{3}[-]?\d{3}[-]?\d{4}"
Dim phoneReplace = "***-***-****"
' Find and mask SSN and phone numbers
allData = Regex.Replace(allData, ssnRegex, ssnReplace)
allData = Regex.Replace(allData, phoneRegex, phoneReplace)
' Write as CSV
File.WriteAllText("output.csv", allData)
' Open file
Process.Start("output.csv")
End Using
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.WriteLine("Press enter key to exit...")
Console.ReadLine()
End Sub
End Module
|
bytescout/ByteScout-SDK-SourceCode
|
Premium Suite/VB.NET/Data masking in pdf with pdf extractor sdk/Program.vb
|
Visual Basic
|
apache-2.0
| 2,268
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Composition
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.QualityGuidelines.Analyzers
Namespace Microsoft.QualityGuidelines.VisualBasic.Analyzers
''' <summary>
''' CA2000: Dispose Objects Before Losing Scope
''' </summary>
<ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]>
Public NotInheritable Class BasicDisposeObjectsBeforeLosingScopeFixer
Inherits DisposeObjectsBeforeLosingScopeFixer
End Class
End Namespace
|
qinxgit/roslyn-analyzers
|
src/Microsoft.QualityGuidelines.Analyzers/VisualBasic/BasicDisposeObjectsBeforeLosingScope.Fixer.vb
|
Visual Basic
|
apache-2.0
| 678
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Option Strict Off
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.CodeFixes.Suppression
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.SimplifyTypeNames
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.Suppression
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Suppression
Public MustInherit Class VisualBasicSuppressionTests
Inherits AbstractSuppressionDiagnosticTest
Private ReadOnly _compilationOptions As CompilationOptions =
New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionInfer(True)
Protected Overrides Function GetScriptOptions() As ParseOptions
Return TestOptions.Script
End Function
Protected Overrides Function CreateWorkspaceFromFile(initialMarkup As String, parameters As TestParameters) As TestWorkspace
Return TestWorkspace.CreateVisualBasic(
initialMarkup,
parameters.parseOptions,
If(parameters.compilationOptions, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)))
End Function
Protected Overrides Function GetLanguage() As String
Return LanguageNames.VisualBasic
End Function
#Region "Pragma disable tests"
Public MustInherit Class VisualBasicPragmaWarningDisableSuppressionTests
Inherits VisualBasicSuppressionTests
Protected NotOverridable Overrides ReadOnly Property CodeActionIndex() As Integer
Get
Return 0
End Get
End Property
Public Class CompilerDiagnosticSuppressionTests
Inherits VisualBasicPragmaWarningDisableSuppressionTests
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, ISuppressionFixProvider)
Return Tuple.Create(Of DiagnosticAnalyzer, ISuppressionFixProvider)(Nothing, New VisualBasicSuppressionCodeFixProvider())
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirective() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method()
[|Dim x As Integer|]
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' {WRN_UnusedLocal_Title}
Dim x As Integer
#Enable Warning BC42024 ' {WRN_UnusedLocal_Title}
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' Unused local variable
[|Dim x As Integer|]
#Enable Warning BC42024 ' Unused local variable
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective1() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method()
[|Dim x _
As Integer|]
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' {WRN_UnusedLocal_Title}
Dim x _
As Integer
#Enable Warning BC42024 ' {WRN_UnusedLocal_Title}
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' Unused local variable
[|Dim x _
As Integer|]
#Enable Warning BC42024 ' Unused local variable
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective2() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method(i As Integer, j As Short)
If i < [|j.MaxValue|] AndAlso
i > 0 Then
Console.WriteLine(i)
End If
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method(i As Integer, j As Short)
#Disable Warning BC42025 ' {WRN_SharedMemberThroughInstance_Title}
If i < j.MaxValue AndAlso
i > 0 Then
#Enable Warning BC42025 ' {WRN_SharedMemberThroughInstance_Title}
Console.WriteLine(i)
End If
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method(i As Integer, j As Short)
#Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
If i < [|j.MaxValue|] AndAlso
i > 0 Then
#Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
Console.WriteLine(i)
End If
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective3() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method(i As Integer, j As Short)
If i > 0 AndAlso
i < [|j.MaxValue|] Then
Console.WriteLine(i)
End If
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method(i As Integer, j As Short)
#Disable Warning BC42025 ' {WRN_SharedMemberThroughInstance_Title}
If i > 0 AndAlso
i < j.MaxValue Then
#Enable Warning BC42025 ' {WRN_SharedMemberThroughInstance_Title}
Console.WriteLine(i)
End If
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method(i As Integer, j As Short)
#Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
If i > 0 AndAlso
i < [|j.MaxValue|] Then
#Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
Console.WriteLine(i)
End If
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective4() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method()
Dim [|x As Integer|],
y As Integer
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' {WRN_UnusedLocal_Title}
Dim x As Integer,
y As Integer
#Enable Warning BC42024 ' {WRN_UnusedLocal_Title}
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' Unused local variable
Dim [|x As Integer|],
y As Integer
#Enable Warning BC42024 ' Unused local variable
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective5() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method()
Dim x As Integer,
[|y As Integer|]
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' {WRN_UnusedLocal_Title}
Dim x As Integer,
y As Integer
#Enable Warning BC42024 ' {WRN_UnusedLocal_Title}
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' Unused local variable
Dim x As Integer,
[|y As Integer|]
#Enable Warning BC42024 ' Unused local variable
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective6() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method(i As Integer, j As Short)
Dim x = <root>
<condition value=<%= i < [|j.MaxValue|] %>/>
</root>
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method(i As Integer, j As Short)
#Disable Warning BC42025 ' {WRN_SharedMemberThroughInstance_Title}
Dim x = <root>
<condition value=<%= i < j.MaxValue %>/>
</root>
#Enable Warning BC42025 ' {WRN_SharedMemberThroughInstance_Title}
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method(i As Integer, j As Short)
#Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
Dim x = <root>
<condition value=<%= i < [|j.MaxValue|] %>/>
</root>
#Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective7() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method(j As Short)
Dim x = From i As Integer In {}
Where i < [|j.MaxValue|]
Select i
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method(j As Short)
#Disable Warning BC42025 ' {WRN_SharedMemberThroughInstance_Title}
Dim x = From i As Integer In {{}}
Where i < j.MaxValue
Select i
#Enable Warning BC42025 ' {WRN_SharedMemberThroughInstance_Title}
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method(j As Short)
#Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
Dim x = From i As Integer In {}
Where i < [|j.MaxValue|]
Select i
#Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveWithExistingTrivia() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method()
' Trivia previous line
[|Dim x As Integer|] ' Trivia same line
' Trivia next line
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method()
' Trivia previous line
#Disable Warning BC42024 ' {WRN_UnusedLocal_Title}
Dim x As Integer ' Trivia same line
#Enable Warning BC42024 ' {WRN_UnusedLocal_Title}
' Trivia next line
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method()
' Trivia previous line
#Disable Warning BC42024 ' Unused local variable
[|Dim x As Integer|] ' Trivia same line
#Enable Warning BC42024 ' Unused local variable
' Trivia next line
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(970129, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/970129")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionAroundSingleToken() As Task
Dim source = <![CDATA[
Imports System
<Obsolete>
Class C
End Class
Module Module1
Sub Main
[|C|]
End Sub
End Module]]>
Dim expected = $"
Imports System
<Obsolete>
Class C
End Class
Module Module1
Sub Main
#Disable Warning BC40008 ' {WRN_UseOfObsoleteSymbolNoMessage1_Title}
C
#Enable Warning BC40008 ' {WRN_UseOfObsoleteSymbolNoMessage1_Title}
End Sub
End Module"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
<Obsolete>
Class C
End Class
Module Module1
Sub Main
#Disable Warning BC40008 ' Type or member is obsolete
[|C|]
#Enable Warning BC40008 ' Type or member is obsolete
End Sub
End Module]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveAroundTrivia1() As Task
Dim source = <![CDATA[
Class C
' Comment
' Comment
''' <summary><see [|cref="abc"|]/></summary>
Sub M() ' Comment
End Sub
End Class]]>
Dim expected = $"
Class C
' Comment
' Comment
#Disable Warning BC42309 ' {WRN_XMLDocCrefAttributeNotFound1_Title}
''' <summary><see cref=""abc""/></summary>
Sub M() ' Comment
#Enable Warning BC42309 ' {WRN_XMLDocCrefAttributeNotFound1_Title}
End Sub
End Class"
Dim enableDocCommentProcessing = VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)
Await TestAsync(source.Value, expected, enableDocCommentProcessing)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = $"
Class C
' Comment
' Comment
#Disable Warning BC42309 ' {WRN_XMLDocCrefAttributeNotFound1_Title}
''' <summary><see [|cref=""abc""|]/></summary>
Sub M() ' Comment
#Enable Warning BC42309 ' {WRN_XMLDocCrefAttributeNotFound1_Title}
End Sub
End Class"
Await TestMissingAsync(fixedSource,
New TestParameters(enableDocCommentProcessing))
End Function
<WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveAroundTrivia2() As Task
Dim source = <![CDATA['''[|<summary></summary>|]]]>
Dim expected = $"#Disable Warning BC42312 ' {WRN_XMLDocWithoutLanguageElement_Title}
'''<summary></summary>
#Enable Warning BC42312 ' {WRN_XMLDocWithoutLanguageElement_Title}"
Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
End Function
<WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveAroundTrivia3() As Task
Dim source = <![CDATA[ '''[|<summary></summary>|] ]]>
Dim expected = $"#Disable Warning BC42312 ' {WRN_XMLDocWithoutLanguageElement_Title}
'''<summary></summary>
#Enable Warning BC42312 ' {WRN_XMLDocWithoutLanguageElement_Title}"
Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
End Function
<WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveAroundTrivia4() As Task
Dim source = <![CDATA[
'''<summary><see [|cref="abc"|]/></summary>
Class C : End Class
]]>
Dim expected = $"
#Disable Warning BC42309 ' {WRN_XMLDocCrefAttributeNotFound1_Title}
'''<summary><see cref=""abc""/></summary>
Class C : End Class
#Enable Warning BC42309 ' {WRN_XMLDocCrefAttributeNotFound1_Title}
"
Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
End Function
<WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveAroundTrivia5() As Task
Dim source = <![CDATA[class C1 : End Class
'''<summary><see [|cref="abc"|]/></summary>
Class C2 : End Class
Class C3 : End Class]]>
Dim expected = $"class C1 : End Class
#Disable Warning BC42309 ' {WRN_XMLDocCrefAttributeNotFound1_Title}
'''<summary><see cref=""abc""/></summary>
Class C2 : End Class
#Enable Warning BC42309 ' {WRN_XMLDocCrefAttributeNotFound1_Title}
Class C3 : End Class"
Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
End Function
<WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveAroundTrivia6() As Task
Dim source = <![CDATA[class C1 : End Class
Class C2 : End Class [|'''|]
Class C3 : End Class]]>
Dim expected = $"class C1 : End Class
#Disable Warning BC42302 ' {WRN_XMLDocNotFirstOnLine_Title}
Class C2 : End Class '''
#Enable Warning BC42302 ' {WRN_XMLDocNotFirstOnLine_Title}
Class C3 : End Class"
Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
End Function
End Class
Public Class UserHiddenDiagnosticSuppressionTests
Inherits VisualBasicPragmaWarningDisableSuppressionTests
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, ISuppressionFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, ISuppressionFixProvider)(New VisualBasicSimplifyTypeNamesDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestHiddenDiagnosticCannotBeSuppressed() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method()
Dim i as [|System.Int32|] = 0
Console.WriteLine(i)
End Sub
End Class]]>
Await TestMissingAsync(source.Value)
End Function
End Class
Public Class UserInfoDiagnosticSuppressionTests
Inherits VisualBasicPragmaWarningDisableSuppressionTests
Private Class UserDiagnosticAnalyzer
Inherits DiagnosticAnalyzer
Private _descriptor As New DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault:=True)
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor)
Get
Return ImmutableArray.Create(_descriptor)
End Get
End Property
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement)
End Sub
Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext)
Dim classDecl = DirectCast(context.Node, ClassStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation()))
End Sub
End Class
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, ISuppressionFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, ISuppressionFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestInfoDiagnosticSuppressed() As Task
Dim source = <![CDATA[
Imports System
[|Class C|]
Sub Method()
End Sub
End Class]]>
Dim expected = <![CDATA[
Imports System
#Disable Warning InfoDiagnostic ' InfoDiagnostic
Class C
#Enable Warning InfoDiagnostic ' InfoDiagnostic
Sub Method()
End Sub
End Class]]>
Await TestAsync(source.Value, expected.Value)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
#Disable Warning InfoDiagnostic ' InfoDiagnostic
[|Class C|]
#Enable Warning InfoDiagnostic ' InfoDiagnostic
Sub Method()
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
End Class
Public Class DiagnosticWithBadIdSuppressionTests
Inherits VisualBasicPragmaWarningDisableSuppressionTests
Protected Overrides ReadOnly Property IncludeNoLocationDiagnostics As Boolean
Get
' Analyzer driver generates a no-location analyzer exception diagnostic, which we don't intend to test here.
Return False
End Get
End Property
Private Class UserDiagnosticAnalyzer
Inherits DiagnosticAnalyzer
Private _descriptor As New DiagnosticDescriptor("#$DiagnosticWithBadId", "DiagnosticWithBadId", "DiagnosticWithBadId", "DiagnosticWithBadId", DiagnosticSeverity.Info, isEnabledByDefault:=True)
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor)
Get
Return ImmutableArray.Create(_descriptor)
End Get
End Property
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement)
End Sub
Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext)
Dim classDecl = DirectCast(context.Node, ClassStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation()))
End Sub
End Class
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, ISuppressionFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, ISuppressionFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestDiagnosticWithBadIdSuppressed() As Task
' Diagnostics with bad/invalid ID are not reported.
Dim source = <![CDATA[
Imports System
[|Class C|]
Sub Method()
End Sub
End Class]]>
Await TestMissingAsync(source.Value)
End Function
End Class
Public Class UserWarningDiagnosticWithNameMatchingKeywordSuppressionTests
Inherits VisualBasicPragmaWarningDisableSuppressionTests
Private Class UserDiagnosticAnalyzer
Inherits DiagnosticAnalyzer
Private _descriptor As New DiagnosticDescriptor("REm", "REm Title", "REm", "REm", DiagnosticSeverity.Warning, isEnabledByDefault:=True)
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor)
Get
Return ImmutableArray.Create(_descriptor)
End Get
End Property
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement)
End Sub
Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext)
Dim classDecl = DirectCast(context.Node, ClassStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation()))
End Sub
End Class
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, ISuppressionFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, ISuppressionFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestWarningDiagnosticWithNameMatchingKeywordSuppressed() As Task
Dim source = <![CDATA[
Imports System
[|Class C|]
Sub Method()
End Sub
End Class]]>
Dim expected = <![CDATA[
Imports System
#Disable Warning [REm] ' REm Title
Class C
#Enable Warning [REm] ' REm Title
Sub Method()
End Sub
End Class]]>
Await TestAsync(source.Value, expected.Value)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
#Disable Warning [REm] ' REm Title
[|Class C|]
#Enable Warning [REm] ' REm Title
Sub Method()
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
End Class
Public Class UserErrorDiagnosticSuppressionTests
Inherits VisualBasicPragmaWarningDisableSuppressionTests
Private Class UserDiagnosticAnalyzer
Inherits DiagnosticAnalyzer
Private _descriptor As New DiagnosticDescriptor("ErrorDiagnostic", "ErrorDiagnostic", "ErrorDiagnostic", "ErrorDiagnostic", DiagnosticSeverity.[Error], isEnabledByDefault:=True)
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor)
Get
Return ImmutableArray.Create(_descriptor)
End Get
End Property
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement)
End Sub
Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext)
Dim classDecl = DirectCast(context.Node, ClassStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation()))
End Sub
End Class
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, ISuppressionFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, ISuppressionFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestErrorDiagnosticCanBeSuppressed() As Task
Dim source = <![CDATA[
Imports System
[|Class C|]
Sub Method()
End Sub
End Class]]>
Dim expected = <![CDATA[
Imports System
#Disable Warning ErrorDiagnostic ' ErrorDiagnostic
Class C
#Enable Warning ErrorDiagnostic ' ErrorDiagnostic
Sub Method()
End Sub
End Class]]>
Await TestAsync(source.Value, expected.Value)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
#Disable Warning ErrorDiagnostic ' ErrorDiagnostic
[|Class C|]
#Enable Warning ErrorDiagnostic ' ErrorDiagnostic
Sub Method()
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
End Class
End Class
#End Region
#Region "SuppressMessageAttribute tests"
Public MustInherit Class VisualBasicGlobalSuppressMessageSuppressionTests
Inherits VisualBasicSuppressionTests
Protected NotOverridable Overrides ReadOnly Property CodeActionIndex() As Integer
Get
Return 1
End Get
End Property
Public Class CompilerDiagnosticSuppressionTests
Inherits VisualBasicGlobalSuppressMessageSuppressionTests
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, ISuppressionFixProvider)
Return Tuple.Create(Of DiagnosticAnalyzer, ISuppressionFixProvider)(Nothing, New VisualBasicSuppressionCodeFixProvider())
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestCompilerDiagnosticsCannotBeSuppressed() As Task
Dim source = <![CDATA[
Class Class1
Sub Method()
[|Dim x|]
End Sub
End Class]]>
Await TestActionCountAsync(source.Value, 1)
End Function
End Class
Public Class UserHiddenDiagnosticSuppressionTests
Inherits VisualBasicGlobalSuppressMessageSuppressionTests
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, ISuppressionFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, ISuppressionFixProvider)(New VisualBasicSimplifyTypeNamesDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestHiddenDiagnosticsCannotBeSuppressed() As Task
Dim source = <![CDATA[
Imports System
Class Class1
Sub Method()
[|Dim x As System.Int32 = 0|]
End Sub
End Class]]>
Await TestMissingAsync(source.Value)
End Function
End Class
Public Class UserInfoDiagnosticSuppressionTests
Inherits VisualBasicGlobalSuppressMessageSuppressionTests
Private Class UserDiagnosticAnalyzer
Inherits DiagnosticAnalyzer
Private _descriptor As New DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault:=True)
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor)
Get
Return ImmutableArray.Create(_descriptor)
End Get
End Property
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement, SyntaxKind.NamespaceStatement, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.PropertyStatement, SyntaxKind.FieldDeclaration, SyntaxKind.EventStatement)
End Sub
Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext)
Select Case context.Node.Kind()
Case SyntaxKind.ClassStatement
Dim classDecl = DirectCast(context.Node, ClassStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation()))
Exit Select
Case SyntaxKind.NamespaceStatement
Dim ns = DirectCast(context.Node, NamespaceStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, ns.Name.GetLocation()))
Exit Select
Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement
Dim method = DirectCast(context.Node, MethodStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, method.Identifier.GetLocation()))
Exit Select
Case SyntaxKind.PropertyStatement
Dim p = DirectCast(context.Node, PropertyStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, p.Identifier.GetLocation()))
Exit Select
Case SyntaxKind.FieldDeclaration
Dim f = DirectCast(context.Node, FieldDeclarationSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, f.Declarators.First().Names.First.GetLocation()))
Exit Select
Case SyntaxKind.EventStatement
Dim e = DirectCast(context.Node, EventStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, e.Identifier.GetLocation()))
Exit Select
End Select
End Sub
End Class
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, ISuppressionFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, ISuppressionFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnSimpleType() As Task
Dim source = <![CDATA[
Imports System
[|Class Class1|]
Sub Method()
Dim x
End Sub
End Class]]>
Dim expected = $"
' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class1"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class1"")>
[|Class Class1|]
Sub Method()
Dim x
End Sub
End Class"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnNamespace() As Task
Dim source = <![CDATA[
Imports System
[|Namespace N|]
Class Class1
Sub Method()
Dim x
End Sub
End Class
End Namespace]]>
Dim expected = $"
' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""namespace"", Target:=""~N:N"")>
"
Await TestInRegularAndScriptAsync(source.Value, expected, index:=1)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""namespace"", Target:=""~N:N"")>
[|Namespace N|]
Class Class1
Sub Method()
Dim x
End Sub
End Class
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnTypeInsideNamespace() As Task
Dim source = <![CDATA[
Imports System
Namespace N1
Namespace N2
[|Class Class1|]
Sub Method()
Dim x
End Sub
End Class
End Namespace
End Namespace]]>
Dim expected = $"
' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N1.N2.Class1"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N1.N2.Class1"")>
Namespace N1
Namespace N2
[|Class Class1|]
Sub Method()
Dim x
End Sub
End Class
End Namespace
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnNestedType() As Task
Dim source = <![CDATA[
Imports System
Namespace N
Class Generic(Of T)
[|Class Class1|]
Sub Method()
Dim x
End Sub
End Class
End Class
End Namespace]]>
Dim expected = $"
' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N.Generic`1.Class1"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N.Generic`1.Class1"")>
Namespace N
Class Generic(Of T)
[|Class Class1|]
Sub Method()
Dim x
End Sub
End Class
End Class
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnMethod() As Task
Dim source = <![CDATA[
Imports System
Namespace N
Class Generic(Of T)
Class Class1
[|Sub Method()
Dim x
End Sub|]
End Class
End Class
End Namespace]]>
Dim expected = $"
' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method"")>
Namespace N
Class Generic(Of T)
Class Class1
[|Sub Method()
Dim x
End Sub|]
End Class
End Class
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnOverloadedMethod() As Task
Dim source = <![CDATA[
Imports System
Namespace N
Class Generic(Of T)
Class Class1
[|Sub Method(y as Integer, ByRef z as Integer)
Dim x
End Sub|]
Sub Method()
Dim x
End Sub
End Class
End Class
End Namespace]]>
Dim expected = $"
' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method(System.Int32,System.Int32@)"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method(System.Int32,System.Int32@)"")>
Namespace N
Class Generic(Of T)
Class Class1
[|Sub Method(y as Integer, ByRef z as Integer)
Dim x
End Sub|]
Sub Method()
Dim x
End Sub
End Class
End Class
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnGenericMethod() As Task
Dim source = <![CDATA[
Imports System
Namespace N
Class Generic(Of T)
Class Class1
[|Sub Method(Of U)(y as U, ByRef z as Integer)
Dim x
End Sub|]
Sub Method()
Dim x
End Sub
End Class
End Class
End Namespace]]>
Dim expected = $"
' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method``1(``0,System.Int32@)"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method``1(``0,System.Int32@)"")>
Namespace N
Class Generic(Of T)
Class Class1
[|Sub Method(Of U)(y as U, ByRef z as Integer)
Dim x
End Sub|]
Sub Method()
Dim x
End Sub
End Class
End Class
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnProperty() As Task
Dim source = <![CDATA[
Imports System
Namespace N
Class Generic
Private Class C
[|Private ReadOnly Property P() As Integer|]
Get
Dim x As Integer = 0
End Get
End Property
End Class
End Class
End Namespace]]>
Dim expected = $"
' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~P:N.Generic.C.P"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~P:N.Generic.C.P"")>
Namespace N
Class Generic
Private Class C
[|Private ReadOnly Property P() As Integer|]
Get
Dim x As Integer = 0
End Get
End Property
End Class
End Class
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnField() As Task
Dim source = <![CDATA[
Imports System
Class C
[|Private ReadOnly F As Integer|]
End Class]]>
Dim expected = $"
' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~F:C.F"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~F:C.F"")>
Class C
[|Private ReadOnly F As Integer|]
End Class"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnEvent() As Task
Dim source = <![CDATA[
Imports System
Public Class SampleEventArgs
Public Sub New(s As String)
Text = s
End Sub
Public Property Text() As [String]
Get
Return m_Text
End Get
Private Set
m_Text = Value
End Set
End Property
Private m_Text As [String]
End Class
Class C
' Declare the delegate (if using non-generic pattern).
Public Delegate Sub SampleEventHandler(sender As Object, e As SampleEventArgs)
' Declare the event.
[|Public Custom Event SampleEvent As SampleEventHandler|]
AddHandler(ByVal value As SampleEventHandler)
End AddHandler
RemoveHandler(ByVal value As SampleEventHandler)
End RemoveHandler
End Event
End Class]]>
Dim expected = $"
' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~E:C.SampleEvent"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~E:C.SampleEvent"")>
Public Class SampleEventArgs
Public Sub New(s As String)
Text = s
End Sub
Public Property Text() As [String]
Get
Return m_Text
End Get
Private Set
m_Text = Value
End Set
End Property
Private m_Text As [String]
End Class
Class C
' Declare the delegate (if using non-generic pattern).
Public Delegate Sub SampleEventHandler(sender As Object, e As SampleEventArgs)
' Declare the event.
[|Public Custom Event SampleEvent As SampleEventHandler|]
AddHandler(ByVal value As SampleEventHandler)
End AddHandler
RemoveHandler(ByVal value As SampleEventHandler)
End RemoveHandler
End Event
End Class"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionWithExistingGlobalSuppressionsDocument() As Task
Dim source =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="CurrentDocument.vb"><![CDATA[
Imports System
Class Class1
End Class
[|Class Class2|]
End Class]]>
</Document>
<Document FilePath="GlobalSuppressions.vb"><![CDATA[
' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification:="<Pending>", Scope:="type", Target:="Class1")>
]]>
</Document>
</Project>
</Workspace>
Dim expected = $"
' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""<Pending>"", Scope:=""type"", Target:=""Class1"")>
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")>
"
Await TestAsync(source.ToString(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionWithExistingGlobalSuppressionsDocument2() As Task
' Own custom file named GlobalSuppressions.cs
Dim source =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="CurrentDocument.vb"><![CDATA[
Imports System
Class Class1
End Class
[|Class Class2|]
End Class]]>
</Document>
<Document FilePath="GlobalSuppressions.vb"><![CDATA[
' My own file named GlobalSuppressions.vb
Class Class3
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected = $"
' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")>
"
Await TestAsync(source.ToString(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionWithExistingGlobalSuppressionsDocument3() As Task
' Own custom file named GlobalSuppressions.vb + existing GlobalSuppressions2.vb with global suppressions
Dim source =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="CurrentDocument.vb"><![CDATA[
Imports System
Class Class1
End Class
[|Class Class2|]
End Class]]>
</Document>
<Document FilePath="GlobalSuppressions.vb"><![CDATA[
' My own file named GlobalSuppressions.vb
Class Class3
End Class
]]>
</Document>
<Document FilePath="GlobalSuppressions2.vb"><![CDATA[
' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification:="<Pending>", Scope:="type", Target:="Class1")>
]]>
</Document>
</Project>
</Workspace>
Dim expected = $"
' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""<Pending>"", Scope:=""type"", Target:=""Class1"")>
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")>
"
Await TestAsync(source.ToString(), expected)
End Function
End Class
End Class
#End Region
End Class
End Namespace
|
VSadov/roslyn
|
src/EditorFeatures/VisualBasicTest/Diagnostics/Suppression/SuppressionTests.vb
|
Visual Basic
|
apache-2.0
| 61,382
|
' 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.Diagnostics
Imports Microsoft.CodeAnalysis.PooledObjects
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Function that help implement the overloading rules for VB, in particular the rules
''' for recasing method and property names.
''' </summary>
Friend Module OverloadingHelper
''' <summary>
''' Set the correct metadata name for all overloads of a particular name and symbol kind
''' (must be method or property) inside a container.
'''
''' The rules are as follows:
''' 1) If a method or property overrides one from its base class, its metadata name
''' must match that.
''' 2) If method overloads those in the base (because the Overloads keyword is used), and
''' all metadata names in the base are consistent in case, use that name.
''' 3) All overloads with a class should match, except possibly for overrides. If there is
''' an override or overload from base, use that. Otherwise, use casing of first member in
''' class.
''' </summary>
Public Sub SetMetadataNameForAllOverloads(name As String, kind As SymbolKind, container As NamedTypeSymbol)
Debug.Assert(kind = SymbolKind.Method OrElse kind = SymbolKind.Property)
Dim compilation = container.DeclaringCompilation
Dim overloadedMembers = ArrayBuilder(Of Symbol).GetInstance() ' the set of overloaded symbols.
Dim hasOverloadSpecifier As Boolean = False ' do any overloads have "Overloads" (not counting Overrides)
Dim hasOverrideSpecifier As Boolean = False ' do any overloads have "Overrides"
Dim metadataName As String = Nothing ' the metadata name we have chosen
Try
' Check for overloads or overrides.
' Find all the overloads that we are processing, and if any have "Overloads" or "Overrides"
FindOverloads(name, kind, container, overloadedMembers, hasOverloadSpecifier, hasOverrideSpecifier)
If overloadedMembers.Count = 1 AndAlso Not hasOverloadSpecifier AndAlso Not hasOverrideSpecifier Then
' Quick, common case: one symbol of name in type, no "Overrides" or "Overloads".
' Just use the current name.
overloadedMembers(0).SetMetadataName(overloadedMembers(0).Name)
Return
ElseIf hasOverrideSpecifier Then
' Note: in error conditions (an override didn't exist), this could return Nothing.
' That is dealt with below.
metadataName = SetMetadataNamesOfOverrides(overloadedMembers, compilation)
ElseIf hasOverloadSpecifier Then
metadataName = GetBaseMemberMetadataName(name, kind, container)
End If
If metadataName Is Nothing Then
' We did not get a name from the overrides or base class. Pick the name of the first member
metadataName = NameOfFirstMember(overloadedMembers, compilation)
End If
' We now have the metadata name we want to apply to each non-override member
' (override member names have already been applied)
For Each member In overloadedMembers
If Not (member.IsOverrides AndAlso member.OverriddenMember() IsNot Nothing) Then
member.SetMetadataName(metadataName)
End If
Next
Finally
overloadedMembers.Free()
End Try
End Sub
''' <summary>
''' Collect all overloads in "container" of the given name and kind.
''' Also determine if any have "Overloads" or "Overrides" specifiers.
''' </summary>
Private Sub FindOverloads(name As String,
kind As SymbolKind,
container As NamedTypeSymbol,
overloadsMembers As ArrayBuilder(Of Symbol),
ByRef hasOverloadSpecifier As Boolean,
ByRef hasOverrideSpecifier As Boolean)
For Each member In container.GetMembers(name)
If IsCandidateMember(member, kind) Then
overloadsMembers.Add(member)
If member.IsOverrides Then
hasOverrideSpecifier = True
ElseIf member.IsOverloads Then
hasOverloadSpecifier = True
End If
End If
Next
End Sub
''' <summary>
''' For each member in "overloadedMembers" that is marked Overrides, set its
''' metadata name to be the metadata name of its overridden member. Return the
''' first such name, lexically.
'''
''' Note: can return null if no override member with an actual overridden member was found.
''' </summary>
Private Function SetMetadataNamesOfOverrides(overloadedMembers As ArrayBuilder(Of Symbol), compilation As VisualBasicCompilation) As String
Dim locationOfFirstOverride As Location = Nothing
Dim firstOverrideName As String = Nothing
For Each member In overloadedMembers
If member.IsOverrides Then
Dim overriddenMember As Symbol = member.OverriddenMember()
If overriddenMember IsNot Nothing Then
Dim metadataName As String = overriddenMember.MetadataName
member.SetMetadataName(metadataName)
' Remember the metadata name of the lexically first override
If firstOverrideName Is Nothing OrElse compilation.CompareSourceLocations(member.Locations(0), locationOfFirstOverride) < 0 Then
firstOverrideName = metadataName
locationOfFirstOverride = member.Locations(0)
End If
End If
End If
Next
Return firstOverrideName
End Function
''' <summary>
''' Return the name of the lexically first symbol in "overloadedMembers".
''' </summary>
Private Function NameOfFirstMember(overloadedMembers As ArrayBuilder(Of Symbol), compilation As VisualBasicCompilation) As String
Dim firstName As String = Nothing
Dim locationOfFirstName As Location = Nothing
For Each member In overloadedMembers
Dim memberLocation = member.Locations(0)
If firstName Is Nothing OrElse compilation.CompareSourceLocations(memberLocation, locationOfFirstName) < 0 Then
firstName = member.Name
locationOfFirstName = memberLocation
End If
Next
Return firstName
End Function
''' <summary>
''' Check all accessible, visible members of the base types of container for the given name and kind. If they
''' all have the same case-sensitive metadata name, return that name. Otherwise, return Nothing.
''' </summary>
Private Function GetBaseMemberMetadataName(name As String, kind As SymbolKind, container As NamedTypeSymbol) As String
Dim metadataName As String = Nothing
Dim metadataLocation As Location = Nothing
' We are creating a binder for the first partial declaration, so we can use member lookup to find accessible & visible
' members. For the lookup we are doing, it doesn't matter which partial we use because Imports and Options can't
' affect a lookup that ignores extension methods.
Dim binder = BinderBuilder.CreateBinderForType(DirectCast(container.ContainingModule, SourceModuleSymbol),
container.Locations(0).PossiblyEmbeddedOrMySourceTree(),
container)
Dim result = LookupResult.GetInstance()
binder.LookupMember(result, container, name, 0, LookupOptions.AllMethodsOfAnyArity Or LookupOptions.IgnoreExtensionMethods, useSiteDiagnostics:=Nothing)
If result.IsGoodOrAmbiguous Then
Dim lookupSymbols As ArrayBuilder(Of Symbol) = result.Symbols
If result.Kind = LookupResultKind.Ambiguous AndAlso result.HasDiagnostic AndAlso TypeOf result.Diagnostic Is AmbiguousSymbolDiagnostic Then
lookupSymbols.AddRange(DirectCast(result.Diagnostic, AmbiguousSymbolDiagnostic).AmbiguousSymbols)
End If
For Each foundMember In lookupSymbols
' Go through each member found in a base class or interface
If IsCandidateMember(foundMember, kind) AndAlso foundMember.ContainingType IsNot container Then
If metadataName Is Nothing Then
metadataName = foundMember.MetadataName
Else
' Intentionally using case-sensitive comparison here.
If Not String.Equals(metadataName, foundMember.MetadataName, StringComparison.Ordinal) Then
' We have found two members with conflicting casing of metadata names.
metadataName = Nothing
Exit For
End If
End If
End If
Next
End If
result.Free()
Return metadataName
End Function
Private Function IsCandidateMember(member As Symbol, kind As SymbolKind) As Boolean
Return member.Kind = kind AndAlso Not member.IsAccessor()
End Function
End Module
End Namespace
|
mmitche/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/Source/OverloadingHelper.vb
|
Visual Basic
|
apache-2.0
| 10,337
|
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("GalileoTest")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("GalileoTest")>
<Assembly: AssemblyCopyright("Copyright © 2015")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("75c612b0-0f72-46e7-9964-0f82565d7592")>
' 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")>
|
eclay42/DMF_EWoD_controller
|
DMF_EWoD_PC/DMF_EWoD_PC/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,131
|
#Region "Microsoft.VisualBasic::6d1e1c07af29c6eff8636233d2a8a870, src\metadna\MetaDNA_visual\Algorithm.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:
' Module Algorithm
'
' Function: CreateGraph
'
' /********************************************************************************/
#End Region
Imports System.Runtime.CompilerServices
Imports Microsoft.VisualBasic.Data.visualize.Network
Imports Microsoft.VisualBasic.Data.visualize.Network.FileStream.Generic
Imports Microsoft.VisualBasic.Data.visualize.Network.Graph
Public Module Algorithm
<Extension>
Public Function CreateGraph(metaDNA As XML) As NetworkGraph
Dim g As New NetworkGraph
Dim kegg_compound As Graph.Node
Dim candidate_compound As Graph.Node
Dim edge As Edge
Dim candidateParent As node
Dim seedNode As Graph.Node
For Each compound As compound In metaDNA.compounds
kegg_compound = New Graph.Node With {
.Label = compound.kegg,
.data = New NodeData() With {
.label = compound.kegg,
.origID = compound.kegg,
.Properties = New Dictionary(Of String, String) From {
{NamesOf.REFLECTION_ID_MAPPING_NODETYPE, "kegg_compound"},
{"candidates", compound.size}
}
}
}
Call g.AddNode(kegg_compound)
For Each candidate As unknown In compound.candidates
candidate_compound = New Graph.Node With {
.Label = candidate.name,
.data = New NodeData With {
.label = candidate.name,
.origID = candidate.Msn,
.Properties = New Dictionary(Of String, String) From {
{NamesOf.REFLECTION_ID_MAPPING_NODETYPE, "MetaDNA.candidate"},
{"intensity", candidate.intensity},
{"infer.depth", candidate.length}
}
}
}
edge = New Edge With {
.U = kegg_compound,
.V = candidate_compound,
.weight = candidate.edges.Length,
.data = New EdgeData With {
.label = $"{candidate_compound.Label} infer as {kegg_compound.Label}",
.Properties = New Dictionary(Of String, String) From {
{NamesOf.REFLECTION_ID_MAPPING_INTERACTION_TYPE, "is_candidate"},
{"score.forward", candidate.scores.ElementAtOrNull(0)},
{"score.reverse", candidate.scores.ElementAtOrNull(1)}
}
}
}
Call g.AddNode(candidate_compound)
Call g.AddEdge(edge)
' add common seed node
' is a metaDNA seed from reference library
' spectrum alignment result
seedNode = g.GetElementByID(candidate.edges(Scan0).ms1)
If seedNode Is Nothing Then
' 还没有添加进入网络之中
seedNode = New Graph.Node With {
.Label = candidate.edges(Scan0).ms1,
.data = New NodeData With {
.label = candidate.edges(Scan0).ms1,
.origID = candidate.edges(Scan0).ms2,
.Properties = New Dictionary(Of String, String) From {
{NamesOf.REFLECTION_ID_MAPPING_NODETYPE, "seed"}
}
}
}
Call g.AddNode(seedNode)
End If
For i As Integer = 0 To candidate.length - 2
seedNode = g.GetElementByID(candidate.edges(i).ms1)
edge = New Edge With {
.data = New EdgeData With {
.label = $"{candidate.edges(i).kegg} -> {candidate.edges(i + 1).kegg}",
.Properties = New Dictionary(Of String, String) From {
{NamesOf.REFLECTION_ID_MAPPING_INTERACTION_TYPE, "infer"}
}
},
.U = seedNode,
.V = g.GetElementByID(candidate.edges(i + 1).ms1)
}
Call g.AddEdge(edge)
Next
' add edge that infer to current candidate
candidateParent = candidate.edges.Last
edge = New Edge With {
.data = New EdgeData With {
.label = $"{candidateParent.kegg} -> {compound.kegg}",
.Properties = New Dictionary(Of String, String) From {
{NamesOf.REFLECTION_ID_MAPPING_INTERACTION_TYPE, "infer"}
}
},
.U = g.GetElementByID(candidateParent.ms1),
.V = g.GetElementByID(candidate.name)
}
Call g.AddEdge(edge)
Next
Next
Return g
End Function
End Module
|
xieguigang/MassSpectrum-toolkits
|
src/metadna/MetaDNA_visual/Algorithm.vb
|
Visual Basic
|
mit
| 6,797
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "PAS_fCRetencion_PatenteProveedores"
'-------------------------------------------------------------------------------------------'
Partial Class PAS_fCRetencion_PatenteProveedores
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 loComandoSeleccionar As New StringBuilder()
loComandoSeleccionar.AppendLine("SELECT Cuentas_Pagar.Tip_Ori AS Tipo_Origen,")
loComandoSeleccionar.AppendLine(" Cuentas_Pagar.Fec_Ini AS Fecha_Retencion,")
loComandoSeleccionar.AppendLine(" Cuentas_Pagar.Doc_Ori AS Numero_Pago,")
loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Cod_Tip AS Tipo_Documento,")
loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Doc_Ori AS Numero_Documento,")
loComandoSeleccionar.AppendLine(" Renglones_Pagos.Control AS Control_Documento,")
loComandoSeleccionar.AppendLine(" Renglones_Pagos.Factura AS Factura_Documento,")
loComandoSeleccionar.AppendLine(" Renglones_Pagos.Fec_Ini AS Fecha_Factura,")
loComandoSeleccionar.AppendLine(" Renglones_Pagos.Mon_Net AS Monto_Documento,")
loComandoSeleccionar.AppendLine(" Renglones_Pagos.Mon_Abo AS Monto_Abonado,")
loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Num_Com AS Comprobante,")
loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Mon_Bas AS Base_Retencion,")
loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Por_Ret AS Porcentaje_Retenido,")
loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Mon_Sus AS Sustraendo_Retenido,")
loComandoSeleccionar.AppendLine(" Retenciones_Documentos.Mon_Ret AS Monto_Retenido,")
loComandoSeleccionar.AppendLine(" Cuentas_Pagar.Cod_Pro AS Cod_Pro,")
loComandoSeleccionar.AppendLine(" Proveedores.Nom_Pro AS Nom_Pro,")
loComandoSeleccionar.AppendLine(" Proveedores.Rif AS Rif,")
loComandoSeleccionar.AppendLine(" Proveedores.Nit AS Nit,")
loComandoSeleccionar.AppendLine(" Proveedores.Dir_Fis AS Direccion")
loComandoSeleccionar.AppendLine("FROM Cuentas_Pagar")
loComandoSeleccionar.AppendLine(" JOIN Pagos ON Pagos.documento = Cuentas_Pagar.Doc_Ori")
loComandoSeleccionar.AppendLine(" JOIN Retenciones_Documentos ON Retenciones_Documentos.Documento = Pagos.documento")
loComandoSeleccionar.AppendLine(" AND Retenciones_Documentos.doc_des = Cuentas_Pagar.documento")
loComandoSeleccionar.AppendLine(" AND Retenciones_Documentos.clase = 'PATENTE'")
loComandoSeleccionar.AppendLine(" JOIN Renglones_Pagos ON Renglones_Pagos.Documento = Pagos.documento")
loComandoSeleccionar.AppendLine(" AND Renglones_Pagos.Doc_Ori = Retenciones_Documentos.Doc_Ori")
loComandoSeleccionar.AppendLine(" JOIN Proveedores ON Proveedores.Cod_Pro = Cuentas_Pagar.Cod_Pro")
loComandoSeleccionar.AppendLine(" LEFT JOIN Retenciones ON Retenciones.Cod_Ret = Retenciones_Documentos.Cod_Ret")
loComandoSeleccionar.AppendLine(" WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal)
'Me.mEscribirConsulta(loComandoSeleccionar.ToString)
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString(), "curReportes")
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.goFormatos.mCargarInforme("PAS_fCRetencion_PatenteProveedores", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrPAS_fCRetencion_PatenteProveedores.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 '
'-------------------------------------------------------------------------------------------'
' RJG: 09/04/15: Codigo inicial, a partir de rCRetencion_ISLRProveedores. '
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
PAS_fCRetencion_PatenteProveedores.aspx.vb
|
Visual Basic
|
mit
| 6,438
|
Imports System.Threading
Friend NotInheritable Class Program
Private Sub New()
End Sub
''' <summary>
''' The main entry point for the application.
''' </summary>
<STAThread>
Public Shared Sub Main()
' Redirect standard output and error
' Add the event handler for handling UI thread exceptions to the event.
AddHandler Application.ThreadException, AddressOf UIThreadException
' Set the unhandled exception mode to force all Windows Forms errors to go through our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException)
' Add the event handler for handling non-UI thread exceptions to the event.
AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf CurrentDomain_UnhandledException
' Run the application
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New Form1)
End Sub
' Handle the UI exceptions by showing a dialog box, and asking the user whether or not they wish to abort execution.
Private Shared Sub UIThreadException(sender As Object, t As ThreadExceptionEventArgs)
Dim result As DialogResult = DialogResult.Cancel
Try
' Todo: make this translatable
ErrorWindow.ShowErrorDialog("An unhandled exception has occurred." & vbLf & "You can continue running the program, but please report this error.", t.Exception, True)
Catch
Try
' Todo: make this translatable
MessageBox.Show("A fatal error has occurred, and the details could not be displayed. Please report this to the author.", "Error", MessageBoxButtons.OK, MessageBoxIcon.[Stop])
Finally
Application.[Exit]()
End Try
End Try
' Exits the program when the user clicks Abort.
If result = DialogResult.Abort Then
Application.[Exit]()
End If
End Sub
' Handle the UI exceptions by showing a dialog box, and asking the user whether
' or not they wish to abort execution.
' NOTE: This exception cannot be kept from terminating the application - it can only
' log the event, and inform the user about it.
Private Shared Sub CurrentDomain_UnhandledException(sender As Object, e As UnhandledExceptionEventArgs)
Try
Dim ex = DirectCast(e.ExceptionObject, Exception)
' Todo: make this translatable
ErrorWindow.ShowErrorDialog("An unhandled exception has occurred." & vbLf & "The program must now close.", ex, False)
Catch
Try
' Todo: make this translatable
MessageBox.Show("A fatal non-UI error has occurred, and the details could not be displayed. Please report this to the author.", "Error", MessageBoxButtons.OK, MessageBoxIcon.[Stop])
Finally
Application.[Exit]()
End Try
End Try
End Sub
End Class
|
evandixon/DotNet3dsToolkit
|
Old/ToolkitForm/Program.vb
|
Visual Basic
|
mit
| 3,038
|
Imports SistFoncreagro.BussinessEntities
Imports SistFoncreagro.DataAccess
Public Class RequisitoAdicionalBL : Implements IRequisitoAdicionalBL
Dim factoryrepository As IRequisitoAdicionalRepository
Public Sub New()
factoryrepository = New RequisitoAdicionalRepository
End Sub
Public Sub DeleteREQUISITOADICIONAL(ByVal idRequisito As Integer) Implements IRequisitoAdicionalBL.DeleteREQUISITOADICIONAL
factoryrepository.DeleteREQUISITOADICIONAL(idRequisito)
End Sub
Public Function GetAllFromREQUISITOADICIONAL() As System.Collections.Generic.List(Of BussinessEntities.RequisitoAdicional) Implements IRequisitoAdicionalBL.GetAllFromREQUISITOADICIONAL
Return factoryrepository.GetAllFromREQUISITOADICIONAL()
End Function
Public Function GetREQUISITOADICIONALByIdPosicion(ByVal IdPosicion As Integer) As System.Collections.Generic.List(Of BussinessEntities.RequisitoAdicional) Implements IRequisitoAdicionalBL.GetREQUISITOADICIONALByIdPosicion
Return factoryrepository.GetREQUISITOADICIONALByIdPosicion(IdPosicion)
End Function
Public Function GetREQUISITOADICIONALByIdRequisitoAndIdPosicion(ByVal IdRequisito As Integer, ByVal IdPosicion As Integer) As BussinessEntities.RequisitoAdicional Implements IRequisitoAdicionalBL.GetREQUISITOADICIONALByIdRequisitoAndIdPosicion
Return factoryrepository.GetREQUISITOADICIONALByIdRequisitoAndIdPosicion(IdRequisito, IdPosicion)
End Function
Public Function SaveREQUISITOADICIONAL(ByVal RequisitoAdicional As BussinessEntities.RequisitoAdicional) As Integer Implements IRequisitoAdicionalBL.SaveREQUISITOADICIONAL
Return factoryrepository.SaveREQUISITOADICIONAL(RequisitoAdicional)
End Function
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.BussinesLogic/RequisitoAdicionalBL.vb
|
Visual Basic
|
mit
| 1,752
|
Imports System.IO
Imports Grasshopper.Kernel.Parameters
Public Class FileWatcher
Inherits OwlComponentBase
Sub New()
MyBase.New("File Watch", "Watcher", "Watch file for changes", "Owl", "Scripting")
Me.Message = DateTime.Now.ToLongTimeString
End Sub
Protected Overrides ReadOnly Property Icon As Bitmap
Get
Return My.Resources.Icons_new_06
End Get
End Property
Public Overrides ReadOnly Property ComponentGuid As Guid
Get
Return New Guid("{E5BE32D4-6868-4A1C-A190-D46A5F046979}")
End Get
End Property
Public Overrides ReadOnly Property Exposure As GH_Exposure
Get
Return GH_Exposure.primary
End Get
End Property
Protected Overrides Sub RegisterInputParams(pManager As GH_InputParamManager)
pManager.AddParameter(New Param_FilePath, "Directory", "D", "Directory to watch", GH_ParamAccess.tree)
Me.Params.Input(0).Optional = True
End Sub
Protected Overrides Sub RegisterOutputParams(pManager As GH_OutputParamManager)
pManager.AddTextParameter("Path", "P", "Path will be outputted here whenever a change happens", GH_ParamAccess.item)
End Sub
Public Overrides Sub RemovedFromDocument(document As GH_Document)
MyBase.RemovedFromDocument(document)
RemoveWatcher()
End Sub
Dim watcher As FileSystemWatcher = Nothing
Dim filename As String = ""
Protected Overrides Sub SolveInstance(DA As IGH_DataAccess)
Me.Message = DateTime.Now.ToLongTimeString
Dim FilePath As String = GetInput(DA)
If FilePath = "" Then
If watcher IsNot Nothing Then
RemoveWatcher()
filename = ""
End If
Else
If FilePath <> filename Then
RemoveWatcher()
filename = FilePath
AddWatcher(filename)
DA.SetData(0, filename)
Else
If IsFileReady(filename) Then
DA.SetData(0, filename)
Else
DA.AbortComponentSolution()
End If
End If
End If
End Sub
Private Function GetInput(DA As IGH_DataAccess) As String
Dim ghs As New GH_Structure(Of GH_String)
If Not DA.GetDataTree(0, ghs) Then Return ""
Dim str As GH_String = TryCast(ghs.AllData(True)(0), GH_String)
If str Is Nothing Then Return ""
Return str.Value
End Function
Private Sub AddWatcher(FilePath As String)
Dim pth As String = Path.GetDirectoryName(FilePath)
Dim fname As String = Path.GetFileName(FilePath)
Dim watch As FileSystemWatcher = Nothing
watch = New FileSystemWatcher(pth)
AddHandler watch.Created, AddressOf FileChanged
AddHandler watch.Changed, AddressOf FileChanged
AddHandler watch.Deleted, AddressOf FileChanged
AddHandler watch.Renamed, AddressOf FileChanged
watch.EnableRaisingEvents = True
watcher = watch
End Sub
Private Sub RemoveWatcher()
If watcher Is Nothing Then Return
RemoveHandler watcher.Created, AddressOf FileChanged
RemoveHandler watcher.Changed, AddressOf FileChanged
RemoveHandler watcher.Deleted, AddressOf FileChanged
RemoveHandler watcher.Renamed, AddressOf FileChanged
watcher.Dispose()
End Sub
Dim act As New Action(AddressOf Exp)
Private Sub EvalComponent()
Rhino.RhinoApp.MainApplicationWindow.Invoke(act)
End Sub
Private Sub Exp()
ExpireSolution(True)
Message = DateTime.Now.ToLongTimeString
End Sub
Private Sub FileChanged(sender As Object, e As FileSystemEventArgs)
If Path.GetFileName(e.FullPath) <> Path.GetFileName(filename) Then Return
Dim flags As WatcherChangeTypes = WatcherChangeTypes.Created + WatcherChangeTypes.Renamed + WatcherChangeTypes.Changed
If e.ChangeType & flags Then
If IsFileReady(filename) Then
EvalComponent()
End If
If e.ChangeType = WatcherChangeTypes.Deleted Then
RemoveWatcher()
EvalComponent()
End If
End If
End Sub
Private Function IsFileReady(Path As String) As Boolean
Try
Using str = File.Open(Path, FileMode.Open, FileAccess.ReadWrite)
Return True
End Using
Catch ex As Exception
Return False
End Try
End Function
End Class
|
mateuszzwierzycki/Owl
|
Owl.GH/Components/Owl/Scripting/FileWatcher.vb
|
Visual Basic
|
mit
| 4,547
|
Public Class TimerClass
Dim _TargetTimeString As String
Public Enum TimePeriod
Daily
Hourly
End Enum
Public ReadOnly Property GetInterval() As Integer
Get
Return DateDiff(DateInterval.Second, Now, get_Next_ImportDate) * 1000
End Get
End Property
Public ReadOnly Property GetDate() As Date
Get
Return get_Next_ImportDate()
End Get
End Property
Public Sub New(ByVal TargetTime As String)
_TargetTimeString = TargetTime
End Sub
Private Function get_Next_ImportDate() As Date
Dim tmpDateStr As String = Now.ToString("yyyy-MM-dd")
Dim currHour, targetHour As Integer
Dim currMinute, targetMinute As Integer
Dim targetDate As Date = Nothing
targetHour = CDate(tmpDateStr & " " & _TargetTimeString).Hour
targetMinute = CDate(tmpDateStr & " " & _TargetTimeString).Minute
currHour = Now.Hour
currMinute = Now.Minute
If currHour >= targetHour AndAlso currMinute >= targetMinute Then
targetDate = CDate(DateAdd(DateInterval.Day, 1, Now).ToString("yyyy-MM-dd") & " " & _TargetTimeString)
Else
targetDate = CDate(tmpDateStr & " " & _TargetTimeString)
End If
Return targetDate
End Function
End Class
|
diblos/itramas.protocol_emulator
|
code/emu_common/class/TimerClass.vb
|
Visual Basic
|
mit
| 1,342
|
Namespace Data
Public Class WatcherTimer
Implements IWatcher
Public Event Changed() Implements IWatcher.Changed
Private WithEvents tmrRefresh As System.Timers.Timer = Nothing
Public Sub New(dInterval As Double)
tmrRefresh = New System.Timers.Timer
tmrRefresh.Stop()
tmrRefresh.Interval = dInterval
End Sub
Public Sub Start() Implements IWatcher.Start
OnChanged()
End Sub
Public Sub [Stop]() Implements IWatcher.Stop
tmrRefresh.Stop()
End Sub
Private Sub tmrRefresh_Elapsed(sender As Object, e As System.Timers.ElapsedEventArgs) Handles tmrRefresh.Elapsed
OnChanged()
End Sub
Private Sub OnChanged()
tmrRefresh.Stop()
RaiseEvent Changed()
tmrRefresh.Start()
End Sub
#Region " IDisposable "
Private _Disposed As Boolean = False
Protected Overridable Sub Dispose(disposing As Boolean)
If Not Me._Disposed Then
If disposing Then
Me.Stop()
End If
End If
Me._Disposed = True
End Sub
Public Sub Dispose() Implements IWatcher.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
End Class
End Namespace
|
nublet/DMS
|
DMS.Base/Data/DBWatcher/WatcherTimer.vb
|
Visual Basic
|
mit
| 1,397
|
' 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
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.VisualStudio.Commanding
Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands
Imports Roslyn.Utilities
Imports VSCommanding = Microsoft.VisualStudio.Commanding
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
Partial Friend Class ModernCompletionTestState
Inherits TestStateBase
Friend Const RoslynItem = "RoslynItem"
Friend ReadOnly EditorCompletionCommandHandler As VSCommanding.ICommandHandler
' Do not call directly. Use TestStateFactory
Friend Sub New(workspaceElement As XElement,
extraCompletionProviders As CompletionProvider(),
excludedTypes As List(Of Type),
extraExportedTypes As List(Of Type),
includeFormatCommandHandler As Boolean,
workspaceKind As String)
MyBase.New(
workspaceElement,
extraCompletionProviders,
excludedTypes:=excludedTypes,
extraExportedTypes,
includeFormatCommandHandler,
workspaceKind:=workspaceKind)
EditorCompletionCommandHandler = GetExportedValues(Of VSCommanding.ICommandHandler)().
Single(Function(e As VSCommanding.ICommandHandler) e.GetType().FullName = "Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Implementation.CompletionCommandHandler")
End Sub
#Region "Editor Related Operations"
Public Overrides Sub SendEscape()
' The legacy handler implements VSCommanding.IChainedCommandHandler(Of EscapeKeyCommandArgs)
Dim handler = DirectCast(EditorCompletionCommandHandler, VSCommanding.ICommandHandler(Of EscapeKeyCommandArgs))
MyBase.SendEscape(Sub(a, n, c) handler.ExecuteCommand(a, Sub() SignatureHelpAfterCompletionCommandHandler.ExecuteCommand(a, n, c), c), Sub() Return)
End Sub
Public Overrides Sub SendDownKey()
' The legacy handler implements VSCommanding.IChainedCommandHandler(Of DownKeyCommandArgs)
Dim handler = DirectCast(EditorCompletionCommandHandler, VSCommanding.ICommandHandler(Of DownKeyCommandArgs))
MyBase.SendDownKey(Sub(a, n, c) handler.ExecuteCommand(a, Sub() SignatureHelpAfterCompletionCommandHandler.ExecuteCommand(a, n, c), c), Sub()
EditorOperations.MoveLineDown(extendSelection:=False)
End Sub)
End Sub
Public Overrides Sub SendUpKey()
' The legacy handler implements VSCommanding.IChainedCommandHandler(Of UpKeyCommandArgs)
Dim handler = DirectCast(EditorCompletionCommandHandler, VSCommanding.ICommandHandler(Of UpKeyCommandArgs))
MyBase.SendUpKey(Sub(a, n, c) handler.ExecuteCommand(a, Sub() SignatureHelpAfterCompletionCommandHandler.ExecuteCommand(a, n, c), c), Sub()
EditorOperations.MoveLineUp(extendSelection:=False)
End Sub)
End Sub
Public Overrides Sub SendPageUp()
' The legacy handler implements VSCommanding.IChainedCommandHandler(Of PageUpKeyCommandArgs)
Dim handler = DirectCast(EditorCompletionCommandHandler, VSCommanding.ICommandHandler(Of PageUpKeyCommandArgs))
MyBase.SendPageUp(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overrides Sub SendCut()
' The legacy handler implements VSCommanding.IChainedCommandHandler(Of CutCommandArgs)
Dim handler = DirectCast(EditorCompletionCommandHandler, VSCommanding.ICommandHandler(Of CutCommandArgs))
MyBase.SendCut(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overrides Sub SendPaste()
' The legacy handler implements VSCommanding.IChainedCommandHandler(Of PasteCommandArgs)
Dim handler = DirectCast(EditorCompletionCommandHandler, VSCommanding.ICommandHandler(Of PasteCommandArgs))
MyBase.SendPaste(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overrides Sub SendInvokeCompletionList()
' The legacy handler implements VSCommanding.IChainedCommandHandler(Of InvokeCompletionListCommandArgs)
Dim handler = DirectCast(EditorCompletionCommandHandler, VSCommanding.ICommandHandler(Of InvokeCompletionListCommandArgs))
MyBase.SendInvokeCompletionList(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overrides Sub SendInsertSnippetCommand()
' The legacy handler implements VSCommanding.IChainedCommandHandler(Of InsertSnippetCommandArgs)
Dim handler = DirectCast(EditorCompletionCommandHandler, VSCommanding.ICommandHandler(Of InsertSnippetCommandArgs))
MyBase.SendInsertSnippetCommand(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overrides Sub SendSurroundWithCommand()
' The legacy handler implements VSCommanding.IChainedCommandHandler(Of SurroundWithCommandArgs)
Dim handler = DirectCast(EditorCompletionCommandHandler, VSCommanding.ICommandHandler(Of SurroundWithCommandArgs))
MyBase.SendSurroundWithCommand(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overrides Sub SendSave()
' The legacy handler implements VSCommanding.IChainedCommandHandler(Of SaveCommandArgs)
Dim handler = DirectCast(EditorCompletionCommandHandler, VSCommanding.ICommandHandler(Of SaveCommandArgs))
MyBase.SendSave(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overrides Sub SendSelectAll()
' The legacy handler implements VSCommanding.IChainedCommandHandler(Of SelectAllCommandArgs)
Dim handler = DirectCast(EditorCompletionCommandHandler, VSCommanding.ICommandHandler(Of SelectAllCommandArgs))
MyBase.SendSelectAll(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overrides Sub SendDeleteWordToLeft()
Dim compHandler = DirectCast(EditorCompletionCommandHandler, VSCommanding.ICommandHandler(Of WordDeleteToStartCommandArgs))
MyBase.SendWordDeleteToStart(Sub(a, n, c) compHandler.ExecuteCommand(a, n, c), AddressOf MyBase.SendDeleteWordToLeft)
End Sub
Public Overrides Sub ToggleSuggestionMode()
Dim handler = DirectCast(EditorCompletionCommandHandler, VSCommanding.ICommandHandler(Of ToggleCompletionModeCommandArgs))
MyBase.ToggleSuggestionMode(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Protected Overrides Function GetHandler(Of T As VSCommanding.ICommandHandler)() As T
Return DirectCast(EditorCompletionCommandHandler, T)
End Function
#End Region
#Region "Completion Operations"
Public Overrides Sub SendCommitUniqueCompletionListItem()
' The legacy handler implements VSCommanding.IChainedCommandHandler(Of CommitUniqueCompletionListItemCommandArgs)
Dim handler = DirectCast(EditorCompletionCommandHandler, VSCommanding.ICommandHandler(Of CommitUniqueCompletionListItemCommandArgs))
MyBase.SendCommitUniqueCompletionListItem(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overrides Async Function AssertNoCompletionSession() As Task
Await WaitForAsynchronousOperationsAsync()
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
If session Is Nothing Then
Return
End If
If session.IsDismissed Then
Return
End If
Dim completionItems = session.GetComputedItems(CancellationToken.None)
' During the computation we can explicitly dismiss the session or we can return no items.
' Each of these conditions mean that there is no active completion.
Assert.True(session.IsDismissed OrElse completionItems.Items.Count() = 0)
End Function
Public Overrides Sub AssertNoCompletionSessionWithNoBlock()
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
If session Is Nothing Then
Return
End If
If session.IsDismissed Then
Return
End If
' If completionItems cannot be calculated in 5 seconds, no session exists.
Dim task1 = Task.Delay(5000)
Dim task2 = Task.Run(
Sub()
Dim completionItems = session.GetComputedItems(CancellationToken.None)
' In the non blocking mode, we are not interested for a session appeared later than in 5 seconds.
If task1.Status = TaskStatus.Running Then
' During the computation we can explicitly dismiss the session or we can return no items.
' Each of these conditions mean that there is no active completion.
Assert.True(session.IsDismissed OrElse completionItems.Items.Count() = 0)
End If
End Sub)
Task.WaitAny(task1, task2)
End Sub
Public Overrides Async Function AssertCompletionSession(Optional projectionsView As ITextView = Nothing) As Task
Dim view = If(projectionsView, TextView)
Await WaitForAsynchronousOperationsAsync()
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(view)
Assert.NotNull(session)
End Function
Public Overrides Async Function AssertCompletionSessionAfterTypingHash() As Task
' starting with the modern completion implementation, # is treated as an IntelliSense trigger
Await AssertCompletionSession()
End Function
Public Overrides Sub AssertItemsInOrder(expectedOrder As String())
AssertNoAsynchronousOperationsRunning()
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
Assert.NotNull(session)
Dim items = session.GetComputedItems(CancellationToken.None).Items
Assert.Equal(expectedOrder.Count, items.Count)
For i = 0 To expectedOrder.Count - 1
Assert.Equal(expectedOrder(i), items(i).DisplayText)
Next
End Sub
Public Overrides Async Function AssertSelectedCompletionItem(
Optional displayText As String = Nothing,
Optional displayTextSuffix As String = Nothing,
Optional description As String = Nothing,
Optional isSoftSelected As Boolean? = Nothing,
Optional isHardSelected As Boolean? = Nothing,
Optional shouldFormatOnCommit As Boolean? = Nothing,
Optional inlineDescription As String = Nothing,
Optional projectionsView As ITextView = Nothing) As Task
' inlineDescription is not used in this implementation.
Dim view = If(projectionsView, TextView)
Await WaitForAsynchronousOperationsAsync()
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(view)
Assert.NotNull(session)
Dim items = session.GetComputedItems(CancellationToken.None)
If isSoftSelected.HasValue Then
If isSoftSelected.Value Then
Assert.True(items.UsesSoftSelection, "Current completion is not soft-selected. Expected: soft-selected")
Else
Assert.False(items.UsesSoftSelection, "Current completion is soft-selected. Expected: not soft-selected")
End If
End If
If isHardSelected.HasValue Then
If isHardSelected.Value Then
Assert.True(Not items.UsesSoftSelection, "Current completion is not hard-selected. Expected: hard-selected")
Else
Assert.True(items.UsesSoftSelection, "Current completion is hard-selected. Expected: not hard-selected")
End If
End If
If displayText IsNot Nothing Then
Assert.NotNull(items.SelectedItem)
If displayTextSuffix IsNot Nothing Then
Assert.NotNull(items.SelectedItem)
Assert.Equal(displayText + displayTextSuffix, items.SelectedItem.DisplayText)
Else
Assert.Equal(displayText, items.SelectedItem.DisplayText)
End If
End If
If shouldFormatOnCommit.HasValue Then
Assert.Equal(shouldFormatOnCommit.Value, GetRoslynCompletionItem(items.SelectedItem).Rules.FormatOnCommit)
End If
If description IsNot Nothing Then
Dim document = Me.Workspace.CurrentSolution.Projects.First().Documents.First()
Dim service = CompletionService.GetService(document)
Dim roslynItem = GetRoslynCompletionItem(items.SelectedItem)
Dim itemDescription = Await service.GetDescriptionAsync(document, roslynItem)
Assert.Equal(description, itemDescription.Text)
End If
If inlineDescription IsNot Nothing Then
Assert.Equal(inlineDescription, items.SelectedItem.Suffix)
End If
End Function
Public Overrides Async Function AssertSessionIsNothingOrNoCompletionItemLike(text As String) As Task
Await WaitForAsynchronousOperationsAsync()
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
If Not session Is Nothing Then
AssertCompletionItemsDoNotContainAny({text})
End If
End Function
Public Overrides Function GetSelectedItem() As CompletionItem
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
Assert.NotNull(session)
Dim items = session.GetComputedItems(CancellationToken.None)
Return GetRoslynCompletionItem(items.SelectedItem)
End Function
Public Overrides Sub CalculateItemsIfSessionExists()
AssertNoAsynchronousOperationsRunning()
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
If session IsNot Nothing Then
Dim item = session.GetComputedItems(CancellationToken.None).SelectedItem
End If
End Sub
Private Function GetRoslynCompletionItemOpt(editorCompletionItem As Data.CompletionItem) As CompletionItem
Dim roslynCompletionItem As CompletionItem = Nothing
If editorCompletionItem?.Properties.TryGetProperty(RoslynItem, roslynCompletionItem) Then
Return roslynCompletionItem
End If
Return Nothing
End Function
Public Overrides Function GetCompletionItems() As IList(Of CompletionItem)
WaitForAsynchronousOperationsAsync()
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
Assert.NotNull(session)
Return session.GetComputedItems(CancellationToken.None).Items.Select(Function(item) GetRoslynCompletionItem(item)).ToList()
End Function
Private Shared Function GetRoslynCompletionItem(item As Data.CompletionItem) As CompletionItem
Return DirectCast(item.Properties(RoslynItem), CompletionItem)
End Function
Public Overrides Sub RaiseFiltersChanged(args As CompletionItemFilterStateChangedEventArgs)
Throw ExceptionUtilities.Unreachable
End Sub
Public Overrides Function GetCompletionItemFilters() As ImmutableArray(Of CompletionItemFilter)
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides Function HasSuggestedItem() As Boolean
AssertNoAsynchronousOperationsRunning()
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
Assert.NotNull(session)
Dim computedItems = session.GetComputedItems(CancellationToken.None)
Return computedItems.SuggestionItem IsNot Nothing
End Function
Public Overrides Function IsSoftSelected() As Boolean
AssertNoAsynchronousOperationsRunning()
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
Assert.NotNull(session)
Dim computedItems = session.GetComputedItems(CancellationToken.None)
Return computedItems.UsesSoftSelection
End Function
Public Overrides Sub SendSelectCompletionItem(displayText As String)
AssertNoAsynchronousOperationsRunning()
Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView)
Dim operations = DirectCast(session, IAsyncCompletionSessionOperations)
operations.SelectCompletionItem(session.GetComputedItems(CancellationToken.None).Items.Single(Function(i) i.DisplayText = displayText))
End Sub
Public Overrides Sub SendSelectCompletionItemThroughPresenterSession(item As CompletionItem)
Throw ExceptionUtilities.Unreachable
End Sub
#End Region
End Class
End Namespace
|
MichalStrehovsky/roslyn
|
src/EditorFeatures/TestUtilities2/Intellisense/ModernCompletionTestState.vb
|
Visual Basic
|
apache-2.0
| 18,837
|
'
' This file is generated at http://www.netmftoolbox.com/tools/img_to_bin/
' Original filename: netduino.bmp
' Orientation: column-major order
' Bit order: Most significant bit
' Inverted: no
' Timestamp: 2012-12-24 17:12:36
'
Namespace Bitmaps
''' <summary>
''' netduino.bmp bitmap data
''' </summary>
Public Module netduino_bmp
''' <summary>Bitmap width</summary>
Public Width As Integer = 168
''' <summary>Bitmap height</summary>
Public Height As Integer = 40
''' <summary>Bitmap data</summary>
Public Data() As Byte = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0,
&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0,
&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0,
&H0, &H0, &H0, &H3F, &HFF, &HC0, &H0, &H0, &HFF, &HFF, &HC0, &H0, &H1, &HFF, &HFF, &HC0,
&H0, &H3, &HFF, &HFF, &HC0, &H0, &H3, &HF0, &H0, &H0, &H0, &H7, &HC0, &H0, &H0, &H0,
&H7, &H80, &H0, &H0, &H0, &H7, &H80, &H0, &H0, &H0, &H7, &H80, &H0, &H0, &H0, &H7,
&H80, &H0, &H0, &H0, &H7, &H80, &H0, &H0, &H0, &H7, &HC0, &H0, &H0, &H0, &H7, &HE0,
&H0, &H0, &H0, &H3, &HFF, &HFF, &H80, &H0, &H3, &HFF, &HFF, &HC0, &H0, &H1, &HFF, &HFF,
&HC0, &H0, &H0, &HFF, &HFF, &HC0, &H0, &H0, &H1F, &HFF, &HC0, &H0, &H0, &H0, &H0, &H0,
&H0, &H0, &H7, &H80, &H0, &H0, &H0, &H3F, &HF0, &H0, &H0, &H0, &H7F, &HFC, &H0, &H0,
&H0, &HFF, &HFE, &H0, &H0, &H1, &HFF, &HFF, &H0, &H0, &H3, &HF8, &H3F, &H80, &H0, &H3,
&HE1, &HCF, &H80, &H0, &H7, &HC1, &HE7, &HC0, &H0, &H7, &H83, &HE7, &HC0, &H0, &H7, &H83,
&HC3, &HC0, &H0, &H7, &H87, &HC3, &HC0, &H0, &H7, &H8F, &H83, &HC0, &H0, &H7, &H8F, &H83,
&HC0, &H0, &H7, &H9F, &H3, &HC0, &H0, &H7, &HDE, &H7, &HC0, &H0, &H7, &HFE, &H7, &HC0,
&H0, &H3, &HFC, &HF, &H80, &H0, &H3, &HFC, &H3F, &H80, &H0, &H1, &HF8, &HFF, &H0, &H0,
&H0, &HF8, &HFE, &H0, &H0, &H0, &H70, &HFC, &H0, &H0, &H0, &H0, &HF0, &H0, &H0, &H0,
&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &HFF, &HFF, &HF8, &H0, &H0, &HFF, &HFF,
&HFE, &H0, &H0, &HFF, &HFF, &HFF, &H0, &H0, &HFF, &HFF, &HFF, &H80, &H0, &HFF, &HFF, &HFF,
&HC0, &H0, &H7, &H80, &H7, &HC0, &H0, &H7, &H80, &H3, &HC0, &H0, &H7, &H80, &H3, &HC0,
&H0, &H7, &H80, &H3, &HC0, &H0, &H7, &H80, &H3, &HC0, &H0, &H7, &H80, &H3, &HC0, &H0,
&H7, &H80, &H3, &HC0, &H0, &H0, &H7, &H80, &H0, &H0, &H0, &H3F, &HF0, &H0, &H0, &H0,
&H7F, &HFC, &H0, &H0, &H0, &HFF, &HFE, &H0, &H0, &H1, &HF8, &H7F, &H0, &H0, &H3, &HE0,
&HF, &H80, &H0, &H3, &HC0, &H7, &H80, &H0, &H7, &H80, &H7, &H80, &H0, &H7, &H80, &H3,
&HC0, &H0, &H7, &H80, &H3, &HC0, &H0, &H7, &H80, &H3, &HC0, &H0, &H7, &H80, &H3, &HC0,
&H0, &H7, &H80, &H3, &HC0, &H0, &H7, &H80, &H3, &HC0, &H0, &H3, &H80, &H7, &H80, &H0,
&H3, &HC0, &HF, &H80, &H0, &H0, &H0, &H1F, &H80, &H7, &HFC, &H3F, &HFF, &H0, &HF, &HFF,
&HFF, &HFE, &H0, &HF, &HFF, &HFF, &HFC, &H0, &HF, &HFF, &HFF, &HF0, &H0, &H0, &H0, &H0,
&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H7, &HFF, &HF8,
&H0, &H0, &H7, &HFF, &HFE, &H0, &H0, &H7, &HFF, &HFF, &H0, &H0, &H7, &HFF, &HFF, &H0,
&H0, &H0, &H0, &HF, &H80, &H0, &H0, &H0, &H7, &H80, &H0, &H0, &H0, &H3, &HC0, &H0,
&H0, &H0, &H3, &HC0, &H0, &H0, &H0, &H3, &HC0, &H0, &H0, &H0, &H3, &HC0, &H0, &H0,
&H0, &H3, &HC0, &H0, &H0, &H0, &H7, &HC0, &H0, &H0, &H0, &HF, &H80, &H0, &H0, &H0,
&H3F, &H80, &H0, &H7, &HFF, &HFF, &H0, &H0, &H7, &HFF, &HFE, &H0, &H0, &H7, &HFF, &HFC,
&H0, &H0, &H3, &HFF, &HC0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0,
&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H1, &HC7, &HFF, &HFF, &H80, &H1,
&HE7, &HFF, &HFF, &HC0, &H3, &HE7, &HFF, &HFF, &HC0, &H1, &HE7, &HFF, &HFF, &HC0, &H0, &HC0,
&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0,
&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H3F, &HFF, &HC0, &H0, &H0, &HFF, &HFF,
&HC0, &H0, &H1, &HFF, &HFF, &HC0, &H0, &H3, &HFF, &HFF, &H80, &H0, &H3, &HE0, &H0, &H0,
&H0, &H7, &HC0, &H0, &H0, &H0, &H7, &H80, &H0, &H0, &H0, &H7, &H80, &H0, &H0, &H0,
&H7, &H80, &H0, &H0, &H0, &H7, &H80, &H0, &H0, &H0, &H7, &H80, &H0, &H0, &H0, &H7,
&H80, &H0, &H0, &H0, &H3, &HC0, &H0, &H0, &H0, &H3, &HF0, &H0, &H0, &H0, &H1, &HFF,
&HFF, &HC0, &H0, &H0, &HFF, &HFF, &HC0, &H0, &H0, &H7F, &HFF, &HC0, &H0, &H0, &HF, &HFF,
&H80, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H1F, &HF0, &H0,
&H0, &H0, &H7F, &HFC, &H0, &H0, &H0, &HFF, &HFE, &H0, &H0, &H1, &HFF, &HFF, &H0, &H0,
&H3, &HF0, &H1F, &H0, &H0, &H3, &HE0, &HF, &H80, &H0, &H7, &HC0, &H7, &H80, &H0, &H7,
&H80, &H3, &HC0, &H0, &H7, &H80, &H3, &HC0, &H0, &H7, &H80, &H3, &HC0, &H0, &H7, &H0,
&H3, &HC0, &H0, &H7, &H80, &H3, &HC0, &H0, &H7, &H80, &H3, &HC0, &H0, &H7, &H80, &H3,
&HC0, &H0, &H3, &HC0, &H7, &H80, &H0, &H3, &HE0, &HF, &H80, &H0, &H1, &HF8, &H3F, &H0,
&H0, &H1, &HFF, &HFE, &H0, &H0, &H0, &HFF, &HFC, &H0, &H0, &H0, &H3F, &HF8, &H0, &H0,
&H0, &HF, &HE0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0,
&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0,
&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0
}
End Module
End Namespace
|
JakeLardinois/NetMF.Toolbox
|
Samples/Visual Basic/Thermal Printer/Bitmaps/netduino_bmp.vb
|
Visual Basic
|
apache-2.0
| 5,293
|
' Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports EnvDTE
Imports VB = Microsoft.VisualBasic
Imports Microsoft.VisualStudio.Shell.Interop
Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Drawing
Imports System.IO
Imports System.Windows.Forms
Imports System.Windows.Forms.Design
Namespace Microsoft.VisualStudio.Editors.Common
''' <summary>
''' Utilities relating to the Visual Studio shell, services, etc.
''' </summary>
''' <remarks></remarks>
Friend NotInheritable Class ShellUtil
''' <summary>
''' Gets a color from the shell's color service. If for some reason this fails, returns the supplied
''' default color.
''' </summary>
''' <param name="VsUIShell">The IVsUIShell interface that must also implement IVsUIShell2 (if not, or if Nothing, default color is returned)</param>
''' <param name="VsSysColorIndex">The color index to look up.</param>
''' <param name="DefaultColor">The default color to return if the call fails.</param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function GetColor(ByVal VsUIShell As IVsUIShell, ByVal VsSysColorIndex As __VSSYSCOLOREX, ByVal DefaultColor As Color) As Color
Return GetColor(TryCast(VsUIShell, IVsUIShell2), VsSysColorIndex, DefaultColor)
End Function
''' <summary>
''' Gets a color from the shell's color service. If for some reason this fails, returns the supplied
''' default color.
''' </summary>
''' <param name="VsUIShell2">The IVsUIShell2 interface to use (if Nothing, default color is returned)</param>
''' <param name="VsSysColorIndex">The color index to look up.</param>
''' <param name="DefaultColor">The default color to return if the call fails.</param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function GetColor(ByVal VsUIShell2 As IVsUIShell2, ByVal VsSysColorIndex As __VSSYSCOLOREX, ByVal DefaultColor As Color) As Color
If VsUIShell2 IsNot Nothing Then
Dim abgrValue As System.UInt32
Dim Hr As Integer = VsUIShell2.GetVSSysColorEx(VsSysColorIndex, abgrValue)
If VSErrorHandler.Succeeded(Hr) Then
Return COLORREFToColor(abgrValue)
End If
End If
Debug.Fail("Unable to get color from the shell, using a predetermined default color instead." & VB.vbCrLf & "Color Index = " & VsSysColorIndex & ", Default Color = &h" & VB.Hex(DefaultColor.ToArgb))
Return DefaultColor
End Function
''' <summary>
''' Converts a COLORREF value (as UInteger) to System.Drawing.Color
''' </summary>
''' <param name="abgrValue">The UInteger COLORREF value</param>
''' <returns>The System.Drawing.Color equivalent.</returns>
''' <remarks></remarks>
Private Shared Function COLORREFToColor(ByVal abgrValue As System.UInt32) As Color
Return Color.FromArgb(CInt(abgrValue And &HFFUI), CInt((abgrValue And &HFF00UI) >> 8), CInt((abgrValue And &HFF0000UI) >> 16))
End Function
''' <summary>
''' Retrieves the window that should be used as the owner of all dialogs and messageboxes.
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Friend Shared Function GetDialogOwnerWindow(ByVal serviceProvider As IServiceProvider) As IWin32Window
Dim dialogOwner As IWin32Window = Nothing
Dim UIService As IUIService = DirectCast(serviceProvider.GetService(GetType(IUIService)), IUIService)
If UIService IsNot Nothing Then
dialogOwner = UIService.GetDialogOwnerWindow()
End If
Debug.Assert(dialogOwner IsNot Nothing, "Couldn't get DialogOwnerWindow")
Return dialogOwner
End Function
''' <summary>
''' Given an IVsCfg, get its configuration and platform names.
''' </summary>
''' <param name="Config">The IVsCfg to get the configuration and platform name from.</param>
''' <param name="ConfigName">[out] The configuration name.</param>
''' <param name="PlatformName">[out] The platform name.</param>
''' <remarks></remarks>
Public Shared Sub GetConfigAndPlatformFromIVsCfg(ByVal Config As IVsCfg, ByRef ConfigName As String, ByRef PlatformName As String)
Dim DisplayName As String = Nothing
VSErrorHandler.ThrowOnFailure(Config.get_DisplayName(DisplayName))
Debug.Assert(DisplayName IsNot Nothing AndAlso DisplayName <> "")
'The configuration name and platform name are separated by a vertical bar. The configuration
' part is the only portion that is user-defined. Although the shell doesn't allow vertical bar
' in the configuration name, let's not take chances, so we'll find the last vertical bar in the
' string.
Dim IndexOfBar As Integer = DisplayName.LastIndexOf("|"c)
If IndexOfBar = 0 Then
'It is possible that some old projects' configurations may not have the platform in the name.
' In this case, the correct thing to do is assume the platform is "Any CPU"
ConfigName = DisplayName
PlatformName = "Any CPU"
Else
ConfigName = DisplayName.Substring(0, IndexOfBar)
PlatformName = DisplayName.Substring(IndexOfBar + 1)
End If
Debug.Assert(ConfigName <> "" AndAlso PlatformName <> "")
End Sub
''' <summary>
''' Returns whether or not we're in simplified config mode for this project, which means that
''' we hide the configuration/platform comboboxes.
''' </summary>
''' <param name="ProjectHierarchy">The hierarchy to check</param>
''' <remarks></remarks>
Public Shared Function GetIsSimplifiedConfigMode(ByVal ProjectHierarchy As IVsHierarchy) As Boolean
Try
If ProjectHierarchy IsNot Nothing Then
Dim Project As Project = DTEProjectFromHierarchy(ProjectHierarchy)
If Project IsNot Nothing Then
Return CanHideConfigurationsForProject(ProjectHierarchy) AndAlso Not ToolsOptionsShowAdvancedBuildConfigurations(Project.DTE)
End If
End If
Catch ex As Exception
Common.RethrowIfUnrecoverable(ex)
Debug.Fail("Exception determining if we're in simplified configuration mode - default to advanced configs mode")
End Try
Return False 'Default to advanced configs
End Function
''' <summary>
''' Returns whether it's permissible to hide configurations for this project. This should normally
''' be returned as true until the user changes any of the default configurations (i.e., adds, deletes
''' or removes a configuration, at which point the project wants to show the advanced settings
''' from then on out).
''' </summary>
''' <param name="ProjectHierarchy">The project hierarchy to check</param>
''' <remarks></remarks>
Private Shared Function CanHideConfigurationsForProject(ByVal ProjectHierarchy As IVsHierarchy) As Boolean
Dim ReturnValue As Boolean = False 'If failed to get config value, default to not hiding configs
Dim ConfigProviderObject As Object = Nothing
Dim ConfigProvider As IVsCfgProvider2 = Nothing
If VSErrorHandler.Succeeded(ProjectHierarchy.GetProperty(VSITEMID.ROOT, __VSHPROPID.VSHPROPID_ConfigurationProvider, ConfigProviderObject)) Then
ConfigProvider = TryCast(ConfigProviderObject, IVsCfgProvider2)
End If
If ConfigProvider IsNot Nothing Then
Dim ValueObject As Object = Nothing
'Ask the project system if configs can be hidden
Dim hr As Integer = ConfigProvider.GetCfgProviderProperty(__VSCFGPROPID2.VSCFGPROPID_HideConfigurations, ValueObject)
If VSErrorHandler.Succeeded(hr) AndAlso TypeOf ValueObject Is Boolean Then
ReturnValue = CBool(ValueObject)
Else
Debug.Fail("Failed to get VSCFGPROPID_HideConfigurations from project config provider")
ReturnValue = False
End If
End If
Return ReturnValue
End Function
''' <summary>
''' Retrieves the current value of the "Show Advanced Build Configurations" options in
''' Tools.Options.
''' </summary>
''' <param name="DTE">The DTE extensibility object</param>
''' <remarks></remarks>
Private Shared Function ToolsOptionsShowAdvancedBuildConfigurations(ByVal DTE As DTE) As Boolean
'Now check for if the Tools option setting to show Advanced Config Settings is on
Dim ShowAdvancedBuildIntValue As Integer = -1
Dim ShowValue As Boolean
Dim ProjAndSolutionProperties As EnvDTE.Properties
Const EnvironmentCategory As String = "Environment"
Const ProjectsAndSolution As String = "ProjectsandSolution"
Try
ProjAndSolutionProperties = DTE.Properties(EnvironmentCategory, ProjectsAndSolution)
If ProjAndSolutionProperties IsNot Nothing Then
ShowValue = CBool(ProjAndSolutionProperties.Item("ShowAdvancedBuildConfigurations").Value)
Else
Debug.Fail("Couldn't get ProjAndSolutionProperties property from DTE.Properties")
ShowValue = True 'If can't get to the property, assume advanced mode
End If
Catch ex As Exception
Common.RethrowIfUnrecoverable(ex)
Debug.Fail("Couldn't get ShowAdvancedBuildConfigurations property from tools.options")
Return True 'default to showing advanced
End Try
Return ShowValue
End Function
''' <summary>
''' Given an IVsHierarchy, fetch the DTE Project for it, if it exists. For project types that
''' don't support this, returns Nothing (e.g. C++).
''' </summary>
''' <param name="ProjectHierarchy"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function DTEProjectFromHierarchy(ByVal ProjectHierarchy As IVsHierarchy) As Project
If ProjectHierarchy Is Nothing Then
Return Nothing
End If
Dim hr As Integer
Dim Obj As Object = Nothing
hr = ProjectHierarchy.GetProperty(VSITEMID.ROOT, __VSHPROPID.VSHPROPID_ExtObject, Obj)
If VSErrorHandler.Succeeded(hr) Then
Return TryCast(Obj, EnvDTE.Project)
End If
Return Nothing
End Function
''' <summary>
''' Given a DTE Project, get the hierarchy corresponding to it.
''' </summary>
''' <param name="sp"></param>
''' <param name="project"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function VsHierarchyFromDTEProject(ByVal sp As IServiceProvider, ByVal project As Project) As IVsHierarchy
Debug.Assert(sp IsNot Nothing)
If sp Is Nothing OrElse project Is Nothing Then
Return Nothing
End If
Dim vssolution As IVsSolution = TryCast(sp.GetService(GetType(IVsSolution)), IVsSolution)
If vssolution IsNot Nothing Then
Dim hierarchy As IVsHierarchy = Nothing
If VSErrorHandler.Succeeded(vssolution.GetProjectOfUniqueName(project.UniqueName, hierarchy)) Then
Return hierarchy
Else
Debug.Fail("Why didn't we get the hierarchy from the project?")
End If
End If
Return Nothing
End Function
''' <summary>
''' Returns the IVsCfgProvider2 for the given project hierarchy
''' </summary>
''' <param name="ProjectHierarchy"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function GetConfigProvider(ByVal ProjectHierarchy As IVsHierarchy) As IVsCfgProvider2
'CONSIDER: This will not work for all project types because they do not support this property.
Dim ConfigProvider As Object = Nothing
If VSErrorHandler.Failed(ProjectHierarchy.GetProperty(VSITEMID.ROOT, __VSHPROPID.VSHPROPID_ConfigurationProvider, ConfigProvider)) Then
Return Nothing
End If
Return TryCast(ConfigProvider, IVsCfgProvider2)
End Function
''' <summary>
''' Given a hierarhy, determine if this is a devices project...
''' </summary>
''' <param name="hierarchy"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function IsDeviceProject(ByVal hierarchy As IVsHierarchy) As Boolean
If hierarchy Is Nothing Then
Debug.Fail("I can't determine if this is a devices project from a NULL hierarchy!?")
Return False
End If
Dim vsdProperty As Object = Nothing
Dim hr As Integer = hierarchy.GetProperty(VSITEMID.ROOT, 8000, vsdProperty)
If Interop.NativeMethods.Succeeded(hr) AndAlso vsdProperty IsNot Nothing AndAlso TryCast(vsdProperty, IVSDProjectProperties) IsNot Nothing Then
Return True
End If
Return False
End Function
''' <summary>
''' Is this a web (Venus WSP or WAP project)
''' </summary>
''' <param name="hierarchy"></param>
''' <returns></returns>
''' <remarks></remarks>
Friend Shared Function IsWebProject(ByVal hierarchy As IVsHierarchy) As [Boolean]
Const WebAppProjectGuid As String = "{349c5851-65df-11da-9384-00065b846f21}"
If hierarchy Is Nothing Then
Return False
End If
Try
' VS WAP Projects are traditional vb/c# apps, but 'flavored' to add functionality
' for ASP.Net. This flavoring is marked by adding a guid to the AggregateProjectType guids
' Get the project type guid list
Dim guidList As New System.Collections.Generic.List(Of Guid)
Dim WAPGuid As New Guid(WebAppProjectGuid)
Dim aggregatableProject As IVsAggregatableProject = TryCast(hierarchy, IVsAggregatableProject)
If aggregatableProject IsNot Nothing Then
Dim guidStrings As String = Nothing
' The project guids string looks like "{Guid 1};{Guid 2};...{Guid n}" with Guid n the inner most
aggregatableProject.GetAggregateProjectTypeGuids(guidStrings)
For Each guidString As String In guidStrings.Split(New Char() {";"c})
If guidString <> "" Then
' Insert Guid to the front
Try
Dim flavorGuid As New Guid(guidString)
If WAPGuid.Equals(flavorGuid) Then
Return True
End If
Catch ex As Exception
System.Diagnostics.Debug.Fail(String.Format("We received a broken guid string from IVsAggregatableProject: '{0}'", guidStrings))
End Try
End If
Next
Else
' Should not happen, but if they decide to make this project type non-flavored.
Dim typeGuid As Guid = Nothing
VSErrorHandler.ThrowOnFailure(hierarchy.GetGuidProperty(VSITEMID.ROOT, __VSHPROPID.VSHPROPID_TypeGuid, typeGuid))
If Guid.Equals(WAPGuid, typeGuid) Then
Return True
End If
End If
Catch ex As Exception
' We failed. Assume that this isn't a web project...
End Try
Return False
End Function
''' <summary>
'''
''' </summary>
''' <param name="fileName">IN: name of the file to get the document info from</param>
''' <param name="rdt">IN: Running document table to find the info in</param>
''' <param name="hierarchy">OUT: Hierarchy that the document was found in</param>
''' <param name="itemid">OUT: Found itemId</param>
''' <param name="readLocks">OUT: Number of read locks for the document</param>
''' <param name="editLocks">OUT: Number of edit locks on the document</param>
''' <param name="docCookie">OUT: A cookie for the doc, 0 if the doc isn't found in the RDT</param>
''' <remarks></remarks>
Friend Shared Sub GetDocumentInfo(ByVal fileName As String, ByVal rdt As IVsRunningDocumentTable, ByRef hierarchy As IVsHierarchy, ByRef readLocks As UInteger, ByRef editLocks As UInteger, ByRef itemid As UInteger, ByRef docCookie As UInteger)
If fileName Is Nothing Then Throw New ArgumentNullException("fileName")
If rdt Is Nothing Then Throw New ArgumentNullException("rdt")
'
' Initialize out parameters...
'
readLocks = 0
editLocks = 0
itemid = VSITEMID.NIL
docCookie = 0
hierarchy = Nothing
' Now, look in the RDT to see if this doc data already has an edit lock on it.
' if it does, we keep it and we begin tracking changes. Otherwise, we
' let it get disposed.
'
Dim flags As UInteger
Dim localPunk As IntPtr = IntPtr.Zero
Dim localFileName As String = Nothing
Try
VSErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument(CType(_VSRDTFLAGS.RDT_NoLock, UInteger), fileName, hierarchy, itemid, localPunk, docCookie))
Finally
If (localPunk <> IntPtr.Zero) Then
System.Runtime.InteropServices.Marshal.Release(localPunk)
localPunk = IntPtr.Zero
End If
End Try
Try
VSErrorHandler.ThrowOnFailure(rdt.GetDocumentInfo(docCookie, flags, readLocks, editLocks, localFileName, hierarchy, itemid, localPunk))
Finally
If (localPunk <> IntPtr.Zero) Then
System.Runtime.InteropServices.Marshal.Release(localPunk)
localPunk = IntPtr.Zero
End If
End Try
End Sub
''' <summary>
''' Get the name of a project item as well as a SFG generated child item (if any)
''' Used in order to check out all dependent files for a project item
''' </summary>
''' <param name="projectitem">The parent project item that is to be checked out</param>
''' <param name="suffix">Suffix added by the single file generator</param>
''' <param name="requireExactlyOneChild">
''' Only add the child item to the list of items to check out if there is exactly one child
''' project item.
''' </param>
''' <param name="exclude">
''' Predicate used to filter items that we don't want to check out.
''' The predicate is passed each full path to the project item, and if it returns
''' true, the item will not be added to the list of items to check out.
''' </param>
''' <returns>
''' The list of items that are to be checked out
''' </returns>
''' <remarks></remarks>
Friend Shared Function FileNameAndGeneratedFileName(ByVal projectitem As EnvDTE.ProjectItem, _
Optional ByVal suffix As String = ".Designer", _
Optional ByVal requireExactlyOneChild As Boolean = True, _
Optional ByVal exclude As Predicate(Of String) = Nothing) _
As Collections.Generic.List(Of String)
Dim result As New List(Of String)
If projectitem IsNot Nothing AndAlso projectitem.Name <> "" Then
result.Add(DTEUtils.FileNameFromProjectItem(projectitem))
End If
' For each child, check if the name matches the filename for the generated file
If projectitem IsNot Nothing AndAlso projectitem.ProjectItems IsNot Nothing Then
' If we require exactly one child, we better check the number of children
' and bail if more than one child.
If projectitem.ProjectItems.Count = 1 OrElse Not requireExactlyOneChild Then
For childNo As Integer = 1 To projectitem.ProjectItems.Count
Try
Dim childItemName As String = DTEUtils.FileNameFromProjectItem(projectitem.ProjectItems.Item(childNo))
' Make sure that the filename matches what we expect.
If String.Equals( _
System.IO.Path.GetFileNameWithoutExtension(childItemName), _
System.IO.Path.GetFileNameWithoutExtension(DTEUtils.FileNameFromProjectItem(projectitem)) & suffix, _
StringComparison.OrdinalIgnoreCase) _
Then
' If we've got a filter predicate, we remove anything that we've been
' told we shouldn't check out...
Dim isExcluded As Boolean = exclude IsNot Nothing AndAlso exclude.Invoke(childItemName)
If Not isExcluded Then
result.Add(childItemName)
End If
End If
Catch ex As ArgumentException
' If the child name wasn't a file moniker, then we may throw an argument exception here...
'
' Don't really care about that scenario!
End Try
Next
End If
End If
Return result
End Function
'''<summary>
''' a fake IVSDProjectProperties definition. We only use this to check whether the project supports this interface, but don't pay attention to the detail.
'''</summary>
<System.Runtime.InteropServices.ComImport(), System.Runtime.InteropServices.ComVisible(True), System.Runtime.InteropServices.Guid("1A27878B-EE15-41CE-B427-58B10390C821"), System.Runtime.InteropServices.InterfaceType(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsDual)> _
Private Interface IVSDProjectProperties
End Interface
''' <summary>
''' Wrapper class for IVsShell.OnBroadcastMessage
''' </summary>
''' <remarks></remarks>
Friend Class BroadcastMessageEventsHelper
Implements IVsBroadcastMessageEvents
Implements IDisposable
Public Event BroadcastMessage(ByVal msg As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr)
'Cookie for use with IVsShell.{Advise,Unadvise}BroadcastMessages
Private m_CookieBroadcastMessages As UInteger
Private m_ServiceProvider As IServiceProvider
Friend Sub New(ByVal sp As IServiceProvider)
m_ServiceProvider = sp
ConnectBroadcastEvents()
End Sub
#Region "Helper methods to advise/unadvise broadcast messages from the IVsShell service"
Friend Sub ConnectBroadcastEvents()
Dim VSShell As IVsShell = Nothing
If m_ServiceProvider IsNot Nothing Then
VSShell = DirectCast(m_ServiceProvider.GetService(GetType(IVsShell)), IVsShell)
End If
If VSShell IsNot Nothing Then
VSErrorHandler.ThrowOnFailure(VSShell.AdviseBroadcastMessages(Me, m_CookieBroadcastMessages))
Else
Debug.Fail("Unable to get IVsShell for broadcast messages")
End If
End Sub
Private Sub DisconnectBroadcastMessages()
If m_CookieBroadcastMessages <> 0 Then
Dim VsShell As IVsShell = DirectCast(m_ServiceProvider.GetService(GetType(IVsShell)), IVsShell)
If VsShell IsNot Nothing Then
VSErrorHandler.ThrowOnFailure(VsShell.UnadviseBroadcastMessages(m_CookieBroadcastMessages))
m_CookieBroadcastMessages = 0
End If
End If
End Sub
#End Region
''' <summary>
''' Forward to overridable OnBrodcastMessage handler
''' </summary>
''' <param name="msg"></param>
''' <param name="wParam"></param>
''' <param name="lParam"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Function IVsBroadcastMessageEvents_OnBroadcastMessage(ByVal msg As UInteger, ByVal wParam As System.IntPtr, ByVal lParam As System.IntPtr) As Integer Implements IVsBroadcastMessageEvents.OnBroadcastMessage
OnBroadcastMessage(msg, wParam, lParam)
Return Interop.NativeMethods.S_OK
End Function
''' <summary>
''' Raise OnBroadcastMessage event. Can be overridden to implement custom handling of broadcast messages
''' </summary>
''' <param name="msg"></param>
''' <param name="wParam"></param>
''' <param name="lParam"></param>
''' <remarks></remarks>
Protected Overridable Sub OnBroadcastMessage(ByVal msg As UInteger, ByVal wParam As System.IntPtr, ByVal lParam As System.IntPtr)
RaiseEvent BroadcastMessage(msg, wParam, lParam)
End Sub
#Region "Standard dispose pattern - the only thing we need to do is to unadvise events..."
Private disposed As Boolean = False
' IDisposable
Private Overloads Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposed Then
If disposing Then
DisconnectBroadcastMessages()
End If
End If
Me.disposed = True
End Sub
#Region " IDisposable Support "
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Overloads Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Protected Overrides Sub Finalize()
' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
Dispose(False)
MyBase.Finalize()
End Sub
#End Region
#End Region
End Class
''' <summary>
''' Monitor and set font when font changes...
''' </summary>
''' <remarks></remarks>
Friend NotInheritable Class FontChangeMonitor
Inherits BroadcastMessageEventsHelper
' Control that we are going to set the font on (if any)
Private m_Control As System.Windows.Forms.Control
Private m_ServiceProvider As IServiceProvider
''' <summary>
''' Create a new instance...
''' </summary>
''' <param name="sp"></param>
''' <param name="ctrl"></param>
''' <param name="SetFontInitially">If true, set the font of the provided control when this FontChangeMonitor is created</param>
''' <remarks></remarks>
Public Sub New(ByVal sp As IServiceProvider, ByVal ctrl As System.Windows.Forms.Control, ByVal SetFontInitially As Boolean)
MyBase.new(sp)
Debug.Assert(sp IsNot Nothing, "Why did we get a NULL service provider!?")
Debug.Assert(ctrl IsNot Nothing, "Why didn't we get a control to provide the dialog font for!?")
m_ServiceProvider = sp
m_Control = ctrl
If SetFontInitially Then
m_Control.Font = GetDialogFont(sp)
End If
End Sub
''' <summary>
''' Override to get WM_SETTINGCHANGE notifications and set the font accordingly...
''' </summary>
''' <param name="msg"></param>
''' <param name="wParam"></param>
''' <param name="lParam"></param>
''' <remarks></remarks>
Protected Overrides Sub OnBroadcastMessage(ByVal msg As UInteger, ByVal wParam As System.IntPtr, ByVal lParam As System.IntPtr)
MyBase.OnBroadcastMessage(msg, wParam, lParam)
If m_Control IsNot Nothing Then
If msg = Interop.win.WM_SETTINGCHANGE Then
' Only set font if it is different from the current font...
Dim newFont As Font = GetDialogFont(m_ServiceProvider)
If Not newFont.Equals(m_Control.Font) Then
m_Control.Font = newFont
End If
End If
End If
End Sub
''' <summary>
''' Pick current dialog font...
''' </summary>
''' <value></value>
''' <remarks></remarks>
Friend Shared ReadOnly Property GetDialogFont(ByVal ServiceProvider As IServiceProvider) As Font
Get
If ServiceProvider IsNot Nothing Then
Dim uiSvc As System.Windows.Forms.Design.IUIService = CType(ServiceProvider.GetService(GetType(System.Windows.Forms.Design.IUIService)), System.Windows.Forms.Design.IUIService)
If uiSvc IsNot Nothing Then
Return CType(uiSvc.Styles("DialogFont"), Font)
End If
End If
Debug.Fail("Couldn't get a IUIService... cheating instead :)")
Return System.Windows.Forms.Form.DefaultFont
End Get
End Property
End Class
''' <summary>
''' Determine if the specified custom tool is registered for the current project system
''' </summary>
''' <param name="hierarchy">Hierarchy to check if the custom tool is registered for</param>
''' <param name="customToolName">Name of custom tool to look for</param>
''' <returns>True if registered, false otherwise</returns>
''' <remarks></remarks>
Friend Shared Function IsCustomToolRegistered(ByVal hierarchy As IVsHierarchy, ByVal customToolName As String) As Boolean
If hierarchy Is Nothing Then Throw New ArgumentNullException("hierarchy")
If customToolName Is Nothing Then Throw New ArgumentNullException("customToolName")
' All project systems support empty string (= no custom tool)
If customToolName.Length = 0 Then Return True
Dim sfgFactory As IVsSingleFileGeneratorFactory = TryCast(hierarchy, IVsSingleFileGeneratorFactory)
If sfgFactory Is Nothing Then
' If the hierarchy doesn't support IVsSingleFileGeneratorFactory, then we assume that
' the custom tools aren't supported by the project system.
Return False
End If
Dim pbGeneratesDesignTimeSource As Integer
Dim pbGeneratesSharedDesignTimeSource As Integer
Dim pbUseTempPEFlag As Integer
Dim pguidGenerator As System.Guid
Dim hr As Integer = sfgFactory.GetGeneratorInformation(customToolName, pbGeneratesDesignTimeSource, pbGeneratesSharedDesignTimeSource, pbUseTempPEFlag, pguidGenerator)
If VSErrorHandler.Succeeded(hr) Then
Return True
Else
Return False
End If
End Function
End Class
End Namespace
|
chkn/fsharp
|
vsintegration/src/vs/FsPkgs/FSharp.Project/VB/FSharpPropPage/Common/ShellUtil.vb
|
Visual Basic
|
apache-2.0
| 33,161
|
Imports System.Xml
Imports System.Web.Configuration
Imports System.Text.RegularExpressions
Imports Protean.Cms.Cart
Namespace Providers
Namespace Payment
Public Class Pay360
Public Sub New()
'do nothing
End Sub
Public Sub Initiate(ByRef _AdminXforms As Object, ByRef _AdminProcess As Object, ByRef _Activities As Object, ByRef MemProvider As Object, ByRef myWeb As Cms)
MemProvider.AdminXforms = New AdminXForms(myWeb)
MemProvider.AdminProcess = New AdminProcess(myWeb)
MemProvider.AdminProcess.oAdXfm = MemProvider.AdminXforms
MemProvider.Activities = New Activities()
End Sub
Public Class AdminXForms
Inherits Cms.Admin.AdminXforms
Private Const mcModuleName As String = "Providers.Providers.Eonic.AdminXForms"
Sub New(ByRef aWeb As Cms)
MyBase.New(aWeb)
End Sub
End Class
Public Class AdminProcess
Inherits Cms.Admin
Dim _oAdXfm As Protean.Providers.Payment.Pay360.AdminXForms
Public Property oAdXfm() As Object
Set(ByVal value As Object)
_oAdXfm = value
End Set
Get
Return _oAdXfm
End Get
End Property
Sub New(ByRef aWeb As Cms)
MyBase.New(aWeb)
End Sub
End Class
Public Class Activities
Inherits Protean.Providers.Payment.DefaultProvider.Activities
Private Const mcModuleName As String = "Providers.Payment.Pay360.Activities"
Private myWeb As Protean.Cms
Protected moPaymentCfg As XmlNode
Private nTransactionMode As TransactionMode
Enum TransactionMode
Live = 0
Test = 1
Fail = 2
End Enum
Private ScheduleIntervals() As String = {"yearly", "half-yearly", "quarterly", "monthly", "weekly", "daily"}
Public Overloads Function GetPaymentForm(ByRef oWeb As Protean.Cms, ByRef oCart As Cms.Cart, ByRef oOrder As XmlElement, Optional returnCmd As String = "cartCmd=SubmitPaymentDetails") As xForm
PerfMon.Log("PaymentProviders", "GetPaymentForm")
Dim sSql As String
Dim ccXform As xForm
Dim Xform3dSec As xForm = Nothing
Dim bIsValid As Boolean
Dim err_msg As String = ""
Dim err_msg_log As String = ""
Dim sProcessInfo As String = ""
Dim aResponse() As String
Dim oDictResp As Hashtable
Dim cResponse As String
Dim oDictOpt As Hashtable = New Hashtable
Dim sSubmitPath As String = oCart.mcPagePath & returnCmd
Dim i As Integer
Dim nPos As Integer
Dim sOpts As String
Dim cOrderType As String
Dim bCv2 As Boolean = False
Dim b3DSecure As Boolean = False
Dim b3DAuthorised As Boolean = False
Dim sRedirectURL As String = ""
Dim sPaymentRef As String = ""
Dim cProcessInfo As String = "payGetPaymentForm"
'Get the payment options into a hashtable
Dim oPay360Cfg As XmlNode
Dim bSavePayment As Boolean = False
Dim bAllowSavePayment As Boolean = False
Dim sProfile As String = ""
Try
myWeb = oWeb
moPaymentCfg = WebConfigurationManager.GetWebApplicationSection("protean/payment")
oPay360Cfg = moPaymentCfg.SelectSingleNode("provider[@name='Pay360']")
oDictOpt = xmlTools.xmlToHashTable(oPay360Cfg, "value")
Dim oEwProv As Protean.Cms.Cart.PaymentProviders = New PaymentProviders(myWeb)
'Get values form cart
oEwProv.mcCurrency = IIf(oCart.mcCurrencyCode = "", oCart.mcCurrency, oCart.mcCurrencyCode)
oEwProv.mcCurrencySymbol = oCart.mcCurrencySymbol
If oOrder.GetAttribute("payableType") = "" Then
oEwProv.mnPaymentAmount = oOrder.GetAttribute("total")
Else
oEwProv.mnPaymentAmount = oOrder.GetAttribute("payableAmount")
oEwProv.mnPaymentMaxAmount = oOrder.GetAttribute("total")
oEwProv.mcPaymentType = oOrder.GetAttribute("payableType")
End If
oEwProv.mnCartId = oCart.mnCartId
oEwProv.mcPaymentOrderDescription = "Ref:" & oCart.OrderNoPrefix & CStr(oCart.mnCartId) & " An online purchase from: " & oCart.mcSiteURL & " on " & niceDate(Now) & " " & TimeValue(Now)
oEwProv.mcCardHolderName = oOrder.SelectSingleNode("Contact[@type='Billing Address']/GivenName").InnerText
If sProfile <> "" Then
oPay360Cfg = moPaymentCfg.SelectSingleNode("provider[@name='Pay360' and @profile='" & sProfile & "']")
Else
oPay360Cfg = moPaymentCfg.SelectSingleNode("provider[@name='Pay360']")
End If
' Get the payment options
'oPay360Cfg = moPaymentCfg.SelectSingleNode("provider[@name='SecPay']")
oDictOpt = xmlTools.xmlToHashTable(oPay360Cfg, "value")
Select Case oDictOpt("opperationMode")
Case "true"
nTransactionMode = TransactionMode.Test
Case "false"
nTransactionMode = TransactionMode.Fail
Case "live"
nTransactionMode = TransactionMode.Live
End Select
' override the currency
If oDictOpt.ContainsKey("currency") Then oDictOpt.Remove("currency")
oDictOpt.Add("currency", oEwProv.mcCurrency)
' Set common variables
If oDictOpt("validateCV2") = "on" Then bCv2 = True
If oDictOpt("secure3d") = "on" Then b3DSecure = True
If oDictOpt("allowSavePayment") = "on" Then bAllowSavePayment = True
'Load the Xform
ccXform = oEwProv.creditCardXform(oOrder, "PayForm", sSubmitPath, oDictOpt("cardsAccepted"), bCv2, "Make Payment of " & FormatNumber(oEwProv.mnPaymentAmount, 2) & " " & oDictOpt("currency") & " by Credit/Debit Card", b3DSecure, , , bAllowSavePayment)
If b3DSecure Then
'check for return from aquiring bank
If myWeb.moRequest("MD") <> "" Then
b3DAuthorised = True
End If
End If
If ccXform.valid Or b3DAuthorised Then
' Set up card options
sOpts = "test_status=" & oDictOpt("opperationMode")
sOpts = sOpts & ",dups=false,card_type=" & myWeb.moRequest("creditCard/type")
' Account for scheduled payments from the payment config.
Dim scheduleInterval As String = (oDictOpt("scheduleInterval") & "").ToLower
Dim scheduleMaxRepeats As String = oDictOpt("scheduleMaxRepeats") & ""
If Not String.IsNullOrEmpty(scheduleInterval) _
AndAlso Array.IndexOf(ScheduleIntervals, scheduleInterval) >= 0 Then
Dim maxRepeats As Integer
If Not String.IsNullOrEmpty(scheduleMaxRepeats) _
AndAlso IsNumeric(scheduleMaxRepeats) _
AndAlso Convert.ToInt16(scheduleMaxRepeats) > 0 Then
maxRepeats = scheduleMaxRepeats
Else
maxRepeats = -1
End If
' We need to send through an immediate payment - ie, the actual payment
' and then schedule the same payment based on the interval
Dim scheduleDate As Date
Select Case scheduleInterval
Case "yearly"
scheduleDate = Today.AddYears(1)
Case "half-yearly"
scheduleDate = Today.AddMonths(6)
Case "quarterly"
scheduleDate = Today.AddMonths(3)
Case "monthly"
scheduleDate = Today.AddMonths(1)
Case "weekly"
scheduleDate = Today.AddDays(7)
Case "daily"
scheduleDate = Today.AddDays(1)
End Select
sOpts &= ",repeat=" & Format(scheduleDate, "yyyyMMdd")
sOpts &= "/" & scheduleInterval
sOpts &= "/" & maxRepeats.ToString
sOpts &= ":" & oEwProv.mnPaymentAmount.ToString
End If
' Currency - if no currency then use GBP
If oEwProv.mcCurrency <> "" Then
sOpts = sOpts & ",currency=" & UCase(oEwProv.mcCurrency)
Else
sOpts = sOpts & ",currency=GBP"
End If
' Optional - CV2
If bCv2 Then
sOpts = sOpts & ",cv2=" & myWeb.moRequest("creditCard/CV2")
End If
' Optional - 3DSecure
If oDictOpt("opperationMode") = "true" And b3DSecure Then
sOpts = sOpts & ",test_mpi_status=true"
End If
' If test mode, then we must turn on cv2-avs checks - mandatory Visa mandate May 2009
If LCase(oDictOpt("opperationMode")) = "true" Or LCase(oDictOpt("opperationMode")) = "false" Then
sOpts = sOpts & ",default_cv2avs=ALL MATCH"
End If
If LCase(oDictOpt("transactionType")) = "defer" Or LCase(oDictOpt("transactionType")) = "deferred" Then
If IsNumeric(oDictOpt("ccDeferDays")) And IsNumeric(oDictOpt("dcDeferDays")) Then
sOpts &= ",deferred=reuse:" & oDictOpt("ccDeferDays") & ":" & oDictOpt("dcDeferDays")
Else
sOpts &= ",deferred=true"
End If
End If
If oDictOpt("digest") = "on" Then
Dim cDigest As String = ""
If Not oDictOpt("accountId") = "secpay" Then
cDigest = CStr(oEwProv.mnCartId) & CStr(oEwProv.mnPaymentAmount) & CStr(oDictOpt("accountPassword"))
Else
cDigest = "secpay"
End If
Dim encode As New System.Text.UnicodeEncoding
Dim inputDigest() As Byte = encode.GetBytes(cDigest)
Dim hash() As Byte
' get hash
Dim md5 As New System.Security.Cryptography.MD5CryptoServiceProvider
hash = md5.ComputeHash(inputDigest)
' convert hash value to hex string
Dim sb As New System.Text.StringBuilder
Dim outputByte As Byte
For Each outputByte In hash
' convert each byte to a Hexadecimal upper case string
sb.Append(outputByte.ToString("x2"))
Next outputByte
sOpts &= ",digest=" & sb.ToString
End If
Dim oSecVpn As Paypoint.SECVPNClient = New Paypoint.SECVPNClient
cOrderType = oOrder.GetAttribute("orderType")
If Not (cOrderType <> "" And CStr(oDictOpt("UseOrderType")) = "true") Then cOrderType = CStr(oDictOpt("accountId"))
If Not b3DSecure Then
cResponse = oSecVpn.validateCardFull(cOrderType,
CStr(oDictOpt("accountPassword")),
CStr(oEwProv.mnCartId),
myWeb.moRequest.ServerVariables("REMOTE_ADDR"),
oEwProv.mcCardHolderName,
myWeb.moRequest("creditCard/number"),
CStr(oEwProv.mnPaymentAmount),
fmtSecPayDate(myWeb.moRequest("creditCard/expireDate")),
myWeb.moRequest("creditCard/issueNumber"),
fmtSecPayDate(myWeb.moRequest("creditCard/issueDate")),
getPay360Order(oOrder),
getPay360Address(oOrder, "Delivery Address"),
getPay360Address(oOrder, "Billing Address"),
sOpts)
bSavePayment = True
Else
If Not b3DAuthorised Then
cResponse = oSecVpn.threeDSecureEnrolmentRequest(cOrderType,
CStr(oDictOpt("accountPassword")),
CStr(oEwProv.mnCartId),
myWeb.moRequest.ServerVariables("REMOTE_ADDR"),
oEwProv.mcCardHolderName,
myWeb.moRequest("creditCard/number"),
CStr(oEwProv.mnPaymentAmount),
fmtSecPayDate(myWeb.moRequest("creditCard/expireDate")),
myWeb.moRequest("creditCard/issueNumber"),
fmtSecPayDate(myWeb.moRequest("creditCard/issueDate")),
getPay360Order(oOrder),
getPay360Address(oOrder, "Delivery Address"),
getPay360Address(oOrder, "Billing Address"),
sOpts,
"0",
myWeb.moRequest.ServerVariables("HTTP_ACCEPT"),
myWeb.moRequest.ServerVariables("HTTP_USER_AGENT"),
"",
"",
"",
"",
"",
"")
bSavePayment = True
Else
'Pass the process back to Secpay
cResponse = oSecVpn.threeDSecureAuthorisationRequest(cOrderType,
CStr(oDictOpt("accountPassword")),
CStr(oEwProv.mnCartId),
myWeb.moRequest("MD"),
myWeb.moRequest("PaRes"),
sOpts)
'Save in the session the MD and the instance to save
End If
End If
' Parse the response
oDictResp = New Hashtable
'cResponse = Replace(oXMLHttp.responseXML.selectSingleNode("//node()[local-name()='validateCardFullReturn']").Text, "+", " ")
Dim cAuthCode As String = ""
If cResponse <> "" Then
aResponse = Split(Right(cResponse, Len(cResponse) - 1), "&")
For i = 0 To UBound(aResponse)
Dim cPos As String = InStr(aResponse(i), "=")
If IsNumeric(cPos) Then
nPos = CInt(cPos)
oDictResp.Add(Left(aResponse(i), nPos - 1), Right(aResponse(i), Len(aResponse(i)) - nPos))
Else
oDictResp.Add(Trim(aResponse(i)), "")
End If
Next
If oDictResp("valid") = "true" Then
If Not b3DSecure Then
bIsValid = True
err_msg = "Payment Authorised Ref: " & CStr(oEwProv.mnCartId)
ccXform.valid = True
Else
Select Case oDictResp("mpi_status_code")
Case "200"
'we have to get the browser to redirect
' v4 change - don't explicitly redirect to /deafault.ashx - this breaks everything.
' AJG Remove defualt.ashx from RedirectUrl Compare this line to 4.1
If oEwProv.moCartConfig("SecureURL").EndsWith("/") Then
sRedirectURL = oEwProv.moCartConfig("SecureURL") & "?cartCmd=Redirect3ds"
Else
sRedirectURL = oEwProv.moCartConfig("SecureURL") & "/?cartCmd=Redirect3ds"
End If
Dim cleanACSURL As String = myWeb.goServer.UrlDecode(oDictResp("acs_url"))
cleanACSURL = Replace(cleanACSURL, "&", "&")
bIsValid = False
ccXform.valid = False
err_msg = "customer redirected to:" & cleanACSURL
'Save MD as paymentRef
sPaymentRef = oDictResp("MD")
'Save the payment instance in the session
Xform3dSec = oEwProv.xfrmSecure3D(oDictResp("acs_url"), oDictResp("MD"), oDictResp("PaReq"), sRedirectURL)
Case "212"
'not subscribes to 3D Secure
bIsValid = True
err_msg = "Payment Authorised Ref: " & CStr(oEwProv.mnCartId)
err_msg = err_msg & " 3D Secure:" & oDictResp("mpi_message")
ccXform.valid = True
Case "237"
'Payer Authenticated
bIsValid = True
err_msg = "Payment Authorised Ref: " & CStr(oEwProv.mnCartId)
err_msg = err_msg & " 3D Secure:" & oDictResp("mpi_message")
ccXform.valid = True
Case "236"
' Payer Declined 3D Secure but Proceeded to confirm
' the(authentication)
bIsValid = True
err_msg = "Payment Authorised Ref: " & CStr(oEwProv.mnCartId)
err_msg = err_msg & " 3D Secure:" & oDictResp("mpi_message")
ccXform.valid = True
Case "234"
' unable to verify erolement but secpay passes
bIsValid = True
err_msg = "Payment Authorised Ref: " & CStr(oEwProv.mnCartId)
err_msg = err_msg & " 3D Secure:" & oDictResp("mpi_message")
ccXform.valid = True
Case "229"
'Payer Not Authenticated
bIsValid = False
ccXform.valid = False
err_msg = err_msg & " 3D Secure:" & oDictResp("mpi_message")
Case Else
If oDictResp("code") = "A" Then
bIsValid = True
err_msg = "Payment Authorised Ref: " & CStr(oEwProv.mnCartId)
err_msg = err_msg & " 3D Secure:" & oDictResp("mpi_message")
ccXform.valid = True
Else
'Payer Not Authenticated
bIsValid = False
ccXform.valid = False
err_msg = err_msg & " 3D Secure:" & oDictResp("mpi_status_code") & " - " & oDictResp("mpi_message")
End If
End Select
End If
Else
ccXform.valid = False
bIsValid = False
err_msg_log = "Payment Failed : " & oDictResp("message") & " (Code::" & oDictResp("code") & ")"
' Produce nice format error messages.
Select Case oDictResp("code")
Case "N"
err_msg = "The transaction was not authorised by your payment provider."
Case "C"
err_msg = "There was a comunication problem. Please try resubmitting your order later."
Case "P:A"
err_msg = "There was a system error - the amount was not supplied or invalid. Please call for assistance."
Case "P:X"
err_msg = "There was a system error - not all the mandatory parameters were supplied. Please call for assistance."
Case "P:P"
err_msg = "The payment has already been processed. This is a duplicate payment, and will not be processed."
Case "P:S"
err_msg = "The start date is invalid. Please check that you have entered your card details correctly."
Case "P:E"
err_msg = "The expiry date is invalid. Please check that you have entered your card details correctly."
Case "P:I"
err_msg = "The issue number is invalid. Please check that you have entered your card details correctly."
Case "P:C"
err_msg = "The card number supplied is invalid. Please check that you have entered your card details correctly."
Case "P:T"
err_msg = "The card type does not match the card number entered. Please check that you have entered your card details correctly."
Case "P:N"
err_msg = "There was a system error - the customer name was not supplied. Please call for assistance."
Case "P:M"
err_msg = "There was a system error - the merchant account deos not exist or has not been registered. Please call for assistance."
Case "P:B"
err_msg = "There was a system error - the merchant account for this card type does not exist. Please call for assistance."
Case "P:D"
err_msg = "There was a system error - the merchant account for this currency does not exist. Please call for assistance."
Case "P:V"
err_msg = "The security code is invalid. Please check that you have entered your card details correctly. The security code can be found on the back of your card and is the last 3 digits of the series of digits on the back."
Case "P:R"
err_msg = "There was a communication problem and the transaction has timed out. Please try resubmitting your order later."
Case "P:#"
err_msg = "There was a system error - no encryption key has been set up against this account. Please call for assistance."
Case Else
err_msg = "There was an unspecified error. Please call for assistance.(code::" & oDictResp("code") & " | " & oDictResp("message")
End Select
err_msg = "Payment Failed : " & err_msg
End If
Else
bIsValid = False
ccXform.valid = False
err_msg = "Payment Failed : no response from Pay360 check settings and password"
End If
If bSavePayment Then
'We Save the payment method prior to ultimate validation because we only have access to the request object at the point it is submitted
'only do this for a valid payment method
Dim oSaveElmt As XmlElement = ccXform.Instance.SelectSingleNode("creditCard/bSavePayment")
Debug.WriteLine(myWeb.moRequest("creditCard/expireDate"))
Dim oDate As New Date("20" & Right(myWeb.moRequest("creditCard/expireDate"), 2), CInt(Left(myWeb.moRequest("creditCard/expireDate"), 2)), 1)
oDate = oDate.AddMonths(1)
oDate = oDate.AddDays(-1)
Dim cMethodName As String = myWeb.moRequest("creditCard/type") & ": " & MaskString(myWeb.moRequest("creditCard/number"), "*", False, 4) & " Expires: " & oDate.ToShortDateString
cAuthCode = oDictResp("auth_code")
' Dim oPay360Elmt As XmlElement = ccXform.Instance.OwnerDocument.CreateElement("Pay360")
' oPay360Elmt.SetAttribute("AuthCode", cAuthCode)
' ccXform.Instance.FirstChild.AppendChild(oPay360Elmt)
If Not oSaveElmt Is Nothing Then
If oSaveElmt.InnerText = "true" And bIsValid Then
oCart.mnPaymentId = oEwProv.savePayment(myWeb.mnUserId, "Pay360", oEwProv.mnCartId, cMethodName, ccXform.Instance.FirstChild, oDate, True, oEwProv.mnPaymentAmount)
Else
oCart.mnPaymentId = oEwProv.savePayment(myWeb.mnUserId, "Pay360", oEwProv.mnCartId, cMethodName, ccXform.Instance.FirstChild, Now, False, oEwProv.mnPaymentAmount)
End If
Else
oCart.mnPaymentId = oEwProv.savePayment(myWeb.mnUserId, "Pay360", oEwProv.mnCartId, cMethodName, ccXform.Instance.FirstChild, Now, False, oEwProv.mnPaymentAmount)
End If
End If
ccXform.addNote(ccXform.moXformElmt, xForm.noteTypes.Alert, err_msg)
Else
If ccXform.isSubmitted And ccXform.validationError = "" Then
err_msg = "Unknown Error: Please call"
ccXform.addNote(ccXform.moXformElmt, xForm.noteTypes.Alert, err_msg)
Else
err_msg = ccXform.validationError
End If
ccXform.valid = False
End If
If ccXform.isSubmitted Or b3DAuthorised Then
'Update Seller Notes:
sSql = "select * from tblCartOrder where nCartOrderKey = " & oEwProv.mnCartId
Dim oDs As DataSet
Dim oRow As DataRow
oDs = myWeb.moDbHelper.getDataSetForUpdate(sSql, "Order", "Cart")
For Each oRow In oDs.Tables("Order").Rows
If bIsValid Or b3DAuthorised Then
oRow("cSellerNotes") = oRow("cSellerNotes") & vbLf & Today & " " & TimeOfDay & ": changed to: (Payment Received) " & vbLf & "comment: " & err_msg & vbLf & "Full Response:' " & cResponse & "'"
Else
If err_msg_log = "" Then err_msg_log = err_msg
oRow("cSellerNotes") = oRow("cSellerNotes") & vbLf & Today & " " & TimeOfDay & ": changed to: (Payment Failed) " & vbLf & "comment: " & err_msg_log & vbLf & "Full Response:' " & cResponse & "'"
End If
If b3DSecure And bIsValid = False Then
oRow("cPaymentRef") = sPaymentRef
End If
Next
myWeb.moDbHelper.updateDataset(oDs, "Order")
End If
If Not Xform3dSec Is Nothing Then
Return Xform3dSec
Else
Return ccXform
End If
Catch ex As Exception
returnException(myWeb.msException, mcModuleName, "GetPaymentForm", ex, "", cProcessInfo, gbDebug)
Return Nothing
End Try
End Function
Private Function getPay360Address(ByRef oRoot As XmlElement, ByRef sType As String) As String
PerfMon.Log("PaymentProviders", "getSecPayAddress")
Dim oCartAdd As XmlElement
Dim sAddress As String
Dim sPrefix As String
Dim cProcessInfo As String = "getSecPayAddress"
Try
sAddress = ""
oCartAdd = oRoot.SelectSingleNode("Contact[@type='" & sType & "']")
If sType = "Delivery" Then sType = "Shipping"
If Not oCartAdd Is Nothing Then
sPrefix = LCase(Left(sType, 4)) & "_"
'given name
If Not oCartAdd.SelectSingleNode("GivenName") Is Nothing Then
sAddress = sAddress & sPrefix & "name=" & Replace(oCartAdd.SelectSingleNode("GivenName").InnerText, ",", ",") & ","
End If
If Not oCartAdd.SelectSingleNode("Company") Is Nothing Then
sAddress = sAddress & sPrefix & "company=" & Replace(oCartAdd.SelectSingleNode("Company").InnerText, ",", ",") & ","
End If
Dim cStreet() As String = Split(oCartAdd.SelectSingleNode("Street").InnerText, ",")
Select Case UBound(cStreet)
Case 0
If Not oCartAdd.SelectSingleNode("Street") Is Nothing Then
sAddress = sAddress & sPrefix & "addr_1=" & cStreet(0) & ","
End If
Case 1
If Not oCartAdd.SelectSingleNode("Street") Is Nothing Then
sAddress = sAddress & sPrefix & "addr_1=" & cStreet(0) & ","
sAddress = sAddress & sPrefix & "addr_2=" & cStreet(1) & ","
End If
Case Else
If Not oCartAdd.SelectSingleNode("Street") Is Nothing Then
sAddress = sAddress & sPrefix & "addr_1=" & cStreet(0) & ","
'remove commas AVC doesn't like em.
sAddress = sAddress & sPrefix & "addr_2=" & Replace(Replace(oCartAdd.SelectSingleNode("Street").InnerText, cStreet(0), ""), ",", " ") & ","
End If
End Select
If Not oCartAdd.SelectSingleNode("City") Is Nothing Then
sAddress = sAddress & sPrefix & "city=" & Replace(oCartAdd.SelectSingleNode("City").InnerText, ",", ",") & ","
End If
If Not oCartAdd.SelectSingleNode("State") Is Nothing Then
sAddress = sAddress & sPrefix & "state=" & Replace(oCartAdd.SelectSingleNode("State").InnerText, ",", ",") & ","
End If
If Not oCartAdd.SelectSingleNode("Country") Is Nothing Then
sAddress = sAddress & sPrefix & "country=" & Replace(oCartAdd.SelectSingleNode("Country").InnerText, ",", ",") & ","
End If
If Not oCartAdd.SelectSingleNode("PostalCode") Is Nothing Then
sAddress = sAddress & sPrefix & "post_code=" & Replace(oCartAdd.SelectSingleNode("PostalCode").InnerText, ",", ",") & ","
End If
If Not oCartAdd.SelectSingleNode("Telephone") Is Nothing Then
sAddress = sAddress & sPrefix & "tel=" & Replace(oCartAdd.SelectSingleNode("Telephone").InnerText, ",", ",") & ","
End If
If Not oCartAdd.SelectSingleNode("Email") Is Nothing Then
sAddress = sAddress & sPrefix & "email=" & Replace(oCartAdd.SelectSingleNode("Email").InnerText, ",", ",") & ","
End If
If sAddress <> "" Then sAddress = Left(sAddress, Len(sAddress) - 1)
End If
Return sAddress
Catch ex As Exception
returnException(myWeb.msException, mcModuleName, "getSecPayAddress", ex, "", cProcessInfo, gbDebug)
Return Nothing
End Try
End Function
Private Function getPay360Order(ByRef oRoot As XmlElement) As String
PerfMon.Log("PaymentProviders", "getSecPayOrder")
Dim sOrder As String
Dim cProcessInfo As String = "getSecPayOrder"
Dim oItem As XmlElement
Try
sOrder = ""
For Each oItem In oRoot.SelectNodes("Item")
sOrder = sOrder & "prod=" & Replace(oItem.SelectSingleNode("Name").InnerText, " ", "_")
sOrder = sOrder & ", item_amount=" & oItem.SelectSingleNode("@price").InnerText & "x" & oItem.SelectSingleNode("@quantity").InnerText & ";"
Next
'add the shipping
If CInt("0" & oRoot.SelectSingleNode("@shippingCost").InnerText) > 0 Then
sOrder = sOrder & "prod=SHIPPING,item_amount=" & oRoot.SelectSingleNode("@shippingCost").InnerText & "x1;"
End If
'add the tax
If CInt("0" & oRoot.SelectSingleNode("@vatAmt").InnerText) > 0 Then
sOrder = sOrder & "prod=TAX,item_amount=" & oRoot.SelectSingleNode("@vatAmt").InnerText & "x1;"
End If
'strip the trailing semiColon
sOrder = Left(sOrder, Len(sOrder) - 1)
Return sOrder
Catch ex As Exception
returnException(myWeb.msException, mcModuleName, "getSecPayOrder", ex, "", cProcessInfo, gbDebug)
Return Nothing
End Try
End Function
Private Function fmtSecPayDate(ByVal sdate As String) As String
PerfMon.Log("PaymentProviders", "fmtSecPayDate")
Dim cProcessInfo As String = "fmtSecPayDate"
Dim strReturn As String = ""
Try
' The dates are formatted "mm yyyy" - convert them to "mmyy"
If sdate <> "" Then strReturn = Left(sdate, 2) & Right(sdate, 2)
Return strReturn
Catch ex As Exception
returnException(myWeb.msException, mcModuleName, "fmtSecPayDate", ex, "", cProcessInfo, gbDebug)
Return ""
End Try
End Function
Public Function FormatCreditCardNumber(ByVal sCCNumber As String) As Long
PerfMon.Log("PaymentProviders", "FormatCreditCardNumber")
Dim cResult As String = ""
Dim oRE As Regex = New Regex("\D")
cResult = oRE.Replace(sCCNumber, "")
cResult = Replace(cResult, " ", "") 'also strip out spaces
If cResult = "" Then cResult = 0
Return cResult
End Function
Public Function FullMoneyString(ByVal amount As String) As String
Try
If Not amount.Contains(".") Then Return Replace(amount, ",", "")
amount = Replace(amount, ",", "")
Dim cAmounts() As String = Split(amount, ".")
If UBound(cAmounts) > 2 Then Return amount
amount = cAmounts(0) & "."
If cAmounts(1).Length < 2 Then
amount &= cAmounts(1) & "0"
Else
amount &= cAmounts(1)
End If
Return amount
Catch ex As Exception
returnException(myWeb.msException, mcModuleName, "FullMoneyString", ex, "", "", gbDebug)
Return amount
End Try
End Function
Public Function CheckStatus(ByRef oWeb As Protean.Cms, ByRef nPaymentProviderRef As String) As String
Dim cProcessInfo As String = ""
' Dim moPaymentCfg = WebConfigurationManager.GetWebApplicationSection("protean/payment")
' Dim oSagePayV3Cfg As XmlNode
' Dim nTransactionMode As TransactionMode
Try
'moPaymentCfg = WebConfigurationManager.GetWebApplicationSection("protean/payment")
'oPay360Cfg = moPaymentCfg.SelectSingleNode("provider[@name='Pay360']")
'oDictOpt = xmlTools.xmlToHashTable(oPay360Cfg, "value")
'Dim oSecVpn As Paypoint.SECVPNClient = New Paypoint.SECVPNClient
'Dim cResponse As String
'cResponse = oSecVpn.repeatCardFull(cOrderType,
' CStr(oDictOpt("accountPassword")),
' CStr(oEwProv.mnCartId),
' myWeb.moRequest.ServerVariables("REMOTE_ADDR"),
' oEwProv.mcCardHolderName,
' myWeb.moRequest("creditCard/number"),
' CStr(oEwProv.mnPaymentAmount),
' fmtSecPayDate(myWeb.moRequest("creditCard/expireDate")),
' myWeb.moRequest("creditCard/issueNumber"),
' fmtSecPayDate(myWeb.moRequest("creditCard/issueDate")),
' getPay360Order(oOrder),
' getPay360Address(oOrder, "Delivery Address"),
' getPay360Address(oOrder, "Billing Address"),
' sOpts)
Return "Active"
Catch ex As Exception
returnException(myWeb.msException, mcModuleName, "CheckStatus", ex, "", cProcessInfo, gbDebug)
Return ""
End Try
End Function
Public Function CollectPayment(ByRef oWeb As Protean.Cms, ByVal nPaymentMethodId As Long, ByVal Amount As Double, ByVal CurrencyCode As String, ByVal PaymentDescription As String, ByRef oOrder As Protean.Cms.Cart) As String
Dim cProcessInfo As String = ""
Dim oPay360Cfg As XmlElement
Dim oDictOpt As Hashtable = New Hashtable
Dim sOpts As String
Try
moPaymentCfg = WebConfigurationManager.GetWebApplicationSection("protean/payment")
oPay360Cfg = moPaymentCfg.SelectSingleNode("provider[@name='Pay360']")
oDictOpt = xmlTools.xmlToHashTable(oPay360Cfg, "value")
Dim RemotePassword As String = ""
Dim sToken As String = myWeb.moDbHelper.GetDataValue("select cPayMthdProviderRef from tblCartPaymentMethod where nPayMthdKey = " & nPaymentMethodId)
Dim cardXml As New XmlDocument
cardXml.LoadXml(myWeb.moDbHelper.GetDataValue("select cPayMthdProviderRef from tblCartPaymentMethod where nPayMthdKey = " & nPaymentMethodId))
Dim cardExpireDate As String = cardXml.SelectSingleNode("creditCard/expireDate").InnerText
Dim cardType As String = cardXml.SelectSingleNode("creditCard/type").InnerText
Dim CV2 As String = cardXml.SelectSingleNode("creditCard/CV2").InnerText
sOpts = "test_status=" & oDictOpt("opperationMode")
sOpts = sOpts & ",dups=false,card_type=" & cardType
' Currency - if no currency then use GBP
If oOrder.mcCurrency <> "" Then
sOpts = sOpts & ",currency=" & UCase(oOrder.mcCurrency)
Else
sOpts = sOpts & ",currency=GBP"
End If
If CV2 <> "" Then
sOpts = sOpts & ",cv2=" & CV2
End If
Dim oSecVpn As Paypoint.SECVPNClient = New Paypoint.SECVPNClient
Dim cResponse As String
cResponse = oSecVpn.repeatCardFull(CStr(oDictOpt("accountId")),
CStr(oDictOpt("accountPassword")),
sToken,
Amount,
oDictOpt("remotePassword"),
fmtSecPayDate(cardExpireDate),
oOrder.mnCartId,
sOpts
)
Dim aResponse As String() = Split(Right(cResponse, Len(cResponse) - 1), "&")
Dim i As Int16
Dim nPos As Int16
Dim oDictResp As New Hashtable
For i = 0 To UBound(aResponse)
Dim cPos As String = InStr(aResponse(i), "=")
If IsNumeric(cPos) Then
nPos = CInt(cPos)
oDictResp.Add(Left(aResponse(i), nPos - 1), Right(aResponse(i), Len(aResponse(i)) - nPos))
Else
oDictResp.Add(Trim(aResponse(i)), "")
End If
Next
Dim bIsValid As Boolean = False
Dim err_msg As String = ""
If oDictResp("valid") = "true" Then
Select Case oDictResp("mpi_status_code")
Case "212"
'not subscribes to 3D Secure
bIsValid = True
err_msg = "Payment Authorised Ref: " & CStr(oOrder.mnCartId)
err_msg = err_msg & " 3D Secure:" & oDictResp("mpi_message")
Case "237"
'Payer Authenticated
bIsValid = True
err_msg = "Payment Authorised Ref: " & CStr(oOrder.mnCartId)
err_msg = err_msg & " 3D Secure:" & oDictResp("mpi_message")
Case "236"
' Payer Declined 3D Secure but Proceeded to confirm
' the(authentication)
bIsValid = True
err_msg = "Payment Authorised Ref: " & CStr(oOrder.mnCartId)
err_msg = err_msg & " 3D Secure:" & oDictResp("mpi_message")
Case "234"
' unable to verify erolement but secpay passes
bIsValid = True
err_msg = "Payment Authorised Ref: " & CStr(oOrder.mnCartId)
err_msg = err_msg & " 3D Secure:" & oDictResp("mpi_message")
Case "229"
'Payer Not Authenticated
bIsValid = False
err_msg = err_msg & " 3D Secure:" & oDictResp("mpi_message")
Case Else
If oDictResp("code") = "A" Then
bIsValid = True
err_msg = "Payment Authorised Ref: " & CStr(oOrder.mnCartId)
err_msg = err_msg & " 3D Secure:" & oDictResp("mpi_message")
Else
'Payer Not Authenticated
bIsValid = False
err_msg = err_msg & " 3D Secure:" & oDictResp("mpi_status_code") & " - " & oDictResp("mpi_message")
End If
End Select
End If
If bIsValid Then
Return "Success"
Else
Return err_msg
End If
Catch ex As Exception
returnException(myWeb.msException, mcModuleName, "CollectPayment", ex, "", cProcessInfo, gbDebug)
Return "Payment Error"
End Try
End Function
Public Function CancelPayments(ByRef oWeb As Protean.Cms, ByRef nPaymentProviderRef As String) As String
Dim cProcessInfo As String = ""
Dim moPaymentCfg = WebConfigurationManager.GetWebApplicationSection("protean/payment")
' Dim oPay360Cfg As XmlNode
Try
Catch ex As Exception
returnException(myWeb.msException, mcModuleName, "CancelPayments", ex, "", cProcessInfo, gbDebug)
Return ""
End Try
End Function
End Class
End Class
End Namespace
End Namespace
|
Eonic/EonicWeb5
|
Assemblies/ProteanCMS/CMS/Cart/PaymentProviders/Pay360.vb
|
Visual Basic
|
apache-2.0
| 52,296
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports System.Globalization
Imports System.Resources
Imports System.Windows
' 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("HierarchicalVirtualization")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("HierarchicalVirtualization")>
<Assembly: AssemblyCopyright("Copyright © 2018")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(false)>
'In order to begin building localizable applications, set
'<UICulture>CultureYouAreCodingWith</UICulture> in your .vbproj file
'inside a <PropertyGroup>. For example, if you are using US english
'in your source files, set the <UICulture> to "en-US". Then uncomment the
'NeutralResourceLanguage attribute below. Update the "en-US" in the line
'below to match the UICulture setting in the project file.
'<Assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)>
'The ThemeInfo attribute describes where any theme specific and generic resource dictionaries can be found.
'1st parameter: where theme specific resource dictionaries are located
'(used if a resource is not found in the page,
' or application resource dictionaries)
'2nd parameter: where the generic resource dictionary is located
'(used if a resource is not found in the page,
'app, and any theme specific resource dictionaries)
<Assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("5f3196e7-f3f5-4c0f-8eeb-d1ec1921f60e")>
' 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")>
|
DlhSoftTeam/GanttChartLightLibrary-Demos
|
GanttChartLightLibraryDemos/Demos/Samples/WPF-VisualBasic/GanttChartDataGrid/HierarchicalVirtualization/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 2,272
|
Imports System.Collections.ObjectModel
''' <summary>
''' Interaction logic for MainWindow.xaml
''' </summary>
Partial Public Class MainWindow
Inherits Window
Public Sub New()
InitializeComponent()
Dim resourceItems = New ObservableCollection(Of CustomResourceItem) From {
New CustomResourceItem With {.Name = "Resource 1", .Description = "Description of custom resource 1", .AssignedTasks = New ObservableCollection(Of CustomTaskItem) From {New CustomTaskItem With {.Name = "Task 1", .StartDate = Date.Today.Add(TimeSpan.Parse("08:00:00")), .FinishDate = Date.Today.Add(TimeSpan.Parse("16:00:00")), .CompletionCurrentDate = Date.Today.Add(TimeSpan.Parse("12:00:00"))}, New CustomTaskItem With {.Name = "Task 2", .StartDate = Date.Today.AddDays(1).Add(TimeSpan.Parse("12:00:00")), .FinishDate = Date.Today.AddDays(2).Add(TimeSpan.Parse("16:00:00")), .AssignmentsString = "50%"}}},
New CustomResourceItem With {.Name = "Resource 2", .Description = "Description of custom resource 2", .AssignedTasks = New ObservableCollection(Of CustomTaskItem) From {New CustomTaskItem With {.Name = "Task 2", .StartDate = Date.Today.AddDays(1).Add(TimeSpan.Parse("12:00:00")), .FinishDate = Date.Today.AddDays(2).Add(TimeSpan.Parse("16:00:00"))}}}
}
For i As Integer = 3 To 16
Dim item As CustomResourceItem = New CustomResourceItem With {.Name = "Resource " & i, .Description = "Description of custom resource " & i, .AssignedTasks = New ObservableCollection(Of CustomTaskItem)()}
For j As Integer = 1 To (i - 1) Mod 4 + 1
item.AssignedTasks.Add(New CustomTaskItem With {.Name = "Task " & i & "." & j, .StartDate = Date.Today.AddDays(i + (i - 1) * (j - 1)), .FinishDate = Date.Today.AddDays(i * 1.2 + (i - 1) * (j - 1) + 1), .CompletionCurrentDate = Date.Today.AddDays(i + (i - 1) * (j - 1)).AddDays(If((i + j) Mod 5 = 2, 2, 0))})
Next j
resourceItems.Add(item)
Next i
ScheduleChartDataGrid.DataContext = resourceItems
End Sub
Private theme As String = "Generic-bright"
Public Sub New(theme As String)
Me.New()
Me.theme = theme
ApplyTemplate()
End Sub
Public Overrides Sub OnApplyTemplate()
LoadTheme()
MyBase.OnApplyTemplate()
End Sub
Private Sub LoadTheme()
If theme Is Nothing OrElse theme = "Default" OrElse theme = "Aero" Then
Return
End If
Dim themeResourceDictionary = New ResourceDictionary With {.Source = New Uri("/" & Me.GetType().Assembly.GetName().Name & ";component/Themes/" & theme & ".xaml", UriKind.Relative)}
ScheduleChartDataGrid.Resources.MergedDictionaries.Add(themeResourceDictionary)
End Sub
End Class
|
DlhSoftTeam/GanttChartLightLibrary-Demos
|
GanttChartLightLibraryDemos/Demos/Samples/WPF-VisualBasic/ScheduleChartDataGrid/DataBinding/MainWindow.xaml.vb
|
Visual Basic
|
mit
| 2,790
|
' 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.CompilerServices
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.VisualStudio.Debugger.Clr
Imports Microsoft.VisualStudio.Debugger.ComponentInterfaces
Imports Microsoft.VisualStudio.Debugger.Evaluation
Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
Friend Module TestTypeExtensions
<Extension>
Public Function GetTypeName(type As System.Type, Optional dynamicFlags As Boolean() = Nothing, Optional escapeKeywordIdentifiers As Boolean = False) As String
Return type.GetTypeName(DynamicFlagsCustomTypeInfo.Create(dynamicFlags).GetCustomTypeInfo(), escapeKeywordIdentifiers, Nothing)
End Function
<Extension>
Public Function GetTypeName(type As System.Type, typeInfo As DkmClrCustomTypeInfo, Optional escapeKeywordIdentifiers As Boolean = False, Optional inspectionContext As DkmInspectionContext = Nothing) As String
Dim formatter = New VisualBasicFormatter()
Dim clrType = New DkmClrType(New TypeImpl(type))
If inspectionContext Is Nothing Then
Dim inspectionSession = New DkmInspectionSession(ImmutableArray.Create(Of IDkmClrFormatter)(New VisualBasicFormatter()), ImmutableArray.Create(Of IDkmClrResultProvider)(New VisualBasicResultProvider()))
inspectionContext = New DkmInspectionContext(inspectionSession, DkmEvaluationFlags.None, radix:=10, runtimeInstance:=Nothing)
End If
Return If(escapeKeywordIdentifiers,
DirectCast(formatter, IDkmClrFullNameProvider).GetClrTypeName(inspectionContext, clrType, typeInfo),
DirectCast(formatter, IDkmClrFormatter).GetTypeName(inspectionContext, clrType, typeInfo, Microsoft.CodeAnalysis.ExpressionEvaluator.Formatter.NoFormatSpecifiers))
End Function
End Module
End Namespace
|
MatthieuMEZIL/roslyn
|
src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/Helpers/TestTypeExtensions.vb
|
Visual Basic
|
apache-2.0
| 2,156
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System
Imports System.Globalization
Imports System.Linq
Imports System.Text
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.Shared.Utilities
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Partial Module ExpressionGenerator
Private Structure StringPiece
Public ReadOnly Value As String
Public ReadOnly Kind As StringPieceKind
Public Sub New(value As String, kind As StringPieceKind)
Me.Value = value
Me.Kind = kind
End Sub
Private Shared Function IsPrintable(c As Char) As Boolean
Dim category = CharUnicodeInfo.GetUnicodeCategory(c)
Return IsPrintable(category) AndAlso Not IsQuoteCharacter(c)
End Function
Private Shared Function IsPrintable(c As UnicodeCategory) As Boolean
Return c <> UnicodeCategory.OtherNotAssigned AndAlso
c <> UnicodeCategory.ParagraphSeparator AndAlso
c <> UnicodeCategory.Control AndAlso
c <> UnicodeCategory.Surrogate
End Function
Private Shared Function IsQuoteCharacter(c As Char) As Boolean
Const DWCH_LSMART_DQ As Char = ChrW(&H201CS) '// DW left single
Const DWCH_RSMART_DQ As Char = ChrW(&H201DS) '// DW right single smart quote
Const DWCH_DQ As Char = ChrW(AscW(""""c) + (&HFF00US - &H20US)) '// DW dual quote
Return c = DWCH_LSMART_DQ OrElse c = DWCH_RSMART_DQ OrElse c = DWCH_DQ
End Function
Public Function GenerateExpression() As ExpressionSyntax
Select Case Me.Kind
Case StringPieceKind.Normal
Dim literal = VisualBasic.SymbolDisplay.FormatPrimitive(Me.Value, quoteStrings:=True, useHexadecimalNumbers:=False)
Return SyntaxFactory.StringLiteralExpression(
SyntaxFactory.StringLiteralToken(literal, Me.Value))
Case StringPieceKind.NonPrintable
Return GenerateChrWExpression(Me.Value(0))
Case StringPieceKind.Cr
Return GenerateStringConstantExpression("vbCr")
Case StringPieceKind.Lf
Return GenerateStringConstantExpression("vbLf")
Case StringPieceKind.CrLf
Return GenerateStringConstantExpression("vbCrLf")
Case StringPieceKind.NullChar
Return GenerateStringConstantExpression("vbNullChar")
Case StringPieceKind.Back
Return GenerateStringConstantExpression("vbBack")
Case StringPieceKind.FormFeed
Return GenerateStringConstantExpression("vbFormFeed")
Case StringPieceKind.Tab
Return GenerateStringConstantExpression("vbTab")
Case StringPieceKind.VeriticalTab
Return GenerateStringConstantExpression("vbVerticalTab")
End Select
Throw ExceptionUtilities.Unreachable
End Function
Private Shared Function GenerateStringConstantExpression(name As String) As MemberAccessExpressionSyntax
Dim factory = New VisualBasicSyntaxGenerator()
Dim result = GenerateMemberAccessExpression("Microsoft", "VisualBasic", "Constants", name)
Return result.WithAdditionalAnnotations(Simplifier.Annotation)
End Function
Public Shared Function Split(value As String) As IList(Of StringPiece)
Dim result = New List(Of StringPiece)
Dim sb = New StringBuilder()
Dim i = 0
While i < value.Length
Dim c = value(i)
i += 1
' Handle unicode surrogates. If this character is a surrogate, but we get a
' viable surrogate pair, then just add the pair to the resultant string piece.
Dim category = CharUnicodeInfo.GetUnicodeCategory(c)
If category = UnicodeCategory.Surrogate Then
Dim fullCategory = CharUnicodeInfo.GetUnicodeCategory(value, i - 1)
If IsPrintable(fullCategory) Then
sb.Append(c)
sb.Append(value(i))
i += 1
Continue While
End If
End If
If IsPrintable(c) Then
sb.Append(c)
Else
If sb.Length > 0 Then
result.Add(New StringPiece(sb.ToString(), StringPieceKind.Normal))
sb.Clear()
End If
If c = vbNullChar Then
result.Add(New StringPiece(Nothing, StringPieceKind.NullChar))
ElseIf c = vbBack Then
result.Add(New StringPiece(Nothing, StringPieceKind.Back))
ElseIf c = vbFormFeed Then
result.Add(New StringPiece(Nothing, StringPieceKind.FormFeed))
ElseIf c = vbTab Then
result.Add(New StringPiece(Nothing, StringPieceKind.Tab))
ElseIf c = vbVerticalTab Then
result.Add(New StringPiece(Nothing, StringPieceKind.VeriticalTab))
ElseIf c = vbCr Then
If i < value.Length AndAlso value(i) = vbLf Then
result.Add(New StringPiece(Nothing, StringPieceKind.CrLf))
i = i + 1
Else
result.Add(New StringPiece(Nothing, StringPieceKind.Cr))
End If
ElseIf c = vbLf Then
result.Add(New StringPiece(Nothing, StringPieceKind.Lf))
Else
result.Add(New StringPiece(c, StringPieceKind.NonPrintable))
End If
End If
End While
If sb.Length > 0 Then
result.Add(New StringPiece(sb.ToString(), StringPieceKind.Normal))
sb.Clear()
End If
Return result
End Function
End Structure
End Module
End Namespace
|
jgglg/roslyn
|
src/Workspaces/VisualBasic/Portable/CodeGeneration/ExpressionGenerator.StringPiece.vb
|
Visual Basic
|
apache-2.0
| 7,201
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.DocumentationComments
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.SignatureHelp
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp
<ExportSignatureHelpProvider("RaiseEventSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]>
Friend Class RaiseEventStatementSignatureHelpProvider
Inherits AbstractVisualBasicSignatureHelpProvider
Public Overrides Function IsTriggerCharacter(ch As Char) As Boolean
Return ch = "("c OrElse ch = ","c
End Function
Public Overrides Function IsRetriggerCharacter(ch As Char) As Boolean
Return False
End Function
Public Overrides Function GetCurrentArgumentState(root As SyntaxNode, position As Integer, syntaxFacts As ISyntaxFactsService, currentSpan As TextSpan, cancellationToken As CancellationToken) As SignatureHelpState
Dim statement As RaiseEventStatementSyntax = Nothing
If TryGetRaiseEventStatement(root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, statement) AndAlso
currentSpan.Start = statement.Name.SpanStart Then
Return SignatureHelpUtilities.GetSignatureHelpState(statement.ArgumentList, position)
End If
Return Nothing
End Function
Private Function TryGetRaiseEventStatement(root As SyntaxNode, position As Integer, syntaxFacts As ISyntaxFactsService, triggerReason As SignatureHelpTriggerReason, cancellationToken As CancellationToken, ByRef statement As RaiseEventStatementSyntax) As Boolean
If Not CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, AddressOf IsTriggerToken, AddressOf IsArgumentListToken, cancellationToken, statement) Then
Return False
End If
Return statement.ArgumentList IsNot Nothing
End Function
Private Shared Function IsTriggerToken(token As SyntaxToken) As Boolean
Return (token.Kind = SyntaxKind.OpenParenToken OrElse token.Kind = SyntaxKind.CommaToken) AndAlso
TypeOf token.Parent Is ArgumentListSyntax AndAlso
TypeOf token.Parent.Parent Is RaiseEventStatementSyntax
End Function
Private Shared Function IsArgumentListToken(statement As RaiseEventStatementSyntax, token As SyntaxToken) As Boolean
Return statement.ArgumentList IsNot Nothing AndAlso
statement.ArgumentList.Span.Contains(token.SpanStart) AndAlso
statement.ArgumentList.CloseParenToken <> token
End Function
Protected Overrides Async Function GetItemsWorkerAsync(
document As Document,
position As Integer,
triggerInfo As SignatureHelpTriggerInfo,
cancellationToken As CancellationToken
) As Task(Of SignatureHelpItems)
Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
Dim raiseEventStatement As RaiseEventStatementSyntax = Nothing
If Not TryGetRaiseEventStatement(root, position, document.GetLanguageService(Of ISyntaxFactsService), triggerInfo.TriggerReason, cancellationToken, raiseEventStatement) Then
Return Nothing
End If
Dim semanticModel = Await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False)
Dim containingType = semanticModel.GetEnclosingSymbol(position, cancellationToken).ContainingType
Dim syntaxFactsService = document.Project.LanguageServices.GetService(Of ISyntaxFactsService)()
Dim events = If(syntaxFactsService.IsInStaticContext(raiseEventStatement),
semanticModel.LookupStaticMembers(raiseEventStatement.SpanStart, containingType, raiseEventStatement.Name.Identifier.ValueText),
semanticModel.LookupSymbols(raiseEventStatement.SpanStart, containingType, raiseEventStatement.Name.Identifier.ValueText))
Dim symbolDisplayService = document.Project.LanguageServices.GetService(Of ISymbolDisplayService)()
Dim allowedEvents = events.WhereAsArray(Function(s) s.Kind = SymbolKind.Event AndAlso s.ContainingType Is containingType).
OfType(Of IEventSymbol)().
ToImmutableArrayOrEmpty().
FilterToVisibleAndBrowsableSymbolsAndNotUnsafeSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation).
Sort(symbolDisplayService, semanticModel, raiseEventStatement.SpanStart)
Dim anonymousTypeDisplayService = document.Project.LanguageServices.GetService(Of IAnonymousTypeDisplayService)()
Dim documentationCommentFormattingService = document.Project.LanguageServices.GetService(Of IDocumentationCommentFormattingService)()
Dim textSpan = SignatureHelpUtilities.GetSignatureHelpSpan(raiseEventStatement.ArgumentList, raiseEventStatement.Name.SpanStart)
Dim syntaxFacts = document.GetLanguageService(Of ISyntaxFactsService)
Return CreateSignatureHelpItems(
allowedEvents.Select(Function(e) Convert(e, raiseEventStatement, semanticModel, symbolDisplayService, anonymousTypeDisplayService, documentationCommentFormattingService, cancellationToken)).ToList(),
textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken))
End Function
Private Overloads Function Convert(
eventSymbol As IEventSymbol,
raiseEventStatement As RaiseEventStatementSyntax,
semanticModel As SemanticModel,
symbolDisplayService As ISymbolDisplayService,
anonymousTypeDisplayService As IAnonymousTypeDisplayService,
documentationCommentFormattingService As IDocumentationCommentFormattingService,
cancellationToken As CancellationToken
) As SignatureHelpItem
Dim position = raiseEventStatement.SpanStart
Dim type = DirectCast(eventSymbol.Type, INamedTypeSymbol)
Dim item = CreateItem(
eventSymbol, semanticModel, position,
symbolDisplayService, anonymousTypeDisplayService,
False,
eventSymbol.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService),
GetPreambleParts(eventSymbol, semanticModel, position),
GetSeparatorParts(),
GetPostambleParts(eventSymbol, semanticModel, position),
type.DelegateInvokeMethod.GetParameters().Select(Function(p) Convert(p, semanticModel, position, documentationCommentFormattingService, cancellationToken)).ToList())
Return item
End Function
Private Function GetPreambleParts(
eventSymbol As IEventSymbol,
semanticModel As SemanticModel,
position As Integer
) As IList(Of SymbolDisplayPart)
Dim result = New List(Of SymbolDisplayPart)()
result.AddRange(eventSymbol.ContainingType.ToMinimalDisplayParts(semanticModel, position))
result.Add(Punctuation(SyntaxKind.DotToken))
Dim format = MinimallyQualifiedWithoutParametersFormat
format = format.RemoveMemberOptions(SymbolDisplayMemberOptions.IncludeType Or SymbolDisplayMemberOptions.IncludeContainingType)
format = format.RemoveKindOptions(SymbolDisplayKindOptions.IncludeMemberKeyword)
result.AddRange(eventSymbol.ToMinimalDisplayParts(semanticModel, position, format))
result.Add(Punctuation(SyntaxKind.OpenParenToken))
Return result
End Function
Private Function GetPostambleParts(
eventSymbol As IEventSymbol,
semanticModel As SemanticModel,
position As Integer) As IList(Of SymbolDisplayPart)
Return {Punctuation(SyntaxKind.CloseParenToken)}
End Function
End Class
End Namespace
|
Pvlerick/roslyn
|
src/Features/VisualBasic/Portable/SignatureHelp/RaiseEventStatementSignatureHelpProvider.vb
|
Visual Basic
|
apache-2.0
| 8,494
|
' 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 Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.PooledObjects
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Partial Friend NotInheritable Class AnonymousTypeManager
Private NotInheritable Class AnonymousTypeTemplateSymbol
Inherits AnonymousTypeOrDelegateTemplateSymbol
Private ReadOnly _properties As ImmutableArray(Of AnonymousTypePropertySymbol)
Private ReadOnly _members As ImmutableArray(Of Symbol)
Private ReadOnly _interfaces As ImmutableArray(Of NamedTypeSymbol)
Friend ReadOnly HasAtLeastOneKeyField As Boolean
Public Sub New(manager As AnonymousTypeManager,
typeDescr As AnonymousTypeDescriptor)
MyBase.New(manager, typeDescr)
Dim fieldsCount As Integer = typeDescr.Fields.Length
Dim methodMembersBuilder = ArrayBuilder(Of Symbol).GetInstance()
Dim otherMembersBuilder = ArrayBuilder(Of Symbol).GetInstance()
' The array storing property symbols to be used in
' generation of constructor and other methods
Dim propertiesArray = New AnonymousTypePropertySymbol(fieldsCount - 1) {}
' Anonymous types with at least one Key field are being generated slightly different
HasAtLeastOneKeyField = False
' Process fields
For fieldIndex = 0 To fieldsCount - 1
Dim field As AnonymousTypeField = typeDescr.Fields(fieldIndex)
If field.IsKey Then
HasAtLeastOneKeyField = True
End If
' Add a property
Dim [property] As New AnonymousTypePropertySymbol(Me, field, fieldIndex, Me.TypeParameters(fieldIndex))
propertiesArray(fieldIndex) = [property]
' Property related symbols
otherMembersBuilder.Add([property])
methodMembersBuilder.Add([property].GetMethod)
If [property].SetMethod IsNot Nothing Then
methodMembersBuilder.Add([property].SetMethod)
End If
otherMembersBuilder.Add([property].AssociatedField)
Next
_properties = propertiesArray.AsImmutableOrNull()
' Add a constructor
methodMembersBuilder.Add(New AnonymousTypeConstructorSymbol(Me))
' Add 'ToString'
methodMembersBuilder.Add(New AnonymousTypeToStringMethodSymbol(Me))
' Add optional members
If HasAtLeastOneKeyField AndAlso Me.Manager.System_IEquatable_T_Equals IsNot Nothing Then
' Add 'GetHashCode'
methodMembersBuilder.Add(New AnonymousTypeGetHashCodeMethodSymbol(Me))
' Add optional 'Inherits IEquatable'
Dim equatableInterface As NamedTypeSymbol = Me.Manager.System_IEquatable_T.Construct(ImmutableArray.Create(Of TypeSymbol)(Me))
_interfaces = ImmutableArray.Create(Of NamedTypeSymbol)(equatableInterface)
' Add 'IEquatable.Equals'
Dim method As Symbol = DirectCast(equatableInterface, SubstitutedNamedType).GetMemberForDefinition(Me.Manager.System_IEquatable_T_Equals)
Dim iEquatableEquals As MethodSymbol = New AnonymousType_IEquatable_EqualsMethodSymbol(Me, DirectCast(method, MethodSymbol))
methodMembersBuilder.Add(iEquatableEquals)
' Add 'Equals'
methodMembersBuilder.Add(New AnonymousTypeEqualsMethodSymbol(Me, iEquatableEquals))
Else
_interfaces = ImmutableArray(Of NamedTypeSymbol).Empty
End If
methodMembersBuilder.AddRange(otherMembersBuilder)
otherMembersBuilder.Free()
_members = methodMembersBuilder.ToImmutableAndFree()
End Sub
Friend Overrides Function GetAnonymousTypeKey() As AnonymousTypeKey
Dim properties = _properties.SelectAsArray(Function(p) New AnonymousTypeKeyField(p.Name, isKey:=p.IsReadOnly, ignoreCase:=True))
Return New AnonymousTypeKey(properties)
End Function
Friend Overrides ReadOnly Property GeneratedNamePrefix As String
Get
Return GeneratedNames.AnonymousTypeTemplateNamePrefix
End Get
End Property
Public ReadOnly Property Properties As ImmutableArray(Of AnonymousTypePropertySymbol)
Get
Return Me._properties
End Get
End Property
Public Overrides Function GetMembers() As ImmutableArray(Of Symbol)
Return _members
End Function
Friend Overrides Iterator Function GetFieldsToEmit() As IEnumerable(Of FieldSymbol)
For Each m In GetMembers()
If m.Kind = SymbolKind.Field Then
Yield DirectCast(m, FieldSymbol)
End If
Next
End Function
Friend Overrides Function MakeAcyclicBaseType(diagnostics As DiagnosticBag) As NamedTypeSymbol
Return Me.Manager.System_Object
End Function
Friend Overrides Function MakeAcyclicInterfaces(diagnostics As DiagnosticBag) As ImmutableArray(Of NamedTypeSymbol)
Return _interfaces
End Function
Public Overrides ReadOnly Property TypeKind As TypeKind
Get
Return TypeKind.Class
End Get
End Property
Friend Overrides ReadOnly Property IsInterface As Boolean
Get
Return False
End Get
End Property
Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))
MyBase.AddSynthesizedAttributes(compilationState, attributes)
' Attribute: System.Runtime.CompilerServices.CompilerGeneratedAttribute()
AddSynthesizedAttribute(attributes, Manager.Compilation.TrySynthesizeAttribute(
WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor))
' VB emits this attribute regardless of /debug settings (unlike C#, which only emits it for /debug:full)
' Attribute: System.Diagnostics.DebuggerDisplayAttribute("a={a}, b={b}, c={c}, ...")
AddSynthesizedAttribute(attributes, SynthesizeDebuggerDisplayAttribute())
End Sub
Private Function SynthesizeDebuggerDisplayAttribute() As SynthesizedAttributeData
' VB doesn't allow empty anon types
Debug.Assert(Me.Properties.Length > 0)
Dim builder = PooledStringBuilder.GetInstance()
Dim sb = builder.Builder
Dim displayCount As Integer = Math.Min(Me.Properties.Length, 4)
For fieldIndex = 0 To displayCount - 1
Dim fieldName As String = Me.Properties(fieldIndex).Name
If fieldIndex > 0 Then
sb.Append(", ")
End If
sb.Append(fieldName)
sb.Append("={")
sb.Append(fieldName)
sb.Append("}")
Next
If Me.Properties.Length > displayCount Then
sb.Append(", ...")
End If
Return Manager.Compilation.TrySynthesizeAttribute(
WellKnownMember.System_Diagnostics_DebuggerDisplayAttribute__ctor,
ImmutableArray.Create(New TypedConstant(Manager.System_String, TypedConstantKind.Primitive, builder.ToStringAndFree())))
End Function
End Class
End Class
End Namespace
|
VSadov/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType_TemplateSymbol.vb
|
Visual Basic
|
apache-2.0
| 8,490
|
' 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.Diagnostics
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend Partial Class BoundFieldAccess
Public Sub New(syntax As SyntaxNode, receiverOpt As BoundExpression, fieldSymbol As FieldSymbol, isLValue As Boolean, type As TypeSymbol, Optional hasErrors As Boolean = False)
Me.New(syntax, receiverOpt, fieldSymbol, isLValue, False, Nothing, type, hasErrors)
End Sub
Public Overrides ReadOnly Property ExpressionSymbol As Symbol
Get
Return Me.FieldSymbol
End Get
End Property
Protected Overrides Function MakeRValueImpl() As BoundExpression
Return MakeRValue()
End Function
Public Shadows Function MakeRValue() As BoundFieldAccess
If _IsLValue Then
Return Update(_ReceiverOpt, _FieldSymbol, False, Me.SuppressVirtualCalls, Me.ConstantsInProgressOpt, Type)
End If
Return Me
End Function
Public Overrides ReadOnly Property ConstantValueOpt As ConstantValue
Get
' decimal and datetime const fields require one-time synthesized assignment in cctor
' when used as a LHS of an assignment, the access is not a const.
If _IsLValue Then
Return Nothing
End If
Dim result As ConstantValue
Dim constantsInProgress = Me.ConstantsInProgressOpt
If constantsInProgress IsNot Nothing Then
result = Me.FieldSymbol.GetConstantValue(constantsInProgress)
Else
result = Me.FieldSymbol.GetConstantValue(SymbolsInProgress(Of FieldSymbol).Empty)
End If
#If DEBUG Then
ValidateConstantValue(Me.Type, result)
#End If
Return result
End Get
End Property
End Class
End Namespace
|
mmitche/roslyn
|
src/Compilers/VisualBasic/Portable/BoundTree/BoundFieldAccess.vb
|
Visual Basic
|
apache-2.0
| 2,237
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.18331
'
' 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("VBAddCategory.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
|
age-killer/Electronic-invoice-document-processing
|
MailSort_CSHARP/packages/Independentsoft.Exchange.3.0.400/Tutorial/VBAddCategory/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,722
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.