code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitThrowStatement(node As BoundThrowStatement) As BoundNode Dim expressionOpt As BoundExpression = node.ExpressionOpt If expressionOpt IsNot Nothing Then expressionOpt = VisitExpressionNode(expressionOpt) If expressionOpt.Type.SpecialType = SpecialType.System_Int32 Then Debug.Assert(node.Syntax.Kind = SyntaxKind.ErrorStatement, "Must be an Error statement.") Dim nodeFactory As New SyntheticBoundNodeFactory(_topMethod, _currentMethodOrLambda, node.Syntax, _compilationState, _diagnostics) Dim createProjectError As MethodSymbol = nodeFactory.WellKnownMember(Of MethodSymbol)(WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__CreateProjectError) If createProjectError IsNot Nothing Then expressionOpt = New BoundCall(node.Syntax, createProjectError, Nothing, Nothing, ImmutableArray.Create(Of BoundExpression)(expressionOpt), Nothing, createProjectError.ReturnType) End If End If End If Dim rewritten As BoundStatement = node.Update(expressionOpt) If ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Then rewritten = RegisterUnstructuredExceptionHandlingResumeTarget(node.Syntax, rewritten, canThrow:=True) End If Return MarkStatementWithSequencePoint(rewritten) End Function End Class End Namespace
droyad/roslyn
src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_Throw.vb
Visual Basic
apache-2.0
2,222
Imports Codeer.Friendly.Windows.Grasp Imports NUnit.Framework Imports Ong.Friendly.FormsStandardControls Imports TechTalk.SpecFlow Namespace Features.Steps <Binding()> _ Public Class StepDefinitions Private Shared ReadOnly Form1DriverName As String = GetType(Form1Driver).FullName Private Property driver() As Form1Driver Get If Not ScenarioContext.Current.ContainsKey(Form1DriverName) Then Return Nothing End If Return ScenarioContext.Current.Get(Of Form1Driver)(Form1DriverName) End Get Set(ByVal value As Form1Driver) ScenarioContext.Current.Set(value, Form1DriverName) End Set End Property <AfterScenario()> Public Sub AfterScenario() If driver Is Nothing Then Return End If driver.Dispose() End Sub <Given("起動する")> _ Public Sub Given起動する() driver = Form1Driver.Start End Sub <TechTalk.SpecFlow.When("TextBox ""(.+)"" に ""(.+)"" を入力する")> _ Public Sub WhenTextBoxにvalueを入力する(ByVal name As String, ByVal value As String) Dim textbox As New FormsTextBox(driver.MainForm(name)()) textbox.EmulateChangeText(value) End Sub <TechTalk.SpecFlow.When("Button ""(.+)"" を押す")> _ Public Sub WhenButtonを押す(ByVal buttonLabel As String) Dim controls As WindowControl() = driver.MainForm.GetFromWindowText(buttonLabel) Assert.That(controls, [Is].Not.Empty, buttonLabel & " があるはず") Dim button As New FormsButton(controls(0)) button.EmulateClick() End Sub <TechTalk.SpecFlow.Then("TextBox ""(.+)"" は ""(.+)"" になる")> _ Public Sub ThenTextBoxはvalueになる(ByVal name As String, ByVal expectedValue As String) Dim textbox As New FormsTextBox(driver.MainForm(name)()) Assert.That(textbox.Text, [Is].EqualTo(expectedValue)) End Sub <TechTalk.SpecFlow.When("以下を入力する")> _ Public Sub When以下を入力する(ByVal aTable As Table) For Each aTableRow As TableRow In aTable.Rows Dim aType As String = aTableRow("Type") Dim name As String = aTableRow("Name") Dim value As String = aTableRow("Value") If "TextBox".Equals(aType, StringComparison.OrdinalIgnoreCase) Then Dim textbox As New FormsTextBox(driver.MainForm(name)()) textbox.EmulateChangeText(value) Else Throw New NotImplementedException(String.Format("'{0}'は未対応", aType)) End If Next End Sub End Class End Namespace
takas-ho/SkeletonCodeerFriendly.2008
SkeletonCodeerFriendlyTest/Features/Steps/StepDefinitions.vb
Visual Basic
mit
2,904
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On 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", "15.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("BSApplicationProfiler.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 '''<summary> ''' Looks up a localized resource of type System.Drawing.Icon similar to (Icon). '''</summary> Friend ReadOnly Property _100Sampleicons_21_40_78() As System.Drawing.Icon Get Dim obj As Object = ResourceManager.GetObject("_100Sampleicons_21_40_78", resourceCulture) Return CType(obj,System.Drawing.Icon) End Get End Property '''<summary> ''' Looks up a localized resource of type System.Drawing.Icon similar to (Icon). '''</summary> Friend ReadOnly Property _100Sampleicons_81_100_26() As System.Drawing.Icon Get Dim obj As Object = ResourceManager.GetObject("_100Sampleicons_81_100_26", resourceCulture) Return CType(obj,System.Drawing.Icon) End Get End Property End Module End Namespace
burnsoftnet/BSApplicationProfiler
BSApplicationProfiler/My Project/Resources.Designer.vb
Visual Basic
mit
3,699
Option Strict On Option Explicit On Option Infer Off Imports System.Drawing Public NotInheritable Class ColorHelper Public Shared Function Multiply(Prototype As Color, ByVal Ratio As Double) As Color Dim RGB() As Integer = {Prototype.R, Prototype.G, Prototype.B} For i As Integer = 0 To 2 RGB(i) = CInt(RGB(i) * (Ratio)) If RGB(i) > 255 Then RGB(i) = 255 ElseIf RGB(i) < 0 Then RGB(i) = 0 End If Next Return Color.FromArgb(RGB(0), RGB(1), RGB(2)) End Function Public Overloads Shared Function Add(Prototype As Color, ByVal Amount As Integer) As Color Dim RGB() As Integer = {Prototype.R, Prototype.G, Prototype.B} For i As Integer = 0 To 2 RGB(i) += Amount If RGB(i) > 255 Then RGB(i) = 255 ElseIf RGB(i) < 0 Then RGB(i) = 0 End If Next Return Color.FromArgb(RGB(0), RGB(1), RGB(2)) End Function Public Overloads Shared Function Add(Prototype As Color, AddColor As Color) As Color Dim RGB() As Integer = {Prototype.R, Prototype.G, Prototype.B} RGB(0) += AddColor.R RGB(1) += AddColor.G RGB(2) += AddColor.B For i As Integer = 0 To 2 If RGB(i) > 255 Then RGB(i) = 255 ElseIf RGB(i) < 0 Then RGB(i) = 0 End If Next Return Color.FromArgb(RGB(0), RGB(1), RGB(2)) End Function Public Shared Function Mix(FirstColor As Color, SecondColor As Color, Optional Ratio As Double = 0.5) As Color Dim RGB(2) As Integer Dim RatioSecond As Double = 1 - Ratio RGB(0) = CInt((FirstColor.R * Ratio + SecondColor.R * RatioSecond) / 2) RGB(1) = CInt((FirstColor.G * Ratio + SecondColor.G * RatioSecond) / 2) RGB(2) = CInt((FirstColor.B * Ratio + SecondColor.B * RatioSecond) / 2) For i As Integer = 0 To 2 If RGB(i) > 255 Then RGB(i) = 255 ElseIf RGB(i) < 0 Then RGB(i) = 0 End If Next Return Color.FromArgb(RGB(0), RGB(1), RGB(2)) End Function Public Shared Function FillRemainingRGB(Prototype As Color, Optional Power As Double = 0.5) As Color Dim Remaining() As Integer = {255 - Prototype.R, 255 - Prototype.G, 255 - Prototype.B} Dim Colors() As Integer = {Prototype.R + CInt(Power * Remaining(0)), Prototype.G + CInt(Power * Remaining(1)), Prototype.B + CInt(Power * Remaining(2))} For i As Integer = 0 To 2 If Colors(i) > 255 Then Colors(i) = 255 ElseIf Colors(i) < 0 Then Colors(i) = 0 End If Next Dim Ret As Color = Color.FromArgb(Colors(0), Colors(1), Colors(2)) Return Ret End Function End Class
Audiopolis/Gruppe21-prosjekt
AudiopoLib/AudiopoLib/ColorHelper.vb
Visual Basic
mit
2,924
Imports NetOffice Imports PowerPoint = NetOffice.PowerPointApi Imports NetOffice.PowerPointApi.Enums Imports Office = NetOffice.OfficeApi Imports NetOffice.OfficeApi.Enums Imports Tests.Core Public Class Test05 Implements ITestPackage Dim _presentationClose As Boolean Dim _afterNewPresentation As Boolean Public ReadOnly Property Description As String Implements Tests.Core.ITestPackage.Description Get Return "Using events." End Get End Property Public ReadOnly Property Language As String Implements Tests.Core.ITestPackage.Language Get Return "VB" End Get End Property Public ReadOnly Property Name As String Implements Tests.Core.ITestPackage.Name Get Return "Test05" End Get End Property Public ReadOnly Property OfficeProduct As String Implements Tests.Core.ITestPackage.OfficeProduct Get Return "PowerPoint" End Get End Property Public Function DoTest() As Tests.Core.TestResult Implements Tests.Core.ITestPackage.DoTest Dim application As PowerPoint.Application = Nothing Dim startTime As DateTime = DateTime.Now Try application = New PowerPoint.Application() application.Visible = MsoTriState.msoTrue ' PowerPoint 2000 doesnt support DisplayAlerts, we check at runtime its available and set If (application.EntityIsAvailable("DisplayAlerts")) Then application.DisplayAlerts = PpAlertLevel.ppAlertsNone End If ' we register some events. note: the event trigger was called from power point, means an other Thread ' remove the Quit() call below and check out more events if you want Dim newCloseHandler As PowerPoint.Application_PresentationCloseEventHandler = AddressOf Me.powerApplication_PresentationCloseEvent AddHandler application.PresentationCloseEvent, newCloseHandler Dim newAfterNewHandler As PowerPoint.Application_AfterNewPresentationEventHandler = AddressOf Me.powerApplication_AfterNewPresentationEvent AddHandler application.AfterNewPresentationEvent, newAfterNewHandler ' add a new presentation with one new slide Dim presentation As PowerPoint.Presentation = application.Presentations.Add(MsoTriState.msoTrue) Dim slide As PowerPoint.Slide = presentation.Slides.Add(1, PpSlideLayout.ppLayoutBlank) System.Threading.Thread.Sleep(2000) ' close the document presentation.Close() If (_afterNewPresentation And _presentationClose) Then Return New TestResult(True, DateTime.Now.Subtract(startTime), "", Nothing, "") Else Return New TestResult(False, DateTime.Now.Subtract(startTime), String.Format("AfterNewPresentation:{0} , PresentationClose:{1}", _afterNewPresentation, _presentationClose), Nothing, "") End If Catch ex As Exception Return New TestResult(False, DateTime.Now.Subtract(startTime), ex.Message, ex, "") Finally If Not IsNothing(application) Then application.Quit() application.Dispose() End If End Try End Function Private Sub powerApplication_PresentationCloseEvent(ByVal Pres As NetOffice.PowerPointApi.Presentation) _presentationClose = True Pres.Dispose() End Sub Private Sub powerApplication_AfterNewPresentationEvent(ByVal Pres As NetOffice.PowerPointApi.Presentation) _afterNewPresentation = True Pres.Dispose() End Sub End Class
NetOfficeFw/NetOffice
Tests/Main Tests/PowerPointTestsVB/Test05.vb
Visual Basic
mit
3,725
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class frmTableViewer Inherits DocumentWindow 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.components = New System.ComponentModel.Container() Me.DataGridView1 = New System.Windows.Forms.DataGridView() Me.ContextMenuStrip1 = New System.Windows.Forms.ContextMenuStrip(Me.components) Me.ViewToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).BeginInit() Me.ContextMenuStrip1.SuspendLayout() Me.SuspendLayout() ' 'DataGridView1 ' Me.DataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize Me.DataGridView1.ContextMenuStrip = Me.ContextMenuStrip1 Me.DataGridView1.Dock = System.Windows.Forms.DockStyle.Fill Me.DataGridView1.Location = New System.Drawing.Point(0, 0) Me.DataGridView1.Name = "DataGridView1" Me.DataGridView1.Size = New System.Drawing.Size(962, 266) Me.DataGridView1.TabIndex = 0 ' 'ContextMenuStrip1 ' Me.ContextMenuStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ViewToolStripMenuItem}) Me.ContextMenuStrip1.Name = "ContextMenuStrip1" Me.ContextMenuStrip1.Size = New System.Drawing.Size(100, 26) ' 'ViewToolStripMenuItem ' Me.ViewToolStripMenuItem.Name = "ViewToolStripMenuItem" Me.ViewToolStripMenuItem.Size = New System.Drawing.Size(99, 22) Me.ViewToolStripMenuItem.Text = "View" ' 'frmTableViewer ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(962, 266) Me.Controls.Add(Me.DataGridView1) Me.DoubleBuffered = True Me.Name = "frmTableViewer" CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).EndInit() Me.ContextMenuStrip1.ResumeLayout(False) Me.ResumeLayout(False) End Sub Friend WithEvents DataGridView1 As DataGridView Friend WithEvents ContextMenuStrip1 As ContextMenuStrip Friend WithEvents ViewToolStripMenuItem As ToolStripMenuItem End Class
xieguigang/MassSpectrum-toolkits
src/mzkit/mzkit/pages/dockWindow/documents/frmTableViewer.Designer.vb
Visual Basic
mit
3,097
Imports System.Runtime.InteropServices Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim objApp As SolidEdgeFramework.Application = Nothing Dim objType As Type = Nothing Dim objMatTable As SolidEdgeFramework.MatTable = Nothing Dim strLibrary As String = "Materials" Dim objDocument As SolidEdgePart.PartDocument = Nothing Dim strMaterial As String = "" Dim strMessage As String Dim nNumOfCustProps As Integer Try ' Get SE handle objApp = Marshal.GetActiveObject("SolidEdge.Application") If objApp Is Nothing Then ' Get the type from the Solid Edge ProgID objType = Type.GetTypeFromProgID("SolidEdge.Application") ' Start Solid Edge objApp = Activator.CreateInstance(objType) ' Make Solid Edge visible objApp.Visible = True End If ' Get material table object handle objMatTable = objApp.GetMaterialTable() strMaterial = "Steel" objMatTable.GetCountOfCustomProperties(strMaterial, strLibrary, nNumOfCustProps) strMessage = String.Format("Steel has {0} custom Properties", nNumOfCustProps) MsgBox(strMessage) Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
SolidEdgeCommunity/docs
docfx_project/snippets/SolidEdgeFramework.MatTable.GetCountOfCustomProperties.vb
Visual Basic
mit
1,462
'--------------------------------------------------------------------- ' <copyright file="AssemblyVersion.vb" company="Microsoft"> ' Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. ' </copyright> '--------------------------------------------------------------------- Imports System.Reflection Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Resources ' The following assembly information is common to all product assemblies. ' If you get compiler errors CS0579, "Duplicate '<attributename>' attribute", check your ' Properties\AssemblyInfo.vb file and remove any lines duplicating the ones below. <Assembly: AssemblyFileVersion("0.0.0.0")> #If ASSEMBLY_ATTRIBUTE_NO_BUILD_NUM_IN_VERSION Then <Assembly: AssemblyVersion("0.0.0.0")> <assembly: SatelliteContractVersion("0.0.0.0")> #Else <Assembly: AssemblyVersion("0.0.0")> <Assembly: SatelliteContractVersion("0.0.0")> #End If
kouweizhong/odata.net
src/AssemblyInfo/AssemblyVersion.vb
Visual Basic
mit
1,032
Imports SistFoncreagro.BussinessEntities Public Interface IPermisosRepository Function GetAllFromPermisos() As List(Of Permisos) Function GetPermisosByDescripcion(ByVal descripcion As String) As Permisos Function PASolicitaAprobacion(ByVal IdPersonal As Int32) As Int32 End Interface
crackper/SistFoncreagro
SistFoncreagro.DataAccess/IPermisosRepository.vb
Visual Basic
mit
300
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("Test_NUnit_Mysql_VB")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("Test_NUnit_Mysql_VB")> <Assembly: AssemblyCopyright("Copyright © 2008")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("a8590f10-b5f6-4280-9d9a-8309abbead59")> ' 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")>
lytico/dblinq2007
src/DbLinq.MySql/Test/My Project/AssemblyInfo.vb
Visual Basic
mit
1,156
Imports BVSoftware.BVC5.Core Partial Class FAQ Inherits BaseStorePage Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit Me.MasterPageFile = PersonalizationServices.GetSafeMasterPage("Service.master") End Sub Protected Sub PageLoad(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Me.ManualBreadCrumbTrail1.ClearTrail() Me.ManualBreadCrumbTrail1.AddLink(Content.SiteTerms.GetTerm("Home"), "~") Me.ManualBreadCrumbTrail1.AddLink(Content.SiteTerms.GetTerm("CustomerService"), "~/ContactUs.aspx") Me.ManualBreadCrumbTrail1.AddNonLink(Content.SiteTerms.GetTerm("FAQ")) PageTitle = Content.SiteTerms.GetTerm("FAQ") If Not Page.IsPostBack Then Me.TitleLabel.Text = Content.SiteTerms.GetTerm("FAQ") LoadPolicies() End If End Sub Sub LoadPolicies() Try Dim p As Content.Policy = Content.Policy.FindByBvin(WebAppSettings.FAQPolicy) If p IsNot Nothing Then dlPolicy.DataSource = p.Blocks dlPolicy.DataBind() dlQuestions.DataSource = p.Blocks dlQuestions.DataBind() End If Catch Ex As Exception msg.Visible = True msg.ShowException(Ex) End Try End Sub End Class
ajaydex/Scopelist_2015
FAQ.aspx.vb
Visual Basic
apache-2.0
1,390
Public Class Upload Private Sub Upload_Load(sender As Object, e As EventArgs) Handles MyBase.Load lblDone.Text = "Your Signing Key is now made. You can find it in " + System.Environment.GetEnvironmentVariable("userprofile") + " it will be called " + iOSWinSigner.lblRequest.Text + ".certSigningRequest You should upload it to http://developer.apple.com/ios/manage/certificates/team/index.action" End Sub End Class
LinuxPhreak/iOS-Win-Signer
iOSWinSigner2/iOSWinSigner2/Upload.vb
Visual Basic
apache-2.0
438
 Namespace Forms Public Class SelectIndex #Region " Attributes " Protected m_aryIndices As New Collections.NeuralIndices(Nothing) Protected m_iMin As Integer = 0 Protected m_iMax As Integer = 100 #End Region #Region " Properties " Public Property Indices() As Collections.NeuralIndices Get Return m_aryIndices End Get Set(value As Collections.NeuralIndices) m_aryIndices.Clear() For Each iIdx As Integer In value If iIdx >= m_iMin AndAlso iIdx <= m_iMax Then m_aryIndices.Add(iIdx) End If Next End Set End Property Public Property Min() As Integer Get Return m_iMin End Get Set(value As Integer) m_iMin = value End Set End Property Public Property Max() As Integer Get Return m_iMax End Get Set(value As Integer) m_iMax = value End Set End Property #End Region #Region " Methods " #End Region #Region " Events " Private Sub SelectIndex_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load Try For iIdx As Integer = m_iMin To m_iMax cboNeurons.Items.Add(iIdx) Next For Each iIdx As Integer In m_aryIndices lbIndices.Items.Add(iIdx) If cboNeurons.Items.Contains(iIdx) Then cboNeurons.Items.Remove(iIdx) Next If cboNeurons.Items.Count > 0 Then cboNeurons.SelectedIndex = 0 End If Catch ex As System.Exception AnimatGUI.Framework.Util.DisplayError(ex) End Try End Sub Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click Try If Not cboNeurons.SelectedItem Is Nothing Then lbIndices.Items.Add(cboNeurons.SelectedItem) cboNeurons.Items.Remove(cboNeurons.SelectedItem) If cboNeurons.Items.Count > 0 Then cboNeurons.SelectedIndex = 0 End If End If Catch ex As System.Exception AnimatGUI.Framework.Util.DisplayError(ex) End Try End Sub Private Sub btnRemove_Click(sender As System.Object, e As System.EventArgs) Handles btnRemove.Click Try If Not lbIndices.SelectedItem Is Nothing Then cboNeurons.Items.Add(lbIndices.SelectedItem) lbIndices.Items.Remove(lbIndices.SelectedItem) 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/AnimatCarlGUI/Forms/SelectIndex.vb
Visual Basic
bsd-3-clause
3,094
' 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 System.Collections.Immutable Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.UnitTests.Diagnostics.SystemLanguage Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class OperationAnalyzerTests Inherits BasicTestBase <Fact> Public Sub EmptyArrayVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Sub M1() Dim arr1 As Integer() = New Integer(-1) { } ' yes Dim arr2 As Byte() = { } ' yes Dim arr3 As C() = New C(-1) { } ' yes Dim arr4 As String() = New String() { Nothing } ' no Dim arr5 As Double() = New Double(1) { } ' no Dim arr6 As Integer() = { -1 } ' no Dim arr7 as Integer()() = New Integer(-1)() { } ' yes Dim arr8 as Integer()()()() = New Integer( -1)()()() { } ' yes Dim arr9 as Integer(,) = New Integer(-1,-1) { } ' no Dim arr10 as Integer()(,) = New Integer(-1)(,) { } ' yes Dim arr11 as Integer()(,) = New Integer(1)(,) { } ' no Dim arr12 as Integer(,)() = New Integer(-1,-1)() { } ' no Dim arr13 as Integer() = New Integer(0) { } ' no End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New EmptyArrayAnalyzer}, Nothing, Nothing, False, Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer(-1) { }").WithLocation(3, 33), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "{ }").WithLocation(4, 30), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New C(-1) { }").WithLocation(5, 27), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer(-1)() { }").WithLocation(9, 35), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer( -1)()()() { }").WithLocation(10, 39), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer(-1)(,) { }").WithLocation(12, 37)) End Sub <Fact> Public Sub BoxingVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Function M1(p1 As Object, p2 As Object, p3 As Object) As Object Dim v1 As New S Dim v2 As S = v1 Dim v3 As S = v1.M1(v2) Dim v4 As Object = M1(3, Me, v1) Dim v5 As Object = v3 If p1 Is Nothing return 3 End If If p2 Is Nothing return v3 End If If p3 Is Nothing Return v4 End If Return v5 End Function End Class Structure S Public X As Integer Public Y As Integer Public Z As Object Public Function M1(p1 As S) As S p1.GetType() Z = Me Return p1 End Function End Structure ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New BoxingOperationAnalyzer}, Nothing, Nothing, False, Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "3").WithLocation(6, 32), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v1").WithLocation(6, 39), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v3").WithLocation(7, 29), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "3").WithLocation(9, 21), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v3").WithLocation(12, 21), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "p1").WithLocation(27, 9), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "Me").WithLocation(28, 13)) End Sub <Fact> Public Sub BigForVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1() Dim x as Integer For x = 1 To 200000 : Next For x = 1 To 2000000 : Next For x = 1500000 To 0 Step -2 : Next For x = 3000000 To 0 Step -2 : Next End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New BigForTestAnalyzer}, Nothing, Nothing, False, Diagnostic(BigForTestAnalyzer.BigForDescriptor.Id, "For x = 1 To 2000000 : Next").WithLocation(5, 9), Diagnostic(BigForTestAnalyzer.BigForDescriptor.Id, "For x = 3000000 To 0 Step -2 : Next").WithLocation(7, 9)) End Sub <Fact> Public Sub SparseSwitchVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1(x As Integer) Select Case x Case 1, 2 Exit Select Case = 10 Exit Select Case Else Exit Select End Select Select Case x Case 1 Exit Select Case = 1000 Exit Select Case Else Exit Select End Select Select Case x Case 10 To 500 Exit Select Case = 1000 Exit Select Case Else Exit Select End Select Select Case x Case 1, 980 To 985 Exit Select Case Else Exit Select End Select Select Case x Case 1 to 3, 980 To 985 Exit Select End Select Select Case x Case 1 Exit Select Case > 100000 Exit Select End Select End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New SparseSwitchTestAnalyzer}, Nothing, Nothing, False, Diagnostic(SparseSwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(12, 21), Diagnostic(SparseSwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(30, 21), Diagnostic(SparseSwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(37, 21)) End Sub <Fact> Public Sub InvocationVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(a As Integer, ParamArray b As Integer()) End Sub Public Sub M1(a As Integer, b As Integer, c As Integer, x As Integer, y As Integer, z As Integer) End Sub Public Sub M2() M1(1, 2, 3, 4, 5, 6) M1(a:=1, b:=2, c:=3, x:=4, y:=5, z:=6) M1(a:=1, c:=2, b:=3, x:=4, y:=5, z:=6) M1(z:=1, x:=2, y:=3, c:=4, a:=5, b:=6) M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13) M0(1) M0(1, 2, 4, 3) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New InvocationTestAnalyzer}, Nothing, Nothing, False, Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "2").WithLocation(11, 21), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "1").WithLocation(12, 15), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "2").WithLocation(12, 21), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "4").WithLocation(12, 33), Diagnostic(InvocationTestAnalyzer.BigParamarrayArgumentsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)").WithLocation(14, 9), Diagnostic(InvocationTestAnalyzer.BigParamarrayArgumentsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)").WithLocation(15, 9), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "3").WithLocation(17, 21)) End Sub <Fact> Public Sub FieldCouldBeReadOnlyVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public F1 As Integer Public Const F2 As Integer = 2 Public ReadOnly F3 As Integer Public F4 As Integer Public F5 As Integer Public F6 As Integer = 6 Public F7 As Integer Public F9 As S Public F10 As New C1 Public Sub New() F1 = 1 F4 = 4 F5 = 5 End Sub Public Sub M0() Dim x As Integer = F1 x = F2 x = F3 x = F4 x = F5 x = F6 x = F7 F4 = 4 F7 = 7 M1(F1, F5) F9.A = 10 F9.B = 20 F10.A = F9.A F10.B = F9.B End Sub Public Sub M1(ByRef X As Integer, Y As Integer) x = 10 End Sub Structure S Public A As Integer Public B As Integer End Structure Class C1 Public A As Integer Public B As Integer End Class End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New FieldCouldBeReadOnlyAnalyzer}, Nothing, Nothing, False, Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F5").WithLocation(6, 12), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F6").WithLocation(7, 12), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F10").WithLocation(10, 12)) End Sub <Fact> Public Sub StaticFieldCouldBeReadOnlyVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Shared F1 As Integer Public Shared ReadOnly F2 As Integer = 2 Public Shared Readonly F3 As Integer Public Shared F4 As Integer Public Shared F5 As Integer Public Shared F6 As Integer = 6 Public Shared F7 As Integer Public Shared F9 As S Public Shared F10 As New C1 Shared Sub New() F1 = 1 F4 = 4 F5 = 5 End Sub Public Shared Sub M0() Dim x As Integer = F1 x = F2 x = F3 x = F4 x = F5 x = F6 x = F7 F4 = 4 F7 = 7 M1(F1, F5) F9.A = 10 F9.B = 20 F10.A = F9.A F10.B = F9.B End Sub Public Shared Sub M1(ByRef X As Integer, Y As Integer) x = 10 End Sub Structure S Public A As Integer Public B As Integer End Structure Class C1 Public A As Integer Public B As Integer End Class End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New FieldCouldBeReadOnlyAnalyzer}, Nothing, Nothing, False, Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F5").WithLocation(6, 19), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F6").WithLocation(7, 19), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F10").WithLocation(10, 19)) End Sub <Fact> Public Sub LocalCouldBeConstVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(p as Integer) Dim x As Integer = p Dim y As Integer = x Const z As Integer = 1 Dim a As Integer = 2 Dim b As Integer = 3 Dim c As Integer = 4 Dim d As Integer = 5 Dim e As Integer = 6 Dim s As String = "ZZZ" b = 3 c -= 12 d += e + b M1(y, z, a, s) Dim n As S n.A = 10 n.B = 20 Dim o As New C1 o.A = 10 o.B = 20 End Sub Public Sub M1(ByRef x As Integer, y As Integer, ByRef z as Integer, s as String) x = 10 End Sub End Class Structure S Public A As Integer Public B As Integer End Structure Class C1 Public A As Integer Public B As Integer End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New LocalCouldBeConstAnalyzer}, Nothing, Nothing, False, Diagnostic(LocalCouldBeConstAnalyzer.LocalCouldBeConstDescriptor.Id, "e").WithLocation(10, 13), Diagnostic(LocalCouldBeConstAnalyzer.LocalCouldBeConstDescriptor.Id, "s").WithLocation(11, 13)) End Sub <Fact> Public Sub SymbolCouldHaveMoreSpecificTypeVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0() Dim a As Object = New Middle() Dim b As Object = New Value(10) Dim c As Object = New Middle() c = New Base() Dim d As Base = New Derived() Dim e As Base = New Derived() e = New Middle() Dim f As Base = New Middle() f = New Base() Dim g As Object = New Derived() g = New Base() g = New Middle() Dim h As New Middle() h = New Derived() Dim i As Object = 3 Dim j As Object j = 10 j = 10.1 Dim k As Middle = New Derived() Dim l As Middle = New Derived() Dim o As Object = New Middle() MM(l, o) Dim ibase1 As IBase1 = Nothing Dim ibase2 As IBase2 = Nothing Dim imiddle As IMiddle = Nothing Dim iderived As IDerived = Nothing Dim ia As Object = imiddle Dim ic As Object = imiddle ic = ibase1 Dim id As IBase1 = iderived Dim ie As IBase1 = iderived ie = imiddle Dim iff As IBase1 = imiddle iff = ibase1 Dim ig As Object = iderived ig = ibase1 ig = imiddle Dim ih = imiddle ih = iderived Dim ik As IMiddle = iderived Dim il As IMiddle = iderived Dim io As Object = imiddle IMM(il, io) Dim im As IBase2 = iderived Dim isink As Object = ibase2 isink = 3 End Sub Private fa As Object = New Middle() Private fb As Object = New Value(10) Private fc As Object = New Middle() Private fd As Base = New Derived() Private fe As Base = New Derived() Private ff As Base = New Middle() Private fg As Object = New Derived() Private fh As New Middle() Private fi As Object = 3 Private fj As Object Private fk As Middle = New Derived() Private fl As Middle = New Derived() Private fo As Object = New Middle() Private Shared fibase1 As IBase1 = Nothing Private Shared fibase2 As IBase2 = Nothing Private Shared fimiddle As IMiddle= Nothing Private Shared fiderived As IDerived = Nothing Private fia As Object = fimiddle Private fic As Object = fimiddle Private fid As IBase1 = fiderived Private fie As IBase1 = fiderived Private fiff As IBase1 = fimiddle Private fig As Object = fiderived Private fih As IMiddle = fimiddle Private fik As IMiddle = fiderived Private fil As IMiddle = fiderived Private fio As Object = fimiddle Private fisink As Object = fibase2 Private fim As IBase2 = fiderived Sub M1() fc = New Base() fe = New Middle() ff = New Base() fg = New Base() fg = New Middle() fh = New Derived() fj = 10 fj = 10.1 MM(fl, fo) fic = fibase1 fie = fimiddle fiff = fibase1 fig = fibase1 fig = fimiddle fih = fiderived IMM(fil, fio) fisink = 3 End Sub Sub MM(ByRef p1 As Middle, ByRef p2 As Object) p1 = New Middle() p2 = Nothing End Sub Sub IMM(ByRef p1 As IMiddle, ByRef p2 As object) p1 = Nothing p2 = Nothing End Sub End Class Class Base End Class Class Middle Inherits Base End Class Class Derived Inherits Middle End Class Structure Value Public Sub New(a As Integer) X = a End Sub Public X As Integer End Structure Interface IBase1 End Interface Interface IBase2 End Interface Interface IMiddle Inherits IBase1 End Interface Interface IDerived Inherits IMiddle Inherits IBase2 End Interface ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New SymbolCouldHaveMoreSpecificTypeAnalyzer}, Nothing, Nothing, False, Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "a").WithArguments("a", "Middle").WithLocation(3, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "b").WithArguments("b", "Value").WithLocation(4, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "c").WithArguments("c", "Base").WithLocation(5, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "d").WithArguments("d", "Derived").WithLocation(7, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "e").WithArguments("e", "Middle").WithLocation(8, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "g").WithArguments("g", "Base").WithLocation(12, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "i").WithArguments("i", "Integer").WithLocation(17, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "k").WithArguments("k", "Derived").WithLocation(21, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ia").WithArguments("ia", "IMiddle").WithLocation(31, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ic").WithArguments("ic", "IBase1").WithLocation(32, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "id").WithArguments("id", "IDerived").WithLocation(34, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ie").WithArguments("ie", "IMiddle").WithLocation(35, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ig").WithArguments("ig", "IBase1").WithLocation(39, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ik").WithArguments("ik", "IDerived").WithLocation(44, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "im").WithArguments("im", "IDerived").WithLocation(48, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fa").WithArguments("Private fa As Object", "Middle").WithLocation(53, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fb").WithArguments("Private fb As Object", "Value").WithLocation(54, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fc").WithArguments("Private fc As Object", "Base").WithLocation(55, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fd").WithArguments("Private fd As Base", "Derived").WithLocation(56, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fe").WithArguments("Private fe As Base", "Middle").WithLocation(57, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fg").WithArguments("Private fg As Object", "Base").WithLocation(59, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fi").WithArguments("Private fi As Object", "Integer").WithLocation(61, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fk").WithArguments("Private fk As Middle", "Derived").WithLocation(63, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fia").WithArguments("Private fia As Object", "IMiddle").WithLocation(72, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fic").WithArguments("Private fic As Object", "IBase1").WithLocation(73, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fid").WithArguments("Private fid As IBase1", "IDerived").WithLocation(74, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fie").WithArguments("Private fie As IBase1", "IMiddle").WithLocation(75, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fig").WithArguments("Private fig As Object", "IBase1").WithLocation(77, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fik").WithArguments("Private fik As IMiddle", "IDerived").WithLocation(79, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fim").WithArguments("Private fim As IBase2", "IDerived").WithLocation(83, 13)) End Sub <Fact> Public Sub ValueContextsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(Optional a As Integer = 16, Optional b As Integer = 17, Optional c As Integer = 18) End Sub Public F1 As Integer = 16 Public F2 As Integer = 17 Public F3 As Integer = 18 Public Sub M1() M0(16, 17, 18) M0(f1, f2, f3) M0() End Sub End Class Enum E A = 16 B C = 17 D = 18 End Enum Class C1 Public Sub New (a As Integer, b As Integer, c As Integer) End Sub Public F1 As C1 = New C1(c:=16, a:=17, b:=18) Public F2 As New C1(16, 17, 18) Public F3(16) As Integer Public F4(17) As Integer ' The upper bound specification is not presently treated as a code block. This is suspect. Public F5(18) As Integer Public F6 As Integer() = New Integer(16) {} Public F7 As Integer() = New Integer(17) {} End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New SeventeenTestAnalyzer}, Nothing, Nothing, False, Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(2, 71), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(6, 28), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(10, 16), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(19, 9), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(27, 40), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(28, 29), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(33, 42), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "M0").WithLocation(12, 9)) ' The M0 diagnostic is an artifact of the VB compiler filling in default values in the high-level bound tree, and is questionable. End Sub End Class End Namespace
moozzyk/roslyn
src/Compilers/VisualBasic/Test/Semantic/Diagnostics/OperationAnalyzerTests.vb
Visual Basic
apache-2.0
28,084
' 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.CodeGen Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class IteratorRewriter Inherits StateMachineRewriter(Of FieldSymbol) Private Class IteratorMethodToClassRewriter Inherits StateMachineMethodToClassRewriter ''' <summary> ''' The field of the generated iterator class that underlies the Current property. ''' </summary> Private ReadOnly _current As FieldSymbol Private ReadOnly _originalMethodDeclaration As VisualBasicSyntaxNode Private _exitLabel As LabelSymbol Private _methodValue As LocalSymbol Private _tryNestingLevel As Integer Friend Sub New(method As MethodSymbol, F As SyntheticBoundNodeFactory, state As FieldSymbol, current As FieldSymbol, hoistedVariables As IReadOnlySet(Of Symbol), localProxies As Dictionary(Of Symbol, FieldSymbol), SynthesizedLocalOrdinals As SynthesizedLocalOrdinalsDispenser, slotAllocatorOpt As VariableSlotAllocator, nextFreeHoistedLocalSlot As Integer, diagnostics As DiagnosticBag) MyBase.New(F, state, hoistedVariables, localProxies, SynthesizedLocalOrdinals, slotAllocatorOpt, nextFreeHoistedLocalSlot, diagnostics) Me._current = current Me._originalMethodDeclaration = method.DeclaringSyntaxReferences(0).GetVisualBasicSyntax End Sub Public Sub GenerateMoveNextAndDispose(Body As BoundStatement, moveNextMethod As SynthesizedMethod, disposeMethod As SynthesizedMethod) ' Generate the body for MoveNext() F.CurrentMethod = moveNextMethod Dim initialStateInfo = AddState() Dim initialState As Integer = initialStateInfo.Number Dim initialLabel As GeneratedLabelSymbol = initialStateInfo.ResumeLabel Me._methodValue = Me.F.SynthesizedLocal(F.CurrentMethod.ReturnType, SynthesizedLocalKind.StateMachineReturnValue, F.Syntax) Dim newBody = DirectCast(Visit(Body), BoundStatement) ' Select Me.state ' Case 0: ' GoTo state_0 ' Case 1: ' GoTo state_1 ' 'etc ' Case Else: ' return false ' } ' state_0: ' state = -1 ' [[rewritten body]] F.CloseMethod( F.Block( ImmutableArray.Create(Me._methodValue, Me.CachedState), F.HiddenSequencePoint(), F.Assignment(Me.F.Local(Me.CachedState, True), F.Field(F.Me, Me.StateField, False)), Dispatch(), GenerateReturn(finished:=True), F.Label(initialLabel), F.Assignment(F.Field(F.Me, Me.StateField, True), Me.F.AssignmentExpression(Me.F.Local(Me.CachedState, True), Me.F.Literal(StateMachineStates.NotStartedStateMachine))), F.SequencePoint(_originalMethodDeclaration), newBody, HandleReturn() )) Me._exitLabel = Nothing Me._methodValue = Nothing ' Generate the body for Dispose(). F.CurrentMethod = disposeMethod Dim breakLabel = F.GenerateLabel("break") Dim sections = (From ft In FinalizerStateMap Where ft.Value <> -1 Group ft.Key By ft.Value Into Group Select F.SwitchSection( New List(Of Integer)(Group), F.Assignment(F.Field(F.Me, Me.StateField, True), F.Literal(Value)), F.Goto(breakLabel))).ToArray() If (sections.Length > 0) Then F.CloseMethod(F.Block( F.Select( F.Field(F.Me, Me.StateField, False), sections), F.Assignment(F.Field(F.Me, Me.StateField, True), F.Literal(StateMachineStates.NotStartedStateMachine)), F.Label(breakLabel), F.ExpressionStatement(F.Call(F.Me, moveNextMethod)), F.Return() )) Else F.CloseMethod(F.Return()) End If End Sub Private Function HandleReturn() As BoundStatement If Me._exitLabel Is Nothing Then ' did not see indirect returns Return F.Block() Else ' _methodValue = False ' exitlabel: ' Return _methodValue Return F.Block( F.HiddenSequencePoint(), F.Assignment(F.Local(Me._methodValue, True), F.Literal(True)), F.Label(Me._exitLabel), F.Return(Me.F.Local(Me._methodValue, False)) ) End If End Function Protected Overrides Function GenerateReturn(finished As Boolean) As BoundStatement Dim result = F.Literal(Not finished) If Me._tryNestingLevel = 0 Then ' direct return Return F.Return(result) Else ' indirect return If Me._exitLabel Is Nothing Then Me._exitLabel = F.GenerateLabel("exitLabel") End If Return Me.F.Block( Me.F.Assignment(Me.F.Local(Me._methodValue, True), result), Me.F.Goto(Me._exitLabel) ) End If End Function Public Overrides Function VisitTryStatement(node As BoundTryStatement) As BoundNode Me._tryNestingLevel += 1 Dim result = MyBase.VisitTryStatement(node) Me._tryNestingLevel -= 1 Return result End Function Protected Overrides ReadOnly Property IsInExpressionLambda As Boolean Get Return False End Get End Property Protected Overrides ReadOnly Property ResumeLabelName As String Get Return "iteratorLabel" End Get End Property #Region "Visitors" Public Overrides Function VisitReturnStatement(node As BoundReturnStatement) As BoundNode Return GenerateReturn(finished:=True) End Function Public Overrides Function VisitYieldStatement(node As BoundYieldStatement) As BoundNode ' Yield expression ' is translated to - ' Me.current = expression ' Me.state = <next_state> ' return true ' <next_state_label>: ' Me.state = -1 Dim newState = AddState() Return F.SequencePoint( node.Syntax, F.Block( F.Assignment(F.Field(F.Me, Me._current, True), DirectCast(Visit(node.Expression), BoundExpression)), F.Assignment(F.Field(F.Me, Me.StateField, True), F.AssignmentExpression(F.Local(Me.CachedState, True), F.Literal(newState.Number))), GenerateReturn(finished:=False), F.Label(newState.ResumeLabel), F.Assignment(F.Field(F.Me, Me.StateField, True), F.AssignmentExpression(F.Local(Me.CachedState, True), F.Literal(StateMachineStates.NotStartedStateMachine))) ) ) End Function #End Region 'Visitors Friend Overrides Sub AddProxyFieldsForStateMachineScope(proxy As FieldSymbol, proxyFields As ArrayBuilder(Of FieldSymbol)) proxyFields.Add(proxy) End Sub Protected Overrides Function MaterializeProxy(origExpression As BoundExpression, proxy As FieldSymbol) As BoundNode Dim syntax As VisualBasicSyntaxNode = Me.F.Syntax Dim framePointer As BoundExpression = Me.FramePointer(syntax, proxy.ContainingType) Dim proxyFieldParented = proxy.AsMember(DirectCast(framePointer.Type, NamedTypeSymbol)) Return Me.F.Field(framePointer, proxyFieldParented, origExpression.IsLValue) End Function End Class End Class End Namespace
marksantos/roslyn
src/Compilers/VisualBasic/Portable/Lowering/IteratorRewriter/IteratorRewriter.IteratorMethodToClassRewriter.vb
Visual Basic
apache-2.0
9,503
' 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.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedParametersAndValues Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnusedParametersAndValues Public MustInherit Class RemoveUnusedValuesTestsBase Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (New VisualBasicRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), New VisualBasicRemoveUnusedValuesCodeFixProvider()) End Function Protected MustOverride ReadOnly Property PreferNone As IDictionary(Of OptionKey, Object) Protected MustOverride ReadOnly Property PreferDiscard As IDictionary(Of OptionKey, Object) Protected MustOverride ReadOnly Property PreferUnusedLocal As IDictionary(Of OptionKey, Object) Protected Overloads Function TestMissingInRegularAndScriptAsync(initialMarkup As String, options As IDictionary(Of OptionKey, Object)) As Task Return TestMissingInRegularAndScriptAsync(initialMarkup, New TestParameters(options:=options)) End Function End Class End Namespace
VSadov/roslyn
src/EditorFeatures/VisualBasicTest/RemoveUnusedParametersAndValues/RemoveUnusedValuesTestsBase.vb
Visual Basic
apache-2.0
1,568
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading.Tasks Imports Microsoft.VisualStudio.GraphModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression Public Class ImplementedByGraphQueryTests <Fact, Trait(Traits.Feature, Traits.Features.Progression)> Public Async Function TestImplementedBy1() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> using System; interface $$IBlah { } abstract class Base { public abstract int CompareTo(object obj); } class Foo : Base, IComparable, IBlah { public override int CompareTo(object obj) { throw new NotImplementedException(); } } class Foo2 : Base, IBlah { public override int CompareTo(object obj) { throw new NotImplementedException(); } } </Document> </Project> </Workspace>) Dim inputGraph = await testState.GetGraphWithMarkedSymbolNodeAsync() Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New ImplementedByGraphQuery(), GraphContextDirection.Target) AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 Type=Foo)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Foo" Icon="Microsoft.VisualStudio.Class.Internal" Label="Foo"/> <Node Id="(@1 Type=Foo2)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Foo2" Icon="Microsoft.VisualStudio.Class.Internal" Label="Foo2"/> <Node Id="(@1 Type=IBlah)" Category="CodeSchema_Interface" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsInternal="True" CommonLabel="IBlah" Icon="Microsoft.VisualStudio.Interface.Internal" Label="IBlah"/> </Nodes> <Links> <Link Source="(@1 Type=Foo)" Target="(@1 Type=IBlah)" Category="Implements"/> <Link Source="(@1 Type=Foo2)" Target="(@1 Type=IBlah)" Category="Implements"/> </Links> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/> </IdentifierAliases> </DirectedGraph>) End Using End Function End Class End Namespace
weltkante/roslyn
src/VisualStudio/Core/Test/Progression/ImplementedByGraphQueryTests.vb
Visual Basic
apache-2.0
3,010
' Licensed to the .NET Foundation under one or more 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.Security Imports System.Text Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Reflection Imports System.Diagnostics Imports Microsoft.VisualBasic.CompilerServices.ExceptionUtils Imports Microsoft.VisualBasic.CompilerServices.Symbols Namespace Microsoft.VisualBasic.CompilerServices ' Purpose: various helpers for the vb runtime functions Partial Public NotInheritable Class Utils Friend Const SEVERITY_ERROR As Integer = &H80000000I Friend Const FACILITY_CONTROL As Integer = &HA0000I Friend Const FACILITY_RPC As Integer = &H10000I Friend Const FACILITY_ITF As Integer = &H40000I Friend Const SCODE_FACILITY As Integer = &H1FFF0000I Private Const s_ERROR_INVALID_PARAMETER As Integer = 87 Friend Const chPeriod As Char = "."c Friend Const chSpace As Char = ChrW(32) Friend Const chIntlSpace As Char = ChrW(&H3000) Friend Const chZero As Char = "0"c Friend Const chHyphen As Char = "-"c Friend Const chPlus As Char = "+"c Friend Const chLetterA As Char = "A"c Friend Const chLetterZ As Char = "Z"c Friend Const chColon As Char = ":"c Friend Const chSlash As Char = "/"c Friend Const chBackslash As Char = "\"c Friend Const chTab As Char = ControlChars.Tab Friend Const chCharH0A As Char = ChrW(&HA) Friend Const chCharH0B As Char = ChrW(&HB) Friend Const chCharH0C As Char = ChrW(&HC) Friend Const chCharH0D As Char = ChrW(&HD) Friend Const chLineFeed As Char = ChrW(10) Friend Const chDblQuote As Char = ChrW(34) Friend Const chGenericManglingChar As Char = "`"c Friend Const OptionCompareTextFlags As CompareOptions = (CompareOptions.IgnoreCase Or CompareOptions.IgnoreWidth Or CompareOptions.IgnoreKanaType) Private Shared ReadOnly s_resourceManagerSyncObj As Object = New Object Friend Shared m_achIntlSpace() As Char = {chSpace, chIntlSpace} Private Shared ReadOnly s_voidType As Type = System.Type.GetType("System.Void") Private Shared s_VBRuntimeAssembly As System.Reflection.Assembly '============================================================================ ' Shared Error functions '============================================================================ Private Shared Function IntToHex(ByVal n As Integer) As Char System.Diagnostics.Debug.Assert(n < &H10) If n <= 9 Then Return ChrW(n + AscW("0"c)) Else Return ChrW(n - 10 + AscW("a"c)) End If End Function '***************************************************************************** ';GetResourceString ' 'Summary: Retrieves a resource string and formats it by replacing placeholders ' with params. For example if the unformatted string is ' "Hello, {0}" then GetString("StringID", "World") will return "Hello, World" ' This one is exposed because I have to be able to get at localized error ' strings from the MY template ' Param: ID - Identifier for the string to be retrieved ' Param: Args - An array of params used to replace placeholders. 'Returns: The resource string if found or an error message string '***************************************************************************** Public Shared Function GetResourceString(ByVal resourceKey As String, ByVal ParamArray args() As String) As String Return SR.Format(resourceKey, args) End Function Friend Shared Function GetCultureInfo() As CultureInfo Return CultureInfo.CurrentCulture End Function Friend Shared Function GetInvariantCultureInfo() As CultureInfo Return CultureInfo.InvariantCulture End Function Friend Shared ReadOnly Property VBRuntimeAssembly() As System.Reflection.Assembly Get If Not s_VBRuntimeAssembly Is Nothing Then Return s_VBRuntimeAssembly End If ' if the cached assembly ref has not been set, then set it here s_VBRuntimeAssembly = GetType(Utils).Assembly Return s_VBRuntimeAssembly End Get End Property Friend Shared Function ToHalfwidthNumbers(ByVal s As String, ByVal culture As CultureInfo) As String Return s End Function Friend Shared Function IsHexOrOctValue(ByVal value As String, ByRef i64Value As Int64) As Boolean Dim ch As Char Dim length As Integer Dim firstNonspace As Integer Dim tmpValue As String length = value.Length Do While (firstNonspace < length) ch = value.Chars(firstNonspace) 'We check that the length is at least FirstNonspace + 2 because otherwise the function 'will throw undesired exceptions. If ch = "&"c AndAlso firstNonspace + 2 < length Then GoTo GetSpecialValue End If If ch <> chSpace AndAlso ch <> chIntlSpace Then Return False End If firstNonspace += 1 Loop Return False GetSpecialValue: ch = System.Char.ToLowerInvariant(value.Chars(firstNonspace + 1)) tmpValue = ToHalfwidthNumbers(value.Substring(firstNonspace + 2), GetCultureInfo()) If ch = "h"c Then i64Value = System.Convert.ToInt64(tmpValue, 16) ElseIf ch = "o"c Then i64Value = System.Convert.ToInt64(tmpValue, 8) Else Throw New FormatException End If Return True End Function Friend Shared Function IsHexOrOctValue(ByVal value As String, ByRef ui64Value As UInt64) As Boolean Dim ch As Char Dim length As Integer Dim firstNonspace As Integer Dim tmpValue As String length = value.Length Do While (firstNonspace < length) ch = value.Chars(firstNonspace) 'We check that the length is at least FirstNonspace + 2 because otherwise the function 'will throw undesired exceptions. If ch = "&"c AndAlso firstNonspace + 2 < length Then GoTo GetSpecialValue End If If ch <> chSpace AndAlso ch <> chIntlSpace Then Return False End If firstNonspace += 1 Loop Return False GetSpecialValue: ch = System.Char.ToLowerInvariant(value.Chars(firstNonspace + 1)) tmpValue = ToHalfwidthNumbers(value.Substring(firstNonspace + 2), GetCultureInfo()) If ch = "h"c Then ui64Value = System.Convert.ToUInt64(tmpValue, 16) ElseIf ch = "o"c Then ui64Value = System.Convert.ToUInt64(tmpValue, 8) Else Throw New FormatException End If Return True End Function Friend Shared Function VBFriendlyName(ByVal obj As Object) As String If obj Is Nothing Then Return "Nothing" End If Return VBFriendlyName(obj.GetType, obj) End Function Friend Shared Function VBFriendlyName(ByVal typ As System.Type) As String Return VBFriendlyNameOfType(typ) End Function Friend Shared Function VBFriendlyName(ByVal typ As System.Type, ByVal o As Object) As String Return VBFriendlyNameOfType(typ) End Function Friend Shared Function VBFriendlyNameOfType(ByVal typ As System.Type, Optional ByVal fullName As Boolean = False) As String Dim result As String Dim arraySuffix As String arraySuffix = GetArraySuffixAndElementType(typ) Debug.Assert(typ IsNot Nothing AndAlso Not typ.IsArray, "Error in array type processing!!!") Dim tc As TypeCode If typ.IsEnum Then tc = TypeCode.Object Else tc = typ.GetTypeCode End If Select Case tc Case TypeCode.Boolean : result = "Boolean" Case TypeCode.SByte : result = "SByte" Case TypeCode.Byte : result = "Byte" Case TypeCode.Int16 : result = "Short" Case TypeCode.UInt16 : result = "UShort" Case TypeCode.Int32 : result = "Integer" Case TypeCode.UInt32 : result = "UInteger" Case TypeCode.Int64 : result = "Long" Case TypeCode.UInt64 : result = "ULong" Case TypeCode.Decimal : result = "Decimal" Case TypeCode.Single : result = "Single" Case TypeCode.Double : result = "Double" Case TypeCode.DateTime : result = "Date" Case TypeCode.Char : result = "Char" Case TypeCode.String : result = "String" Case Else If IsGenericParameter(typ) Then result = typ.Name Exit Select End If Dim qualifier As String = Nothing 'yes, defaults to nothing but makes a warning go away about use before assignment Dim name As String Dim genericArgsSuffix As String = GetGenericArgsSuffix(typ) If fullName Then If typ.DeclaringType IsNot Nothing Then qualifier = VBFriendlyNameOfType(typ.DeclaringType, fullName:=True) name = typ.Name Else name = typ.FullName ' Some types do not have FullName If name Is Nothing Then name = typ.Name End If End If Else name = typ.Name End If If genericArgsSuffix IsNot Nothing Then Dim manglingCharIndex As Integer = name.LastIndexOf(chGenericManglingChar) If manglingCharIndex <> -1 Then name = name.Substring(0, manglingCharIndex) End If result = name & genericArgsSuffix Else result = name End If If qualifier IsNot Nothing Then result = qualifier & chPeriod & result End If End Select If arraySuffix IsNot Nothing Then result = result & arraySuffix End If Return result End Function Private Shared Function GetArraySuffixAndElementType(ByRef typ As Type) As String If Not typ.IsArray Then Return Nothing End If Dim arraySuffix As New Text.StringBuilder 'Notice the reversing - VB array notation is reverse of clr array notation 'i.e. (,)() in VB is [][,] in clr ' Do arraySuffix.Append("(") arraySuffix.Append(","c, typ.GetArrayRank() - 1) arraySuffix.Append(")") typ = typ.GetElementType Loop While typ.IsArray Return arraySuffix.ToString() End Function Private Shared Function GetGenericArgsSuffix(ByVal typ As Type) As String If Not typ.IsGenericType Then Return Nothing End If Dim typeArgs As Type() = typ.GetGenericArguments Dim totalTypeArgsCount As Integer = typeArgs.Length Dim typeArgsCount As Integer = totalTypeArgsCount If typ.DeclaringType IsNot Nothing AndAlso typ.DeclaringType.IsGenericType Then typeArgsCount = typeArgsCount - typ.DeclaringType.GetGenericArguments().Length End If If typeArgsCount = 0 Then Return Nothing End If Dim genericArgsSuffix As New Text.StringBuilder genericArgsSuffix.Append("(Of ") For i As Integer = totalTypeArgsCount - typeArgsCount To totalTypeArgsCount - 1 genericArgsSuffix.Append(VBFriendlyNameOfType(typeArgs(i))) If i <> totalTypeArgsCount - 1 Then genericArgsSuffix.Append(","c) End If Next genericArgsSuffix.Append(")") Return genericArgsSuffix.ToString End Function Friend Shared Function ParameterToString(ByVal parameter As ParameterInfo) As String Dim resultString As String = "" Dim parameterType As Type = parameter.ParameterType If parameter.IsOptional Then resultString &= "[" End If If parameterType.IsByRef Then resultString &= "ByRef " parameterType = parameterType.GetElementType ElseIf IsParamArray(parameter) Then resultString &= "ParamArray " End If resultString &= parameter.Name & " As " & VBFriendlyNameOfType(parameterType, fullName:=True) If parameter.IsOptional Then Dim defaultValue As Object = parameter.DefaultValue If defaultValue Is Nothing Then resultString &= " = Nothing" Else Dim defaultValueType As System.Type = defaultValue.GetType If defaultValueType IsNot s_voidType Then If IsEnum(defaultValueType) Then Throw New InvalidOperationException() Else resultString &= " = " & CStr(defaultValue) End If End If End If resultString &= "]" End If Return resultString End Function Public Shared Function MethodToString(ByVal method As Reflection.MethodBase) As String Dim returnType As System.Type = Nothing Dim first As Boolean MethodToString = "" If method.MemberType = MemberTypes.Method Then returnType = DirectCast(method, MethodInfo).ReturnType If method.IsPublic Then MethodToString &= "Public " ElseIf method.IsPrivate Then MethodToString &= "Private " ElseIf method.IsAssembly Then MethodToString &= "Friend " End If If (method.Attributes And System.Reflection.MethodAttributes.Virtual) <> 0 Then If Not method.DeclaringType.IsInterface Then MethodToString &= "Overrides " End If ElseIf IsShared(method) Then MethodToString &= "Shared " End If Dim op As UserDefinedOperator = UserDefinedOperator.UNDEF If IsUserDefinedOperator(method) Then op = MapToUserDefinedOperator(method) End If If op <> UserDefinedOperator.UNDEF Then If op = UserDefinedOperator.Narrow Then MethodToString &= "Narrowing " ElseIf op = UserDefinedOperator.Widen Then MethodToString &= "Widening " End If MethodToString &= "Operator " ElseIf returnType Is Nothing OrElse returnType Is s_voidType Then MethodToString &= "Sub " Else MethodToString &= "Function " End If If op <> UserDefinedOperator.UNDEF Then MethodToString &= OperatorNames(op) ElseIf method.MemberType = MemberTypes.Constructor Then MethodToString &= "New" Else MethodToString &= method.Name End If If IsGeneric(method) Then MethodToString &= "(Of " first = True For Each t As Type In GetTypeParameters(method) If Not first Then MethodToString &= ", " Else first = False MethodToString &= VBFriendlyNameOfType(t) Next MethodToString &= ")" End If MethodToString &= "(" first = True For Each parameter As ParameterInfo In method.GetParameters() If Not first Then MethodToString &= ", " Else first = False End If MethodToString &= ParameterToString(parameter) Next MethodToString &= ")" If returnType Is Nothing OrElse returnType Is s_voidType Then 'Sub has no return type Else MethodToString &= " As " & VBFriendlyNameOfType(returnType, fullName:=True) End If End Function Private Enum PropertyKind ReadWrite [ReadOnly] [WriteOnly] End Enum Friend Shared Function PropertyToString(ByVal prop As Reflection.PropertyInfo) As String Dim resultString As String = "" Dim kind As PropertyKind = PropertyKind.ReadWrite Dim parameters As ParameterInfo() Dim propertyType As Type 'Most of the work will be done using the Getter or Setter. Dim accessor As MethodInfo = prop.GetGetMethod If accessor IsNot Nothing Then If prop.GetSetMethod IsNot Nothing Then kind = PropertyKind.ReadWrite Else kind = PropertyKind.ReadOnly End If parameters = accessor.GetParameters propertyType = accessor.ReturnType Else kind = PropertyKind.WriteOnly accessor = prop.GetSetMethod Dim setParameters As ParameterInfo() = accessor.GetParameters parameters = New ParameterInfo(setParameters.Length - 2) {} System.Array.Copy(setParameters, parameters, parameters.Length) propertyType = setParameters(setParameters.Length - 1).ParameterType End If resultString &= "Public " If (accessor.Attributes And MethodAttributes.Virtual) <> 0 Then If Not prop.DeclaringType.IsInterface Then resultString &= "Overrides " End If ElseIf IsShared(accessor) Then resultString &= "Shared " End If If kind = PropertyKind.ReadOnly Then resultString &= "ReadOnly " If kind = PropertyKind.WriteOnly Then resultString &= "WriteOnly " resultString &= "Property " & prop.Name & "(" Dim first As Boolean = True For Each parameter As ParameterInfo In parameters If Not first Then resultString &= ", " Else first = False resultString &= ParameterToString(parameter) Next resultString &= ") As " & VBFriendlyNameOfType(propertyType, fullName:=True) Return resultString End Function Friend Shared Function MemberToString(ByVal member As MemberInfo) As String Select Case member.MemberType Case MemberTypes.Method, MemberTypes.Constructor Return MethodToString(DirectCast(member, MethodBase)) Case MemberTypes.Field Return FieldToString(DirectCast(member, FieldInfo)) Case MemberTypes.Property Return PropertyToString(DirectCast(member, PropertyInfo)) Case Else Return member.Name End Select End Function Friend Shared Function FieldToString(ByVal field As FieldInfo) As String Dim rtype As System.Type FieldToString = "" rtype = field.FieldType If field.IsPublic Then FieldToString &= "Public " ElseIf field.IsPrivate Then FieldToString &= "Private " ElseIf field.IsAssembly Then FieldToString &= "Friend " ElseIf field.IsFamily Then FieldToString &= "Protected " ElseIf field.IsFamilyOrAssembly Then FieldToString &= "Protected Friend " End If FieldToString &= field.Name FieldToString &= " As " FieldToString &= VBFriendlyNameOfType(rtype, fullName:=True) End Function End Class End Namespace
Ermiar/corefx
src/Microsoft.VisualBasic/src/Microsoft/VisualBasic/CompilerServices/Utils.LateBinder.vb
Visual Basic
mit
21,514
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading.Tasks Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Expressions Public Class AwaitKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function InSynchronousMethodTest() As Task Await VerifyRecommendationsContainAsync(<File> Class C Sub Foo() Dim z = | End Sub End Class </File>, "Await") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function InMethodStatementTest() As Task Await VerifyRecommendationsContainAsync(<File> Class C Async Sub Foo() | End Sub End Class </File>, "Await") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function InMethodExpressionTest() As Task Await VerifyRecommendationsContainAsync(<File> Class C Async Sub Foo() Dim z = | End Sub End Class </File>, "Await") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function NotInCatchTest() As Task Await VerifyRecommendationsMissingAsync(<File> Class C Async Sub Foo() Try Catch Dim z = | End Try End Sub End Class </File>, "Await") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function NotInCatchExceptionFilterTest() As Task Await VerifyRecommendationsMissingAsync(<File> Class C Async Sub Foo() Try Catch When Err = | End Try End Sub End Class </File>, "Await") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function InCatchNestedDelegateTest() As Task Await VerifyRecommendationsContainAsync(<File> Class C Async Sub Foo() Try Catch Dim z = Function() | End Try End Sub End Class </File>, "Await") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function NotInFinallyTest() As Task Await VerifyRecommendationsMissingAsync(<File> Class C Async Sub Foo() Try Finally Dim z = | End Try End Sub End Class </File>, "Await") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function NotInSyncLockTest() As Task Await VerifyRecommendationsMissingAsync(<File> Class C Async Sub Foo() SyncLock True Dim z = | End SyncLock End Sub End Class </File>, "Await") End Function End Class End Namespace
ericfe-ms/roslyn
src/EditorFeatures/VisualBasicTest/Recommendations/Expressions/AwaitKeywordRecommenderTests.vb
Visual Basic
apache-2.0
3,342
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Diagnostics Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class LocalRewriter Private Structure XmlLiteralFixupData Public Structure LocalWithInitialization Public ReadOnly Local As LocalSymbol Public ReadOnly Initialization As BoundExpression Public Sub New(local As LocalSymbol, initialization As BoundExpression) Me.Local = local Me.Initialization = initialization End Sub End Structure Private _locals As ArrayBuilder(Of LocalWithInitialization) Public Sub AddLocal(local As LocalSymbol, initialization As BoundExpression) If Me._locals Is Nothing Then Me._locals = ArrayBuilder(Of LocalWithInitialization).GetInstance End If Me._locals.Add(New LocalWithInitialization(local, initialization)) End Sub Public ReadOnly Property IsEmpty As Boolean Get Return Me._locals Is Nothing End Get End Property Public Function MaterializeAndFree() As ImmutableArray(Of LocalWithInitialization) Debug.Assert(Not Me.IsEmpty) Dim materialized = Me._locals.ToImmutableAndFree Me._locals = Nothing Return materialized End Function End Structure End Class End Namespace
physhi/roslyn
src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_XmlLiteralFixupData.vb
Visual Basic
apache-2.0
1,999
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.PreprocessorDirectives ''' <summary> ''' Recommends the "#End Region" directive ''' </summary> Friend Class EndRegionDirectiveKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As IEnumerable(Of RecommendedKeyword) If context.IsPreprocessorEndDirectiveKeywordContext AndAlso HasUnmatchedRegionDirective(context, cancellationToken) Then Return SpecializedCollections.SingletonEnumerable(New RecommendedKeyword("Region", VBFeaturesResources.Terminates_a_SharpRegion_block)) End If If context.IsPreprocessorStartContext Then Dim directives = context.SyntaxTree.GetStartDirectives(cancellationToken) If HasUnmatchedRegionDirective(context, cancellationToken) Then Return SpecializedCollections.SingletonEnumerable(New RecommendedKeyword("#End Region", VBFeaturesResources.Terminates_a_SharpRegion_block)) End If End If Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)() End Function Private Function HasUnmatchedRegionDirective(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As Boolean Dim directives = context.SyntaxTree.GetStartDirectives(cancellationToken) For Each directive In directives If directive.Kind = SyntaxKind.RegionDirectiveTrivia AndAlso directive.Span.End <= context.Position Then If directive.GetMatchingStartOrEndDirective(cancellationToken) Is Nothing Then Return True End If End If Next Return False End Function End Class End Namespace
jhendrixMSFT/roslyn
src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/PreprocessorDirectives/EndRegionDirectiveKeywordRecommender.vb
Visual Basic
apache-2.0
2,286
' 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.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 VisualBasicSyntaxNode, <[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 VisualBasicSyntaxNode, <[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 VisualBasicSyntaxNode, <[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 VisualBasicSyntaxNode, 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.IsSameTypeIgnoringCustomModifiers(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.IsSameTypeIgnoringCustomModifiers(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.IsSameTypeIgnoringCustomModifiers(argType) Then Return ApplicabilityComparisonResult.LeftIsMoreApplicable End If If right.IsSameTypeIgnoringCustomModifiers(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.IsSameTypeIgnoringCustomModifiers(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 VisualBasicSyntaxNode, 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 Foo(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 Foo(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 VisualBasicSyntaxNode, 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 arrayType.Rank <> 1 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.IsSameTypeIgnoringCustomModifiers(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 VisualBasicSyntaxNode) As Boolean Dim parent As VisualBasicSyntaxNode = 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 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 Then 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.IsSameTypeIgnoringCustomModifiers(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.IsSameTypeIgnoringCustomModifiers(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.IsSameTypeIgnoringCustomModifiers(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.Rank = rightArray.Rank 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, NamedTypeSymbol) Dim rightNamedType = DirectCast(rightType, 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.IsSameTypeIgnoringCustomModifiers(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.IsSameTypeIgnoringCustomModifiers(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
droyad/roslyn
src/Compilers/VisualBasic/Portable/Semantics/OverloadResolution.vb
Visual Basic
apache-2.0
249,103
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports Microsoft.Cci Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' A representation of a property symbol that is intended only to be used for comparison purposes ''' (esp in PropertySignatureComparer). ''' </summary> Friend Class SignatureOnlyPropertySymbol Inherits PropertySymbol Private ReadOnly _name As String Private ReadOnly _containingType As NamedTypeSymbol Private ReadOnly _isReadOnly As Boolean Private ReadOnly _isWriteOnly As Boolean Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) Private ReadOnly _returnsByRef As Boolean Private ReadOnly _type As TypeSymbol Private ReadOnly _typeCustomModifiers As ImmutableArray(Of CustomModifier) Private ReadOnly _refCustomModifiers As ImmutableArray(Of CustomModifier) Private ReadOnly _isOverrides As Boolean Private ReadOnly _isWithEvents As Boolean Public Sub New(name As String, containingType As NamedTypeSymbol, isReadOnly As Boolean, isWriteOnly As Boolean, parameters As ImmutableArray(Of ParameterSymbol), returnsByRef As Boolean, [type] As TypeSymbol, typeCustomModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier), Optional isOverrides As Boolean = False, Optional isWithEvents As Boolean = False) _name = name _containingType = containingType _isReadOnly = isReadOnly _isWriteOnly = isWriteOnly _parameters = parameters _returnsByRef = returnsByRef _type = [type] _typeCustomModifiers = typeCustomModifiers _refCustomModifiers = refCustomModifiers _isOverrides = isOverrides _isWithEvents = isWithEvents End Sub Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingType End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return _containingType End Get End Property Public Overrides ReadOnly Property IsReadOnly As Boolean Get Return _isReadOnly End Get End Property Public Overrides ReadOnly Property IsWriteOnly As Boolean Get Return _isWriteOnly End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return _returnsByRef End Get End Property Public Overrides ReadOnly Property Type As TypeSymbol Get Return _type End Get End Property Public Overrides ReadOnly Property TypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Return _typeCustomModifiers End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return _refCustomModifiers End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Nothing End Get End Property #Region "Not used by PropertySignatureComparer" Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Throw ExceptionUtilities.Unreachable End Get End Property Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of PropertySymbol) Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property GetMethod As MethodSymbol Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property SetMethod As MethodSymbol Get Throw ExceptionUtilities.Unreachable End Get End Property Friend Overrides ReadOnly Property AssociatedField As FieldSymbol Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property IsDefault As Boolean Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return _isOverrides End Get End Property Public Overrides ReadOnly Property IsWithEvents As Boolean Get Return _isWithEvents End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Throw ExceptionUtilities.Unreachable End Get End Property Friend Overrides ReadOnly Property IsMyGroupCollectionProperty As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of PropertySymbol) Get Throw ExceptionUtilities.Unreachable End Get End Property #End Region End Class End Namespace
sharwell/roslyn
src/Compilers/VisualBasic/Portable/Symbols/SignatureOnlyPropertySymbol.vb
Visual Basic
mit
8,018
'-------------------------------------------------------------------------------------------' ' Inicio del codigo '-------------------------------------------------------------------------------------------' ' Importando librerias '-------------------------------------------------------------------------------------------' Imports System.Data '-------------------------------------------------------------------------------------------' ' Inicio de clase "rBcotizaciones_Totalizadas" '-------------------------------------------------------------------------------------------' Partial Class rBcotizaciones_Totalizadas Inherits vis2formularios.frmReporte Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Try Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0)) Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0)) Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia) Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia) Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2)) Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2)) Dim lcParametro3Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(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 loComandoSeleccionar As New StringBuilder() loComandoSeleccionar.AppendLine(" SELECT Cotizaciones.Cod_Ven, ") loComandoSeleccionar.AppendLine(" SUM((CASE WHEN Cotizaciones.Cod_For = '102' THEN Renglones_Cotizaciones.Can_Art1 ELSE 0 END)) As P_Alta, ") loComandoSeleccionar.AppendLine(" SUM((CASE WHEN Cotizaciones.Cod_For = '101' THEN Renglones_Cotizaciones.Can_Art1 ELSE 0 END)) As P_Media, ") loComandoSeleccionar.AppendLine(" SUM((CASE WHEN Cotizaciones.Cod_For = '100' THEN Renglones_Cotizaciones.Can_Art1 ELSE 0 END)) As P_Baja ") 'loComandoSeleccionar.AppendLine(" Renglones_Cotizaciones.Renglon, ") 'loComandoSeleccionar.AppendLine(" Cotizaciones.Cod_Tra, ") 'loComandoSeleccionar.AppendLine(" Cotizaciones.Cod_For, ") 'loComandoSeleccionar.AppendLine(" Cotizaciones.Cod_Cli, ") 'loComandoSeleccionar.AppendLine(" Renglones_Cotizaciones.Documento ") loComandoSeleccionar.AppendLine(" FROM Cotizaciones, ") loComandoSeleccionar.AppendLine(" Renglones_Cotizaciones ") loComandoSeleccionar.AppendLine(" WHERE Cotizaciones.Documento = Renglones_Cotizaciones.Documento ") loComandoSeleccionar.AppendLine(" AND Cotizaciones.Documento BETWEEN " & lcParametro0Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta) loComandoSeleccionar.AppendLine(" AND Cotizaciones.Fec_Ini BETWEEN " & lcParametro1Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta) loComandoSeleccionar.AppendLine(" AND Cotizaciones.Cod_Cli BETWEEN " & lcParametro2Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta) loComandoSeleccionar.AppendLine(" AND Cotizaciones.Status IN (" & lcParametro3Desde & ")") loComandoSeleccionar.AppendLine(" AND Cotizaciones.Cod_Ven BETWEEN " & lcParametro4Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta) loComandoSeleccionar.AppendLine(" AND Cotizaciones.Cod_For BETWEEN " & lcParametro5Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta) loComandoSeleccionar.AppendLine(" GROUP BY Cotizaciones.Cod_Ven ") 'loComandoSeleccionar.AppendLine(" Cotizaciones.Cod_For, ") 'loComandoSeleccionar.AppendLine(" Renglones_Cotizaciones.Renglon, ") 'loComandoSeleccionar.AppendLine(" Cotizaciones.Cod_Tra, ") 'loComandoSeleccionar.AppendLine(" Cotizaciones.Cod_Cli, ") 'loComandoSeleccionar.AppendLine(" Renglones_Cotizaciones.Documento ") loComandoSeleccionar.AppendLine(" ORDER BY Cotizaciones.Cod_Ven ") 'Me.Response.Clear() 'Me.Response.ContentType = "text/plain" 'Me.Response.Write(loComandoSeleccionar.ToString()) 'Me.Response.Flush() 'Me.Response.End() 'Return Dim loServicios As New cusDatos.goDatos Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString(), "curReportes") loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rBcotizaciones_Totalizadas", laDatosReporte) Me.mTraducirReporte(loObjetoReporte) Me.mFormatearCamposReporte(loObjetoReporte) Me.crvrBcotizaciones_Totalizadas.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 '-------------------------------------------------------------------------------------------' ' MVP: 13/08/08: Codigo inicial '-------------------------------------------------------------------------------------------' ' CMS: 27/04/09: Estandarización de código '-------------------------------------------------------------------------------------------' ' JJD: 01/05/09: Ajustes al Select '-------------------------------------------------------------------------------------------'
kodeitsolutions/ef-reports
rBcotizaciones_Totalizadas.aspx.vb
Visual Basic
mit
7,414
'------------------------------------------------------------------------------ ' <auto-generated> ' Dieser Code wurde von einem Tool generiert. ' Laufzeitversion:4.0.30319.18444 ' ' Ä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("Softeis.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 '''<summary> ''' Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property _10Rp_front() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("10Rp_front", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property _1Fr_front() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("1Fr_front", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property _20Rp_front() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("20Rp_front", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property _2Fr_front() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("2Fr_front", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property _50Rp_front() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("50Rp_front", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property _5Fr_front() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("5Fr_front", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property End Module End Namespace
lbischof/gibb
303_Softeis/Softeis/My Project/Resources.Designer.vb
Visual Basic
mit
5,378
Imports System.IO Public Structure PROFILE_STEP Public StartTemperature_C As Single Public EndTemperature_C As Single Public Duration_seconds As UInt32 Public Function Serialize() As Byte() Using ms As New MemoryStream() ms.Write(BitConverter.GetBytes(StartTemperature_C), 0, 4) ms.Write(BitConverter.GetBytes(EndTemperature_C), 0, 4) ms.Write(BitConverter.GetBytes(Duration_seconds), 0, 4) Return ms.ToArray() End Using End Function Public Sub New(sourceData As Byte(), sourceOffset As Integer) Dim offset As Integer = sourceOffset StartTemperature_C = CSng(BitConverter.ToSingle(sourceData, offset)) offset += 4 EndTemperature_C = CSng(BitConverter.ToSingle(sourceData, offset)) offset += 4 Duration_seconds = BitConverter.ToUInt32(sourceData, offset) offset += 4 End Sub Public Sub New(StartTemp As Double, EndTemp As Double, Duration As Integer) Me.StartTemperature_C = StartTemp Me.EndTemperature_C = EndTemp Me.Duration_seconds = Duration End Sub Public Overrides Function ToString() As String Return StartTemperature_C.ToString & "C to " & EndTemperature_C.ToString & "C Over " & Duration_seconds & " Seconds" End Function End Structure
pdoh00/Time2Brew-FermentationController
HardwareDriver/TestApp/DataStructures/PROFILE_STEP.vb
Visual Basic
mit
1,350
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class frmConversion 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.lblMiles = New System.Windows.Forms.Label() Me.lblYards = New System.Windows.Forms.Label() Me.lblFeet = New System.Windows.Forms.Label() Me.lblInches = New System.Windows.Forms.Label() Me.txtMiles = New System.Windows.Forms.TextBox() Me.txtYards = New System.Windows.Forms.TextBox() Me.txtFeet = New System.Windows.Forms.TextBox() Me.txtInches = New System.Windows.Forms.TextBox() Me.btnConvert = New System.Windows.Forms.Button() Me.lstResults = New System.Windows.Forms.ListBox() Me.SuspendLayout() ' 'lblMiles ' Me.lblMiles.AutoSize = True Me.lblMiles.Location = New System.Drawing.Point(16, 31) Me.lblMiles.Name = "lblMiles" Me.lblMiles.Size = New System.Drawing.Size(34, 13) Me.lblMiles.TabIndex = 0 Me.lblMiles.Text = "Miles:" ' 'lblYards ' Me.lblYards.AutoSize = True Me.lblYards.Location = New System.Drawing.Point(13, 57) Me.lblYards.Name = "lblYards" Me.lblYards.Size = New System.Drawing.Size(37, 13) Me.lblYards.TabIndex = 1 Me.lblYards.Text = "Yards:" ' 'lblFeet ' Me.lblFeet.AutoSize = True Me.lblFeet.Location = New System.Drawing.Point(19, 83) Me.lblFeet.Name = "lblFeet" Me.lblFeet.Size = New System.Drawing.Size(31, 13) Me.lblFeet.TabIndex = 2 Me.lblFeet.Text = "Feet:" ' 'lblInches ' Me.lblInches.AutoSize = True Me.lblInches.Location = New System.Drawing.Point(8, 109) Me.lblInches.Name = "lblInches" Me.lblInches.Size = New System.Drawing.Size(42, 13) Me.lblInches.TabIndex = 3 Me.lblInches.Text = "Inches:" ' 'txtMiles ' Me.txtMiles.Location = New System.Drawing.Point(56, 28) Me.txtMiles.Name = "txtMiles" Me.txtMiles.Size = New System.Drawing.Size(100, 20) Me.txtMiles.TabIndex = 4 ' 'txtYards ' Me.txtYards.Location = New System.Drawing.Point(56, 54) Me.txtYards.Name = "txtYards" Me.txtYards.Size = New System.Drawing.Size(100, 20) Me.txtYards.TabIndex = 5 ' 'txtFeet ' Me.txtFeet.Location = New System.Drawing.Point(56, 80) Me.txtFeet.Name = "txtFeet" Me.txtFeet.Size = New System.Drawing.Size(100, 20) Me.txtFeet.TabIndex = 6 ' 'txtInches ' Me.txtInches.Location = New System.Drawing.Point(56, 106) Me.txtInches.Name = "txtInches" Me.txtInches.Size = New System.Drawing.Size(100, 20) Me.txtInches.TabIndex = 7 ' 'btnConvert ' Me.btnConvert.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.btnConvert.Location = New System.Drawing.Point(187, 12) Me.btnConvert.Name = "btnConvert" Me.btnConvert.Size = New System.Drawing.Size(150, 35) Me.btnConvert.TabIndex = 8 Me.btnConvert.Text = "Convert to Metric" Me.btnConvert.UseVisualStyleBackColor = True ' 'lstResults ' Me.lstResults.FormattingEnabled = True Me.lstResults.Location = New System.Drawing.Point(187, 57) Me.lstResults.Name = "lstResults" Me.lstResults.Size = New System.Drawing.Size(150, 69) Me.lstResults.TabIndex = 9 ' 'frmConversion ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(354, 142) Me.Controls.Add(Me.lstResults) Me.Controls.Add(Me.btnConvert) Me.Controls.Add(Me.txtInches) Me.Controls.Add(Me.txtFeet) Me.Controls.Add(Me.txtYards) Me.Controls.Add(Me.txtMiles) Me.Controls.Add(Me.lblInches) Me.Controls.Add(Me.lblFeet) Me.Controls.Add(Me.lblYards) Me.Controls.Add(Me.lblMiles) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog Me.MaximizeBox = False Me.Name = "frmConversion" Me.Text = "Length Conversion" Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents lblMiles As System.Windows.Forms.Label Friend WithEvents lblYards As System.Windows.Forms.Label Friend WithEvents lblFeet As System.Windows.Forms.Label Friend WithEvents lblInches As System.Windows.Forms.Label Friend WithEvents txtMiles As System.Windows.Forms.TextBox Friend WithEvents txtYards As System.Windows.Forms.TextBox Friend WithEvents txtFeet As System.Windows.Forms.TextBox Friend WithEvents txtInches As System.Windows.Forms.TextBox Friend WithEvents btnConvert As System.Windows.Forms.Button Friend WithEvents lstResults As System.Windows.Forms.ListBox End Class
patkub/visual-basic-intro
Length Conversion/Length Conversion/frmConversion.Designer.vb
Visual Basic
mit
5,950
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("nunit.tests.vb")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("nunit.tests.vb")> <Assembly: AssemblyCopyright("Copyright © 2019")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> ' 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")>
nunit/nunit.templates
nunit.tests.vb/My Project/AssemblyInfo.vb
Visual Basic
mit
1,003
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.0 ' ' 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.Explorer.My.MySettings Get Return Global.Explorer.My.MySettings.Default End Get End Property End Module End Namespace
jcrout/Explorer
Explorer/My Project/Settings.Designer.vb
Visual Basic
mit
2,902
Public Class Form1 'Variables Dim intAge, intMonths, intTotalMonths As Integer Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalc.Click 'Assign Variables intAge = CInt(txtAge.Text) intMonths = CInt(txtMonths.Text) 'Calculate intTotalMonths = intAge * 12 + intMonths 'Display MessageBox.Show("You are " + CStr(intTotalMonths) + " Months old!") 'Clear txtAge.Clear() txtMonths.Clear() End Sub End Class ' ****************** ' * Kaleb Haslam * ' * Age Calculator * ' ******************
hhaslam11/Visual-Basic-Projects
Age in Months/Age in Months/Form1.vb
Visual Basic
mit
651
' Copyright 2015, Google Inc. All Rights Reserved. ' ' Licensed under the Apache License, Version 2.0 (the "License"); ' you may not use this file except in compliance with the License. ' You may obtain a copy of the License at ' ' http://www.apache.org/licenses/LICENSE-2.0 ' ' Unless required by applicable law or agreed to in writing, software ' distributed under the License is distributed on an "AS IS" BASIS, ' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ' See the License for the specific language governing permissions and ' limitations under the License. ' Author: api.anash@gmail.com (Anash P. Oommen) Imports Google.Api.Ads.AdWords.Lib Imports Google.Api.Ads.AdWords.v201506 Imports System Imports System.Collections.Generic Imports System.IO Imports System.Web Namespace Google.Api.Ads.AdWords.Examples.VB.v201506 ''' <summary> ''' This code example adds keywords to an ad group. To get ad groups, run ''' GetAdGroups.vb. ''' ''' Tags: AdGroupCriterionService.mutate ''' </summary> Public Class AddKeywords Inherits ExampleBase ''' <summary> ''' Items being added in this code example. ''' </summary> ReadOnly KEYWORDS As String() = New String() {"mars cruise", "space hotel"} ''' <summary> ''' Main method, to run this code example as a standalone application. ''' </summary> ''' <param name="args">The command line arguments.</param> Public Shared Sub Main(ByVal args As String()) Dim codeExample As New AddKeywords Console.WriteLine(codeExample.Description) Try Dim adGroupId As Long = Long.Parse("INSERT_ADGROUP_ID_HERE") codeExample.Run(New AdWordsUser, adGroupId) Catch ex As Exception Console.WriteLine("An exception occurred while running this code example. {0}", _ ExampleUtilities.FormatException(ex)) End Try End Sub ''' <summary> ''' Returns a description about the code example. ''' </summary> Public Overrides ReadOnly Property Description() As String Get Return "This code example adds keywords to an ad group. To get ad groups, run " & _ "GetAdGroups.vb." End Get End Property ''' <summary> ''' Runs the code example. ''' </summary> ''' <param name="user">The AdWords user.</param> ''' <param name="adGroupId">Id of the ad group to which keywords are added. ''' </param> Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId As Long) ' Get the AdGroupCriterionService. Dim adGroupCriterionService As AdGroupCriterionService = CType(user.GetService( _ AdWordsService.v201506.AdGroupCriterionService), AdWords.v201506.AdGroupCriterionService) Dim operations As New List(Of AdGroupCriterionOperation) For Each keywordText As String In KEYWORDS ' Create the keyword. Dim keyword As New Keyword keyword.text = keywordText keyword.matchType = KeywordMatchType.BROAD ' Create the biddable ad group criterion. Dim keywordCriterion As New BiddableAdGroupCriterion keywordCriterion.adGroupId = adGroupId keywordCriterion.criterion = keyword ' Optional: Set the user status. keywordCriterion.userStatus = UserStatus.PAUSED ' Optional: Set the keyword destination url. keywordCriterion.finalUrls = New UrlList() keywordCriterion.finalUrls.urls = New String() {"http://example.com/mars/cruise/?kw=" & _ HttpUtility.UrlEncode(keywordText)} ' Create the operations. Dim operation As New AdGroupCriterionOperation operation.operator = [Operator].ADD operation.operand = keywordCriterion operations.Add(operation) Next Try ' Create the keywords. Dim retVal As AdGroupCriterionReturnValue = adGroupCriterionService.mutate( _ operations.ToArray()) ' Display the results. If ((Not retVal Is Nothing) AndAlso (Not retVal.value Is Nothing)) Then For Each adGroupCriterion As AdGroupCriterion In retVal.value ' If you are adding multiple type of criteria, then you may need to ' check for ' ' if (adGroupCriterion is Keyword) { ... } ' ' to identify the criterion type. Console.WriteLine("Keyword with ad group id = '{0}, keyword id = '{1}, text = " & _ "'{2}' and match type = '{3}' was created.", adGroupCriterion.adGroupId, _ adGroupCriterion.criterion.id, TryCast(adGroupCriterion.criterion, Keyword).text, _ TryCast(adGroupCriterion.criterion, Keyword).matchType) Next Else Console.WriteLine("No keywords were added.") End If Catch ex As Exception Throw New System.ApplicationException("Failed to create keywords.", ex) End Try End Sub End Class End Namespace
stevemanderson/googleads-dotnet-lib
examples/AdWords/Vb/v201506/BasicOperations/AddKeywords.vb
Visual Basic
apache-2.0
4,978
Imports System.Resources Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' Allgemeine Informationen über eine Assembly werden über die folgenden ' Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, ' die mit einer Assembly verknüpft sind. ' Die Werte der Assemblyattribute überprüfen <Assembly: AssemblyTitle("BinDiff")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("BinDiff")> <Assembly: AssemblyCopyright("Moritz Bellach")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird <Assembly: Guid("4dcc6c2d-b4e9-4842-95fb-58e19989ccaa")> ' Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: ' ' Hauptversion ' Nebenversion ' Buildnummer ' Revision ' ' Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern ' übernehmen, indem Sie "*" eingeben: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")> <Assembly: NeutralResourcesLanguageAttribute("en")>
flat235/BinDiff
My Project/AssemblyInfo.vb
Visual Basic
bsd-2-clause
1,265
Imports System.Windows Imports System.Windows.Controls Imports ESRI.ArcGIS.Client.Symbols Partial Public Class MarkerSymbolAngle Inherits UserControl Public Sub New() InitializeComponent() End Sub Private Sub RadioButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Dim angleTag As String = CStr((CType(sender, RadioButton)).Tag) TryCast(LayoutRoot.Resources("MyAngleSymbol"), MarkerSymbol).AngleAlignment = CType(System.Enum.Parse(GetType(MarkerSymbol.MarkerAngleAlignment), angleTag, True), MarkerSymbol.MarkerAngleAlignment) End Sub End Class
MrChen2015/arcgis-samples-silverlight
src/VBNet/ArcGISSilverlightSDK/Graphics/MarkerSymbolAngle.xaml.vb
Visual Basic
apache-2.0
610
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:$clrversion$ ' ' 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("$safeprojectname$.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
russpowers/ILSupport
IL Support.ProjectTemplates/VisualBasic/WindowsApplication/Resources.Designer.vb
Visual Basic
mit
2,785
' 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.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Partial Public Class GetExtendedSemanticInfoTests <Fact> Public Sub Lambda1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Dim x As String = Nothing Dim y As System.Action(Of String) = Sub(z) z.Clone()'BIND:"z" End Sub End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("z As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Lambda2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Dim x As String = Nothing Dim y As System.Action(Of String) = Sub(z) z.Clone()'BIND:"z" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("z As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Lambda3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Dim x As String = Nothing Dim y As System.Func(Of String, Object) = Function(z) Return z.Clone() 'BIND:"z" End Sub End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("z As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Lambda4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Dim x As String = Nothing Dim y As System.Func(Of String, Object) = Function(z) z.Clone()'BIND:"z" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("z As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Lambda5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Module1 Sub Main() Dim x As String = Nothing Dim y As System.Func(Of System.Action(Of String)) = Function() Sub(z) z.Clone() 'BIND:"z" End Sub End Sub End Module </file> </compilation>) Dim node As ExpressionSyntax = FindBindingText(Of ExpressionSyntax)(compilation, "a.vb") Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim semanticInfo As SemanticInfoSummary = CompilationUtils.GetSemanticInfoSummary(semanticModel, DirectCast(node, ExpressionSyntax)) Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.NotNull(semanticInfo.Symbol) Dim paramSymbol = semanticInfo.Symbol Assert.Equal("z As System.String", paramSymbol.ToTestDisplayString()) ' Get info again semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, DirectCast(node, ExpressionSyntax)) Assert.Same(paramSymbol, semanticInfo.Symbol) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, DirectCast(node.Parent.Parent, ExpressionSyntax)) Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString()) End Sub <Fact> Public Sub Lambda6() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Dim x As String = Nothing Test(Function() Sub(z) z.Clone()'BIND:"z" End Sub) End Sub Sub Test(v As System.Func(Of System.Action(Of String))) End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("z As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Lambda7() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Dim x As String = Nothing Test(Function() Sub(z) z.Clone()'BIND:"z" End Sub) End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("z As System.Object", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Lambda8() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Dim x As String = Nothing Test(Function() Function(z As String) Return z.Clone()'BIND:"z" End Function) End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("z As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Lambda9() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Dim x As String = Nothing Test(Function() As System.Func(Of String, Object) Return Function(z) Return z.Clone()'BIND:"z" End Function End Function) End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("z As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Lambda10() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Test(Sub(x As System.Func(Of String, Object)) x = Function(z) Return z.Clone()'BIND:"z" End Function End Sub) End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("z As System.String", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Lambda11() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Test(Sub(x As System.Func(Of String, Object)) x = Function(z) Dim y As System.Guid Return y'BIND:"y" End Function End Sub) End Sub 'Sub Test(p As System.Action(Of System.Func(Of String, Object))) 'End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Guid", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningValue, semanticInfo.ImplicitConversion.Kind) Assert.Equal("y As System.Guid", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Lambda12() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Test(Sub(x As System.Func(Of String, Object)) x = Function(z) If z Is Nothing Dim y As System.Guid Return y'BIND:"y" End If Return z End Function End Sub) End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("System.Guid", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningValue, semanticInfo.ImplicitConversion.Kind) Assert.Equal("y As System.Guid", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact> Public Sub Lambda13() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation name="GetSemanticInfo"> <file name="a.vb"> Module Module1 Sub Main() Dim x As System.Func(Of String, Object) = Function(z) z 'BIND:"Function(z) z" End Sub End Module </file> </compilation>) Dim node As ExpressionSyntax = FindBindingText(Of ExpressionSyntax)(compilation, "a.vb") Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim semanticInfo1 = CompilationUtils.GetSemanticInfoSummary(semanticModel, DirectCast(node, ExpressionSyntax)) Assert.Null(semanticInfo1.Type) Assert.NotNull(semanticInfo1.Symbol) Assert.IsAssignableFrom(Of LambdaSymbol)(semanticInfo1.Symbol) Assert.Equal("System.Func(Of System.String, System.Object)", semanticInfo1.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWidening, semanticInfo1.ImplicitConversion.Kind) Dim semanticInfo2 = CompilationUtils.GetSemanticInfoSummary(semanticModel, DirectCast(node, ExpressionSyntax)) Assert.Equal("System.Func(Of System.String, System.Object)", semanticInfo2.ConvertedType.ToTestDisplayString()) Assert.NotNull(semanticInfo2.Symbol) Assert.IsAssignableFrom(Of LambdaSymbol)(semanticInfo2.Symbol) Assert.Same(semanticInfo1.Symbol, semanticInfo2.Symbol) Assert.Equal("Function (z As System.String) As System.Object", semanticInfo2.Symbol.ToTestDisplayString()) End Sub <Fact> Public Sub Lambda14() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() Me.GetNameToMembersMap(). Where(Function(kvp) kvp.Value.Any(Function(v) v.Kind = SymbolKind.NamedType)). 'BIND1:"kvp" ToDictionary( Function(kvp) kvp.Key, 'BIND2:"kvp" Function(kvp) kvp.Value.OfType(Of NamedTypeSymbol)().AsReadOnly(), IdentifierComparison.Comparer) End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As ExpressionSyntax = FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1) Dim semanticInfo1 = CompilationUtils.GetSemanticInfoSummary(semanticModel, node1) Dim node2 As ExpressionSyntax = FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 2) Dim semanticInfo2 = CompilationUtils.GetSemanticInfoSummary(semanticModel, node2) End Sub <Fact> Public Sub Bug8643() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Try Catch ex As Exception When (Function(e 'BIND1:"e" End Try End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As ModifiedIdentifierSyntax = FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1) Dim e = semanticModel.GetDeclaredSymbol(node1) Assert.Equal(SymbolKind.Parameter, e.Kind) Assert.Equal("e", e.Name) Assert.Same(e, semanticModel.GetDeclaredSymbol(DirectCast(node1, VisualBasicSyntaxNode))) Assert.Same(e, semanticModel.GetDeclaredSymbol(node1.Parent)) Assert.Same(e, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent, ParameterSyntax))) End Sub <Fact> Public Sub Bug8522() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Class A Sub New(x As Action) End Sub Public Const X As Integer = 0 End Class Class C Inherits Attribute Sub New(x As Integer) End Sub End Class <C(New A(Sub() M.Main).X)> 'BIND1:"Main" Module M Friend Const main As Object=Main Sub Main End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As ExpressionSyntax = FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1) Dim semanticInfo1 = CompilationUtils.GetSemanticInfoSummary(semanticModel, node1) Assert.Equal(2, semanticInfo1.AllSymbols.Length) End Sub <WorkItem(9805, "DevDiv_Projects/Roslyn")> <Fact> Public Sub LambdaInWhileStatement() Dim compilation = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Module Test Sub Sub1() While Function() True 'BIND1:"Function() True" End While End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As ExpressionSyntax = FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1) Dim semanticInfo1 = CompilationUtils.GetSemanticInfoSummary(semanticModel, node1) Assert.NotNull(semanticInfo1.Symbol) End Sub <Fact> Public Sub SingleLineLambdaWithDimStatement() Dim compilation = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Module Test Sub Sub1() ' Even though it is an error to have a dim as the statement in the single line sub ' verify that GetDeclaredSymbol returns y with the correct type. dim x = Sub dim y as integer = 1 'BIND1:"y" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As ModifiedIdentifierSyntax = FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1) Dim symbol = DirectCast(semanticModel.GetDeclaredSymbol(node1), LocalSymbol) Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()) End Sub <Fact, WorkItem(544647, "DevDiv")> Public Sub InvokeGenericOverloadedMethod() Dim compilation = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="InstantiatingNamespace"> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Public Class C Public Shared Sub Check(Of T)(p1 As IEnumerable(Of T), p2 As IEnumerable(Of T), p3 As IEqualityComparer(Of T)) End Sub Public Shared Sub Check(Of T)(p1 As T, p2 As T, p3 As IEqualityComparer(Of T)) End Sub End Class Module M Sub Main() Dim list = {"AA", "BB"} C.Check(list.Select(Function(r) r), {"aa", "Bb"}, StringComparer.OrdinalIgnoreCase) End Sub End Module </file> </compilation>, additionalRefs:={SystemCoreRef}) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of InvocationExpressionSyntax)().First() Assert.Equal("C.Check(list.Select(Function(r) r), {""aa"", ""Bb""}, StringComparer.OrdinalIgnoreCase)", node.ToString()) Dim info = model.GetSymbolInfo(node) Assert.Equal(CandidateReason.None, info.CandidateReason) Assert.NotNull(info.Symbol) End Sub <Fact, WorkItem(566495, "DevDiv")> Public Sub Bug566495() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System.Linq Imports System.Collections Imports System.Collections.Generic Module Program Sub Main() Dim L As New List(Of Foo) For i As Integer = 1 To 10 Dim F As New Foo F.Id = i F.Name = "some text" L.Add(F) Next Dim L2 = L.Zip(L, Function(x, y) Return x. 'BIND:"x" End Function).ToList End Sub Public Class Foo Public Property Name As String Public Property Id As Integer End Class End Module ]]></file> </compilation>, {SystemCoreRef}) AssertTheseDiagnostics(compilation, <expected> BC36646: Data type(s) of the type parameter(s) in extension method 'Public Function Zip(Of TSecond, TResult)(second As IEnumerable(Of TSecond), resultSelector As Func(Of Program.Foo, TSecond, TResult)) As IEnumerable(Of TResult)' defined in 'Enumerable' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. Dim L2 = L.Zip(L, Function(x, y) ~~~ BC30203: Identifier expected. Return x. 'BIND:"x" ~ </expected>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Assert.Equal("Program.Foo", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("Program.Foo", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("x As Program.Foo", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact, WorkItem(960755, "DevDiv")> Public Sub Bug960755_01() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="InstantiatingNamespace"> <file name="a.vb"> Imports System.Collections.Generic Class C Sub M(c As IList(Of C)) Dim tmp = New C() tmp.M(Function(a, b) AddressOf c.Add) 'BIND:"c.Add" End Sub End Class </file> </compilation>) Dim node = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb") Dim semanticModel = compilation.GetSemanticModel(node.SyntaxTree) Dim symbolInfo = semanticModel.GetSymbolInfo(node) Assert.Null(symbolInfo.Symbol) Assert.Equal("Sub System.Collections.Generic.ICollection(Of C).Add(item As C)", symbolInfo.CandidateSymbols.Single().ToTestDisplayString()) Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason) End Sub <Fact, WorkItem(960755, "DevDiv")> Public Sub Bug960755_02() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="InstantiatingNamespace"> <file name="a.vb"> Imports System.Collections.Generic Class C Sub M(c As IList(Of C)) Dim tmp As Integer = AddressOf c.Add 'BIND:"c.Add" End Sub End Class </file> </compilation>) Dim node = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb") Dim semanticModel = compilation.GetSemanticModel(node.SyntaxTree) Dim symbolInfo = semanticModel.GetSymbolInfo(node) Assert.Null(symbolInfo.Symbol) Assert.Equal("Sub System.Collections.Generic.ICollection(Of C).Add(item As C)", symbolInfo.CandidateSymbols.Single().ToTestDisplayString()) Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason) End Sub <Fact, WorkItem(960755, "DevDiv")> Public Sub Bug960755_03() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="InstantiatingNamespace"> <file name="a.vb"> Imports System.Collections.Generic Class C Sub M(c As IList(Of C)) Dim tmp = New C() tmp.M(Function(a, b) AddressOf c.Add) 'BIND:"c.Add" End Sub Sub M(x as System.Func(Of Integer, Integer, System.Action(Of C))) End Sub End Class </file> </compilation>) Dim node = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb") Dim semanticModel = compilation.GetSemanticModel(node.SyntaxTree) Dim symbolInfo = semanticModel.GetSymbolInfo(node) Assert.Equal("Sub System.Collections.Generic.ICollection(Of C).Add(item As C)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub End Class End Namespace
ManishJayaswal/roslyn
src/Compilers/VisualBasic/Test/Semantic/Semantics/LambdaSemanticInfoTests.vb
Visual Basic
apache-2.0
30,985
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class AccessorDeclarationHighlighter Inherits AbstractKeywordHighlighter(Of SyntaxNode) Protected Overloads Overrides Function GetHighlights(node As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of TextSpan) Dim methodBlock = node.GetAncestor(Of MethodBlockBaseSyntax)() If methodBlock Is Nothing OrElse Not TypeOf methodBlock.BlockStatement Is AccessorStatementSyntax Then Return SpecializedCollections.EmptyEnumerable(Of TextSpan)() End If Dim highlights As New List(Of TextSpan)() With methodBlock Dim isIterator = False If TypeOf methodBlock.Parent Is PropertyBlockSyntax Then With DirectCast(methodBlock.Parent, PropertyBlockSyntax) isIterator = .PropertyStatement.Modifiers.Any(SyntaxKind.IteratorKeyword) End With End If With DirectCast(.BlockStatement, AccessorStatementSyntax) Dim firstKeyword = If(.Modifiers.Count > 0, .Modifiers.First(), .DeclarationKeyword) highlights.Add(TextSpan.FromBounds(firstKeyword.SpanStart, .DeclarationKeyword.Span.End)) End With Dim blockKind = If(node.HasAncestor(Of PropertyBlockSyntax)(), SyntaxKind.PropertyKeyword, SyntaxKind.None) highlights.AddRange( .GetRelatedStatementHighlights( blockKind, checkReturns:=True)) If isIterator Then highlights.AddRange(.GetRelatedYieldStatementHighlights()) End If highlights.Add(.EndBlockStatement.Span) End With Return highlights End Function End Class End Namespace
VSadov/roslyn
src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/AccessorDeclarationHighlighter.vb
Visual Basic
apache-2.0
2,409
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Public Class M1 End Class
jhendrixMSFT/roslyn
src/Compilers/Test/Resources/Core/SymbolsTests/netModule/CrossRefModule1.vb
Visual Basic
apache-2.0
190
#Region "Microsoft.VisualBasic::419a870a506b1d876ff3ec05aa93cf74, src\assembly\assembly\ASCII\MGF\Ions.vb" ' Author: ' ' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.) ' ' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD. ' ' ' MIT License ' ' ' Permission is hereby granted, free of charge, to any person obtaining a copy ' of this software and associated documentation files (the "Software"), to deal ' in the Software without restriction, including without limitation the rights ' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ' copies of the Software, and to permit persons to whom the Software is ' furnished to do so, subject to the following conditions: ' ' The above copyright notice and this permission notice shall be included in all ' copies or substantial portions of the Software. ' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ' SOFTWARE. ' /********************************************************************************/ ' Summaries: ' Class Ions ' ' Properties: Accession, Charge, Database, Instrument, Locus ' Meta, Peaks, PepMass, Rawfile, RtInSeconds ' Sequence, Title ' ' Function: CreateDocs, ToString ' ' ' /********************************************************************************/ #End Region Imports System.IO Imports System.Text Imports BioNovoGene.Analytical.MassSpectrometry.Math.Spectra Imports Microsoft.VisualBasic.Linq Imports Microsoft.VisualBasic.Text.Xml.Models Namespace ASCII.MGF ''' <summary> ''' Data model of a mgf ion ''' ''' > http://www.matrixscience.com/help/data_file_help.html ''' </summary> Public Class Ions Public Property Title As String ''' <summary> ''' The meta data collection in the title property ''' </summary> ''' <returns></returns> Public Property Meta As Dictionary(Of String, String) ''' <summary> ''' MS1 rt in seconds format ''' </summary> ''' <returns></returns> Public Property RtInSeconds As Double Public Property Charge As Integer ''' <summary> ''' Database entries to be searched ''' </summary> ''' <returns></returns> Public Property Accession As String Public Property Instrument As String Public Property Rawfile As String ''' <summary> ''' Hierarchical scan range identifier ''' </summary> ''' <returns></returns> Public Property Locus As String ''' <summary> ''' Element sequence ''' </summary> ''' <returns></returns> Public Property Sequence As String ''' <summary> ''' ''' </summary> ''' <returns></returns> Public Property Database As String Public Property PepMass As NamedValue ''' <summary> ''' MS/MS peaks ''' </summary> ''' <returns></returns> Public Property Peaks As ms2() Public Overrides Function ToString() As String Return $"{Title} ({Peaks.SafeQuery.Count} peaks)" End Function Public Function CreateDocs() As String Dim text As New StringBuilder Using writer As New StringWriter(text) Call Me.WriteAsciiMgf(out:=writer) End Using Return text.ToString End Function Public Function GetLibrary() As LibraryMatrix Return New LibraryMatrix With { .ms2 = Peaks, .Name = Title } End Function End Class End Namespace
xieguigang/spectrum
src/assembly/assembly/ASCII/MGF/Ions.vb
Visual Basic
mit
4,267
Public Class FriendShips Private token As OauthTokens Friend Sub New(ByVal t As OauthTokens) token = t End Sub ''' <summary> ''' Get Noretweets_ids ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function NoRetweets(Optional ByVal parameter As RequestParam = Nothing) As Task(Of ResponseObject(Of List(Of Decimal))) Return Await Task.Run(Function() token.FriendShips.NoRetweets(parameter)) End Function ''' <summary> ''' Get the friend list of ids. ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function FriendsIds(Optional ByVal parameter As RequestParam = Nothing) As Task(Of ResponseObject(Of UserIdsList)) Return Await Task.Run(Function() token.FriendShips.FriendsIds(parameter)) End Function ''' <summary> ''' Get the friend list of userobject. ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function FriendsList(Optional ByVal parameter As RequestParam = Nothing) As Task(Of ResponseObject(Of UserObjectListWithCursor)) Return Await Task.Run(Function() token.FriendShips.FriendsList(parameter)) End Function ''' <summary> ''' Get the followers list of ids. ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function FollowersIds(Optional ByVal parameter As RequestParam = Nothing) As Task(Of ResponseObject(Of UserIdsList)) Return Await Task.Run(Function() token.FriendShips.FollowersIds(parameter)) End Function ''' <summary> ''' Get the friend list of userobject. ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function FollowersList(Optional ByVal parameter As RequestParam = Nothing) As Task(Of ResponseObject(Of UserObjectListWithCursor)) Return Await Task.Run(Function() token.FriendShips.FollowersList(parameter)) End Function ''' <summary> ''' Lookup users. ''' </summary> ''' <param name="ScreenNames">ScreenNames</param> Public Async Function Lookup(ByVal ScreenNames As String()) As Task(Of ResponseObject(Of FriendsLookupObjectList)) Return Await Task.Run(Function() token.FriendShips.Lookup(ScreenNames)) End Function ''' <summary> ''' Lookup users. ''' </summary> ''' <param name="Ids">Ids</param> Public Async Function Lookup(ByVal Ids As Decimal()) As Task(Of ResponseObject(Of FriendsLookupObjectList)) Return Await Task.Run(Function() token.FriendShips.Lookup(Ids)) End Function ''' <summary> ''' Get IDs for every user who has a pending request to follow the authenticating user. ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function Incoming(Optional ByVal parameter As RequestParam = Nothing) As Task(Of ResponseObject(Of UserIdsList)) Return Await Task.Run(Function() token.FriendShips.Incoming(parameter)) End Function ''' <summary> ''' Get IDs for every protected user for whom the authenticating user has a pending follow request. ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function Outgoing(Optional ByVal parameter As RequestParam = Nothing) As Task(Of ResponseObject(Of UserIdsList)) Return Await Task.Run(Function() token.FriendShips.Outgoing(parameter)) End Function ''' <summary> ''' Follow the user. ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function Create(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of UserObject)) Return Await Task.Run(Function() token.FriendShips.Create(parameter)) End Function ''' <summary> ''' Unfollow the user ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function Destroy(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of UserObject)) Return Await Task.Run(Function() token.FriendShips.Destroy(parameter)) End Function ''' <summary> ''' Update ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function Update(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of FriendRelationObject)) Return Await Task.Run(Function() token.FriendShips.Update(parameter)) End Function ''' <summary> ''' Show ''' </summary> ''' <param name="parameter">Parameters</param> Public Async Function Show(ByVal parameter As RequestParam) As Task(Of ResponseObject(Of FriendRelationObject)) Return Await Task.Run(Function() token.FriendShips.Show(parameter)) End Function End Class
szr2000/FistTwit
FistTwit.Async/Methods/FriendShips.vb
Visual Basic
mit
4,698
Imports NLog Imports Transporter_AEHF.Objects.Enumerations Imports Transporter_AEHF.Objects.Positioners.Directed_Perception Namespace Objects.Positioners ''' <summary> ''' Class to create an object that has all the functionality of a PTU-300 positioner ''' </summary> Public Class FlirUnit Implements IDisposable Implements IPositioner Private Const OneSecondArc = 0.0002778 Private Const DefaulTimeout = -1 Private _connection As FlirConnection Private _resolution As Double Private _getPositions(360) As Int32 Private _factoryMaxPanLimit As String = String.Empty Private _factoryMinPanLimit As String = String.Empty Private _factoryMaxPanSpeedLimit As String = String.Empty Private _factoryMinPanSpeedLimit As String = String.Empty Private _factoryMaxTiltLimit As String = String.Empty Private _factoryMinTiltLimit As String = String.Empty Private _factoryMaxTiltSpeedLimit As String = String.Empty Private _factoryMinTiltSpeedLimit As String = String.Empty Private _userMaxPanLimit As String = String.Empty Private _userMinPanLimit As String = String.Empty Private _userMaxTiltLimit As String = String.Empty Private _userMinTiltLimit As String = String.Empty Private _panBaseSpeed As String = String.Empty Private _tiltBaseSpeed As String = String.Empty Private _cableWrap As Boolean = False Protected Disposed As Boolean = False Private _log As Logger = LogManager.GetCurrentClassLogger Private _loggerSelection As String = String.Empty Public Sub Connect( address As String, port As String, conType As PumaEnums.ConnectionType, loggerSelection As String, Optional panReset As Boolean = False, Optional cableWrap As Boolean = False) Implements IPositioner.Connect _loggerSelection = loggerSelection _connection = New FlirConnection(port) _cableWrap = cableWrap Initialize() If panReset And (cableWrap = False) Then ResetPan() End If End Sub ''' <summary> ''' Sets all parameters for inital use of Flir Unit ''' </summary> ''' <remarks></remarks> Public Sub Initialize() Implements IPositioner.Initialize If _cableWrap Then DisableContinuousRotationPanAxis() ClearConnectionStream() DisableLimits() ResetPan() End If GetPanResolution() BuildPositionsArray() SetSpeedMode(PumaEnums.SpeedMode.Independent) SetCommandMode(PumaEnums.CommandMode.Immediate) SetTimeout(DefaulTimeout) End Sub ''' <summary> ''' set to -1 for infinite timeout ''' </summary> ''' <param name="milliseconds"></param> Private Sub SetTimeout(ByVal milliseconds As Int32) _connection.SetTimeout(milliseconds) End Sub ''' <summary> ''' Convert positions to degrees ''' </summary> ''' <param name="position"></param> ''' <returns></returns> Private Function PositionToDegree(ByVal position As Int32) As Int32 Dim ans As Int32 Dim degreesPerPosition = _resolution * OneSecondArc ans = CInt(Math.Round(degreesPerPosition * position)) Return ans End Function ''' <summary> ''' Resets the Pan axis of the unit. ''' </summary> Public Function ResetPan() As String Implements IPositioner.ResetPan Dim ans As String = String.Empty ans = _connection.QueryPositioner(FlirCommand.ResetPan) Return ans End Function ''' <summary> ''' Resets the Tilt axis of the unit ''' </summary> Public Function ResetTilt() As String Implements IPositioner.ResetTilt Dim ans As String = String.Empty ans = _connection.QueryPositioner(FlirCommand.ResetTilt) Return ans End Function ''' <summary> ''' Moves pan to specified degree ''' </summary> ''' <param name="degree">Degree must be between 0 and 360</param> ''' <exception cref="System.ArgumentOutOfRangeException">Thrown when degree is not in range 0-360</exception> Public Function MovePanToPosition(ByVal degree As Int32) As String Implements IPositioner.MovePanToPosition Dim ans As String = String.Empty Debug.Assert((degree >= 0 And degree <= 360), "Degree out of range, 0-360") If (degree < 0 Or degree > 360) Then 'make sure degree between 0 and 360 Throw New Exception("Out Of Range Exception. When moving pan, the degree must be between 0 and 360.") Return ans Else ans = _connection.QueryPositioner(FlirCommand.SetPanPosition & _getPositions(degree)) 'send command Return ans End If End Function ''' <summary> ''' Moves tilt to specified degree ''' </summary> ''' <param name="degree">Degree must be between -30 and 30</param> ''' <exception cref="System.ArgumentOutOfRangeException">Thrown when degree is not in range -30 to 30</exception> Public Function MoveTiltToPosition(ByVal degree As Int32) As String Implements IPositioner.MoveTiltToPosition Dim ans As String = String.Empty 'Debug.Assert((degree >= -30 And degree <= 30), "Degree out of range, -30 to 30") If (degree < 270 And degree > 30) Then 'make sure degree is betwee -30 and 30 Throw New ArgumentOutOfRangeException("Out Of Range Exception. When moving tilt, the degree must be less than 30 or greater than 270.") Return ans Else ans = _connection.QueryPositioner(FlirCommand.SetTiltPosition & _getPositions(degree)) Return ans End If End Function ''' <summary> ''' Rotates the pan axis left or right until halt command is issued. Speed mode must be velocity ''' </summary> ''' <param name="pd">PanRotationDirection.left or PanRotationDirection.right</param> Public Function RotatePan(ByVal pd As PumaEnums.PanRotationDirection) As String Implements IPositioner.RotatePan Dim ans As String = String.Empty _connection.QueryPositioner(FlirCommand.SetSpeedModeVelocity) _connection.QueryPositioner(_panRotationDirectionArray(CInt(pd)) & GetPanSpeed()) ans = _connection.QueryPositioner(FlirCommand.SetSpeedModeIndependent) Return ans End Function Public Function RotateTilt(ByVal td As PumaEnums.TiltRotationDirection) As String Implements IPositioner.RotateTilt 'not yet implemented Return 0 End Function ''' <summary> ''' Halts all movement of the positioner ''' </summary> Public Function Halt() As String Implements IPositioner.Halt, IPositioner.HaltPan, IPositioner.HaltTilt Dim ans As String = String.Empty ans = _connection.QueryPositioner(FlirCommand.Halt) Return ans End Function ''' <summary> ''' Returns the current pan position in degrees ''' </summary> ''' <returns></returns> Public Function GetPanPosition(Optional count As Int32 = 0) As String Implements IPositioner.GetPanPosition Dim ans = String.Empty Dim numericalAns = New Int32 ClearConnectionStream() EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.GetPanPosition) ans = StringTrim(_connection.Answer) Dim intans As Int32 'this try/catch attempts to fix a situation where the positioner sends back garbage by asking again up to 1000 times Try intans = CInt(ans) Catch ex As Exception If count > 1000 Then Throw New Exception("Positioner is unresponsive or needs to be reset.") count += 1 ans = GetPanPosition(count) Return ans End Try EnableVerboseFeedback() intans = PositionToDegree(intans) ans = CStr(intans) Return ans End Function ''' <summary> ''' Returns the current set pan speed ''' </summary> ''' <returns></returns> Public Function GetPanSpeed(Optional count As Int32 = 0) As String Implements IPositioner.GetPanSpeed Dim ans = String.Empty ClearConnectionStream() EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.GetPanSpeed) ans = StringTrim(_connection.Answer) EnableVerboseFeedback() Return ans End Function ''' <summary> ''' Returns the current tilt position in degrees ''' </summary> ''' <returns></returns> Public Function GetTiltPosition(Optional count As Int32 = 0) As String Implements IPositioner.GetTiltPosition Dim ans = String.Empty ClearConnectionStream() EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.GetTiltPosition) ans = StringTrim(_connection.Answer) Dim intans As Int32 'this try/catch attempts to fix a situation where the positioner sends back garbage by asking again up to 1000 times Try intans = CInt(ans) Catch ex As Exception If count > 1000 Then Throw New Exception("Positioner is unresponsive or needs to be reset.") count += 1 ans = GetTiltPosition(count) Return ans End Try EnableVerboseFeedback() intans = PositionToDegree(intans) ans = CStr(intans) Return ans End Function ''' <summary> ''' Returns the current set tilt speed ''' </summary> ''' <returns></returns> Public Function GetTiltSpeed() As String Implements IPositioner.GetTiltSpeed Dim ans = String.Empty ClearConnectionStream() EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.GetTiltSpeed) ans = StringTrim(_connection.Answer) EnableVerboseFeedback() Return ans End Function ''' <summary> ''' Returns input voltage and current temperature values of positioner ''' </summary> ''' <returns></returns> Public Function GetVoltageAndTemp() As String Implements IPositioner.GetTiltVoltage, IPositioner.GetPanVoltage, IPositioner.GetTiltTemperature, IPositioner.GetPanTemperature _connection.QueryPositioner(FlirCommand.GetVoltageAndTemp) Return _connection.Answer End Function ''' <summary> ''' Set the positioner speed mode independent or velocity ''' </summary> ''' <param name="sm">SpeedMode.independent or SpeedMode.velocity</param> Public Sub SetSpeedMode(ByVal sm As PumaEnums.SpeedMode) _connection.QueryPositioner(_speedModeArray(CInt(sm))) End Sub ''' <summary> ''' Set the step mode for the pan axis ''' </summary> ''' <param name="stm">StepMode.Full, .Half, .Quarter, .Eighth, or .Auto</param> Public Sub SetPanStepMode(ByVal stm As PumaEnums.StepMode) _connection.QueryPositioner(FlirCommand.SetStepModePanAxis & _stepModeArray(CInt(stm))) If (_cableWrap) Then ResetPan() _cableWrap = False Initialize() _cableWrap = True Else ResetPan() Initialize() End If End Sub ''' <summary> ''' Set the step mode for the tilt axis ''' </summary> ''' <param name="stm">StepMode.Full, .Half, .Quarter, .Eighth, or .Auto</param> Public Sub SetTiltStepMode(ByVal stm As PumaEnums.StepMode) _connection.QueryPositioner(FlirCommand.SetStepModeTiltAxis & _stepModeArray(CInt(stm))) If (_cableWrap) Then _cableWrap = False Initialize() _cableWrap = True ResetTilt() Else Initialize() ResetTilt() End If End Sub ''' <summary> ''' Send Ascii Command to positioner ''' </summary> ''' <param name="command">Positioner ascii command</param> Public Function SendCommand(axis As String, command As String) As String Implements IPositioner.SendCommand _connection.QueryPositioner(command) Return _connection.Answer End Function ''' <summary> ''' Set the positioner command mode immediate or slaved ''' </summary> ''' <param name="cm">CommandMode.immediate or CommandMode.slaved</param> Public Sub SetCommandMode(ByVal cm As PumaEnums.CommandMode) _connection.QueryPositioner(_commandModeArray(CInt(cm))) End Sub ''' <summary> ''' Enable continuous rotation on pan axis ''' </summary> Public Function EnableContinousRotationPanAxis() As String Implements IPositioner.EnableContinuousRotationPanAxis Dim ans As String = String.Empty ans = _connection.QueryPositioner(FlirCommand.EnableContinuousPanRotation) Return ans End Function ''' <summary> ''' Disable continuous rotation on pan axis ''' </summary> Public Function DisableContinuousRotationPanAxis() As String Implements IPositioner.DisableContinuousRotationPanAxis Dim ans As String = String.Empty ans = _connection.QueryPositioner(FlirCommand.DisableContinuousPanRotation) Return ans End Function ''' <summary> ''' Disable echoing ''' </summary> Public Sub DisableEchoing() _connection.QueryPositioner(FlirCommand.DisableEchoing) End Sub ''' <summary> ''' Disables limit enforcement on pan and tilt axis ''' </summary> Public Sub DisableLimits() Implements IPositioner.DisableLimits _connection.QueryPositioner(FlirCommand.DisableLimitEnforcement) End Sub ''' <summary> ''' Awaits completion of current pan tilt movement ''' </summary> Public Sub Await() _connection.QueryPositioner(FlirCommand.AwaitCommand) End Sub ''' <summary> ''' Enables the factory set limits on Pan and Tilt axis ''' </summary> Public Sub EnableFactoryLimits() Implements IPositioner.EnablePositionLimits _connection.QueryPositioner(FlirCommand.EnablefactoryLimits) End Sub ''' <summary> ''' Enables user defined limits on pan and tilt axis ''' </summary> Public Sub EnableUserLimits() _connection.QueryPositioner(FlirCommand.EnableUserLimits) End Sub ''' <summary> ''' Restores pan and tilt unit to factory default settings ''' </summary> ''' <remarks></remarks> Public Sub RestoreFactorySettings() _connection.QueryPositioner(FlirCommand.EnableTerseFeedback) _connection.QueryPositioner(FlirCommand.RestoreFactoryDefaults) _connection.QueryPositioner(FlirCommand.DisableEchoing) _connection.QueryPositioner(FlirCommand.EnableVerboseFeedback) End Sub ''' <summary> ''' Clears any data in the input buffer of serial connection ''' </summary> Private Sub ClearConnectionStream() _connection.ClearConnectionStream() End Sub ''' <summary> ''' Returns max pan speed limit ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Function GetMaxPanSpeedLimit() As String EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.QueryMaxPanSpeedLimit) _factoryMaxPanSpeedLimit = StringTrim(_connection.Answer) EnableVerboseFeedback() Return _factoryMaxPanSpeedLimit End Function ''' <summary> ''' Returns max pan factory limit as string ''' </summary> ''' <returns></returns> Private Function GetMaxPanFactoryLimit() As String EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.QueryMaxPanFactoryLimit) _factoryMaxPanLimit = StringTrim(_connection.Answer) '// _connection.Answer.Substring(1).Trim() EnableVerboseFeedback() Return _factoryMaxPanLimit End Function ''' <summary> ''' Returns max pan user set limit as string ''' </summary> ''' <returns></returns> Public Function GetMaxPanUserLimit() As String EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.QueryMaxPanUserLimit) _userMaxPanLimit = StringTrim(_connection.Answer) '// _connection.Answer.Substring(1).Trim() EnableVerboseFeedback() Return _userMaxPanLimit End Function ''' <summary> ''' Returns pan base speed ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Function GetPanBaseSpeed() As String Implements IPositioner.GetPanAcceleration EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.GetPanBaseSpeed) _panBaseSpeed = StringTrim(_connection.Answer) '// _connection.Answer.Substring(1).Trim() EnableVerboseFeedback() Return _panBaseSpeed End Function ''' <summary> ''' Returns tilt base speed ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Function GetTiltBaseSpeed() As String Implements IPositioner.GetTiltAcceleration EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.GetTiltBaseSpeed) _tiltBaseSpeed = StringTrim(_connection.Answer) EnableVerboseFeedback() Return _tiltBaseSpeed End Function ''' <summary> ''' Returns max tilt factory limit as string ''' </summary> ''' <returns></returns> Private Function GetMaxTiltFactoryLimit() As String EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.QueryMaxTiltFactoryLimit) _factoryMaxTiltLimit = StringTrim(_connection.Answer) '// _connection.Answer.Substring(1).Trim() EnableVerboseFeedback() Return _factoryMaxTiltLimit End Function ''' <summary> ''' Returns max tilt user set limit as string ''' </summary> ''' <returns></returns> Public Function GetMaxTiltUserLimit() As String EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.QueryMaxTiltUserLimit) _userMaxTiltLimit = StringTrim(_connection.Answer) '// _connection.Answer.Substring(1).Trim() EnableVerboseFeedback() Return _userMaxTiltLimit End Function ''' <summary> ''' Returns m tilt speed limit ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Function GetMaxTiltSpeedLimit() As String EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.QueryMaxTiltSpeedLimit) _factoryMaxTiltSpeedLimit = StringTrim(_connection.Answer) '// _connection.Answer.Substring(1).Trim() EnableVerboseFeedback() Return _factoryMaxTiltSpeedLimit End Function ''' <summary> ''' Returns min tilt factory limit as string ''' </summary> ''' <returns></returns> Private Function GetMinTiltFactoryLimit() As String EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.QueryMinTiltFactoryLimit) _factoryMinTiltLimit = StringTrim(_connection.Answer) '// _connection.Answer.Substring(1).Trim() EnableVerboseFeedback() Return _factoryMinTiltLimit End Function ''' <summary> ''' Returns min tilt user set limit as string ''' </summary> ''' <returns></returns> Public Function GetMinTiltUserLimit() As String EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.QueryMinTiltUserLimit) _userMinTiltLimit = StringTrim(_connection.Answer) '// _connection.Answer.Substring(1).Trim() EnableVerboseFeedback() Return _userMinTiltLimit End Function ''' <summary> ''' Returns min tilt speed limit ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Function GetMinTiltSpeedLimit() As String EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.QueryMinTiltSpeedLimit) _factoryMinTiltSpeedLimit = StringTrim(_connection.Answer) '// _connection.Answer.Substring(1).Trim() EnableVerboseFeedback() Return _factoryMinTiltSpeedLimit End Function ''' <summary> ''' Returns min pan speed limit ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Function GetMinPanSpeedLimit() As String EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.QueryMinPanSpeedLimit) _factoryMinPanSpeedLimit = StringTrim(_connection.Answer) EnableVerboseFeedback() Return _factoryMinPanSpeedLimit End Function ''' <summary> ''' Returns min pan factory limit as string ''' </summary> ''' <returns></returns> Private Function GetMinPanFactoryLimit() As String EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.QueryMinPanFactoryLimit) _factoryMinPanLimit = StringTrim(_connection.Answer) '// _connection.Answer.Substring(1).Trim() EnableVerboseFeedback() Return _factoryMinPanLimit End Function ''' <summary> ''' Returns min pan user set limit as string ''' </summary> ''' <returns></returns> Public Function GetMinPanUserLimit() As String EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.QueryMinPanUserLimit) _userMinPanLimit = StringTrim(_connection.Answer) '// _connection.Answer.Substring(1).Trim() EnableVerboseFeedback() Return _userMinPanLimit End Function ''' <summary> ''' Trims the string down to eliminate preceding * and all white space ''' </summary> ''' <param name="inString"></param> ''' <returns></returns> Private Function StringTrim(ByVal inString As String) As String Dim result As String() result = inString.Split("*") Return Trim(result(1)) End Function ''' <summary> ''' Set pan axis user limits ''' </summary> ''' <param name="maxDegree">Must be between 1 and 179</param> ''' <param name="minDegree">Must be between -1 and -179</param> Public Sub SetPanUserLimits(ByVal maxDegree As Int32, ByVal minDegree As Int32) Implements IPositioner.SetPanUserLimits Dim maxPosition = DegreeToPosition(maxDegree) Dim minPosition = DegreeToPosition(minDegree) Dim commandMax = CommandBuild(FlirCommand.SetMaxPanUserLimit, maxPosition.ToString()) Dim commandMin = CommandBuild(FlirCommand.SetMinPanUserLimit, minPosition.ToString()) _connection.QueryPositioner(commandMax) ClearConnectionStream() _connection.QueryPositioner(commandMin) End Sub Public Sub SetTiltUserLimits(ByVal maxDegree As Int32, ByVal minDegree As Int32) Implements IPositioner.SetTiltUserLimits 'needs to be implemented End Sub ''' <summary> ''' Set pan axis speed ''' </summary> ''' <param name="speed">Integer that represents a speed unit. Must be between 0 and 1985.</param> ''' <exception cref="System.Exception">Thrown when pan speed is greater than 1985</exception> Public Sub SetPanSpeed(ByVal speed As Int32) Implements IPositioner.SetPanSpeed Debug.Assert(speed < 1985, "Pan speed cannot exceed 1985 positions/sec") Dim command = CommandBuild(FlirCommand.SetPanSpeed, speed.ToString()) If (speed > 1985) Then Throw New Exception("Pan speed cannot exceed 1985 positions/sec") Else _connection.QueryPositioner(FlirCommand.SetSpeedModeIndependent) _connection.QueryPositioner(command) End If End Sub ''' <summary> ''' Set tilt axis speed ''' </summary> ''' <param name="speed">Integer that represents a speed unit. Must be between 0 and 1985.</param> ''' <exception cref="System.Exception">Thrown when speed is greater than 1985</exception> Public Sub SetTiltSpeed(ByVal speed As Int32) Implements IPositioner.SetTiltSpeed Debug.Assert(speed < 1985, "Tilt speed cannot exceed 1985 positions/sec") Dim command = CommandBuild(FlirCommand.SetTiltSpeed, speed.ToString()) If (speed > 1985) Then Throw New Exception("Tilt speed cannot exceed 1985 positions/sec") Else _connection.QueryPositioner(FlirCommand.SetSpeedModeIndependent) _connection.QueryPositioner(command) End If End Sub ''' <summary> ''' Set pan base speed ''' </summary> ''' <param name="speed"></param> ''' <remarks></remarks> Public Sub SetPanBaseSpeed(ByVal speed As Int32) Implements IPositioner.SetPanAccel Dim command = CommandBuild(FlirCommand.SetPanBaseSpeed, speed.ToString()) _connection.QueryPositioner(FlirCommand.SetSpeedModeIndependent) _connection.QueryPositioner(command) End Sub ''' <summary> ''' Set tilt base speed ''' </summary> ''' <param name="speed"></param> ''' <remarks></remarks> Public Sub SetTiltBaseSpeed(ByVal speed As Int32) Implements IPositioner.SetTiltAccel Dim command = CommandBuild(FlirCommand.SetTiltBaseSpeed, speed.ToString()) _connection.QueryPositioner(FlirCommand.SetSpeedModeIndependent) _connection.QueryPositioner(command) End Sub ''' <summary> ''' Flush the input buffer of serial connection ''' </summary> Public Sub Flush() Implements IPositioner.Flush _connection.ClearConnectionStream() End Sub ''' <summary> ''' Returns the current state of echo mode ''' </summary> ''' <returns></returns> Public Function GetEchoModeState() As String _connection.QueryPositioner(FlirCommand.QueryEchoMode) Return _connection.Answer End Function ''' <summary> ''' Returns the current state of limit enforcement ''' </summary> ''' <returns>Returns current state of limit enforcement as string</returns> Public Function GetLimitEnforcementState() As String _connection.QueryPositioner(FlirCommand.QueryLimitEnforcement) Return _connection.Answer End Function ''' <summary> ''' Enable echoing ''' </summary> Public Sub EnableEchoing() _connection.QueryPositioner(FlirCommand.EnableEchoing) End Sub ''' <summary> ''' Enable terse feedback ''' </summary> Public Sub EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.EnableTerseFeedback) End Sub ''' <summary> ''' Enable verbose feedback ''' </summary> Public Sub EnableVerboseFeedback() _connection.QueryPositioner(FlirCommand.EnableVerboseFeedback) End Sub ''' <summary> ''' Sends positioner to 0 degrees pan ''' </summary> Public Sub StowPan() Implements IPositioner.StowPan _connection.QueryPositioner(FlirCommand.StowPan) End Sub ''' <summary> ''' Sends positioner to 0 degrees tilt ''' </summary> Public Sub StowTilt() Implements IPositioner.StowTilt _connection.QueryPositioner(FlirCommand.StowTilt) End Sub Public Sub SetTiltPositiveLimit(positive As Int32) Implements IPositioner.SetTiltPositiveLimit 'needs to be implemented End Sub ''' <summary> ''' Set pan axis user limits to absolute max and min ''' </summary> Private Sub SetPanUserLimits() Dim commandMax = CommandBuild(FlirCommand.SetMaxPanUserLimit, _getPositions(180).ToString()) Dim commandMin = CommandBuild(FlirCommand.SetMinPanUserLimit, _getPositions(181).ToString()) _connection.QueryPositioner(commandMax) _connection.QueryPositioner(commandMin) End Sub ''' <summary> ''' Get the pan resolution of the unit ''' </summary> Public Function GetPanResolution(Optional count As Int32 = 0) As Double Implements IPositioner.GetPanResolution EnableTerseFeedback() _connection.QueryPositioner(FlirCommand.GetPanResolution) Dim ans As String ans = _connection.Answer.Trim Dim dblans As Double 'this try/catch attempts to fix a situation where the positioner sends back garbage by asking again up to 1000 times Try dblans = CDbl(ans) Catch ex As Exception If count > 1000 Then Throw New Exception("Positioner is unresponsive or needs to be reset.") count += 1 ans = GetPanResolution(count) Return ans End Try EnableVerboseFeedback() Return (dblans) End Function Public Function GetTiltResolution(Optional count As Int32 = 0) As Double Implements IPositioner.GetTiltResolution 'Needs to be implemented Dim ans As String = String.Empty Return ans End Function ''' <summary> ''' Returns the firmware version of the positioner ''' </summary> Public Sub GetFirmwareVersion() _connection.QueryPositioner(FlirCommand.GetFirmwareVersion) End Sub Public Function IsPanHomeSet() As Boolean Implements IPositioner.IsPanHomeSet Return True End Function Public Function IsTiltHomeSet() As Boolean Implements IPositioner.IsTiltHomeSet Return True End Function ''' <summary> ''' Conconate the two strings to build command string ''' </summary> ''' <param name="first"></param> ''' <param name="second"></param> ''' <returns>Command string</returns> Private Function CommandBuild(ByVal first As String, ByVal second As String) As String Return first & second End Function ''' <summary> ''' Builds array of positions synonomous with degrees 0-360 ''' </summary> Private Sub BuildPositionsArray() For i As Int32 = 0 To 359 _getPositions(i) = ConvertToPositions(_getDegree(i)) Next End Sub ''' <summary> ''' Converts a degree to a position ''' </summary> ''' <param name="degree"></param> ''' <returns>Equivalent position value</returns> Private Function ConvertToPositions(ByVal degree As Int32) As Int32 Dim positions = New Int32 Dim degreesPerMove = New Double degreesPerMove = _resolution * OneSecondArc 'ticks equal degrees/degrees per move positions = CInt((CDbl((degree)) / degreesPerMove)) Return positions End Function ''' <summary> ''' Returns the position equivilent of supplied degree ''' </summary> ''' <param name="degree">Degree must be between 0 and 360</param> ''' <returns></returns> ''' <exception cref="System.ArgumentOutOfRangeException">Thrown when degree is not in range 0-360</exception> Public Function DegreeToPosition(ByVal degree As Int32) As Int32 While (degree < 0) degree += 360 End While If (degree < 0 Or degree > 360) Then Throw New ArgumentOutOfRangeException("degree", "Degree must be between 0 or 360.") Return False Else Return Convert.ToInt32(_getPositions(degree)) End If End Function ''' <summary> ''' Resolution of positioner in seconds arc per position where 1 sec arc = 1 deg/3600 = .0002778 degrees ''' </summary> Public Property Resolution Get Return _resolution End Get Set(value) End Set End Property ''' <summary> ''' Returns string that contains value of minimum factory set pan limit ''' </summary> Public Property MinimumFactoryPanLimit Get Return GetMinPanFactoryLimit() End Get Set(value) End Set End Property ''' <summary> ''' Returns string that contains value of maximum factory set pan limit ''' </summary> Public Property MaximumFactoryPanLimit Get Return GetMaxPanFactoryLimit() End Get Set(value) End Set End Property ''' <summary> ''' Returns string that contains value of maximum factory set tilt limit ''' </summary> Public Property MaximumFactoryTiltLimit Get Return GetMinTiltFactoryLimit() End Get Set(value) End Set End Property ''' <summary> ''' Returns string that contains value of minimum factory set tilt limit ''' </summary> Public Property MinimumFactoryTiltLimit Get Return GetMinTiltFactoryLimit() End Get Set(value) End Set End Property Public Function EnablePanStabilization() As String Implements IPositioner.EnablePanStabilization Dim ans As String = String.Empty Return ans End Function Public Function DisablePanStabilization() As String Implements IPositioner.DisablePanStabilization Dim ans As String = String.Empty Return ans End Function Public Function EnableTiltStabilization() As String Implements IPositioner.EnableTiltStabilization Dim ans As String = String.Empty Return ans End Function Public Function DisableTiltStabilization() As String Implements IPositioner.DisableTiltStabilization Dim ans As String = String.Empty Return ans End Function Public Function GetPanAmperage() As String Implements IPositioner.GetPanAmperage Dim ans As String = String.Empty Return ans End Function Public Function GetTiltAmperage() As String Implements IPositioner.GetTiltAmperage Dim ans As String = String.Empty Return ans End Function Public Function GetPanTargetPosition(Optional count As Int32 = 0) As String Implements IPositioner.GetPanTargetPosition Dim ans As String = String.Empty Return ans End Function Public Function GetTiltTargetPosition() As String Implements IPositioner.GetTiltTargetPosition Dim ans As String = String.Empty Return ans End Function #Region "IDispose" ''' <summary> ''' Frees any allocated memory when object use is complete ''' </summary> Public Overloads Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub ''' <summary> ''' Frees any allocated memory when object use is complete ''' </summary> ''' <param name="disposing"></param> Protected Overridable Overloads Sub Dispose(ByVal disposing As Boolean) If Not Me.Disposed Then If disposing Then If Not _connection Is Nothing Then _connection.Dispose() End If End If Me.Disposed = True End Sub #End Region #Region "Arrays" #Region "Rotation Direction Array" Private _panRotationDirectionArray As String() = { "PS-", "PS" } #End Region #Region "Speed Mode Array" Private _speedModeArray As String() = { "CI", "CV" } #End Region #Region "Command Mode Array" Private _commandModeArray As String() = { "I", "S" } #End Region #Region "Degree Array" Private _getDegree As Int32() = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, -179, -178, -177, -176, -175, -174, -173, -172, -171, -170, -169, -168, -167, -166, -165, -164, -163, -162, -161, -160, -159, -158, -157, -156, -155, -154, -153, -152, -151, -150, -149, -148, -147, -146, -145, -144, -143, -142, -141, -140, -139, -138, -137, -136, -135, -134, -133, -132, -131, -130, -129, -128, -127, -126, -125, -124, -123, -122, -121, -120, -119, -118, -117, -116, -115, -114, -113, -112, -111, -110, -109, -108, -107, -106, -105, -104, -103, -102, -101, -100, -99, -98, -97, -96, -95, -94, -93, -92, -91, -90, -89, -88, -87, -86, -85, -84, -83, -82, -81, -80, -79, -78, -77, -76, -75, -74, -73, -72, -71, -70, -69, -68, -67, -66, -65, -64, -63, -62, -61, -60, -59, -58, -57, -56, -55, -54, -53, -52, -51, -50, -49, -48, -47, -46, -45, -44, -43, -42, -41, -40, -39, -38, -37, -36, -35, -34, -33, -32, -31, -30, -29, -28, -27, -26, -25, -24, -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1 } #End Region #Region "Step Mode" Private _stepModeArray As String() = { "F", "H", "Q", "E", "A" } #End Region #End Region End Class End Namespace
wboxx1/85-EIS-PUMA
puma/src/Supporting Objects/Positioners/Directed Perception/FlirUnit.vb
Visual Basic
mit
48,498
Imports GemBox.Document Imports GemBox.Document.MailMerging Module Program Sub Main() ' If using Professional version, put your serial key below. ComponentInfo.SetLicense("FREE-LIMITED-KEY") Dim document = DocumentModel.Load("MergeClearOptions.docx") ' Data source with "Populated" value, but no "Empty" value. Dim data As New With {.Populated = "sample value"} ' Execute mail merge on "Example1" merge range. ' Also, remove fields and paragraphs that didn't merge in this range. document.MailMerge.ClearOptions = MailMergeClearOptions.RemoveUnusedFields Or MailMergeClearOptions.RemoveEmptyParagraphs document.MailMerge.Execute(data, "Example1") ' Execute mail merge on "Example2" merge range. ' Also, remove rows that didn't merge in this range. document.MailMerge.ClearOptions = MailMergeClearOptions.RemoveEmptyTableRows document.MailMerge.Execute(data, "Example2") ' Execute mail merge on "Example2" merge range. ' Also, remove the range if all fields didn't merge in this range. document.MailMerge.ClearOptions = MailMergeClearOptions.RemoveEmptyRanges document.MailMerge.Execute(data, "Example3") document.Save("Merged Clear Options Output.docx") End Sub End Module
gemboxsoftware-dev-team/GemBox.Document.Examples
VB.NET/Mail Merge/Clear Options/Program.vb
Visual Basic
mit
1,334
Public Class Calls Private Sub HuraButton1_Click(sender As Object, e As EventArgs) Handles HuraButton1.Click Me.Close() End Sub Private Sub HuraButton2_Click(sender As Object, e As EventArgs) Handles HuraButton2.Click Me.WindowState = FormWindowState.Minimized End Sub Private Sub HuraForm1_Click(sender As Object, e As EventArgs) Handles HuraForm1.Click End Sub Private Sub HuraButton3_Click(sender As Object, e As EventArgs) Handles HuraButton3.Click TextBox1.Clear() Label1.Text = "" Label2.Text = "" Label3.Text = "" End Sub Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged End Sub Private Sub HuraButton4_Click(sender As Object, e As EventArgs) Handles HuraButton4.Click Dim sqrt As Double sqrt = Convert.ToDouble(TextBox1.Text) TextBox1.Text = Convert.ToString(Math.Sqrt(sqrt)) End Sub Private Sub HuraButton5_Click(sender As Object, e As EventArgs) Handles HuraButton5.Click Dim numb As Double numb = Convert.ToDouble(TextBox1.Text) Dim nu As Double nu = numb - numb - numb TextBox1.Text = Convert.ToString(nu) End Sub Private Sub HuraButton7_Click(sender As Object, e As EventArgs) Handles HuraButton7.Click TextBox1.AppendText(1) End Sub Private Sub HuraButton8_Click(sender As Object, e As EventArgs) Handles HuraButton8.Click TextBox1.AppendText(2) End Sub Private Sub HuraButton9_Click(sender As Object, e As EventArgs) Handles HuraButton9.Click TextBox1.AppendText(3) End Sub Private Sub HuraButton10_Click(sender As Object, e As EventArgs) Handles HuraButton10.Click TextBox1.AppendText(4) End Sub Private Sub HuraButton11_Click(sender As Object, e As EventArgs) Handles HuraButton11.Click TextBox1.AppendText(5) End Sub Private Sub HuraButton12_Click(sender As Object, e As EventArgs) Handles HuraButton12.Click TextBox1.AppendText(6) End Sub Private Sub HuraButton13_Click(sender As Object, e As EventArgs) Handles HuraButton13.Click TextBox1.AppendText(7) End Sub Private Sub HuraButton14_Click(sender As Object, e As EventArgs) Handles HuraButton14.Click TextBox1.AppendText(8) End Sub Private Sub HuraButton15_Click(sender As Object, e As EventArgs) Handles HuraButton15.Click TextBox1.AppendText(9) End Sub Private Sub HuraButton20_Click(sender As Object, e As EventArgs) Handles HuraButton20.Click TextBox1.AppendText(0) End Sub Private Sub HuraButton19_Click(sender As Object, e As EventArgs) Handles HuraButton19.Click TextBox1.AppendText(".") End Sub Private Sub HuraButton6_Click(sender As Object, e As EventArgs) Handles HuraButton6.Click Label1.Text = TextBox1.Text Label2.Text = "/" TextBox1.Clear() End Sub Private Sub HuraButton16_Click(sender As Object, e As EventArgs) Handles HuraButton16.Click Label1.Text = TextBox1.Text Label2.Text = "*" TextBox1.Clear() End Sub Private Sub HuraButton17_Click(sender As Object, e As EventArgs) Handles HuraButton17.Click Label1.Text = TextBox1.Text Label2.Text = "-" TextBox1.Clear() End Sub Private Sub HuraButton18_Click(sender As Object, e As EventArgs) Handles HuraButton18.Click Label1.Text = TextBox1.Text Label2.Text = "+" TextBox1.Clear() End Sub Private Sub HuraButton22_Click(sender As Object, e As EventArgs) Handles HuraButton22.Click Label3.Text = TextBox1.Text Dim sign As Char sign = Label2.Text Dim n1 As Double n1 = Convert.ToDouble(Label1.Text) Dim n2 As Double n2 = Convert.ToDouble(Label3.Text) Dim n3 As Double Select Case (sign) Case "+" n3 = n1 + n2 Case "-" n3 = n1 - n2 Case "*" n3 = n1 * n2 Case "/" n3 = n1 / n2 End Select TextBox1.Text = Convert.ToString(n3) End Sub End Class
MJGC-Jonathan/ComputerHelper
Computer Helper/Computer Helper/Calls.vb
Visual Basic
mit
4,230
Imports LearningFluentMigrator.Migrations Imports FluentMigrator.Runner Public Class Form1 Public Sub New() ' この呼び出しは、Windows フォーム デザイナで必要です。 InitializeComponent() ' InitializeComponent() 呼び出しの後で初期化を追加します。 MigrationsConfig.Start() End Sub End Class
takas-ho/LearningFluentMigrator.2008
LearningFluentMigrator/Form1.vb
Visual Basic
mit
375
Imports IPrompt.VisualBasic Class wndMain Private Sub btnIMessageBox_Click(sender As Object, e As RoutedEventArgs) Handles btnIMessageBox.Click tblckResponse.Text = [Enum].GetName(GetType(MsgBoxResult), IMsgBox("Optional IMessageBox text", vbYesNoCancel + vbExclamation, "Optional IMessageBox Title", Me)) End Sub Private Sub btnIInputBox_Click(sender As Object, e As RoutedEventArgs) Handles btnIInputBox.Click tblckResponse.Text = IInputBox("Optional IInputBox text", "IInputBox Title", "default response", vbQuestion).ToString End Sub Private Sub btnIPasswordBox_Click(sender As Object, e As RoutedEventArgs) Handles btnIPasswordBox.Click tblckResponse.Text = IPasswordBox("Optional IPasswordBox text", "IPasswordBox Title", "defaultpassword", vbCritical).ToString End Sub Private Sub wndMain_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded IPrompt.Prompt.OKText = "OK" IPrompt.Prompt.CancelText = "Отмена" IPrompt.Prompt.YesText = "Oui" IPrompt.Prompt.NoText = "Nein" End Sub End Class
ramer/IPrompt
IPromptTestVB/wndMain.xaml.vb
Visual Basic
mit
1,110
'*******************************************************************************************' ' ' ' 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 Bytescout.PDFRenderer Class Program Friend Shared Sub Main(args As String()) ' Create an instance of Bytescout.PDFRenderer.RasterRenderer object and register it. Dim renderer As New RasterRenderer() renderer.RegistrationName = "demo" renderer.RegistrationKey = "demo" ' Load PDF document. renderer.LoadDocumentFromFile("multipage.pdf") For i As Integer = 0 To renderer.GetPageCount() - 1 ' Render document page to JPEG image file. renderer.Save("image" & i & ".jpg", RasterImageFormat.JPEG, i, 96) Next ' Cleanup renderer.Dispose() ' Open the first output file in default image viewer. System.Diagnostics.Process.Start("image0.jpg") End Sub End Class
bytescout/ByteScout-SDK-SourceCode
PDF Renderer SDK/VB.NET/Convert PDF To JPEG/Program.vb
Visual Basic
apache-2.0
1,766
'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 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("TAAddHistoricalTrackingLayer2008")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("ESRI")> <Assembly: AssemblyProduct("TAAddHistoricalTrackingLayer2008")> <Assembly: AssemblyCopyright("Copyright © ESRI 2009")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("c7c7fd28-77e9-47f4-aeab-5732c9376b39")> ' 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")>
Esri/arcobjects-sdk-community-samples
Net/Tracking/Samples/TAAddHistoricalTrackingLayer/VBNet/My Project/AssemblyInfo.vb
Visual Basic
apache-2.0
1,743
Imports System Imports Microsoft.VisualBasic Imports ChartDirector Public Class pareto Implements DemoModule 'Name of demo module Public Function getName() As String Implements DemoModule.getName Return "Pareto Chart" 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 data for the chart Dim data() As Double = {40, 15, 7, 5, 2} ' The labels for the chart Dim labels() As String = {"Hard Disk", "PCB", "Printer", "CDROM", "Keyboard"} ' In the pareto chart, the line data are just the accumulation of the raw data, scaled to a ' range of 0 - 100% Dim lineData As ArrayMath = New ArrayMath(data) lineData.acc() Dim scaleFactor As Double = lineData.max() / 100 If scaleFactor = 0 Then ' Avoid division by zero error for zero data scaleFactor = 1 End If lineData.div2(scaleFactor) ' Create a XYChart object of size 480 x 300 pixels. Set background color to brushed silver, ' with a grey (bbbbbb) border and 2 pixel 3D raised effect. Use rounded corners. Enable soft ' drop shadow. Dim c As XYChart = New XYChart(400, 300, Chart.brushedSilverColor(), &Hbbbbbb, 2) c.setRoundedFrame() c.setDropShadow() ' Add a title to the chart using 15 points Arial Italic. Set top/bottom margins to 12 ' pixels. Dim title As ChartDirector.TextBox = c.addTitle("Pareto Chart Demonstration", _ "Arial Italic", 15) title.setMargin2(0, 0, 12, 12) ' Tentatively set the plotarea at (50, 40). Set the width to 100 pixels less than the chart ' width, and the height to 80 pixels less than the chart height. Use pale grey (f4f4f4) ' background, transparent border, and dark grey (444444) dotted grid lines. c.setPlotArea(50, 40, c.getWidth() - 100, c.getHeight() - 80, &Hf4f4f4, -1, _ Chart.Transparent, c.dashLineColor(&H444444, Chart.DotLine)) ' Add a line layer for the pareto line Dim lineLayer As LineLayer = c.addLineLayer2() ' Add the pareto line using deep blue (0000ff) as the color, with circle symbols lineLayer.addDataSet(lineData.result(), &H0000ff).setDataSymbol(Chart.CircleShape, 9, _ &H0000ff, &H0000ff) ' Set the line width to 2 pixel lineLayer.setLineWidth(2) ' Bind the line layer to the secondary (right) y-axis. lineLayer.setUseYAxis2() ' Tool tip for the line layer lineLayer.setHTMLImageMap("", "", "title='Top {={x}+1} items: {value|2}%'") ' Add a multi-color bar layer using the given data. Dim barLayer As BarLayer = c.addBarLayer3(data) ' Set soft lighting for the bars with light direction from the right barLayer.setBorderColor(Chart.Transparent, Chart.softLighting(Chart.Right)) ' Tool tip for the bar layer barLayer.setHTMLImageMap("", "", "title='{xLabel}: {value} pieces'") ' Set the labels on the x axis. c.xAxis().setLabels(labels) ' Set the secondary (right) y-axis scale as 0 - 100 with a tick every 20 units c.yAxis2().setLinearScale(0, 100, 20) ' Set the format of the secondary (right) y-axis label to include a percentage sign c.yAxis2().setLabelFormat("{value}%") ' Set the relationship between the two y-axes, which only differ by a scaling factor c.yAxis().syncAxis(c.yAxis2(), scaleFactor) ' Set the format of the primary y-axis label foramt to show no decimal point c.yAxis().setLabelFormat("{value|0}") ' Add a title to the primary y-axis c.yAxis().setTitle("Frequency") ' Set all axes to transparent c.xAxis().setColors(Chart.Transparent) c.yAxis().setColors(Chart.Transparent) c.yAxis2().setColors(Chart.Transparent) ' Adjust the plot area size, such that the bounding box (inclusive of axes) is 10 pixels ' from the left edge, just below the title, 10 pixels from the right edge, and 20 pixels ' from the bottom edge. c.packPlotArea(10, title.getHeight(), c.getWidth() - 10, c.getHeight() - 20) ' Output the chart viewer.Chart = c ' Include tool tip for the chart viewer.ImageMap = c.getHTMLImageMap("clickable") End Sub End Class
jojogreen/Orbital-Mechanix-Suite
NetWinCharts/VBNetWinCharts/pareto.vb
Visual Basic
apache-2.0
4,774
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("InstallUpdate")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("Hanzalah Ravat")> <Assembly: AssemblyProduct("InstallUpdate")> <Assembly: AssemblyCopyright("Copyright © Hanzalah 2017")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("ab3f6dcf-4e2d-4fdd-a663-d34e008c0d3a")> ' 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.2.0.0")>
hsravat-4590/automatic-waddle
WaddleWaddle/InstallUpdate/My Project/AssemblyInfo.vb
Visual Basic
apache-2.0
1,161
' Copyright (c) 2015 ZZZ Projects. All rights reserved ' Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods) ' Website: http://www.zzzprojects.com/ ' Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927 ' All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library Imports System.Drawing Public Module Extensions_748 ''' <summary> ''' Translates the specified structure to a Windows color. ''' </summary> ''' <param name="c">The structure to translate.</param> ''' <returns>The Windows color value.</returns> <System.Runtime.CompilerServices.Extension> _ Public Function ToWin32(c As Color) As Int32 Return ColorTranslator.ToWin32(c) End Function End Module
huoxudong125/Z.ExtensionMethods
src (VB.NET)/Z.ExtensionMethods.VB/Z.Drawing/System.Drawing.Color/System.Drawing.ColorTranslator/Color.ToWin32.vb
Visual Basic
mit
793
' Licensed to the .NET Foundation under one or more 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.Globalization Imports System.IO Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Xunit Imports Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers Namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests <Trait(Traits.Feature, Traits.Features.SarifErrorLogging)> Public Class SarifV2ErrorLoggerTests Inherits SarifErrorLoggerTests Protected Overrides ReadOnly Property ErrorLogQualifier As String Get Return ";version=2" End Get End Property Friend Overrides Function GetExpectedOutputForNoDiagnostics( cmd As CommonCompiler) As String Dim expectedOutput = "{{ ""$schema"": ""http://json.schemastore.org/sarif-2.1.0"", ""version"": ""2.1.0"", ""runs"": [ {{ ""results"": [ ], ""tool"": {{ ""driver"": {{ ""name"": ""{0}"", ""version"": ""{1}"", ""dottedQuadFileVersion"": ""{2}"", ""semanticVersion"": ""{3}"", ""language"": ""{4}"" }} }}, ""columnKind"": ""utf16CodeUnits"" }} ] }}" Return FormatOutputText(expectedOutput, cmd) End Function <Fact> Public Sub NoDiagnostics() NoDiagnosticsImpl() End Sub Friend Overrides Function GetExpectedOutputForSimpleCompilerDiagnostics( cmd As CommonCompiler, sourceFilePath As String) As String Dim expectedOutput = "{{ ""$schema"": ""http://json.schemastore.org/sarif-2.1.0"", ""version"": ""2.1.0"", ""runs"": [ {{ ""results"": [ {{ ""ruleId"": ""BC42024"", ""ruleIndex"": 0, ""level"": ""warning"", ""message"": {{ ""text"": ""Unused local variable: 'x'."" }}, ""locations"": [ {{ ""physicalLocation"": {{ ""artifactLocation"": {{ ""uri"": ""{5}"" }}, ""region"": {{ ""startLine"": 4, ""startColumn"": 13, ""endLine"": 4, ""endColumn"": 14 }} }} }} ], ""properties"": {{ ""warningLevel"": 1 }} }}, {{ ""ruleId"": ""BC30420"", ""ruleIndex"": 1, ""level"": ""error"", ""message"": {{ ""text"": ""'Sub Main' was not found in '{6}'."" }} }} ], ""tool"": {{ ""driver"": {{ ""name"": ""{0}"", ""version"": ""{1}"", ""dottedQuadFileVersion"": ""{2}"", ""semanticVersion"": ""{3}"", ""language"": ""{4}"", ""rules"": [ {{ ""id"": ""BC42024"", ""shortDescription"": {{ ""text"": ""Unused local variable"" }}, ""properties"": {{ ""category"": ""Compiler"", ""tags"": [ ""Compiler"", ""Telemetry"" ] }} }}, {{ ""id"": ""BC30420"", ""defaultConfiguration"": {{ ""level"": ""error"" }}, ""properties"": {{ ""category"": ""Compiler"", ""tags"": [ ""Compiler"", ""Telemetry"", ""NotConfigurable"" ] }} }} ] }} }}, ""columnKind"": ""utf16CodeUnits"" }} ] }}" Return FormatOutputText( expectedOutput, cmd, AnalyzerForErrorLogTest.GetUriForPath(sourceFilePath), Path.GetFileNameWithoutExtension(sourceFilePath)) End Function <Fact> Public Sub SimpleCompilerDiagnostics() SimpleCompilerDiagnosticsImpl() End Sub Friend Overrides Function GetExpectedOutputForSimpleCompilerDiagnosticsSuppressed( cmd As CommonCompiler, sourceFilePath As String) As String Dim expectedOutput = "{{ ""$schema"": ""http://json.schemastore.org/sarif-2.1.0"", ""version"": ""2.1.0"", ""runs"": [ {{ ""results"": [ {{ ""ruleId"": ""BC42024"", ""ruleIndex"": 0, ""level"": ""warning"", ""message"": {{ ""text"": ""Unused local variable: 'x'."" }}, ""suppressions"": [ {{ ""kind"": ""inSource"" }} ], ""locations"": [ {{ ""physicalLocation"": {{ ""artifactLocation"": {{ ""uri"": ""{5}"" }}, ""region"": {{ ""startLine"": 5, ""startColumn"": 13, ""endLine"": 5, ""endColumn"": 14 }} }} }} ], ""properties"": {{ ""warningLevel"": 1 }} }}, {{ ""ruleId"": ""BC30420"", ""ruleIndex"": 1, ""level"": ""error"", ""message"": {{ ""text"": ""'Sub Main' was not found in '{6}'."" }} }} ], ""tool"": {{ ""driver"": {{ ""name"": ""{0}"", ""version"": ""{1}"", ""dottedQuadFileVersion"": ""{2}"", ""semanticVersion"": ""{3}"", ""language"": ""{4}"", ""rules"": [ {{ ""id"": ""BC42024"", ""shortDescription"": {{ ""text"": ""Unused local variable"" }}, ""properties"": {{ ""category"": ""Compiler"", ""tags"": [ ""Compiler"", ""Telemetry"" ] }} }}, {{ ""id"": ""BC30420"", ""defaultConfiguration"": {{ ""level"": ""error"" }}, ""properties"": {{ ""category"": ""Compiler"", ""tags"": [ ""Compiler"", ""Telemetry"", ""NotConfigurable"" ] }} }} ] }} }}, ""columnKind"": ""utf16CodeUnits"" }} ] }}" Return FormatOutputText( expectedOutput, cmd, AnalyzerForErrorLogTest.GetUriForPath(sourceFilePath), Path.GetFileNameWithoutExtension(sourceFilePath)) End Function <Fact> Public Sub SimpleCompilerDiagnosticsSuppressed() SimpleCompilerDiagnosticsSuppressedImpl() End Sub Friend Overrides Function GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation( cmd As MockVisualBasicCompiler) As String Dim expectedOutput = "{{ ""$schema"": ""http://json.schemastore.org/sarif-2.1.0"", ""version"": ""2.1.0"", ""runs"": [ {{ {5}, ""tool"": {{ ""driver"": {{ ""name"": ""{0}"", ""version"": ""{1}"", ""dottedQuadFileVersion"": ""{2}"", ""semanticVersion"": ""{3}"", ""language"": ""{4}"", {6} }} }}, ""columnKind"": ""utf16CodeUnits"" }} ] }}" Return FormatOutputText( expectedOutput, cmd, AnalyzerForErrorLogTest.GetExpectedV2ErrorLogResultsText(cmd.Compilation), AnalyzerForErrorLogTest.GetExpectedV2ErrorLogRulesText()) End Function <Fact> Public Sub AnalyzerDiagnosticsWithAndWithoutLocation() AnalyzerDiagnosticsWithAndWithoutLocationImpl() End Sub Private Function FormatOutputText(s As String, compiler as CommonCompiler, ParamArray additionalArguments() As Object) As String Dim arguments = New List(Of Object) From { compiler.GetToolName(), compiler.GetCompilerVersion(), compiler.GetAssemblyVersion(), compiler.GetAssemblyVersion().ToString(fieldCount:=3), compiler.GetCultureName() }.Concat(additionalArguments).ToArray() Return string.Format(CultureInfo.InvariantCulture, s, arguments) End Function End Class End Namespace
jmarolf/roslyn
src/Compilers/VisualBasic/Test/CommandLine/SarifV2ErrorLoggerTests.vb
Visual Basic
mit
8,868
' 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.Threading Imports System.Threading.Tasks Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.MethodXML Partial Public Class MethodXMLTests <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_FieldWithoutMe() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() c = New Class1 End Sub Private c As Class1 End Class </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="3"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>c</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>ClassLibrary1.Class1</Type> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_WithEventsFieldWithoutMe() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() c = New Class1 End Sub Private WithEvents c As Class1 End Class </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="3"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>c</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>ClassLibrary1.Class1</Type> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_FieldWithMe() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Me.c = New Class1 End Sub Private c As Class1 End Class </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="3"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>c</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>ClassLibrary1.Class1</Type> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_PropertyThroughFieldWithoutMe() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() p.c = New Class1 End Sub Private c As Class1 Property p As Class1 End Class </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="3"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>p</Name> </NameRef> </Expression> <Name>c</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>ClassLibrary1.Class1</Type> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_PropertyThroughFieldWithMe() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Me.p.c = New Class1 End Sub Private c As Class1 Property p As Class1 End Class </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="3"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>p</Name> </NameRef> </Expression> <Name>c</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>ClassLibrary1.Class1</Type> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_InferredWithBinaryPlusOperation() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class C $$Sub M() Dim i = 1 + 1 End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <Type>System.Int32</Type> <Name>i</Name> <Expression> <BinaryOperation binaryoperator="plus"> <Expression> <Literal> <Number type="System.Int32">1</Number> </Literal> </Expression> <Expression> <Literal> <Number type="System.Int32">1</Number> </Literal> </Expression> </BinaryOperation> </Expression> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_WithBinaryPlusOperation() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class C $$Sub M() Dim i As Integer = 1 + 1 End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <Type>System.Int32</Type> <Name>i</Name> <Expression> <BinaryOperation binaryoperator="plus"> <Expression> <Literal> <Number type="System.Int32">1</Number> </Literal> </Expression> <Expression> <Literal> <Number type="System.Int32">1</Number> </Literal> </Expression> </BinaryOperation> </Expression> </Local> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_HexNumber() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class C $$Sub M() Dim i As Integer = &amp;H42 End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <Type>System.Int32</Type> <Name>i</Name> <Expression> <Literal> <Number type="System.Int32">66</Number> </Literal> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(462922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/462922")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_Bug462922() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Test Private _vt As System.ValueType = 2.0# Public Property VT() As System.ValueType Get Return _vt End Get Set(ByVal value As System.ValueType) _vt = value End Set End Property End Class Public Class C Private Test1 As New Test $$Sub M() Me.Test1.VT = 2.0R End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="17"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Test1</Name> </NameRef> </Expression> <Name>VT</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Double">2</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_EnumsAndCasts() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class C $$Sub M() Me.Goo = (CType(((AnchorStyles.Top Or AnchorStyles.Left) Or AnchorStyles.Right), AnchorStyles)) End Sub Public Property Goo As AnchorStyles End Class Enum AnchorStyles Top Left Right Bottom End Enum </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="3"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>Goo</Name> </NameRef> </Expression> <Expression> <Parentheses> <Expression> <Cast> <Type>ClassLibrary1.AnchorStyles</Type> <Expression> <Parentheses> <Expression> <BinaryOperation binaryoperator="bitor"> <Expression> <Parentheses> <Expression> <BinaryOperation binaryoperator="bitor"> <Expression> <NameRef variablekind="field"> <Expression> <Literal> <Type>ClassLibrary1.AnchorStyles</Type> </Literal> </Expression> <Name>Top</Name> </NameRef> </Expression> <Expression> <NameRef variablekind="field"> <Expression> <Literal> <Type>ClassLibrary1.AnchorStyles</Type> </Literal> </Expression> <Name>Left</Name> </NameRef> </Expression> </BinaryOperation> </Expression> </Parentheses> </Expression> <Expression> <NameRef variablekind="field"> <Expression> <Literal> <Type>ClassLibrary1.AnchorStyles</Type> </Literal> </Expression> <Name>Right</Name> </NameRef> </Expression> </BinaryOperation> </Expression> </Parentheses> </Expression> </Cast> </Expression> </Parentheses> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WorkItem(743120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743120")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_PropertyOffParameter() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class C Sub $$M(builder As System.Text.StringBuilder) builder.Capacity = 10 End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="3"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <NameRef variablekind="local"> <Name>builder</Name> </NameRef> </Expression> <Name>Capacity</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">10</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_NullableValue() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class C Sub $$M() Dim i As Integer? = 0 Dim j As Integer? = Nothing End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <Type>System.Nullable`1[System.Int32]</Type> <Name>i</Name> <Expression> <Literal> <Number type="System.Int32">0</Number> </Literal> </Expression> </Local> <Local line="4"> <Type>System.Nullable`1[System.Int32]</Type> <Name>j</Name> <Expression> <Literal> <Null/> </Literal> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_ClosedGeneric1() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.Collections.Generic Public Class C Sub $$M() Dim l = New List(Of Integer) End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="4"> <Type>System.Collections.Generic.List`1[System.Int32]</Type> <Name>l</Name> <Expression> <NewClass> <Type>System.Collections.Generic.List`1[System.Int32]</Type> </NewClass> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_ClosedGeneric2() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.Collections.Generic Public Class C Sub $$M() Dim l = New Dictionary(Of String, List(Of Integer)) End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="4"> <Type>System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.List`1[System.Int32]]</Type> <Name>l</Name> <Expression> <NewClass> <Type>System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.List`1[System.Int32]]</Type> </NewClass> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_ClosedGeneric3() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.Collections.Generic Public Class C Sub $$M() Dim l = New List(Of String()) End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="4"> <Type>System.Collections.Generic.List`1[System.String[]]</Type> <Name>l</Name> <Expression> <NewClass> <Type>System.Collections.Generic.List`1[System.String[]]</Type> </NewClass> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_ClosedGeneric4() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.Collections.Generic Public Class C Sub $$M() Dim l = New List(Of String(,,)) End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="4"> <Type>System.Collections.Generic.List`1[System.String[,,]]</Type> <Name>l</Name> <Expression> <NewClass> <Type>System.Collections.Generic.List`1[System.String[,,]]</Type> </NewClass> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(831374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831374")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_TypeConfluence() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports L = System.Collections.Generic.List(Of Byte()) Public Class C Sub $$M() Dim l = New L() End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="4"> <Type>System.Collections.Generic.List`1[System.Byte[]]</Type> <Name>l</Name> <Expression> <NewClass> <Type>System.Collections.Generic.List`1[System.Byte[]]</Type> </NewClass> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(887584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/887584")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_EscapedNames() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Enum E [True] [False] End Enum Public Class C Dim e1 As E Sub $$M() e1 = E.[True] End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="9"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>e1</Name> </NameRef> </Expression> <Expression> <NameRef variablekind="field"> <Expression> <Literal> <Type>E</Type> </Literal> </Expression> <Name>True</Name> </NameRef> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_FloatingPointLiteralInGermanUICulture() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class C $$Sub M() x = 0.42! End Sub Private x As Single End Class </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="3"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>x</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Single">0.42</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Dim currentThread = Thread.CurrentThread Dim oldCulture = currentThread.CurrentCulture Try currentThread.CurrentCulture = CultureInfo.GetCultureInfo("de-DE") Test(definition, expected) Finally currentThread.CurrentCulture = oldCulture End Try End Sub <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_DontThrowWhenLeftHandSideDoesntBind() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class A Public Property Prop As B End Class Public Class C Dim x As New A $$Sub M() x.Prop.NestedProp = "Text" End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="9"> <Expression> <Assignment> <Expression> <NameRef variablekind="unknown"> <Expression> <NameRef variablekind="property"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>x</Name> </NameRef> </Expression> <Name>Prop</Name> </NameRef> </Expression> <Name>NestedProp</Name> </NameRef> </Expression> <Expression> <Literal> <String>Text</String> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Dim currentThread = Thread.CurrentThread Dim oldCulture = currentThread.CurrentCulture Try currentThread.CurrentCulture = CultureInfo.GetCultureInfo("de-DE") Test(definition, expected) Finally currentThread.CurrentCulture = oldCulture End Try End Sub <WorkItem(4312, "https://github.com/dotnet/roslyn/issues/4312")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_PropertyAssignedWithEmptyArray() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Private Property Series As Object() $$Sub M() Me.Series = New Object(-1) {} End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"><Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>Series</Name> </NameRef> </Expression> <Expression> <NewArray> <ArrayType rank="1"> <Type>System.Object</Type> </ArrayType> <Bound> <Expression> <Literal> <Number type="System.Int32">0</Number> </Literal> </Expression> </Bound> </NewArray> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WorkItem(4149, "https://github.com/dotnet/roslyn/issues/4149")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_RoundTrippedDoubles() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub $$M() Dim d As Double = 9.2233720368547758E+18R End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <Type>System.Double</Type> <Name>d</Name> <Expression> <Literal> <Number type="System.Double">9.2233720368547758E+18</Number> </Literal> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(4149, "https://github.com/dotnet/roslyn/issues/4149")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_RoundTrippedSingles() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub $$M() Dim s As Single = 0.333333343F End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <Type>System.Single</Type> <Name>s</Name> <Expression> <Literal> <Number type="System.Single">0.333333343</Number> </Literal> </Expression> </Local> </Block> Test(definition, expected) End Sub End Class End Namespace
mmitche/roslyn
src/VisualStudio/Core/Test/CodeModel/MethodXML/MethodXMLTests_VBAssignments.vb
Visual Basic
apache-2.0
33,288
' Licensed to the .NET Foundation under one or more 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.Threading Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic.Classification <ExportLanguageService(GetType(IClassificationService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicEditorClassificationService Inherits AbstractClassificationService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Overrides Sub AddLexicalClassifications(text As SourceText, textSpan As TextSpan, result As List(Of ClassifiedSpan), cancellationToken As CancellationToken) Dim temp = ArrayBuilder(Of ClassifiedSpan).GetInstance() ClassificationHelpers.AddLexicalClassifications(text, textSpan, temp, cancellationToken) AddRange(temp, result) temp.Free() End Sub Public Overrides Function AdjustStaleClassification(text As SourceText, classifiedSpan As ClassifiedSpan) As ClassifiedSpan Return ClassificationHelpers.AdjustStaleClassification(text, classifiedSpan) End Function End Class End Namespace
ErikSchierboom/roslyn
src/Workspaces/VisualBasic/Portable/Classification/VisualBasicClassificationService.vb
Visual Basic
apache-2.0
1,517
' 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 Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class NameOfTests Inherits BasicTestBase <Fact> Public Sub TestParsing_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(Integer.MaxValue) Dim y = NameOf(Integer) Dim z = NameOf(Variant) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC37244: This expression does not have a name. Dim y = NameOf(Integer) ~~~~~~~ BC30804: 'Variant' is no longer a supported type; use the 'Object' type instead. Dim z = NameOf(Variant) ~~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().ToArray() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) If True Then Dim node1 = nodes(0) Assert.Equal("NameOf(Integer.MaxValue)", node1.ToString()) Assert.Equal("MaxValue", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("System.Int32.MaxValue As System.Int32", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.True(group.IsEmpty) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End If If True Then Dim node2 = nodes(1) Assert.Equal("NameOf(Integer)", node2.ToString()) Assert.Null(model.GetConstantValue(node2).Value) typeInfo = model.GetTypeInfo(node2) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node2) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node2) Assert.True(group.IsEmpty) Dim argument = node2.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.True(group.IsEmpty) End If If True Then Dim node3 = nodes(2) Assert.Equal("NameOf(Variant)", node3.ToString()) Assert.Equal("Variant", model.GetConstantValue(node3).Value) typeInfo = model.GetTypeInfo(node3) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node3) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node3) Assert.True(group.IsEmpty) Dim argument = node3.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.True(group.IsEmpty) End If End Sub <Fact> Public Sub TestParsing_02() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(C2(Of Integer).C3(Of )) Dim y = NameOf(C2(Of ).C3(Of Integer)) Dim z = NameOf(C2(Of Integer).C3(Of Integer)) End Sub End Module Class C2(Of T) Class C3(Of S) End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30182: Type expected. Dim x = NameOf(C2(Of Integer).C3(Of )) ~ BC30182: Type expected. Dim y = NameOf(C2(Of ).C3(Of Integer)) ~ </expected>) End Sub <Fact> Public Sub TestParsing_03() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(C2(Of Integer).C3(Of ).M1) Dim y = NameOf(C2(Of ).C3(Of Integer).M1) Dim z = NameOf(C2(Of Integer).C3(Of Integer).M1) End Sub End Module Class C2(Of T) Class C3(Of S) Sub M1() End Sub End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30182: Type expected. Dim x = NameOf(C2(Of Integer).C3(Of ).M1) ~ BC30182: Type expected. Dim y = NameOf(C2(Of ).C3(Of Integer).M1) ~ </expected>) End Sub <Fact> Public Sub TestParsing_04() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(Global) Dim y = NameOf(Global.System) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC36000: 'Global' must be followed by '.' and an identifier. Dim x = NameOf(Global) ~~~~~~ BC37244: This expression does not have a name. Dim x = NameOf(Global) ~~~~~~ </expected>) End Sub <Fact> Public Sub TestParsing_05() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() End Sub End Module Class CTest Sub Test1() Dim x = NameOf(MyClass) Dim y = NameOf(MyClass.Test1) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC32028: 'MyClass' must be followed by '.' and an identifier. Dim x = NameOf(MyClass) ~~~~~~~ BC37244: This expression does not have a name. Dim x = NameOf(MyClass) ~~~~~~~ </expected>) End Sub <Fact> Public Sub TestParsing_06() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() End Sub End Module Class CTest Sub Test1() Dim x = NameOf(MyBase) Dim y = NameOf(MyBase.GetHashCode) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC32027: 'MyBase' must be followed by '.' and an identifier. Dim x = NameOf(MyBase) ~~~~~~ BC37244: This expression does not have a name. Dim x = NameOf(MyBase) ~~~~~~ </expected>) End Sub <Fact> Public Sub TestParsing_07() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() End Sub End Module Class CTest Sub Test1() Dim x = NameOf(Me) Dim y = NameOf(Me.GetHashCode) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC37244: This expression does not have a name. Dim x = NameOf(Me) ~~ </expected>) End Sub <Fact> Public Sub TestParsing_08() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(Integer?) Dim y = NameOf(Integer?.GetValueOrDefault) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC37244: This expression does not have a name. Dim x = NameOf(Integer?) ~~~~~~~~ </expected>) End Sub <Fact> Public Sub TestParsing_09() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As Integer? = Nothing Dim y = NameOf(x.GetValueOrDefault) Dim z = NameOf((x).GetValueOrDefault) Dim u = NameOf(New Integer?().GetValueOrDefault) Dim v = NameOf(GetVal().GetValueOrDefault) Dim w = NameOf(GetVal.GetValueOrDefault) End Sub Function GetVal() As Integer? Return Nothing End Function End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC37245: This sub-expression cannot be used inside NameOf argument. Dim z = NameOf((x).GetValueOrDefault) ~~~ BC37245: This sub-expression cannot be used inside NameOf argument. Dim u = NameOf(New Integer?().GetValueOrDefault) ~~~~~~~~~~~~~~ BC37245: This sub-expression cannot be used inside NameOf argument. Dim v = NameOf(GetVal().GetValueOrDefault) ~~~~~~~~ </expected>) End Sub <Fact> Public Sub TestParsing_10() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As Integer? = Nothing NameOf(x.GetValueOrDefault) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30035: Syntax error. NameOf(x.GetValueOrDefault) ~~~~~~ </expected>) End Sub <Fact> Public Sub Namespace_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(Global.System)) System.Console.WriteLine(NameOf(Global.system)) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ System system ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(Global.System)", node1.ToString()) Assert.Equal("System", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("System", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("Global", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub Method_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2(Of Integer).C3(Of Short).M1)) System.Console.WriteLine(NameOf(C2(Of Integer).C3(Of Short).m1)) End Sub End Module Class C2(Of T) Class C3(Of S) Sub M1() End Sub End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ M1 m1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2(Of Integer).C3(Of Short).M1)", node1.ToString()) Assert.Equal("M1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Sub C2(Of System.Int32).C3(Of System.Int16).M1()", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(1, group.Length) Assert.Equal("Sub C2(Of System.Int32).C3(Of System.Int16).M1()", group.Single.ToTestDisplayString()) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) receiver = DirectCast(receiver, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub Method_02() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C1.M1)) System.Console.WriteLine(NameOf(C1.m1)) End Sub End Module Class C1 Sub M1(Of T)() End Sub Sub M1(x as Integer) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ M1 m1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C1.M1)", node1.ToString()) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal(2, symbolInfo.CandidateSymbols.Length) Assert.Equal("Sub C1.M1(Of T)()", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Equal("Sub C1.M1(x As System.Int32)", symbolInfo.CandidateSymbols(1).ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(2, group.Length) Assert.Equal("Sub C1.M1(Of T)()", group(0).ToTestDisplayString()) Assert.Equal("Sub C1.M1(x As System.Int32)", group(1).ToTestDisplayString()) End Sub <Fact> Public Sub Method_03() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C1.M1)) End Sub End Module Class C1 Sub M1(Of T)() End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ M1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C1.M1)", node1.ToString()) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Sub C1.M1(Of T)()", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Sub C1.M1(Of T)()", group.Single.ToTestDisplayString()) End Sub <Fact> Public Sub Method_04() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C1.M1(Of Integer))) End Sub End Module Class C1 Sub M1(Of T)() End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC37246: Method type arguments unexpected. System.Console.WriteLine(NameOf(C1.M1(Of Integer))) ~~~~~~~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C1.M1(Of Integer))", node1.ToString()) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Sub C1.M1(Of System.Int32)()", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Sub C1.M1(Of System.Int32)()", group.Single.ToTestDisplayString()) End Sub <Fact> Public Sub Method_05() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C1.M1(Of Integer))) End Sub End Module Class C1 Sub M1(Of T)() End Sub Sub M1(x as Integer) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC37246: Method type arguments unexpected. System.Console.WriteLine(NameOf(C1.M1(Of Integer))) ~~~~~~~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C1.M1(Of Integer))", node1.ToString()) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Sub C1.M1(Of System.Int32)()", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Sub C1.M1(Of System.Int32)()", group.Single.ToTestDisplayString()) End Sub <Fact> Public Sub Method_06() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C1.M1(Of Integer))) End Sub End Module Class C1 Sub M1(x as Integer) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC37246: Method type arguments unexpected. System.Console.WriteLine(NameOf(C1.M1(Of Integer))) ~~~~~~~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C1.M1(Of Integer))", node1.ToString()) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub GenericType_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2(Of Integer).C3(Of Short))) System.Console.WriteLine(NameOf(C2(Of Integer).c3(Of Short))) End Sub End Module Class C2(Of T) Class C3(Of S) End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ C3 c3 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2(Of Integer).C3(Of Short))", node1.ToString()) Assert.Equal("C3", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub AmbiguousType_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2(Of Integer).CC3)) System.Console.WriteLine(NameOf(C2(Of Integer).cc3)) End Sub End Module Class C2(Of T) Class Cc3(Of S) End Class Class cC3(Of U, V) End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC32042: Too few type arguments to 'C2(Of Integer).Cc3(Of S)'. System.Console.WriteLine(NameOf(C2(Of Integer).CC3)) ~~~~~~~~~~~~~~~~~~ BC32042: Too few type arguments to 'C2(Of Integer).Cc3(Of S)'. System.Console.WriteLine(NameOf(C2(Of Integer).cc3)) ~~~~~~~~~~~~~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2(Of Integer).CC3)", node1.ToString()) Assert.Equal("CC3", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("C2(Of System.Int32).Cc3(Of S)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.WrongArity, symbolInfo.CandidateReason) Assert.Equal("C2(Of System.Int32).Cc3(Of S)", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub AmbiguousType_02() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.CC3)) System.Console.WriteLine(NameOf(C2.cc3)) End Sub End Module Class C1 Class Cc3(Of S) End Class End Class Class C2 Inherits C1 Class cC3(Of U, V) End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC32042: Too few type arguments to 'C2.cC3(Of U, V)'. System.Console.WriteLine(NameOf(C2.CC3)) ~~~~~~ BC32042: Too few type arguments to 'C2.cC3(Of U, V)'. System.Console.WriteLine(NameOf(C2.cc3)) ~~~~~~ </expected>) End Sub <Fact> Public Sub InaccessibleNonGenericType_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.CC3)) End Sub End Module Class C2 protected Class Cc3 End Class Class cC3(Of U, V) End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC30389: 'C2.Cc3' is not accessible in this context because it is 'Protected'. System.Console.WriteLine(NameOf(C2.CC3)) ~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2.CC3)", node1.ToString()) Assert.Equal("CC3", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("C2.Cc3", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) Assert.Equal("C2.Cc3", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub Alias_01() Dim compilationDef = <compilation> <file name="a.vb"> Imports [alias] = System Module Module1 Sub Main() System.Console.WriteLine(NameOf([alias])) System.Console.WriteLine(NameOf([ALIAS])) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ alias ALIAS ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf([alias])", node1.ToString()) Assert.Equal("alias", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("System", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Assert.Equal("[alias]=System", model.GetAliasInfo(argument).ToTestDisplayString()) End Sub <Fact> Public Sub InaccessibleMethod_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(C2(Of Integer).C3(Of Short).M1) End Sub End Module Class C2(Of T) Class C3(Of S) Protected Sub M1() End Sub End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30390: 'C3.Protected Sub M1()' is not accessible in this context because it is 'Protected'. Dim x = NameOf(C2(Of Integer).C3(Of Short).M1) ~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2(Of Integer).C3(Of Short).M1)", node1.ToString()) Assert.Equal("M1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) Assert.Equal("Sub C2(Of System.Int32).C3(Of System.Int16).M1()", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(1, group.Length) Assert.Equal("Sub C2(Of System.Int32).C3(Of System.Int16).M1()", group.Single.ToTestDisplayString()) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) receiver = DirectCast(receiver, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub InaccessibleProperty_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(C2(Of Integer).C3(Of Short).P1) End Sub End Module Class C2(Of T) Class C3(Of S) Protected Property P1 As Integer End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30389: 'C2(Of Integer).C3(Of Short).P1' is not accessible in this context because it is 'Protected'. Dim x = NameOf(C2(Of Integer).C3(Of Short).P1) ~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2(Of Integer).C3(Of Short).P1)", node1.ToString()) Assert.Equal("P1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) Assert.Equal("Property C2(Of System.Int32).C3(Of System.Int16).P1 As System.Int32", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(1, group.Length) Assert.Equal("Property C2(Of System.Int32).C3(Of System.Int16).P1 As System.Int32", group.Single.ToTestDisplayString()) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) receiver = DirectCast(receiver, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub InaccessibleField_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(C2(Of Integer).C3(Of Short).F1) End Sub End Module Class C2(Of T) Class C3(Of S) Protected F1 As Integer End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30389: 'C2(Of Integer).C3(Of Short).F1' is not accessible in this context because it is 'Protected'. Dim x = NameOf(C2(Of Integer).C3(Of Short).F1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2(Of Integer).C3(Of Short).F1)", node1.ToString()) Assert.Equal("F1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16).F1 As System.Int32", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) receiver = DirectCast(receiver, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub InaccessibleEvent_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(C2(Of Integer).C3(Of Short).E1) End Sub End Module Class C2(Of T) Class C3(Of S) Protected Event E1 As System.Action End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30389: 'C2(Of Integer).C3(Of Short).E1' is not accessible in this context because it is 'Protected'. Dim x = NameOf(C2(Of Integer).C3(Of Short).E1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2(Of Integer).C3(Of Short).E1)", node1.ToString()) Assert.Equal("E1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason) Assert.Equal("Event C2(Of System.Int32).C3(Of System.Int16).E1 As System.Action", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) receiver = DirectCast(receiver, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub Missing_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(C2(Of Integer).C3(Of Short).Missing) End Sub End Module Class C2(Of T) Class C3(Of S) End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30456: 'Missing' is not a member of 'C2(Of Integer).C3(Of Short)'. Dim x = NameOf(C2(Of Integer).C3(Of Short).Missing) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2(Of Integer).C3(Of Short).Missing)", node1.ToString()) Assert.Equal("Missing", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32).C3(Of System.Int16)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) receiver = DirectCast(receiver, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2(Of System.Int32)", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub Missing_02() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(Missing.M1) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30451: 'Missing' is not declared. It may be inaccessible due to its protection level. Dim x = NameOf(Missing.M1) ~~~~~~~ </expected>) End Sub <Fact> Public Sub Missing_03() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = NameOf(Missing) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC30451: 'Missing' is not declared. It may be inaccessible due to its protection level. Dim x = NameOf(Missing) ~~~~~~~ </expected>) End Sub <Fact> Public Sub AmbiguousMethod_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(Ambiguous)) End Sub End Module Module Module2 Sub Ambiguous() End Sub End Module Module Module3 Sub Ambiguous() End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC30562: 'Ambiguous' is ambiguous between declarations in Modules 'Module2, Module3'. System.Console.WriteLine(NameOf(Ambiguous)) ~~~~~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(Ambiguous)", node1.ToString()) Assert.Equal("Ambiguous", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Void", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason) Assert.Equal(2, symbolInfo.CandidateSymbols.Length) Assert.Equal("Sub Module2.Ambiguous()", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Equal("Sub Module3.Ambiguous()", symbolInfo.CandidateSymbols(1).ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub AmbiguousMethod_02() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(I3.Ambiguous)) End Sub End Module Interface I1 Sub Ambiguous() End Interface Interface I2 Sub Ambiguous(x as Integer) End Interface Interface I3 Inherits I1, I2 End Interface </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ Ambiguous ]]>) End Sub <Fact> Public Sub Local_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim local As Integer = 0 System.Console.WriteLine(NameOf(LOCAL)) System.Console.WriteLine(NameOf(loCal)) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ LOCAL loCal ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(LOCAL)", node1.ToString()) Assert.Equal("LOCAL", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("local As System.Int32", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub Local_02() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(LOCAL)) Dim local As Integer = 0 End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(comp, <expected> BC32000: Local variable 'local' cannot be referred to before it is declared. System.Console.WriteLine(NameOf(LOCAL)) ~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(LOCAL)", node1.ToString()) Assert.Equal("LOCAL", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("local As System.Int32", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub Local_03() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim local = NameOf(LOCAL) System.Console.WriteLine(local) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC30980: Type of 'local' cannot be inferred from an expression containing 'local'. Dim local = NameOf(LOCAL) ~~~~~ </expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(LOCAL)", node1.ToString()) Assert.Equal("LOCAL", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("local As System.String", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub Local_04() Dim compilationDef = <compilation> <file name="a.vb"> Option Explicit Off Module Module1 Sub Main() System.Console.WriteLine(NameOf(LOCAL)) local = 0 End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ LOCAL ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(LOCAL)", node1.ToString()) Assert.Equal("LOCAL", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Object", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("LOCAL As System.Object", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub Local_05() Dim compilationDef = <compilation> <file name="a.vb"> Option Explicit Off Module Module1 Sub Main() local = 3 System.Console.WriteLine(NameOf(LOCAL)) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ LOCAL ]]>) End Sub <Fact> Public Sub Local_06() Dim compilationDef = <compilation> <file name="a.vb"> Option Explicit Off Module Module1 Sub Main() local = NameOf(LOCAL) System.Console.WriteLine(local) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ LOCAL ]]>) End Sub <Fact> Public Sub TypeParameterAsQualifier_01() Dim compilationDef = <compilation> <file name="a.vb"> Option Explicit Off Module Module1 Sub Main() C3(Of C2).Test() End Sub End Module Class C2 Sub M1() End Sub End Class Class C3(Of T As C2) Shared Sub Test() System.Console.WriteLine(NameOf(T.M1)) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC32098: Type parameters cannot be used as qualifiers. System.Console.WriteLine(NameOf(T.M1)) ~~~~ </expected>) End Sub <Fact> Public Sub InstanceOfType_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.F1)) End Sub End Module Class C2 Public F1 As Integer End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ F1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2.F1)", node1.ToString()) Assert.Equal("F1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("C2.F1 As System.Int32", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub InstanceOfType_02() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.F1.F2)) End Sub End Module Class C2 Public F1 As C3 End Class Class C3 Public F2 As Integer End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC30469: Reference to a non-shared member requires an object reference. System.Console.WriteLine(NameOf(C2.F1.F2)) ~~~~~ </expected>) End Sub <Fact> Public Sub InstanceOfType_03() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.P1)) End Sub End Module Class C2 Public Property P1 As Integer End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ P1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2.P1)", node1.ToString()) Assert.Equal("P1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Property C2.P1 As System.Int32", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Property C2.P1 As System.Int32", group.Single.ToTestDisplayString()) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub InstanceOfType_04() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.P1.P2)) End Sub End Module Class C2 Public Property P1 As C3 End Class Class C3 Public Property P2 As Integer End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC30469: Reference to a non-shared member requires an object reference. System.Console.WriteLine(NameOf(C2.P1.P2)) ~~~~~ </expected>) End Sub <Fact> Public Sub InstanceOfType_05() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.M1)) End Sub End Module Class C2 Public Function M1() As Integer Return Nothing End Function End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ M1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2.M1)", node1.ToString()) Assert.Equal("M1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Function C2.M1() As System.Int32", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Function C2.M1() As System.Int32", group.Single.ToTestDisplayString()) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub InstanceOfType_06() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.M1.M2)) End Sub End Module Class C2 Public Function M1() As C3 Return Nothing End Function End Class Class C3 Public Sub M2() End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC30469: Reference to a non-shared member requires an object reference. System.Console.WriteLine(NameOf(C2.M1.M2)) ~~~~~ </expected>) End Sub <Fact> Public Sub InstanceOfType_07() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.M1)) End Sub <System.Runtime.CompilerServices.Extension> Public Function M1(this As C2) As Integer Return Nothing End Function End Module Class C2 End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, {SystemCoreRef}, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ M1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2.M1)", node1.ToString()) Assert.Equal("M1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Function C2.M1() As System.Int32", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Function C2.M1() As System.Int32", group.Single.ToTestDisplayString()) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub InstanceOfType_08() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.M1.M2)) End Sub <System.Runtime.CompilerServices.Extension> Public Function M1(this As C2) As C3 Return Nothing End Function End Module Class C2 End Class Class C3 Public Sub M2() End Sub End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, {SystemCoreRef}, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC30469: Reference to a non-shared member requires an object reference. System.Console.WriteLine(NameOf(C2.M1.M2)) ~~~~~ </expected>) End Sub <Fact> Public Sub InstanceOfType_09() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.E1)) End Sub End Module Class C2 Public Event E1 As System.Action End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ E1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2.E1)", node1.ToString()) Assert.Equal("E1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Action", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("Event C2.E1 As System.Action", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("C2", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("C2", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub InstanceOfType_10() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.E1.Invoke)) End Sub End Module Class C2 Public Event E1 As System.Action End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC30469: Reference to a non-shared member requires an object reference. System.Console.WriteLine(NameOf(C2.E1.Invoke)) ~~~~~ </expected>) End Sub <Fact> Public Sub SharedOfValue_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As New C2() System.Console.WriteLine(NameOf(x.F1)) System.Console.WriteLine(NameOf(x.F1.F2)) End Sub End Module Class C2 Shared Public F1 As C3 End Class Class C3 Shared Public F2 As Integer End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(NameOf(x.F1)) ~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(NameOf(x.F1.F2)) ~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(NameOf(x.F1.F2)) ~~~~~~~ </expected>) CompileAndVerify(comp, expectedOutput:= <![CDATA[ F1 F2 ]]>) End Sub <Fact> Public Sub SharedOfValue_02() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As New C2() System.Console.WriteLine(NameOf(x.P1)) System.Console.WriteLine(NameOf(x.P1.P2)) End Sub End Module Class C2 Shared Public Property P1 As C3 End Class Class C3 Shared Public Property P2 As Integer End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(NameOf(x.P1.P2)) ~~~~ </expected>) CompileAndVerify(comp, expectedOutput:= <![CDATA[ P1 P2 ]]>) End Sub <Fact> Public Sub SharedOfValue_03() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As New C2() System.Console.WriteLine(NameOf(x.M1)) System.Console.WriteLine(NameOf(x.M1.M2)) End Sub End Module Class C2 Shared Public Function M1() As C3 Return Nothing End Function End Class Class C3 Shared Public Sub M2() End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(NameOf(x.M1.M2)) ~~~~ </expected>) CompileAndVerify(comp, expectedOutput:= <![CDATA[ M1 M2 ]]>) End Sub <Fact> Public Sub SharedOfValue_04() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As New C2() System.Console.WriteLine(NameOf(x.E1)) End Sub End Module Class C2 Shared Public Event E1 As System.Action End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(NameOf(x.E1)) ~~~~ </expected>) CompileAndVerify(comp, expectedOutput:= <![CDATA[ E1 ]]>) End Sub <Fact> Public Sub SharedOfValue_05() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As New C2() System.Console.WriteLine(NameOf(x.T1)) System.Console.WriteLine(NameOf(x.P1.T2)) End Sub End Module Class C2 Shared Public Property P1 As C3 Public Class T1 End Class End Class Class C3 Public Class T2 End Class End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(NameOf(x.T1)) ~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(NameOf(x.P1.T2)) ~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. System.Console.WriteLine(NameOf(x.P1.T2)) ~~~~~~~ </expected>) CompileAndVerify(comp, expectedOutput:= <![CDATA[ T1 T2 ]]>) End Sub <Fact> Public Sub DataFlow_01() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As C2 System.Console.WriteLine(NameOf(x.F1)) Dim y As C2 Return System.Console.WriteLine(y.F1) End Sub End Module Class C2 Public F1 As Integer End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ F1 ]]>).VerifyDiagnostics() End Sub <Fact> Public Sub Attribute_01() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ <System.Diagnostics.DebuggerDisplay("={" + NameOf(Test.MTest) + "()}")> Class Test Shared Sub Main() System.Console.WriteLine(DirectCast(GetType(Test).GetCustomAttributes(GetType(System.Diagnostics.DebuggerDisplayAttribute), False)(0), System.Diagnostics.DebuggerDisplayAttribute).Value) End Sub Function MTest() As String Return "" End Function End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ ={MTest()} ]]>).VerifyDiagnostics() Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(Test.MTest)", node1.ToString()) Assert.Equal("MTest", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Function Test.MTest() As System.String", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Function Test.MTest() As System.String", group.Single.ToTestDisplayString()) Dim receiver = DirectCast(argument, MemberAccessExpressionSyntax).Expression typeInfo = model.GetTypeInfo(receiver) Assert.Equal("Test", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(receiver) Assert.Equal("Test", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) End Sub <Fact> Public Sub Attribute_02() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ <System.Diagnostics.DebuggerDisplay("={" + NameOf(MTest) + "()}")> Class Test Shared Sub Main() System.Console.WriteLine(DirectCast(GetType(Test).GetCustomAttributes(GetType(System.Diagnostics.DebuggerDisplayAttribute), False)(0), System.Diagnostics.DebuggerDisplayAttribute).Value) End Sub Function MTest() As String Return "" End Function End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected><![CDATA[ BC30059: Constant expression is required. <System.Diagnostics.DebuggerDisplay("={" + NameOf(MTest) + "()}")> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30451: 'MTest' is not declared. It may be inaccessible due to its protection level. <System.Diagnostics.DebuggerDisplay("={" + NameOf(MTest) + "()}")> ~~~~~ ]]></expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(MTest)", node1.ToString()) Assert.Equal("MTest", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub Attribute_03() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ <System.Diagnostics.DebuggerDisplay("={" + NameOf(.MTest) + "()}")> Class Test Shared Sub Main() System.Console.WriteLine(DirectCast(GetType(Test).GetCustomAttributes(GetType(System.Diagnostics.DebuggerDisplayAttribute), False)(0), System.Diagnostics.DebuggerDisplayAttribute).Value) End Sub Function MTest() As String Return "" End Function End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) AssertTheseDiagnostics(comp, <expected><![CDATA[ BC30059: Constant expression is required. <System.Diagnostics.DebuggerDisplay("={" + NameOf(.MTest) + "()}")> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30157: Leading '.' or '!' can only appear inside a 'With' statement. <System.Diagnostics.DebuggerDisplay("={" + NameOf(.MTest) + "()}")> ~~~~~~ ]]></expected>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(.MTest)", node1.ToString()) Assert.Equal("MTest", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub Attribute_04() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Class Module1 Shared Sub Main() System.Console.WriteLine(DirectCast(GetType(Test).GetCustomAttributes(GetType(System.Diagnostics.DebuggerDisplayAttribute), False)(0), System.Diagnostics.DebuggerDisplayAttribute).Value) End Sub <System.Diagnostics.DebuggerDisplay("={" + NameOf(MTest) + "()}")> Class Test End Class Function MTest() As String Return "" End Function End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ ={MTest()} ]]>).VerifyDiagnostics() Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(MTest)", node1.ToString()) Assert.Equal("MTest", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Function Module1.MTest() As System.String", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Function Module1.MTest() As System.String", group.Single.ToTestDisplayString()) End Sub <Fact> Public Sub Attribute_05() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Class Module1 Shared Sub Main() System.Console.WriteLine(DirectCast(GetType(Test).GetCustomAttributes(GetType(System.Diagnostics.DebuggerDisplayAttribute), False)(0), System.Diagnostics.DebuggerDisplayAttribute).Value) End Sub <System.Diagnostics.DebuggerDisplay("={" + NameOf(MTest) + "()}")> Class Test End Class Property MTest As String End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ ={MTest()} ]]>).VerifyDiagnostics() Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(MTest)", node1.ToString()) Assert.Equal("MTest", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Property Module1.MTest As System.String", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Property Module1.MTest As System.String", group.Single.ToTestDisplayString()) End Sub <Fact> Public Sub Attribute_06() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Class Module1 Shared Sub Main() System.Console.WriteLine(DirectCast(GetType(Test).GetCustomAttributes(GetType(System.Diagnostics.DebuggerDisplayAttribute), False)(0), System.Diagnostics.DebuggerDisplayAttribute).Value) End Sub <System.Diagnostics.DebuggerDisplay("={" + NameOf(MTest) + "()}")> Class Test End Class Dim MTest As String End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ ={MTest()} ]]>).VerifyDiagnostics() Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(MTest)", node1.ToString()) Assert.Equal("MTest", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("Module1.MTest As System.String", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub Attribute_07() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Class Module1 Shared Sub Main() System.Console.WriteLine(DirectCast(GetType(Test).GetCustomAttributes(GetType(System.Diagnostics.DebuggerDisplayAttribute), False)(0), System.Diagnostics.DebuggerDisplayAttribute).Value) End Sub <System.Diagnostics.DebuggerDisplay("={" + NameOf(MTest) + "()}")> Class Test End Class Event MTest As System.Action End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ ={MTest()} ]]>).VerifyDiagnostics() Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(MTest)", node1.ToString()) Assert.Equal("MTest", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Action", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("Event Module1.MTest As System.Action", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub InstanceAndExtension() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() System.Console.WriteLine(NameOf(C2.M1)) End Sub <System.Runtime.CompilerServices.Extension> Public Function M1(this As C2) As Integer Return Nothing End Function End Module Class C2 Sub M1(x as Integer) End Sub End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, {SystemCoreRef}, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ M1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(C2.M1)", node1.ToString()) Assert.Equal("M1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal(2, symbolInfo.CandidateSymbols.Length) Assert.Equal("Sub C2.M1(x As System.Int32)", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Assert.Equal("Function C2.M1() As System.Int32", symbolInfo.CandidateSymbols(1).ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal(2, group.Length) Assert.Equal("Sub C2.M1(x As System.Int32)", group(0).ToTestDisplayString()) Assert.Equal("Function C2.M1() As System.Int32", group(1).ToTestDisplayString()) End Sub <Fact> Public Sub InstanceInShared_01() Dim compilationDef = <compilation> <file name="a.vb"> Class Module1 Shared Sub Main() System.Console.WriteLine(NameOf(F1)) End Sub Public F1 As Integer End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ F1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(F1)", node1.ToString()) Assert.Equal("F1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("Module1.F1 As System.Int32", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub InstanceInShared_02() Dim compilationDef = <compilation> <file name="a.vb"> Class Module1 Shared Sub Main() System.Console.WriteLine(NameOf(F1)) End Sub Event F1 As System.Action End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ F1 ]]>) Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(F1)", node1.ToString()) Assert.Equal("F1", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Equal("System.Action", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(argument) Assert.Equal("Event Module1.F1 As System.Action", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) group = model.GetMemberGroup(argument) Assert.Equal(0, group.Length) End Sub <Fact> Public Sub InstanceInShared_03() Dim compilationDef = <compilation> <file name="a.vb"> Class Module1 Shared Sub Main() System.Console.WriteLine(NameOf(MTest)) End Sub Function MTest() As String Return "" End Function End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ MTest ]]>).VerifyDiagnostics() Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(MTest)", node1.ToString()) Assert.Equal("MTest", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Function Module1.MTest() As System.String", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Function Module1.MTest() As System.String", group.Single.ToTestDisplayString()) End Sub <Fact> Public Sub InstanceInShared_04() Dim compilationDef = <compilation> <file name="a.vb"> Class Module1 Shared Sub Main() System.Console.WriteLine(NameOf(MTest)) End Sub Property MTest As String End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ MTest ]]>).VerifyDiagnostics() Dim tree = comp.SyntaxTrees.First Dim model = comp.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes().Where(Function(n) n.Kind() = SyntaxKind.NameOfExpression).Cast(Of NameOfExpressionSyntax)().First() Dim typeInfo As TypeInfo Dim symbolInfo As SymbolInfo Dim group As ImmutableArray(Of ISymbol) Assert.Equal("NameOf(MTest)", node1.ToString()) Assert.Equal("MTest", model.GetConstantValue(node1).Value) typeInfo = model.GetTypeInfo(node1) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) symbolInfo = model.GetSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) group = model.GetMemberGroup(node1) Assert.True(group.IsEmpty) Dim argument = node1.Argument typeInfo = model.GetTypeInfo(argument) Assert.Null(typeInfo.Type) symbolInfo = model.GetSymbolInfo(argument) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.MemberGroup, symbolInfo.CandidateReason) Assert.Equal("Property Module1.MTest As System.String", symbolInfo.CandidateSymbols.Single.ToTestDisplayString()) group = model.GetMemberGroup(argument) Assert.Equal("Property Module1.MTest As System.String", group.Single.ToTestDisplayString()) End Sub <Fact, WorkItem(543, "https://github.com/dotnet/roslyn")> Public Sub NameOfConstantInInitializer() Dim compilationDef = <compilation> <file name="a.vb"> Class Module1 Const N1 As String = NameOf(N1) Shared Sub Main() Const N2 As String = NameOf(N2) System.Console.WriteLine(N1 &amp; N2) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ N1N2 ]]>).VerifyDiagnostics() End Sub <Fact, WorkItem(564, "https://github.com/dotnet/roslyn/issues/564")> Public Sub NameOfTypeParameterInDefaultValue() Dim compilationDef = <compilation> <file name="a.vb"> Module Program Sub M(Of TP)(Optional name As String = NameOf(TP)) System.Console.WriteLine(name) End Sub Sub Main() M(Of String)() End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:= <![CDATA[ TP ]]>).VerifyDiagnostics() End Sub <Fact, WorkItem(10839, "https://github.com/dotnet/roslyn/issues/10839")> Public Sub NameOfByRefInLambda() Dim compilationDef = <compilation> <file name="a.vb"> Module Program Sub DoSomething(ByRef x As Integer) Dim f = Function() Return NameOf(x) End Function System.Console.WriteLine(f()) End Sub Sub Main() Dim x = 5 DoSomething(x) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:="x").VerifyDiagnostics() End Sub <Fact, WorkItem(10839, "https://github.com/dotnet/roslyn/issues/10839")> Public Sub NameOfByRefInQuery() Dim compilationDef = <compilation> <file name="a.vb"> Imports System.Linq Module Program Sub DoSomething(ByRef x As Integer) Dim f = from y in {1, 2, 3} select nameof(x) System.Console.WriteLine(f.Aggregate("", Function(a, b) a + b)) End Sub Sub Main() Dim x = 5 DoSomething(x) End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, options:=TestOptions.DebugExe, additionalRefs:={LinqAssemblyRef}) CompileAndVerify(comp, expectedOutput:="xxx").VerifyDiagnostics() End Sub <Fact, WorkItem(10839, "https://github.com/dotnet/roslyn/issues/10839")> Public Sub ForbidInstanceQualifiedFromTypeInNestedExpression() Dim compilationDef = <compilation> <file name="a.vb"> Class C Public MyInstance As String Public Shared MyStatic As String Sub M() Dim X As String X = NameOf(C.MyInstance) X = NameOf(C.MyInstance.Length) X = NameOf(C.MyStatic) X = NameOf(C.MyStatic.Length) End Sub End Class Class C(Of T) Public MyInstance As String Public Shared MyStatic As String Sub M() Dim X As String X = NameOf(C(Of Integer).MyInstance) X = NameOf(C(Of Integer).MyInstance.Length) X = NameOf(C(Of Integer).MyStatic) X = NameOf(C(Of Integer).MyStatic.Length) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.DebugDll) AssertTheseDiagnostics(comp, <expected><![CDATA[ BC30469: Reference to a non-shared member requires an object reference. X = NameOf(C.MyInstance.Length) ~~~~~~~~~~~~ BC30469: Reference to a non-shared member requires an object reference. X = NameOf(C(Of Integer).MyInstance.Length) ~~~~~~~~~~~~~~~~~~~~~~~~ ]]></expected>) End Sub End Class End Namespace
OmarTawfik/roslyn
src/Compilers/VisualBasic/Test/Semantic/Semantics/NameOfTests.vb
Visual Basic
apache-2.0
120,175
' Licensed to the .NET Foundation under one or more 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.VisualStudio.LanguageServices.UnitTests.CodeModel Partial Public MustInherit Class AbstractCodeModelObjectTests(Of TCodeModelObject As Class) Protected Class InterfaceData Public Property Name As String Public Property Position As Object = 0 Public Property Bases As Object Public Property Access As EnvDTE.vsCMAccess = EnvDTE.vsCMAccess.vsCMAccessDefault End Class End Class End Namespace
shyamnamboodiripad/roslyn
src/VisualStudio/Core/Test/CodeModel/AbstractCodeModelObjectTests.InterfaceData.vb
Visual Basic
apache-2.0
688
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Shared.Collections Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Shared.Utilities 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.Formatting Friend Class TriviaDataFactory Friend Class TriviaRewriter Inherits VisualBasicSyntaxRewriter Private ReadOnly _node As SyntaxNode Private ReadOnly _spans As SimpleIntervalTree(Of TextSpan) Private ReadOnly _lastToken As SyntaxToken Private ReadOnly _cancellationToken As CancellationToken Private ReadOnly _trailingTriviaMap As Dictionary(Of SyntaxToken, SyntaxTriviaList) Private ReadOnly _leadingTriviaMap As Dictionary(Of SyntaxToken, SyntaxTriviaList) Public Sub New(node As SyntaxNode, spanToFormat As SimpleIntervalTree(Of TextSpan), map As Dictionary(Of ValueTuple(Of SyntaxToken, SyntaxToken), TriviaData), cancellationToken As CancellationToken) Contract.ThrowIfNull(node) Contract.ThrowIfNull(map) _node = node _spans = spanToFormat _lastToken = node.GetLastToken(includeZeroWidth:=True) _cancellationToken = cancellationToken _trailingTriviaMap = New Dictionary(Of SyntaxToken, SyntaxTriviaList)() _leadingTriviaMap = New Dictionary(Of SyntaxToken, SyntaxTriviaList)() PreprocessTriviaListMap(map) End Sub Public Function Transform() As SyntaxNode Return Visit(_node) End Function Private Sub PreprocessTriviaListMap(map As Dictionary(Of ValueTuple(Of SyntaxToken, SyntaxToken), TriviaData)) For Each pair In map _cancellationToken.ThrowIfCancellationRequested() Dim tuple = GetTrailingAndLeadingTrivia(pair) If pair.Key.Item1.Kind <> 0 Then _trailingTriviaMap.Add(pair.Key.Item1, tuple.Item1) End If If pair.Key.Item2.Kind <> 0 Then _leadingTriviaMap.Add(pair.Key.Item2, tuple.Item2) End If Next pair End Sub Private Function GetTrailingAndLeadingTrivia(pair As KeyValuePair(Of ValueTuple(Of SyntaxToken, SyntaxToken), TriviaData)) As ValueTuple(Of SyntaxTriviaList, SyntaxTriviaList) If pair.Key.Item1.Kind = 0 OrElse _lastToken = pair.Key.Item2 Then Return ValueTuple.Create(Of SyntaxTriviaList, SyntaxTriviaList)(SyntaxTriviaList.Empty, GetSyntaxTriviaList(GetTextSpan(pair.Key), pair.Value, _cancellationToken)) End If Dim vbTriviaData = TryCast(pair.Value, TriviaDataWithList(Of SyntaxTrivia)) If vbTriviaData IsNot Nothing Then Dim triviaList = vbTriviaData.GetTriviaList(_cancellationToken) Dim index = GetIndexForEndOfLeadingTrivia(triviaList) Return ValueTuple.Create(SyntaxFactory.TriviaList(CreateTriviaListFromTo(triviaList, 0, index)), SyntaxFactory.TriviaList(CreateTriviaListFromTo(triviaList, index + 1, triviaList.Count - 1))) End If Return ValueTuple.Create(Of SyntaxTriviaList, SyntaxTriviaList)(GetSyntaxTriviaList(GetTextSpan(pair.Key), pair.Value, _cancellationToken), SyntaxTriviaList.Empty) End Function Private Function GetTextSpan(pair As ValueTuple(Of SyntaxToken, SyntaxToken)) As TextSpan If pair.Item1.Kind = 0 Then Return TextSpan.FromBounds(_node.FullSpan.Start, pair.Item2.SpanStart) End If If pair.Item2.Kind = 0 Then Return TextSpan.FromBounds(pair.Item1.Span.End, _node.FullSpan.End) End If Return TextSpan.FromBounds(pair.Item1.Span.End, pair.Item2.SpanStart) End Function Private Function CreateTriviaListFromTo(triviaList As List(Of SyntaxTrivia), startIndex As Integer, endIndex As Integer) As IEnumerable(Of SyntaxTrivia) If startIndex > endIndex Then Return SpecializedCollections.EmptyEnumerable(Of SyntaxTrivia)() End If Dim returnTriviaList = New List(Of SyntaxTrivia)(endIndex - startIndex) For i As Integer = startIndex To endIndex returnTriviaList.Add(triviaList(i)) Next i Return returnTriviaList End Function Private Function GetIndexForEndOfLeadingTrivia(triviaList As List(Of SyntaxTrivia)) As Integer For i As Integer = 0 To triviaList.Count - 1 Dim trivia = triviaList(i) If trivia.Kind = SyntaxKind.EndOfLineTrivia Or trivia.Kind = SyntaxKind.ColonTrivia Then Return i End If Next i Return triviaList.Count - 1 End Function Private Function GetSyntaxTriviaList(textSpan As TextSpan, triviaData As TriviaData, cancellationToken As CancellationToken) As SyntaxTriviaList Dim vbTriviaData = TryCast(triviaData, TriviaDataWithList(Of SyntaxTrivia)) If vbTriviaData IsNot Nothing Then Return SyntaxFactory.TriviaList(vbTriviaData.GetTriviaList(cancellationToken)) End If ' there is no difference between ParseLeading and ParseTrailing for the given text Dim text = triviaData.GetTextChanges(textSpan).Single().NewText Return SyntaxFactory.ParseLeadingTrivia(text) End Function Public Overrides Function Visit(node As SyntaxNode) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() If node Is Nothing OrElse Not Me._spans.IntersectsWith(node.FullSpan) Then Return node End If Return MyBase.Visit(node) End Function Public Overrides Function VisitToken(token As SyntaxToken) As SyntaxToken _cancellationToken.ThrowIfCancellationRequested() If Not Me._spans.IntersectsWith(token.FullSpan) Then Return token End If Dim hasChanges = False ' check whether we have trivia info belongs to this token Dim leadingTrivia = token.LeadingTrivia Dim trailingTrivia = token.TrailingTrivia If _trailingTriviaMap.ContainsKey(token) Then ' okay, we have this situation ' token|trivia trailingTrivia = _trailingTriviaMap(token) hasChanges = True End If If _leadingTriviaMap.ContainsKey(token) Then ' okay, we have this situation ' trivia|token leadingTrivia = _leadingTriviaMap(token) hasChanges = True End If If hasChanges Then Return CreateNewToken(leadingTrivia, token, trailingTrivia) End If ' we have no trivia belongs to this one Return token End Function Private Function CreateNewToken(leadingTrivia As SyntaxTriviaList, token As SyntaxToken, trailingTrivia As SyntaxTriviaList) As SyntaxToken Return token.With(leadingTrivia, trailingTrivia) End Function End Class End Class End Namespace
hanu412/roslyn
src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.TriviaRewriter.vb
Visual Basic
apache-2.0
8,440
Imports System.Windows.Controls.Primitives Public Class MainWindowContext Public Property Spielerliste As ICollection(Of SpielerInfo) Public Property KlassementListe As IEnumerable(Of KlassementName) End Class Public Class MeineCommands Public Shared ReadOnly Property FremdSpielerLöschen As RoutedUICommand = New RoutedUICommand("Löscht ausschließlich Fremdspieler", "Löschen", GetType(MeineCommands)) End Class Class MainWindow Private ReadOnly _KlassementListe As IEnumerable(Of String) Private ReadOnly _SpeichernAction As Action Private ReadOnly _SpielerListe As ICollection(Of SpielerInfo) Public Sub New(spielerListe As ICollection(Of SpielerInfo), klassementListe As IEnumerable(Of String), speichernAction As Action) _SpielerListe = spielerListe _KlassementListe = klassementListe _SpeichernAction = speichernAction Dim klassements = (From x In klassementListe Select New KlassementName With {.Name = x}).ToList DataContext = New MainWindowContext With { .KlassementListe = klassements, .Spielerliste = spielerListe } InitializeComponent() End Sub Private Sub MainWindow_Closing(sender As Object, e As ComponentModel.CancelEventArgs) Handles Me.Closing SpielerGrid.CommitEdit(DataGridEditingUnit.Row, True) Select Case MessageBox.Show("Dieses Programm wird jetzt geschlossen. Sollen Änderungen gespeichert werden?" _ , "Speichern und schließen?", MessageBoxButton.YesNoCancel, MessageBoxImage.Question) Case MessageBoxResult.Cancel : e.Cancel = True Case MessageBoxResult.Yes : _SpeichernAction() End Select End Sub Private Sub CommandBinding_CanExecute(sender As Object, e As CanExecuteRoutedEventArgs) e.CanExecute = True End Sub Private Sub CommandFremdSpieler_CanExecute(sender As Object, e As CanExecuteRoutedEventArgs) e.CanExecute = SpielerGrid?.SelectedItem IsNot Nothing AndAlso DirectCast(SpielerGrid.SelectedItem, SpielerInfo).Fremd End Sub Private Sub CommandNew_Executed(sender As Object, e As ExecutedRoutedEventArgs) Dim neuerTTR As Integer = 0 If SpielerGrid.SelectedItem IsNot Nothing Then neuerTTR = DirectCast(SpielerGrid.SelectedItem, SpielerInfo).TTR - 1 End If Dim dialog As New FremdSpielerDialog(_KlassementListe, New SpielerInfo With {.TTR = neuerTTR}) If dialog.ShowDialog() Then SpielerGrid.BeginInit() _SpielerListe.Add(dialog.EditierterSpieler) SpielerGrid.EndInit() End If End Sub Private Sub CommandDelete_Executed(sender As Object, e As ExecutedRoutedEventArgs) Dim aktuellerSpieler = DirectCast(SpielerGrid.SelectedItem, SpielerInfo) If MessageBox.Show("Wollen Sie wirklich diesen Spieler entfernen?", "Löschen?", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) = MessageBoxResult.OK Then _SpielerListe.Remove(aktuellerSpieler) End If End Sub Private Sub CommandReplace_Executed(sender As Object, e As ExecutedRoutedEventArgs) Dim aktuellerSpieler = DirectCast(SpielerGrid.SelectedItem, SpielerInfo) Dim dialog As New FremdSpielerDialog(_KlassementListe, New SpielerInfo(aktuellerSpieler)) If dialog.ShowDialog() Then SpielerGrid.BeginInit() _SpielerListe.Remove(aktuellerSpieler) _SpielerListe.Add(dialog.EditierterSpieler) SpielerGrid.EndInit() End If End Sub Private Sub Save_Click(sender As Object, e As RoutedEventArgs) SpielerGrid.CommitEdit(DataGridEditingUnit.Row, True) _SpeichernAction() End Sub Shared Function FindVisualParent(Of T As UIElement)(element As UIElement) As T Dim parent = element While parent IsNot Nothing Dim correctlyTyped = TryCast(parent, T) If correctlyTyped IsNot Nothing Then Return correctlyTyped End If parent = TryCast(VisualTreeHelper.GetParent(parent), UIElement) End While Return Nothing End Function ' Click-Through Verhalten adaptiert von ' http://wpf.codeplex.com/wikipage?title=Single-Click%20Editing&referringTitle=Tips%20%26%20Tricks&ProjectName=wpf Public Sub DataGridCell_PreviewMouseLeftButtonDown(sender As Object, e As MouseButtonEventArgs) Dim cell = DirectCast(sender, DataGridCell) If cell Is Nothing OrElse cell.IsEditing OrElse cell.IsReadOnly Then Return If Not cell.IsFocused Then cell.Focus() End If Dim DataGrid = FindVisualParent(Of DataGrid)(cell) If DataGrid Is Nothing Then Return If DataGrid.SelectionUnit <> DataGridSelectionUnit.FullRow Then If Not cell.IsSelected Then cell.IsSelected = True End If Else Dim row = FindVisualParent(Of DataGridRow)(cell) If (row IsNot Nothing AndAlso Not row.IsSelected) Then row.IsSelected = True End If End If End Sub Private Sub SuchFilter(sender As Object, e As FilterEventArgs) e.Accepted = True If Suche Is Nothing Then Return Dim KlassementButtons = FindVisualChildren(Of ToggleButton)(KlassementFilterListe) Dim KlassementFilterAktiv = Aggregate x In KlassementButtons Where x.IsChecked Into Any() With DirectCast(e.Item, SpielerInfo) If Unbezahlt.IsChecked AndAlso .Bezahlt Then e.Accepted = False Return End If If NichtAnwesend.IsChecked AndAlso .Anwesend Then e.Accepted = False Return End If If KlassementFilterAktiv Then e.Accepted = False For Each tb In FindVisualChildren(Of ToggleButton)(KlassementFilterListe) If tb.IsChecked AndAlso tb.Content.ToString = .Klassement Then e.Accepted = True End If Next If Not e.Accepted Then Return End If If Not e.Accepted Then Return e.Accepted = True If String.IsNullOrEmpty(Suche.Text) Then Return Dim SuchText = Suche.Text.ToLower If .Vorname.ToLower.Contains(SuchText) Then Return If .Nachname.ToLower.Contains(SuchText) Then Return If .Verein.ToLower.Contains(SuchText) Then Return If .Klassement.ToLower.Contains(SuchText) Then Return End With e.Accepted = False End Sub Shared Function FindVisualChildren(Of T As DependencyObject)(parent As DependencyObject) As IEnumerable(Of T) Dim Children As New List(Of T) If TypeOf parent Is T Then Children.Add(DirectCast(parent, T)) Return Children End If For i = 0 To VisualTreeHelper.GetChildrenCount(parent) - 1 Dim child = VisualTreeHelper.GetChild(parent, i) Children.AddRange(FindVisualChildren(Of T)(child)) Next Return Children End Function Private Sub Button_Click(sender As Object, e As RoutedEventArgs) Dim View = DirectCast(FindResource("FilteredSpielerListe"), CollectionViewSource) For Each column In SpielerGrid.Columns column.SortDirection = Nothing Next SpielerGrid.CommitEdit(DataGridEditingUnit.Row, True) With View.SortDescriptions .Clear() .Add(New System.ComponentModel.SortDescription With {.PropertyName = "TTR", .Direction = ComponentModel.ListSortDirection.Descending}) .Add(New System.ComponentModel.SortDescription With {.PropertyName = "TTRMatchCount", .Direction = ComponentModel.ListSortDirection.Descending}) End With End Sub Private Sub UpdateFilter(sender As Object, e As RoutedEventArgs) Dim View = DirectCast(FindResource("FilteredSpielerListe"), CollectionViewSource) SpielerGrid.CommitEdit(DataGridEditingUnit.Row, True) View.View.Refresh() End Sub Private Sub Drucken_Click(sender As Object, e As RoutedEventArgs) With New PrintDialog If .ShowDialog Then Dim CollectionSource = DirectCast(FindResource("FilteredSpielerListe"), CollectionViewSource) Dim l As New List(Of SpielerInfo) For Each item As SpielerInfo In CollectionSource.View l.Add(item) Next Dim doc As New FixedDocument For Each page In New UserControlPaginator(l, New Size(.PrintableAreaWidth, .PrintableAreaHeight)).ErzeugePageContent doc.Pages.Add(page) Next .PrintDocument(doc.DocumentPaginator, "Spielerliste - Aktuelle Sicht") End If End With End Sub End Class Class StringIsEmptyConverter Implements IValueConverter Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As Globalization.CultureInfo) As Object Implements IValueConverter.Convert If String.IsNullOrEmpty(DirectCast(value, String)) Then Return Visibility.Visible Else Return Visibility.Hidden End If End Function Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack Throw New NotImplementedException End Function End Class Public Class KlassementListe Inherits ObjectModel.ObservableCollection(Of KlassementName) End Class Public Class KlassementName Property Name As String End Class Public Class GeschlechtKonverter Implements IValueConverter Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As Globalization.CultureInfo) As Object Implements IValueConverter.Convert Dim geschlecht = DirectCast(value, Integer) Select Case geschlecht Case 0 : Return "w" Case 1 : Return "m" End Select Throw New ArgumentException("Unbekanntes geschlecht: " & geschlecht) End Function Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack Throw New NotImplementedException End Function End Class
GoppeltM/PPC-Manager
Trunk/PPC Manager/StartlistenEditor/View/MainWindow.xaml.vb
Visual Basic
mit
10,828
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.18408 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My.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("PA_1_W_Weinert.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
winny-/CPS-240
Assignments/PA 1 W Weinert/PA 1 W Weinert/My Project/Resources.Designer.vb
Visual Basic
mit
2,723
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.1.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(sender As Global.System.Object, e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class End Namespace Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.OracleHelper.My.MySettings Get Return Global.OracleHelper.My.MySettings.Default End Get End Property End Module End Namespace
Micmaz/DTIControls
DBHelpers/OracleHelper/My Project/Settings.Designer.vb
Visual Basic
mit
2,902
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "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.ProyectoVB001.My.MySettings Get Return Global.ProyectoVB001.My.MySettings.Default End Get End Property End Module End Namespace
Vbnet2016001/proy001
ProyectoVB001/ProyectoVB001/My Project/Settings.Designer.vb
Visual Basic
mit
2,932
Imports System.Data Partial Class PAS_fOrdenes_Compras 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 Dim lcOrdenCompra As String = cusAplicacion.goFormatos.pcCondicionPrincipal lcOrdenCompra = lcOrdenCompra.Substring(lcOrdenCompra.IndexOf("'"), (lcOrdenCompra.LastIndexOf("'") - lcOrdenCompra.IndexOf("'")) + 1) Try Dim loComandoSeleccionar1 As New StringBuilder() loComandoSeleccionar1.AppendLine(" SELECT Ordenes_Compras.Usu_Cre ") loComandoSeleccionar1.AppendLine("FROM Ordenes_Compras") loComandoSeleccionar1.AppendLine(" JOIN Renglones_OCompras") loComandoSeleccionar1.AppendLine(" ON Ordenes_Compras.Documento = Renglones_OCompras.Documento") loComandoSeleccionar1.AppendLine(" JOIN Proveedores") loComandoSeleccionar1.AppendLine(" ON Ordenes_Compras.Cod_Pro = Proveedores.Cod_Pro") loComandoSeleccionar1.AppendLine(" JOIN Formas_Pagos") loComandoSeleccionar1.AppendLine(" ON Ordenes_Compras.Cod_For = Formas_Pagos.Cod_For") loComandoSeleccionar1.AppendLine(" JOIN Articulos ") loComandoSeleccionar1.AppendLine(" ON Articulos.Cod_Art = Renglones_OCompras.Cod_Art") loComandoSeleccionar1.AppendLine("WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal) Dim loServicios1 As New cusDatos.goDatos Dim laDatosReporte1 As DataSet = loServicios1.mObtenerTodosSinEsquema(loComandoSeleccionar1.ToString, "usuarioCreador") Dim aString As String = laDatosReporte1.Tables(0).Rows(0).Item(0) aString = Trim(aString) Dim loComandoSeleccionar2 As New StringBuilder() loComandoSeleccionar2.AppendLine(" SELECT Nom_Usu ") loComandoSeleccionar2.AppendLine(" FROM Usuarios ") loComandoSeleccionar2.AppendLine(" WHERE Cod_Usu = '" & aString & "'") loComandoSeleccionar2.AppendLine(" AND Cod_Cli = " & goServicios.mObtenerCampoFormatoSQL(goCliente.pcCodigo)) Dim loServicios2 As New cusDatos.goDatos goDatos.pcNombreAplicativoExterno = "Framework" Dim laDatosReporte2 As DataSet = loServicios2.mObtenerTodosSinEsquema(loComandoSeleccionar2.ToString, "nombreUsuarioCreador") Dim aString2 As String = laDatosReporte2.Tables("nombreUsuarioCreador").Rows(0).Item(0) aString2 = RTrim(aString2) Dim loComandoSeleccionar3 As New StringBuilder() loComandoSeleccionar3.AppendLine("SELECT TOP 1 Cod_Usu ") loComandoSeleccionar3.AppendLine("FROM Auditorias") loComandoSeleccionar3.AppendLine("WHERE Documento = " & lcOrdenCompra) loComandoSeleccionar3.AppendLine(" AND Tabla = 'Ordenes_Compras'") loComandoSeleccionar3.AppendLine(" AND Accion = 'Confirmar'") loComandoSeleccionar3.AppendLine("ORDER BY Registro DESC ") Dim loServicios3 As New cusDatos.goDatos Dim laDatosReporte3 As DataSet = loServicios3.mObtenerTodosSinEsquema(loComandoSeleccionar3.ToString, "usuarioConfirma") Dim aString3 As String = laDatosReporte3.Tables(0).Rows(0).Item(0) aString3 = Trim(aString3) Dim loComandoSeleccionar4 As New StringBuilder() loComandoSeleccionar4.AppendLine(" SELECT Nom_Usu ") loComandoSeleccionar4.AppendLine(" FROM Usuarios ") loComandoSeleccionar4.AppendLine(" WHERE Cod_Usu = '" & aString3 & "'") loComandoSeleccionar4.AppendLine(" AND Cod_Cli = " & goServicios.mObtenerCampoFormatoSQL(goCliente.pcCodigo)) Dim loServicios4 As New cusDatos.goDatos goDatos.pcNombreAplicativoExterno = "Framework" Dim laDatosReporte4 As DataSet = loServicios4.mObtenerTodosSinEsquema(loComandoSeleccionar4.ToString, "nombreUsuarioConfirma") Dim aString4 As String = laDatosReporte4.Tables("nombreUsuarioConfirma").Rows(0).Item(0) aString4 = RTrim(aString4) Dim loComandoSeleccionar5 As New StringBuilder() loComandoSeleccionar5.AppendLine(" SELECT Ordenes_Compras.Cod_Pro, ") loComandoSeleccionar5.AppendLine(" (CASE WHEN (Proveedores.Generico = 0 AND Ordenes_Compras.Nom_Pro = '') THEN Proveedores.Nom_Pro ELSE ") loComandoSeleccionar5.AppendLine(" (CASE WHEN (Ordenes_Compras.Nom_Pro = '') THEN Proveedores.Nom_Pro ELSE Ordenes_Compras.Nom_Pro END) END) AS Nom_Pro, ") loComandoSeleccionar5.AppendLine(" (CASE WHEN (Proveedores.Generico = 0 AND Ordenes_Compras.Nom_Pro = '') THEN Proveedores.Rif ELSE ") loComandoSeleccionar5.AppendLine(" (CASE WHEN (Ordenes_Compras.Rif = '') THEN Proveedores.Rif ELSE Ordenes_Compras.Rif END) END) AS Rif, ") loComandoSeleccionar5.AppendLine(" Proveedores.Nit, ") loComandoSeleccionar5.AppendLine(" (CASE WHEN (Proveedores.Generico = 0 AND Ordenes_Compras.Nom_Pro = '') THEN SUBSTRING(Proveedores.Dir_Fis,1, 200) ELSE ") loComandoSeleccionar5.AppendLine(" (CASE WHEN (SUBSTRING(Ordenes_Compras.Dir_Fis,1, 200) = '') THEN SUBSTRING(Proveedores.Dir_Fis,1, 200) ELSE SUBSTRING(Ordenes_Compras.Dir_Fis,1, 200) END) END) AS Dir_Fis, ") loComandoSeleccionar5.AppendLine(" (CASE WHEN (Proveedores.Generico = 0 AND Ordenes_Compras.Nom_Pro = '') THEN Proveedores.Telefonos ELSE ") loComandoSeleccionar5.AppendLine(" (CASE WHEN (Ordenes_Compras.Telefonos = '') THEN Proveedores.Telefonos ELSE Ordenes_Compras.Telefonos END) END) AS Telefonos, ") loComandoSeleccionar5.AppendLine(" Proveedores.Correo, ") loComandoSeleccionar5.AppendLine(" Ordenes_Compras.Documento, ") loComandoSeleccionar5.AppendLine(" Ordenes_Compras.Por_Des1 AS Por_Des1_Enc, ") loComandoSeleccionar5.AppendLine(" Ordenes_Compras.Mon_Des1 AS Mon_Des1_Enc, ") loComandoSeleccionar5.AppendLine(" Ordenes_Compras.Por_Rec1 AS Por_Rec1_Enc, ") loComandoSeleccionar5.AppendLine(" Ordenes_Compras.Mon_Rec1 AS Mon_Rec1_Enc, ") loComandoSeleccionar5.AppendLine(" Renglones_OCompras.Cod_Uni, ") loComandoSeleccionar5.AppendLine(" Ordenes_Compras.Fec_Ini, ") loComandoSeleccionar5.AppendLine(" Ordenes_Compras.Fec_Fin, ") loComandoSeleccionar5.AppendLine(" Ordenes_Compras.Mon_Bru, ") loComandoSeleccionar5.AppendLine(" Ordenes_Compras.Por_Imp1, ") loComandoSeleccionar5.AppendLine(" Ordenes_Compras.Dis_Imp, ") loComandoSeleccionar5.AppendLine(" Ordenes_Compras.Mon_Imp1, ") loComandoSeleccionar5.AppendLine(" Ordenes_Compras.Mon_Net, ") loComandoSeleccionar5.AppendLine(" Ordenes_Compras.Comentario, ") loComandoSeleccionar5.AppendLine(" Ordenes_Compras.Status,") loComandoSeleccionar5.AppendLine(" '" & aString2 & "' AS Usuario_Crea,") loComandoSeleccionar5.AppendLine(" '" & aString4 & "' AS Usuario_Confirma,") loComandoSeleccionar5.AppendLine(" Formas_Pagos.Nom_For, ") loComandoSeleccionar5.AppendLine(" Ordenes_Compras.Cod_Ven, ") loComandoSeleccionar5.AppendLine(" Renglones_OCompras.Cod_Art, ") loComandoSeleccionar5.AppendLine(" Articulos.Nom_Art AS Nom_Art, ") loComandoSeleccionar5.AppendLine(" Articulos.Generico AS Generico,") loComandoSeleccionar5.AppendLine(" Renglones_OCompras.Notas AS Notas,") loComandoSeleccionar5.AppendLine(" Renglones_OCompras.Can_Art1, ") loComandoSeleccionar5.AppendLine(" Renglones_OCompras.Precio1 As Precio1, ") loComandoSeleccionar5.AppendLine(" Renglones_OCompras.Mon_Net As Neto, ") loComandoSeleccionar5.AppendLine(" Renglones_OCompras.Doc_Ori, ") loComandoSeleccionar5.AppendLine(" Ordenes_Compras.Registro As Fec_Cre, ") loComandoSeleccionar5.AppendLine(" Ordenes_Compras.Fec_Aut1 As Fec_Aut ") loComandoSeleccionar5.AppendLine("FROM Ordenes_Compras") loComandoSeleccionar5.AppendLine(" JOIN Renglones_OCompras") loComandoSeleccionar5.AppendLine(" ON Ordenes_Compras.Documento = Renglones_OCompras.Documento") loComandoSeleccionar5.AppendLine(" JOIN Proveedores") loComandoSeleccionar5.AppendLine(" ON Ordenes_Compras.Cod_Pro = Proveedores.Cod_Pro") loComandoSeleccionar5.AppendLine(" JOIN Formas_Pagos") loComandoSeleccionar5.AppendLine(" ON Ordenes_Compras.Cod_For = Formas_Pagos.Cod_For") loComandoSeleccionar5.AppendLine(" JOIN Articulos ") loComandoSeleccionar5.AppendLine(" ON Articulos.Cod_Art = Renglones_OCompras.Cod_Art") loComandoSeleccionar5.AppendLine("WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal) 'Me.mEscribirConsulta(loComandoSeleccionar5.ToString()) Dim loServicios5 As New cusDatos.goDatos Dim laDatosReporte5 As DataSet = loServicios5.mObtenerTodosSinEsquema(loComandoSeleccionar5.ToString, "curReportes") Dim lcXml As String = "<impuesto></impuesto>" Dim lcPorcentajesImpueto As String Dim loImpuestos As New System.Xml.XmlDocument() lcPorcentajesImpueto = "(" 'Recorre cada renglon de la tabla For lnNumeroFila As Integer = 0 To laDatosReporte5.Tables(0).Rows.Count - 1 lcXml = laDatosReporte5.Tables(0).Rows(lnNumeroFila).Item("dis_imp") If String.IsNullOrEmpty(lcXml.Trim()) Then Continue For End If loImpuestos.LoadXml(lcXml) 'En cada renglón lee el contenido de la distribució de impuestos For Each loImpuesto As System.Xml.XmlNode In loImpuestos.SelectNodes("impuestos/impuesto") If lnNumeroFila = laDatosReporte5.Tables(0).Rows.Count - 1 Then If CDec(loImpuesto.SelectSingleNode("porcentaje").InnerText) <> 0 Then lcPorcentajesImpueto = lcPorcentajesImpueto & ", " & CDec(loImpuesto.SelectSingleNode("porcentaje").InnerText) & "%" End If End If Next loImpuesto Next lnNumeroFila lcPorcentajesImpueto = lcPorcentajesImpueto & ")" lcPorcentajesImpueto = lcPorcentajesImpueto.Replace("(,", "(") '--------------------------------------------------' ' Carga la imagen del logo en cusReportes ' '--------------------------------------------------' Me.mCargarLogoEmpresa(laDatosReporte5.Tables(0), "LogoEmpresa") '------------------------------------------------------------------------------------------------------- ' Verificando si el select (tabla nº0) trae registros '------------------------------------------------------------------------------------------------------- If (laDatosReporte5.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_fOrdenes_Compras", laDatosReporte5) lcPorcentajesImpueto = lcPorcentajesImpueto.Replace(".", ",") CType(loObjetoReporte.ReportDefinition.ReportObjects("Text25"), CrystalDecisions.CrystalReports.Engine.TextObject).Text = lcPorcentajesImpueto.ToString Me.mTraducirReporte(loObjetoReporte) Me.mFormatearCamposReporte(loObjetoReporte) Me.crvPAS_fOrdenes_Compras.ReportSource = loObjetoReporte Catch loExcepcion As Exception Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _ "No se pudo Completar el Proceso: " & loExcepcion.Message, _ vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _ "auto", _ "auto") End Try End Sub Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload Try loObjetoReporte.Close() Catch loExcepcion As Exception End Try End Sub End Class '-------------------------------------------------------------------------------------------' ' Fin del codigo '-------------------------------------------------------------------------------------------' ' JJD: 08/11/08: Programacion inicial '-------------------------------------------------------------------------------------------' ' CMS: 10/09/09: Se ajusto el nombre del articulo para los casos de aquellos articulos gen. '-------------------------------------------------------------------------------------------' ' JJD: 09/01/10: Se cambio para que leyera datos de genericos de la Cotizacion cuando aplique '-------------------------------------------------------------------------------------------' ' CMS: 17/03/10: Se aplicaron los metodos carga de imagen y validacion de registro cero '-------------------------------------------------------------------------------------------' ' MAT: 02/09/11: Adición de Comentario en Renglones '-------------------------------------------------------------------------------------------'
kodeitsolutions/ef-reports
PAS_fOrdenes_Compras.aspx.vb
Visual Basic
mit
14,354
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "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.CheatGenerator.My.MySettings Get Return Global.CheatGenerator.My.MySettings.Default End Get End Property End Module End Namespace
evandixon/Sky-Editor
CheatGenerator/My Project/Settings.Designer.vb
Visual Basic
mit
3,007
Imports System.Xml Public Class Persona Private _nombre As String Public Property Nombre() As String Get Return _nombre End Get Set(ByVal value As String) _nombre = value End Set End Property Private _apellido As String Public Property Apellido() As String Get Return _apellido End Get Set(ByVal value As String) _apellido = value End Set End Property Private _direccion As String Public Property Direccion() As String Get Return _direccion End Get Set(ByVal value As String) _direccion = value End Set End Property Private _telefono As String Public Property Telefono() As String Get Return _telefono End Get Set(ByVal value As String) _telefono = value End Set End Property Public Sub New() End Sub Public Sub New(nombre As String, apellido As String, telefono As String, direccion As String) Me.Nombre = nombre Me.Apellido = apellido Me.Telefono = telefono Me.Direccion = direccion End Sub Public Overridable Function ValidarDatos() Return False End Function End Class
ProgrammersCats/Proyecto1P
Module/Module/Persona.vb
Visual Basic
mit
1,319
Imports System.Runtime.InteropServices Imports System.Drawing Imports ESRI.ArcGIS.Framework Imports ESRI.ArcGIS.ArcMapUI Imports System.Windows.Forms Imports ESRI.ArcGIS.Editor Imports ESRI.ArcGIS.EditorExt Imports ESRI.ArcGIS.esriSystem Imports ESRI.ArcGIS.Geodatabase Imports ESRI.ArcGIS.Display Imports ESRI.ArcGIS.Geometry '** 'Nom de la composante : cmdAdoucir.vb ' '''<summary> ''' Commande qui permet d'adoucir les lignes et les limites des polygones pour les éléments sélectionnés selon une distance minimum. '''</summary> ''' '''<remarks> '''Ce traitement est utilisable en mode interactif à l'aide de ses interfaces graphiques et doit être utilisé dans ArcMap (ArcGisESRI). ''' '''Auteur : Michel Pothier '''Date : 18 septembre 2017 '''</remarks> ''' Public Class cmdAdoucir Inherits ESRI.ArcGIS.Desktop.AddIns.Button Dim gpApp As IApplication = Nothing 'Interface ESRI contenant l'application ArcMap Dim gpMxDoc As IMxDocument = Nothing 'Interface ESRI contenant un document ArcMap Public Sub New() Try 'Vérifier si l'application est définie If Not Hook Is Nothing Then 'Définir l'application gpApp = CType(Hook, IApplication) 'Vérifier si l'application est ArcMap If TypeOf Hook Is IMxApplication Then 'Rendre active la commande Enabled = True 'Définir le document gpMxDoc = CType(gpApp.Document, IMxDocument) Else 'Rendre désactive la commande Enabled = False End If End If Catch ex As Exception 'Message d'erreur MsgBox(ex.ToString) End Try End Sub Protected Overrides Sub OnClick() 'Déclarer les variables de travail Dim pMouseCursor As IMouseCursor = Nothing 'Interface qui permet de changer l'image du curseur Dim pTrackCancel As ITrackCancel = Nothing 'Interface qui permet d'annuler la sélection avec la touche ESC. Dim dDateDebut As Date = Nothing 'Date de début du traitement. Dim dDateFin As Date = Nothing 'Date de fin du traitement. Dim dTempsTraitement As TimeSpan = Nothing 'Temps d'exécution du traitement. Dim iNbELem As Integer = 0 'Contient le nombre d'éléments traités. Try 'Changer le curseur en Sablier pour montrer qu'une tâche est en cours pMouseCursor = New MouseCursorClass pMouseCursor.SetCursor(2) 'Si la référence spatiale est projeter If TypeOf (m_MxDocument.FocusMap.SpatialReference) Is IProjectedCoordinateSystem Then 'Définir la date de début dDateDebut = System.DateTime.Now 'Permettre d'annuler la sélection avec la touche ESC pTrackCancel = New CancelTracker pTrackCancel.CancelOnKeyPress = True pTrackCancel.CancelOnClick = False 'Permettre l'affichage de la barre de progression iNbELem = m_MxDocument.FocusMap.SelectionCount m_Application.StatusBar.ProgressBar.Position = 0 m_Application.StatusBar.ShowProgressBar("Adoucir les lignes et les limites des polygones ...", 0, iNbELem, 1, True) pTrackCancel.Progressor = m_Application.StatusBar.ProgressBar 'Afficher le message de début du traitement m_MenuGeneralisation.tabEdition.SelectTab(2) m_MenuGeneralisation.rtbMessages.Text = "Adoucir les lignes et les limites des polygones ... " & vbCrLf & vbCrLf m_MenuGeneralisation.rtbMessages.Text = m_MenuGeneralisation.rtbMessages.Text & "Début du traitement : " & dDateDebut.ToString & vbCrLf m_MenuGeneralisation.rtbMessages.Text = m_MenuGeneralisation.rtbMessages.Text & "Précision : " & m_Precision.ToString & vbCrLf m_MenuGeneralisation.rtbMessages.Text = m_MenuGeneralisation.rtbMessages.Text & "Distance latérale : " & m_DistanceLaterale.ToString & vbCrLf m_MenuGeneralisation.rtbMessages.Text = m_MenuGeneralisation.rtbMessages.Text & "Distance minimale entre deux sommets : " & m_DistanceDensifier.ToString & vbCrLf 'Adoucie les lignes et les limites des polygones pour les éléments sélectionnés modGeneralisation.Adoucir(m_Precision, m_DistanceLaterale, m_DistanceDensifier, pTrackCancel) 'Définir la date de fin dDateFin = System.DateTime.Now 'Afficher le message de fin du traitement m_MenuGeneralisation.rtbMessages.Text = m_MenuGeneralisation.rtbMessages.Text & "Fin du traitement : " & dDateFin.ToString & vbCrLf & vbCrLf 'Définir le temp de traitement dTempsTraitement = dDateFin.Subtract(dDateDebut).Add(New TimeSpan(5000000)) 'Afficher le message de temps du traitement m_MenuGeneralisation.rtbMessages.Text = m_MenuGeneralisation.rtbMessages.Text & "Temps de traitement : " & dTempsTraitement.ToString.Substring(0, 8) & vbCrLf 'Afficher le nombre d'éléments m_MenuGeneralisation.rtbMessages.Text = m_MenuGeneralisation.rtbMessages.Text & "Nombre d'éléments traités : " & iNbELem.ToString & vbCrLf 'Si la référence spatiale est géographique Else 'Afficher le nombre d'erreurs m_MenuGeneralisation.tabEdition.SelectTab(2) m_MenuGeneralisation.rtbMessages.Text = "ERREUR : La référence spatiale ne doit pas être géographique!" End If Catch ex As Exception 'Message d'erreur MsgBox(ex.ToString) Finally 'Cacher la barre de progression pTrackCancel.Progressor.Hide() 'Vider la mémoire pMouseCursor = Nothing pTrackCancel = Nothing End Try End Sub Protected Overrides Sub OnUpdate() 'Déclarer les variables Dim pEditor As IEditor = Nothing 'Interface ESRI pour effectuer l'édition des éléments. Try 'Définir la valeur par défaut Enabled = False 'Interface pour vérifer si on est en mode édition pEditor = CType(m_Application.FindExtensionByName("ESRI Object Editor"), IEditor) 'Vérifier si au moins un élément est sélectionné et si on est en mode édition If gpMxDoc.FocusMap.SelectionCount > 0 And pEditor.EditState = esriEditState.esriStateEditing And m_MenuGeneralisation IsNot Nothing Then Enabled = True End If Catch ex As Exception 'Message d'erreur MsgBox(ex.ToString) Finally 'Vider la mémoire pEditor = Nothing End Try End Sub End Class
MichelPothier/GeneralisationCartographique
BarreGeneralisation/vbnet/cmdAdoucir.vb
Visual Basic
mit
7,081
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class FormColors_Category 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.lbCodeDtl = New System.Windows.Forms.Label() Me.lbCode = New System.Windows.Forms.Label() Me.txtnama = New System.Windows.Forms.TextBox() Me.txtkode = New System.Windows.Forms.TextBox() Me.DataGridView1 = New System.Windows.Forms.DataGridView() Me.Label3 = New System.Windows.Forms.Label() Me.MenuStrip1 = New System.Windows.Forms.MenuStrip() Me.SaveToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).BeginInit() Me.MenuStrip1.SuspendLayout() Me.SuspendLayout() ' 'lbCodeDtl ' Me.lbCodeDtl.AutoSize = True Me.lbCodeDtl.Location = New System.Drawing.Point(12, 72) Me.lbCodeDtl.Name = "lbCodeDtl" Me.lbCodeDtl.Size = New System.Drawing.Size(16, 13) Me.lbCodeDtl.TabIndex = 97 Me.lbCodeDtl.Text = "..." ' 'lbCode ' Me.lbCode.AutoSize = True Me.lbCode.Location = New System.Drawing.Point(12, 46) Me.lbCode.Name = "lbCode" Me.lbCode.Size = New System.Drawing.Size(16, 13) Me.lbCode.TabIndex = 96 Me.lbCode.Text = "..." ' 'txtnama ' Me.txtnama.Location = New System.Drawing.Point(92, 69) Me.txtnama.Name = "txtnama" Me.txtnama.Size = New System.Drawing.Size(184, 20) Me.txtnama.TabIndex = 1 ' 'txtkode ' Me.txtkode.Enabled = False Me.txtkode.Location = New System.Drawing.Point(92, 43) Me.txtkode.Name = "txtkode" Me.txtkode.Size = New System.Drawing.Size(184, 20) Me.txtkode.TabIndex = 0 Me.txtkode.TabStop = False ' 'DataGridView1 ' Me.DataGridView1.AllowUserToAddRows = False Me.DataGridView1.AllowUserToDeleteRows = False Me.DataGridView1.AllowUserToOrderColumns = True Me.DataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize Me.DataGridView1.Location = New System.Drawing.Point(12, 123) Me.DataGridView1.Name = "DataGridView1" Me.DataGridView1.ReadOnly = True Me.DataGridView1.Size = New System.Drawing.Size(355, 196) Me.DataGridView1.TabIndex = 98 ' 'Label3 ' Me.Label3.AutoSize = True Me.Label3.Font = New System.Drawing.Font("Microsoft Sans Serif", 36.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Label3.Location = New System.Drawing.Point(338, 15) Me.Label3.Name = "Label3" Me.Label3.Size = New System.Drawing.Size(126, 55) Me.Label3.TabIndex = 99 Me.Label3.Text = "Tittle" Me.Label3.Visible = False ' 'MenuStrip1 ' Me.MenuStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.SaveToolStripMenuItem}) Me.MenuStrip1.Location = New System.Drawing.Point(0, 0) Me.MenuStrip1.Name = "MenuStrip1" Me.MenuStrip1.Size = New System.Drawing.Size(378, 24) Me.MenuStrip1.TabIndex = 100 Me.MenuStrip1.Text = "MenuStrip1" ' 'SaveToolStripMenuItem ' Me.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem" Me.SaveToolStripMenuItem.Size = New System.Drawing.Size(43, 20) Me.SaveToolStripMenuItem.Text = "&Save" ' 'FormColors_Category ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.SystemColors.ButtonHighlight Me.ClientSize = New System.Drawing.Size(378, 331) Me.Controls.Add(Me.Label3) Me.Controls.Add(Me.DataGridView1) Me.Controls.Add(Me.lbCodeDtl) Me.Controls.Add(Me.lbCode) Me.Controls.Add(Me.txtnama) Me.Controls.Add(Me.txtkode) Me.Controls.Add(Me.MenuStrip1) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle Me.MainMenuStrip = Me.MenuStrip1 Me.MaximizeBox = False Me.MinimizeBox = False Me.Name = "FormColors_Category" Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "..." CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).EndInit() Me.MenuStrip1.ResumeLayout(False) Me.MenuStrip1.PerformLayout() Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents lbCodeDtl As System.Windows.Forms.Label Friend WithEvents lbCode As System.Windows.Forms.Label Friend WithEvents txtnama As System.Windows.Forms.TextBox Friend WithEvents txtkode As System.Windows.Forms.TextBox Friend WithEvents DataGridView1 As System.Windows.Forms.DataGridView Friend WithEvents Label3 As System.Windows.Forms.Label Friend WithEvents MenuStrip1 As System.Windows.Forms.MenuStrip Friend WithEvents SaveToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem End Class
doters/electrohell
stockingElectrohell 02-04-16/stockingElectrohell/stockingElectrohell/forms/FormColors_Category.Designer.vb
Visual Basic
mit
6,042
 Imports System.Text Imports Microsoft.VisualStudio.TestTools.UnitTesting Imports Intrigue Imports Intrigue.Nodes Imports Intrigue.Parsing <TestClass()> Public Class ParserAndJsonTest <TestMethod()> Public Sub Parser_json_arrays() Assert.AreEqual( "(make-jarray 1 2 3)", Parser.Parse("[ 1, 2, 3 ]").ToString) 'Assert.AreEqual( ' "(let ((var0 0) (var1 1)) ((do-this var0) (do-that var1)))", ' Parser.Parse( ' Util.NewString( ' <![CDATA[ ' let ' ( ' var0 0 ' var1 1 ' ( ' do-this var0 ' do-that var1 ' ]]>)).ToString) End Sub <TestMethod()> Public Sub Parser_json_objects() Assert.AreEqual( "(make-jobject ""a"" 1 ""b"" 2)", Parser.Parse("{ ""a"": 1, ""b"": 2 }").ToString) Assert.AreEqual( "(make-jobject ""a"" 1 ""b"" 2)", Parser.Parse("{ ""a"": 1, ""b"": 2}").ToString) End Sub <TestMethod()> Public Sub Parser_json_composites() Assert.AreEqual( "(make-jobject ""a"" 1 ""b"" (make-jarray 1 2 (make-jobject ""c"" ""nada"")))", Parser.Parse("{ ""a"": 1, ""b"": [ 1, 2, { ""c"": ""nada"" } ] }").ToString) End Sub <TestMethod()> Public Sub Parser_json_and_errors() Dim e As Exception = Nothing Try Parser.Parse("[ ""a"": 1, ""b"": 2 ]") Catch e End Try Assert.AreEqual("Colons are not allowed in arrays", e.Message) e = Nothing Try Parser.Parse("( 1, 2 )") Catch e End Try Assert.AreEqual("Commas and colons are not allowed in plain lists", e.Message) End Sub End Class
jmettraux/Intrigue
Intrigue.Tests/ParserAndJsonTest.vb
Visual Basic
mit
1,902
'------------------------------------------------------------------------------ ' <auto-generated> ' 此代码由工具生成。 ' 运行时版本:4.0.30319.42000 ' ' 对此文件的更改可能会导致不正确的行为,并且如果 ' 重新生成代码,这些更改将会丢失。 ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Imports System Namespace My.Resources '此类是由 StronglyTypedResourceBuilder '类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 '若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen '(以 /str 作为命令选项),或重新生成 VS 项目。 '''<summary> ''' 一个强类型的资源类,用于查找本地化的字符串等。 '''</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()> _ Public Module Resources Private resourceMan As Global.System.Resources.ResourceManager Private resourceCulture As Global.System.Globalization.CultureInfo '''<summary> ''' 返回此类使用的缓存的 ResourceManager 实例。 '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Public 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("报价.Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' 使用此强类型资源类,为所有资源查找 ''' 重写当前线程的 CurrentUICulture 属性。 '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Public Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set resourceCulture = value End Set End Property '''<summary> ''' 查找 System.Byte[] 类型的本地化资源。 '''</summary> Public ReadOnly Property excel_out() As Byte() Get Dim obj As Object = ResourceManager.GetObject("excel_out", resourceCulture) Return CType(obj,Byte()) End Get End Property End Module End Namespace
2niuhe/vb_access
WindowsApplication1/My Project/Resources.Designer.vb
Visual Basic
mit
3,156
Option Strict Off Option Explicit On Friend Class frmOrderItemQuick Inherits System.Windows.Forms.Form Dim adoPrimaryRS As ADODB.Recordset Private Sub loadLanguage() 'frmOrderItemQuick = No Code [GRV Quick Edit] 'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 'If rsLang.RecordCount Then frmOrderItemQuick.Caption = rsLang("LanguageLayoutLnk_Description"): frmOrderItemQuick.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") 'lblName = No Code/Dynamic/NA? 'chkBreakPack = No Code [Break Pack] 'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 'If rsLang.RecordCount Then chkBreakPack.Caption = rsLang("LanguageLayoutLnk_Description"): chkBreakPack.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") '_lbl_0 = No Code [Quantity] 'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 'If rsLang.RecordCount Then _lbl_0.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_0.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") ' rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1151 'Price|Checked ' If rsLang.RecordCount Then _lbl_2.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_2.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") ' ' rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1662 'Discount|Checked ' If rsLang.RecordCount Then Label1.Caption = rsLang("LanguageLayoutLnk_Description"): Label1.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") ' '_lbl_1 = No Code [Surcharges] 'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 'If rsLang.RecordCount Then _lbl_1.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_1.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") ' rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1217 'Proceed|Checked ' If rsLang.RecordCount Then cmdProceed.Caption = rsLang("LanguageLayoutLnk_Description"): cmdProceed.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") ' ' rsHelp.filter = "Help_Section=0 AND Help_Form='" & Me.Name & "'" ' If rsHelp.RecordCount Then Me.ToolTip1 = rsHelp("Help_ContextID") End Sub Private Sub chkBreakPack_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) 'If chkBreakPack.value Then ' Me.txtMin.Tag = adoPrimaryRS.Fields("StockItem_UnitCost").Value ' Else ' Me.txtMin.Tag = adoPrimaryRS.Fields("StockItem_ListCost").Value ' End If Select Case frmGRVitem.activePrice Case 0 Me.txtMin.Text = FormatNumber(Me.txtMin.Tag, 2) Case 1 Me.txtMin.Text = FormatNumber(CDec(txtMin.Tag) * (1 + CDbl(frmGRVitem.gridItem.get_TextMatrix(frmGRVitem.gridItem.row, frmGRVitem.colVAT)) / 100), 2) Case 2 Me.txtMin.Text = FormatNumber(CDec(Me.txtMin.Tag) + CDec(frmGRVitem.gridItem.get_TextMatrix(frmGRVitem.gridItem.row, frmGRVitem.colDepositExclusive)), 2) Case 3 Me.txtMin.Text = FormatNumber((CDec(Me.txtMin.Tag) + CDec(frmGRVitem.gridItem.get_TextMatrix(frmGRVitem.gridItem.row, frmGRVitem.colDepositExclusive))) * (1 + CDbl(frmGRVitem.gridItem.get_TextMatrix(frmGRVitem.gridItem.row, frmGRVitem.colVAT)) / 100), 2) End Select End Sub Private Sub chkBreakPack_KeyPress(ByRef KeyAscii As Short) If KeyAscii = 27 Then Me.Close() End If End Sub Private Sub cmdProceed_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdProceed.Click Dim sql As String Dim dirty As Boolean dirty = False Dim lPrice, lDiscount As Decimal If CDbl(txtCost.Tag) <> CDec(txtCost.Text) Then dirty = True If CDbl(txtMin.Tag) <> CShort(txtMin.Text) Then dirty = True If CDbl(txtMax.Tag) <> CShort(txtMax.Text) Then dirty = True If dirty Then sql = "UPDATE MinMaxStockItemLnk SET MinMaxStockItemLnk_Minimum = " & CShort(txtMin.Text) & " Where (MinMaxStockItemLnk_MinMaxID = 1) And (MinMaxStockItemLnk_StockItemID = " & CShort(Me.lblName.Tag) & ")" cnnDB.Execute(sql) cnnDB.Execute("UPDATE StockItem SET StockItem.StockItem_MinimumStock = " & CShort(txtMin.Text) & ", StockItem_OrderRounding = " & CShort(txtMax.Text) & " WHERE StockItemID = " & CShort(Me.lblName.Tag) & ";") End If Me.Close() End Sub Private Sub frmOrderItemQuick_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load If frmOrderWizard.Tag <> "" Then loadLanguage() Me.lblName.Tag = Split(frmOrderWizard.Tag, "|")(0) Me.lblName.Text = Split(frmOrderWizard.Tag, "|")(1) Me.txtCost.Text = Split(frmOrderWizard.Tag, "|")(2) Me.txtMin.Text = Split(frmOrderWizard.Tag, "|")(4) Me.txtMax.Text = Split(frmOrderWizard.Tag, "|")(3) txtCost.Tag = CDec(txtCost.Text) txtMin.Tag = CDec(txtMin.Text) txtMax.Tag = CDec(txtMax.Text) Else Me.Close() End If End Sub Private Sub txtMax_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtMax.Enter MyGotFocusNumeric(txtMax) End Sub Private Sub txtMax_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtMax.KeyPress Dim KeyAscii As Short = Asc(eventArgs.KeyChar) If KeyAscii = 27 Then Me.Close() Else MyKeyPress(KeyAscii) End If eventArgs.KeyChar = Chr(KeyAscii) If KeyAscii = 0 Then eventArgs.Handled = True End If End Sub Private Sub txtMax_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtMax.Leave MyLostFocus(txtMax, 0) End Sub Private Sub txtMin_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtMin.Enter MyGotFocusNumeric(txtMin) End Sub Private Sub txtMin_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtMin.KeyPress Dim KeyAscii As Short = Asc(eventArgs.KeyChar) If KeyAscii = 27 Then Me.Close() Else MyKeyPress(KeyAscii) End If eventArgs.KeyChar = Chr(KeyAscii) If KeyAscii = 0 Then eventArgs.Handled = True End If End Sub Private Sub txtMin_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtMin.Leave MyLostFocus(txtMin, 0) End Sub Private Sub txtCost_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtCost.Enter MyGotFocusNumeric(txtCost) End Sub Private Sub txtCost_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtCost.KeyPress Dim KeyAscii As Short = Asc(eventArgs.KeyChar) If KeyAscii = 27 Then Me.Close() Else MyKeyPress(KeyAscii) End If eventArgs.KeyChar = Chr(KeyAscii) If KeyAscii = 0 Then eventArgs.Handled = True End If End Sub Private Sub txtCost_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtCost.Leave MyLostFocus(txtCost, 2) End Sub End Class
nodoid/PointOfSale
VB/4PosBackOffice.NET/frmOrderItemQuick.vb
Visual Basic
mit
7,249
' Copyright (c) $year$ $ownername$ ' All rights reserved. ' ' 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 is an extended version of Christoc's DotNetNuke Module and Theme Development Template. (http://christoctemplate.codeplex.com) ' Copyright under the license http://christoctemplate.codeplex.com/license ' Imports DotNetNuke Imports DotNetNuke.Entities.Modules.Actions Imports DotNetNuke.Entities.Modules Imports DotNetNuke.Services.Exceptions Imports DotNetNuke.Services.Localization $Aspose_Dynamic_References$ ''' <summary> ''' The View class displays the content ''' ''' Typically your view control would be used to display content or functionality in your module. ''' ''' View may be the only control you have in your project depending on the complexity of your module ''' ''' Because the control inherits from $safeprojectname$ModuleBase you have access to any custom properties ''' defined there, as well as properties from DNN such as PortalId, ModuleId, TabId, UserId and many more. ''' ''' </summary> Public Class View Inherits $safeprojectname$ModuleBase Implements IActionable ''' ----------------------------------------------------------------------------- ''' <summary> ''' Page_Load runs when the control is loaded ''' </summary> ''' <remarks> ''' </remarks> ''' <history> ''' </history> ''' ----------------------------------------------------------------------------- Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load Try Catch exc As Exception Exceptions.ProcessModuleLoadException(Me, exc) End Try End Sub ''' ----------------------------------------------------------------------------- ''' <summary> ''' Registers the module actions required for interfacing with the portal framework ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> ''' <history> ''' </history> ''' ----------------------------------------------------------------------------- Public ReadOnly Property ModuleActions() As ModuleActionCollection Implements IActionable.ModuleActions Get Dim Actions As New ModuleActionCollection Actions.Add(GetNextActionID, Localization.GetString("EditModule", LocalResourceFile), Entities.Modules.Actions.ModuleActionType.AddContent, "", "", EditUrl(), False, DotNetNuke.Security.SecurityAccessLevel.Edit, True, False) Return Actions End Get End Property End Class
asposemarketplace/Aspose_for_DNN
Aspose.DNN/Aspose.DotNetNuke.Template/Visual Studio 2013/VSIX/VB-Template/View.ascx.vb
Visual Basic
mit
3,065
#Region "Header" ' Revit API .NET Labs ' ' Copyright (C) 2006-2021 by Autodesk, Inc. ' ' Permission to use, copy, modify, and distribute this software ' for any purpose and without fee is hereby granted, provided ' that the above copyright notice appears in all copies and ' that both that copyright notice and the limited warranty and ' restricted rights notice below appear in all supporting ' documentation. ' ' AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. ' AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF ' MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. ' DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE ' UNINTERRUPTED OR ERROR FREE. ' ' Use, duplication, or disclosure by the U.S. Government is subject to ' restrictions set forth in FAR 52.227-19 (Commercial Computer ' Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) ' (Rights in Technical Data and Computer Software), as applicable. #End Region Namespace XtraVb ''' <summary> ''' Define global numerical and string constants. ''' </summary> Module LabConstants '#region 2.0 Revit unit conversion constants: Public Const MeterToFeet As Double = 3.2808399 Public Const DegreesToRadians As Double = System.Math.PI / 180 '#endregion '#region 2.1 Revit element listing output file constants: Private Const _temp_dir As String = "C:/tmp/" Public FilePath As String = _temp_dir + "RevitElements.txt" '#endregion ' Lab 3_2 and 3_3 Const _libPath As String = "C:\Documents and Settings\All Users\Application Data\Autodesk\RST 2011\Metric Library\Structural\Framing\Steel\" Public Const WholeFamilyFileToLoad1 As String = _libPath + "M_C-Channel.rfa" ' has TXT catalog file Public Const WholeFamilyFileToLoad2 As String = _libPath + "M_Plate.rfa" ' no TXT catalog file Public Const FamilyFileToLoadSingleSymbol As String = _libPath + "M_L-Angle.rfa" Public Const SymbolName As String = "L152x102x12.7" ' Lab 4_3 Public Const SharedParamFilePath As String = _temp_dir + "SharedParams.txt" Public Const SharedParamsGroupAPI As String = "API Parameters" Public Const SharedParamsDefFireRating As String = "API FireRating" ' Lab 4_4 Public Const ParamGroupName As String = "Per-doc Params" Public Const ParamNameVisible As String = "Visible per-doc Integer" Public Const ParamNameInvisible As String = "Invisible per-doc Integer" ' Lab 5_1 Public Const GroupTypeModel As String = "Model Group" 'BEWARE: In the browser, it says only "Model" End Module End Namespace
jeremytammik/AdnRevitApiLabsXtra
XtraVb/LabConstants.vb
Visual Basic
mit
2,661
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("Skolenie")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("Skolenie")> <Assembly: AssemblyCopyright("Copyright © 2012")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("d5afe798-afa6-4940-af8c-28d3def607a7")> ' 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")>
jakubjenis/lecture.net
Vb.Net/Skolenie/Casting/My Project/AssemblyInfo.vb
Visual Basic
mit
1,134
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "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._2016020901vbSnakes_and_Ladders_Game.My.MySettings Get Return Global._2016020901vbSnakes_and_Ladders_Game.My.MySettings.Default End Get End Property End Module End Namespace
Hadesxz/VB-codes
2016020901vbSnakes and Ladders Game/2016020901vbSnakes and Ladders Game/My Project/Settings.Designer.vb
Visual Basic
mit
2,978
Namespace pCloudy.DTO Public Class CaptureDeviceScreenshotDto Public Property result As CaptureDeviceScreenshotResultDto End Class Public Class CaptureDeviceScreenshotResultDto Public Property [error] As String Public Property token As String Public Property code As Integer Public Property filename As String Public Property dir As String End Class End Namespace
pankyopkey/pCloudy-sample-projects
DotNet/pCloudy-vb-connector/pCloudy-dotnet-connector/DTOs/CaptureDeviceScreenshotDto.vb
Visual Basic
apache-2.0
433
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("Void")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("Void")> <Assembly: AssemblyCopyright("Copyright © 2018")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("873646b3-e712-43d8-ab84-a3c1ef3f04a6")> ' 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")>
Cayan-LLC/developer-docs
examples/merchantware/Credit/vb/Void/Void/My Project/AssemblyInfo.vb
Visual Basic
apache-2.0
1,113
Imports System.IO Imports My.Resources Namespace BasicAnalyzers ''' <summary> ''' Analyzer for reporting syntax tree diagnostics, that require some semantic analysis. ''' It reports diagnostics for all source files which have at least one declaration diagnostic. ''' </summary> <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Public Class SemanticModelAnalyzer Inherits DiagnosticAnalyzer #Region "Descriptor fields" Friend Shared ReadOnly Title As LocalizableString = New LocalizableResourceString(NameOf(Resources.SemanticModelAnalyzerTitle), Resources.ResourceManager, GetType(Resources)) Friend Shared ReadOnly MessageFormat As LocalizableString = New LocalizableResourceString(NameOf(Resources.SemanticModelAnalyzerMessageFormat), Resources.ResourceManager, GetType(Resources)) Friend Shared ReadOnly Description As LocalizableString = New LocalizableResourceString(NameOf(Resources.SemanticModelAnalyzerDescription), Resources.ResourceManager, GetType(Resources)) Friend Shared Rule As New DiagnosticDescriptor(DiagnosticIds.SemanticModelAnalyzerRuleId, Title, MessageFormat, DiagnosticCategories.Stateless, DiagnosticSeverity.Warning, isEnabledByDefault:=True, description:=Description) #End Region Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Rule) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSemanticModelAction(AddressOf AnalyzeSemanticModel) End Sub Private Shared Sub AnalyzeSemanticModel(context As SemanticModelAnalysisContext) ' Find just those source files with declaration diagnostics. Dim diagnosticsCount = context.SemanticModel.GetDeclarationDiagnostics().Length If diagnosticsCount > 0 Then ' For all such files, produce a diagnostic. Dim diag = Diagnostic.Create(Rule, Location.None, Path.GetFileName(context.SemanticModel.SyntaxTree.FilePath), diagnosticsCount) context.ReportDiagnostic(diag) End If End Sub End Class End Namespace
stjeong/roslyn
src/Samples/VisualBasic/Analyzers/BasicAnalyzers/BasicAnalyzers/StatelessAnalyzers/SemanticModelAnalyzer.vb
Visual Basic
apache-2.0
2,269
Imports ESRI.ArcGIS.Mobile.MapActions Imports ESRI.ArcGIS.Mobile Imports ESRI.ArcGIS.Mobile.MobileServices Imports ESRI.ArcGIS.Mobile.Geometries Imports System.Windows.Forms Imports System Imports System.Drawing Imports MobileControls.EditControl Imports MobileControls Imports Esri.ArcGISTemplates Public Class CreateFeaturesMapAction Inherits Esri.ArcGIS.Mobile.MapActions.MapAction Private WithEvents m_cboCreateLayers As ComboBox Private m_LongString As String = " " Public Event RaiseMessage(ByVal Message As String) 'Private m_RadioOnTwo As Boolean = True 'Private m_FLay As FeatureLayer Private m_btn As Button 'Ink Collector 'Edit panel to capture redlines attributes Private WithEvents m_EditPanel As MobileControls.EditControl Private m_mousePosition As Coordinate ' stores current mouse position Private m_coordinates As CoordinateCollection ' stores all coordinates used in drawing the measure line Private m_lineColor As Color = Color.Red Private m_LayerName As String 'Private m_DoubleTapToFinish As Boolean = False 'Private m_PointAtTapOnly As Boolean = False Private m_SketchMode As String Private m_ShowCombo As Boolean = True Private m_lineWidth As Integer = 5 Public Event checkGPS() Private m_GPSVal As GPSLocationDetails Private m_Fnt As System.Drawing.Font Private m_FntSize As Single Private m_DT As FeatureDataTable #Region "Public Methods" Public Sub New() MyBase.New() m_coordinates = New CoordinateCollection() End Sub Public Function addMapButton(Optional ByVal TopX As Integer = -1, Optional ByVal TopY As Integer = -1) As Boolean Try 'Create and add the button to toggle the redline map action If m_btn Is Nothing Then 'Create a new button m_btn = New Button With m_btn 'Set the buttons look and feel .BackColor = System.Drawing.SystemColors.Info .BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch .FlatAppearance.BorderSize = 0 .FlatStyle = System.Windows.Forms.FlatStyle.Flat .BackgroundImage = My.Resources.Pen .Name = "btnRedline" .Size = New System.Drawing.Size(50, 50) .UseVisualStyleBackColor = False 'Locate the button TopX = MyBase.Map.Width - 80 TopY = 85 .Location = New System.Drawing.Point(TopX, TopY) 'Add the handler for relocating the button AddHandler MyBase.Map.Resize, AddressOf resize 'Add a handler for the click event AddHandler .MouseClick, AddressOf InkBtnClick End With If m_cboCreateLayers Is Nothing Then m_cboCreateLayers = New ComboBox m_cboCreateLayers.Visible = False m_cboCreateLayers.ForeColor = Drawing.Color.White m_cboCreateLayers.BackColor = Drawing.Color.DarkBlue m_cboCreateLayers.DropDownStyle = ComboBoxStyle.DropDownList ' m_cboCreateLayers.DropDownHeight = 300 m_cboCreateLayers.Font = m_Fnt m_cboCreateLayers.Width = 200 m_cboCreateLayers.Left = m_btn.Left - m_cboCreateLayers.Width - 10 m_cboCreateLayers.Top = CInt(m_btn.Top + (m_btn.Height / 2) - (m_cboCreateLayers.Height / 2)) ' AddHandler m_cboCreateLayers.SelectedIndexChanged, AddressOf m_cboCreateLayers_SelectedIndexChanged ' AddHandler m_cboCreateLayers.MouseDoubleClick, AddressOf m_cboCreateLayers_MouseDoubleClick 'Locate it to the left of the button and add to the map MyBase.Map.Controls.Add(m_cboCreateLayers) End If 'Add the button to the map MyBase.Map.Controls.Add(m_btn) End If Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing Return False End Try Return True End Function Public Function InitControl(ByVal container As Control, Optional ByVal LayerName As String = "") As Boolean Try Single.TryParse(GlobalsFunctions.appConfig.ApplicationSettings.FontSize, m_FntSize) If Not IsNumeric(m_FntSize) Then m_FntSize = 10 ElseIf m_FntSize = 0 Then m_FntSize = 10 End If m_Fnt = New System.Drawing.Font("Microsoft Sans Serif", m_FntSize, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 0) ''Get the redline layer 'Dim pMblLay As Esri.ArcGIS.Mobile.MobileServices.MobileCacheMapLayer 'pMblLay = CType(Map.MapLayers(m_LayerName), MobileCacheMapLayer) ''Return if it was not found 'If pMblLay Is Nothing Then ' MyBase.Map.Controls.Remove(m_btn) ' Return False 'End If addMapButton() 'Create the form is not already created If m_EditPanel Is Nothing Then 'Create a new edit control m_EditPanel = New MobileControls.EditControl(MyBase.Map, Nothing) 'Fill the containter m_EditPanel.Dock = DockStyle.Fill 'Tell the panel to draw the geometry m_EditPanel.DrawGeo = False m_EditPanel.Height = container.Parent.Height 'Clear the controls on the cotainer container.Controls.Clear() 'Add the edit panel container.Dock = DockStyle.Fill container.Controls.Add(m_EditPanel) container.Refresh() container.Update() m_EditPanel.ResumeLayout(True) m_EditPanel.Refresh() m_EditPanel.Update() 'Create a new row on the panel End If ''Set the layer to a global 'pMblLay.Visible = True 'm_FLay = CType(pMblLay.Layer, FeatureLayer) 'If m_FLay Is Nothing Then ' MyBase.Map.Controls.Remove(m_btn) ' Return False 'End If LoadCreateLayers() If m_cboCreateLayers.Items.Count > 0 Then setDataTable(m_cboCreateLayers.Text) End If 'Create a new row SetNewRow() setCurrentLayer() Return True Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing End Try End Function #End Region #Region "Private Methods" Private Sub setCurrentLayer() Dim pCurConfgi As MobileConfigClass.MobileConfigMobileMapConfigCreateFeaturePanelLayersLayer = m_cboCreateLayers.SelectedItem m_SketchMode = m_cboCreateLayers.SelectedValue If m_SketchMode.ToUpper = "Freehand".ToUpper Then m_EditPanel.GPSButtonVisible = False Else m_EditPanel.GPSButtonVisible = True End If If pCurConfgi.SketchColor <> "" Then m_lineColor = System.Drawing.Color.FromArgb(Int32.Parse(pCurConfgi.SketchColor.Replace("#", ""), Globalization.NumberStyles.HexNumber)) End If End Sub Private Sub setDataTable(ByVal LayerName As String) Try 'Gets a datatable from a feature layer Dim pFl As Esri.ArcGIS.Mobile.MobileServices.FeatureLayer = GlobalsFunctions.GetFeatureLayer(LayerName, MyBase.Map) If pFl Is Nothing Then Return m_DT = pFl.GetDataTable() pFl = Nothing Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing End Try End Sub Private Sub SetNewRow() If m_DT IsNot Nothing Then 'Create a new row Dim pDR As DataRow = m_DT.NewRow m_EditPanel.CurrentRecord = CType(pDR, FeatureDataRow) End If End Sub 'Private Sub SetNewRow() ' Try ' 'If the redline layer was not set, return ' If m_FLay Is Nothing Then Return ' 'if the form is not initilize, then exit ' If m_EditPanel Is Nothing Then Return ' 'Get a table from the layer ' Dim pDT As FeatureDataTable = m_FLay.GetDataTable() ' 'Create a new row and assign it to the edit form ' m_EditPanel.CurrentRecord = pDT.NewRow ' 'Cleanup ' pDT = Nothing ' Catch ex As Exception ' Dim st As New StackTrace ' MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) ' st = Nothing ' Return ' End Try 'End Sub Private Sub LoadCreateLayers() Try m_LongString = "" 'Load the inspection types to the inspection dropdown If m_cboCreateLayers Is Nothing Then Return RemoveHandler m_cboCreateLayers.SelectedIndexChanged, AddressOf m_cboCreateLayers_SelectedIndexChanged For Each createLay In GlobalsFunctions.appConfig.CreateFeaturePanel.Layers.Layer If createLay.Name.Length > m_LongString.Length Then m_LongString = createLay.Name End If Next m_cboCreateLayers.DataSource = GlobalsFunctions.appConfig.CreateFeaturePanel.Layers.Layer m_cboCreateLayers.DisplayMember = "Name" m_cboCreateLayers.ValueMember = "EditTool" If GlobalsFunctions.appConfig.CreateFeaturePanel.Layers.Layer.Count = 1 Then m_cboCreateLayers.Visible = False m_ShowCombo = False End If AddHandler m_cboCreateLayers.SelectedIndexChanged, AddressOf m_cboCreateLayers_SelectedIndexChanged Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing End Try End Sub #End Region #Region "Events" Private Sub m_cboCreateLayers_DropDown(ByVal sender As Object, ByVal e As System.EventArgs) Handles m_cboCreateLayers.DropDown Dim g As Graphics = m_cboCreateLayers.CreateGraphics For i = 0 To 5 ' m_layCBO.Width = m_layCBO.Width + 40 ' m_cboCreateLayers.Height = m_cboCreateLayers.Height + 5 Dim pFnt As System.Drawing.Font = New System.Drawing.Font(m_cboCreateLayers.Font.Name, m_cboCreateLayers.Font.Size + i, System.Drawing.FontStyle.Bold) m_cboCreateLayers.Width = g.MeasureString(m_LongString, pFnt).Width + 50 m_cboCreateLayers.Font = pFnt m_cboCreateLayers.Left = m_btn.Left - m_cboCreateLayers.Width - 10 m_cboCreateLayers.Top = CInt(m_btn.Top + (m_btn.Height / 2) - (m_cboCreateLayers.Height / 2)) Next g.Dispose() g = Nothing ' End If End Sub Private Sub m_cboCreateLayers_DropDownClosed(ByVal sender As Object, ByVal e As System.EventArgs) Handles m_cboCreateLayers.DropDownClosed Dim g As Graphics = m_cboCreateLayers.CreateGraphics m_cboCreateLayers.Width = g.MeasureString(m_cboCreateLayers.Text, m_Fnt).Width + 50 m_cboCreateLayers.Font = m_Fnt m_cboCreateLayers.Left = m_btn.Left - m_cboCreateLayers.Width - 10 m_cboCreateLayers.Top = CInt(m_btn.Top + (m_btn.Height / 2) - (m_cboCreateLayers.Height / 2)) g.Dispose() g = Nothing End Sub Private Sub m_cboCreateLayers_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles m_cboCreateLayers.Enter End Sub Private Sub m_cboCreateLayers_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles m_cboCreateLayers.MouseClick End Sub Private Sub m_cboCreateLayers_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles m_cboCreateLayers.SelectedIndexChanged setDataTable(m_cboCreateLayers.Text) 'Create a new row SetNewRow() setCurrentLayer() End Sub Private Sub GPSCreateFinished() Try 'Convert the stoke to a mobile geo Dim pGeo As Geometry = Nothing If m_DT.FeatureLayer.GeometryType = GeometryType.Polygon And m_coordinates.Count > 2 Then pGeo = New Polygon(m_coordinates.Clone) ElseIf m_DT.FeatureLayer.GeometryType = GeometryType.Polyline And m_coordinates.Count >= 2 Then pGeo = New Polyline(m_coordinates.Clone) Else Return End If ' 'If there is not shape, prompt the user and exit If pGeo Is Nothing Then Map.Invalidate() 'delete the strokes Return End If Try 'Try to set the geometry from the stroke to the edit panel m_EditPanel.Geometry = pGeo 'Cleanup pGeo = Nothing Catch ex As Exception 'Capture a invalid geometry 'delete the strokes m_coordinates.Clear() 'Prompt the user Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing 'Clean up and return pGeo = Nothing Map.Invalidate() Return End Try 'The geometry was save to the edit panel, delete the strokes 'm_coordinates.Clear() 'refresh the map ' Map.Refresh() Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing Return End Try End Sub Private Sub CreateFinished() Try 'Convert the stoke to a mobile geo Dim pGeo As Geometry = Nothing If m_DT.FeatureLayer.GeometryType = GeometryType.Polygon Then pGeo = New Polygon(m_coordinates) m_coordinates.Clear() ElseIf m_DT.FeatureLayer.GeometryType = GeometryType.Polyline Then pGeo = New Polyline(m_coordinates) m_coordinates.Clear() Else 'delete the strokes m_coordinates.Clear() Return End If ' 'If there is not shape, prompt the user and exit If pGeo Is Nothing Then Map.Invalidate() 'delete the strokes m_coordinates.Clear() Return End If Try 'Try to set the geometry from the stroke to the edit panel m_EditPanel.Geometry = pGeo 'Cleanup pGeo = Nothing Catch ex As Exception 'Capture a invalid geometry 'delete the strokes m_coordinates.Clear() 'Prompt the user Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing 'Clean up and return pGeo = Nothing Map.Invalidate() Return End Try 'The geometry was save to the edit panel, delete the strokes m_coordinates.Clear() 'refresh the map Map.Refresh() Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing Return End Try End Sub Private Sub MouseDoubleClick(ByVal sender As Object, ByVal e As MapMouseEventArgs) 'If UCase(m_SketchMode) <> UCase("FreeHand") And ActionInProgress Then ' CreateFinished() ' m_coordinates = New CoordinateCollection() ' Map.Invalidate() ' MyBase.Map.Cursor = New Cursor(My.Resources.redline.Handle) ' ' signal to other mapactions that the action is completed ' ActionInProgress = False 'End If 'If m_DoubleTapToFinish = True Then ' RedlineFinished() ' m_coordinates = New CoordinateCollection() ' Map.Invalidate() ' MyBase.Map.Cursor = New Cursor(My.Resources.redline.Handle) ' ' signal to other mapactions that the action is completed ' ActionInProgress = False 'ElseIf m_DoubleTapToFinish = False And m_PointAtTapOnly = True Then ' RedlineFinished() ' m_coordinates = New CoordinateCollection() ' Map.Invalidate() ' MyBase.Map.Cursor = New Cursor(My.Resources.redline.Handle) ' ' signal to other mapactions that the action is completed ' ActionInProgress = False 'End If End Sub Protected Overrides Sub OnMapMouseUp(ByVal e As Esri.ArcGIS.Mobile.MapMouseEventArgs) MyBase.OnMapMouseUp(e) If UCase(m_SketchMode) = UCase("FreeHand") And ActionInProgress Then CreateFinished() m_coordinates = New CoordinateCollection() Map.Invalidate() MyBase.Map.Cursor = New Cursor(My.Resources.redline.Handle) ' signal to other mapactions that the action is completed ActionInProgress = False ElseIf ActionInProgress Then GPSCreateFinished() End If End Sub Protected Overrides Sub OnMapMouseMove(ByVal e As Esri.ArcGIS.Mobile.MapMouseEventArgs) 'MyBase.OnMapMouseMove(e) m_mousePosition = e.MapCoordinate If (m_coordinates.Count < 1) Then Return End If If UCase(m_SketchMode).ToUpper = UCase("FreeHand").ToUpper Then If m_DT.FeatureLayer.GeometryType = GeometryType.Polygon Then If (m_coordinates.Count < 2) Then Return End If m_coordinates.Insert(m_coordinates.Count - 1, m_mousePosition) Else m_coordinates.Add(m_mousePosition) End If If (Map IsNot Nothing) Then Map.Invalidate() End If End If End Sub Protected Overrides Sub OnMapMouseDown(ByVal e As Esri.ArcGIS.Mobile.MapMouseEventArgs) ' MyBase.OnMapMouseDown(e) Map.Focus() If (e.MapCoordinate Is Nothing) Then Return End If 'If ActionInProgress And m_PointAtTapOnly = True Then ' m_coordinates.Insert(m_coordinates.Count - 1, m_mousePosition) ' If (Map IsNot Nothing) Then ' Map.Invalidate() ' End If 'ElseIf ActionInProgress And m_DoubleTapToFinish = False Then ' ActionInProgress = False ' RedlineFinished() ' MyBase.Map.Cursor = New Cursor(My.Resources.redline.Handle) 'Else ' signal to other mapactions that the action is executing ActionInProgress = True If (m_coordinates.Count = 0) Then m_coordinates.Add(e.MapCoordinate) If m_DT.FeatureLayer.GeometryType = GeometryType.Polygon Then m_coordinates.Add(e.MapCoordinate) End If If (Map IsNot Nothing) Then Map.Invalidate() End If 'ElseIf (m_coordinates.Count = 2) Then ' If (m_measureMethod = EsriMeasureMethod.MultiPoint) Then ' m_coordinates.Insert(1, e.MapCoordinate) ' End If 'ElseIf (m_measureMethod = EsriMeasureMethod.MultiPoint) Then ' m_coordinates.Insert(m_coordinates.Count - 1, e.MapCoordinate) Else If m_DT.FeatureLayer.GeometryType = GeometryType.Polygon Then m_coordinates.Insert(m_coordinates.Count - 1, m_mousePosition) Else m_coordinates.Add(m_mousePosition) End If 'm_coordinates.Add(m_mousePosition) If (Map IsNot Nothing) Then Map.Invalidate() End If End If End Sub Private Sub MapPaint(ByVal sender As Object, ByVal e As Esri.ArcGIS.Mobile.MapPaintEventArgs) If m_coordinates.Count = 0 Then Return If m_coordinates.Count = 1 Then e.Display.DrawPoint(New Pen(m_lineColor, m_lineWidth), New SolidBrush(m_lineColor), 1, m_coordinates(0)) Return End If If m_coordinates.Count = 2 Then If m_coordinates(0).EquivalentTo(m_coordinates(1)) Then e.Display.DrawPoint(New Pen(m_lineColor, m_lineWidth), New SolidBrush(m_lineColor), 1, m_coordinates(0)) Return End If End If Dim g As Graphics = e.Graphics 'If m_DT.FeatureLayer.GeometryType = GeometryType.Polygon Then ' If m_coordinates.Count > 3 Then ' e.Display.DrawPolygon(New Pen(m_lineColor, m_lineWidth), Nothing, m_coordinates) ' End If 'ElseIf m_DT.FeatureLayer.GeometryType = GeometryType.Polygon Then e.Display.DrawPolyline(New Pen(m_lineColor, m_lineWidth), m_coordinates) 'End If End Sub Protected Overrides Sub OnActiveChanged(ByVal active As Boolean) If active Then AddHandler Map.MouseDoubleClick, AddressOf MouseDoubleClick AddHandler Map.KeyUp, AddressOf MapKeyUp AddHandler Map.KeyDown, AddressOf MapKeyDown AddHandler Map.Paint, AddressOf MapPaint MyBase.Map.Cursor = New Cursor(My.Resources.redline.Handle) Else RemoveHandler Map.MouseDoubleClick, AddressOf MouseDoubleClick RemoveHandler Map.KeyUp, AddressOf MapKeyUp RemoveHandler Map.KeyDown, AddressOf MapKeyDown RemoveHandler Map.Paint, AddressOf MapPaint MyBase.Map.Cursor = Cursors.Default m_coordinates = New CoordinateCollection() Map.Invalidate() ' signal to other mapactions that the action is completed ActionInProgress = False End If MyBase.OnActiveChanged(active) End Sub Private Sub MapKeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) MyBase.OnMapKeyDown(e) If e.KeyValue = 27 Then m_coordinates.Clear() Map.Invalidate() ActionInProgress = False Return End If End Sub Private Sub MapKeyUp(ByVal sender As Object, ByVal e As KeyEventArgs) MyBase.OnMapKeyUp(e) End Sub Private Sub resize() Try 'Relocate the button If m_btn IsNot Nothing And MyBase.Map IsNot Nothing Then m_btn.Location = New System.Drawing.Point(MyBase.Map.Width - 80, 85) End If m_cboCreateLayers.Width = 200 m_cboCreateLayers.Left = m_btn.Left - m_cboCreateLayers.Width - 10 m_cboCreateLayers.Top = CInt(m_btn.Top + (m_btn.Height / 2) - (m_cboCreateLayers.Height / 2)) Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing End Try End Sub Private Sub CreateFeaturesMapAction_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed Try 'Remove the button from the map If m_btn IsNot Nothing Then If m_btn.Parent IsNot Nothing Then m_btn.Parent.Controls.Remove(m_btn) End If End If 'Release the other objects If m_EditPanel IsNot Nothing Then m_EditPanel.Dispose() End If m_EditPanel = Nothing Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing Return End Try End Sub Private Sub CreateFeaturesMapAction_StatusChanged(ByVal sender As Object, ByVal e As Esri.ArcGIS.Mobile.MapActions.MapActionStatusChangedEventArgs) Handles Me.StatusChanged Try 'Check the map actions status If e.StatusId = Esri.ArcGIS.Mobile.MapActions.MapAction.Activated Then 'If the button has been created, update the buttons image If m_btn IsNot Nothing Then m_btn.BackgroundImage = My.Resources.penDown m_cboCreateLayers.Visible = m_ShowCombo End If ElseIf e.StatusId = Esri.ArcGIS.Mobile.MapActions.MapAction.Deactivated Then 'If the button has been created, update the buttons image If m_btn IsNot Nothing Then m_btn.BackgroundImage = My.Resources.Pen m_cboCreateLayers.Visible = False End If End If Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing Return End Try End Sub Public Sub InkBtnClick(ByVal sender As Object, ByVal e As MouseEventArgs) Try 'Release or assign the map action If MyBase.Map.CurrentMapAction Is Me Then MyBase.Map.CurrentMapAction = Nothing Else MyBase.Map.CurrentMapAction = Me End If Catch ex As Exception Dim st As New StackTrace MsgBox(st.GetFrame(0).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Name & ":" & st.GetFrame(1).GetMethod.Module.Name & vbCrLf & ex.Message) st = Nothing End Try End Sub #End Region Public Property GPSLocation() As GPSLocationDetails Get Return m_GPSVal End Get Set(ByVal value As GPSLocationDetails) m_GPSVal = value End Set End Property Private Sub m_EditPanel_CheckGPS() Handles m_EditPanel.CheckGPS RaiseEvent checkGPS() If (m_GPSVal IsNot Nothing) Then ' MsgBox("") If m_GPSVal.SpatialReference.FactoryCode <> Map.SpatialReference.FactoryCode Then m_coordinates.Add(Map.SpatialReference.FromGps(m_GPSVal.Coordinate)) 'Me.Geometry = New Esri.ArcGIS.Mobile.Geometries.Point(m_Map.SpatialReference.FromDegreeMinuteSecond(m_GPSVal.LongitudeToDegreeMinutesSeconds), m_Map.SpatialReference.FromDegreeMinuteSecond(m_GPSVal.LatitudeToDegreeMinutesSeconds)) 'Me.Geometry = m_GPSVal() Else m_coordinates.Add(m_GPSVal.Coordinate) End If GPSCreateFinished() Map.Invalidate() End If 'm_EditPanel.GPSLocation = m_GPSVal End Sub Private Sub m_EditPanel_RaiseMessage(ByVal Message As String) Handles m_EditPanel.RaiseMessage RaiseEvent RaiseMessage(Message) End Sub Private Sub m_EditPanel_RecordClear() Handles m_EditPanel.RecordClear m_coordinates.Clear() End Sub Private Sub m_EditPanel_RecordSaved(ByVal LayerName As String, ByVal pGeo As Esri.ArcGIS.Mobile.Geometries.Geometry, ByVal OID As Integer) Handles m_EditPanel.RecordSaved m_coordinates.Clear() ' MsgBox("Record Saved", MsgBoxStyle.Information) RaiseEvent RaiseMessage(GlobalsFunctions.appConfig.EditControlOptions.UIComponents.SavedMessage) End Sub End Class
Esri/water-utility-mobile-map
Redline_Control/CreateFeaturesControl.vb
Visual Basic
apache-2.0
29,288
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Completion.CompletionProviders Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders Namespace Tests Public Class XmlDocCommentCompletionProviderTests Inherits AbstractVisualBasicCompletionProviderTests Public Sub New(workspaceFixture As VisualBasicTestWorkspaceFixture) MyBase.New(workspaceFixture) End Sub Friend Overrides Function CreateCompletionProvider() As CompletionListProvider Return New XmlDocCommentCompletionProvider() End Function Private Async Function VerifyItemsExistAsync(markup As String, ParamArray items() As String) As Threading.Tasks.Task For Each item In items Await VerifyItemExistsAsync(markup, item) Next End Function Private Async Function VerifyItemsAbsentAsync(markup As String, ParamArray items() As String) As Threading.Tasks.Task For Each item In items Await VerifyItemIsAbsentAsync(markup, item) Next End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAnyLevelTags1() As Task Dim text = <File> Class C ''' &lt;$$ Sub Foo() End Sub End Class </File>.Value Await VerifyItemsExistAsync(text, "see", "seealso", "![CDATA[", "!--") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAnyLevelTags2() As Task Dim text = <File> Class C ''' &lt;summary&gt; ''' &lt;$$ ''' &lt;/summary&gt; Sub Foo() End Sub End Class </File>.Value Await VerifyItemsExistAsync(text, "see", "seealso", "![CDATA[", "!--") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAnyLevelTags3() As Task Dim text = <File> Class C ''' &lt;summary&gt; ''' &lt; &lt;see&gt;&lt;/see&gt; ''' &lt;$$ ''' &lt;/summary&gt; Sub Foo() End Sub End Class </File>.Value Await VerifyItemsExistAsync(text, "see", "seealso", "![CDATA[", "!--") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRepeatableNestedTags1() As Task Dim text = <File> Class C ''' &lt;$$ Sub Foo() End Sub End Class </File>.Value Await VerifyItemsAbsentAsync(text, "code", "list", "para", "paramref", "typeparamref") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRepeatableNestedTags2() As Task Dim text = <File> Class C ''' &lt;summary&gt; ''' &lt;$$ ''' &lt;summary&gt; Sub Foo() End Sub End Class </File>.Value Await VerifyItemsExistAsync(text, "code", "list", "para", "paramref", "typeparamref") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRepeatableTopLevelOnlyTags1() As Task Dim text = <File> Class C ''' &lt;summary&gt; ''' &lt;$$ ''' &lt;summary&gt; Sub Foo() End Sub End Class </File>.Value Await VerifyItemsAbsentAsync(text, "exception", "include", "permission") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRepeatableTopLevelOnlyTags2() As Task Dim text = <File> Class C ''' &lt;$$ Sub Foo() End Sub End Class </File>.Value Await VerifyItemsExistAsync(text, "exception", "include", "permission") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTopLevelOnlyTags1() As Task Dim text = <File> Class C ''' &lt;summary&gt; ''' &lt;$$ ''' &lt;summary&gt; Sub Foo() End Sub End Class </File>.Value Await VerifyItemsAbsentAsync(text, "example", "remarks", "summary", "value") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTopLevelOnlyTags2() As Task Dim text = <File> Class C ''' &lt;$$ Sub Foo() End Sub End Class </File>.Value Await VerifyItemsExistAsync(text, "example", "remarks", "summary") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTopLevelOnlyTags3() As Task Dim text = <File> Class C ''' &lt;summary&gt;&lt;summary&gt; ''' &lt;$$ Sub Foo() End Sub End Class </File>.Value Await VerifyItemsAbsentAsync(text, "example", "remarks", "summary", "value") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestListOnlyTags() As Task Dim text = <File> Class C ''' &lt;list&gt;&lt;$$&lt;/list&gt; Sub Foo() End Sub End Class </File>.Value Await VerifyItemsExistAsync(text, "listheader", "item", "term", "description") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestListHeaderTags() As Task Dim text = <File> Class C ''' &lt;list&gt; &lt;listheader&gt; &lt;$$ &lt;/listheader&gt; &lt;/list&gt; Sub Foo() End Sub End Class </File>.Value Await VerifyItemsExistAsync(text, "term", "description") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMethodParamTypeParam() As Task Dim text = <File> Class C(Of T) ''' &lt;$$ Sub Foo(Of T)(bar as T) End Sub End Class </File>.Value Await VerifyItemsExistAsync(text, "param name=""bar""", "typeparam name=""T""") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestIndexerParamTypeParam() As Task Dim text = <File> Class C(Of T) ''' &lt;$$ Default Public Property Item(bar as T) Get End Get Set End Set End Sub End Property </File>.Value Await VerifyItemsExistAsync(text, "param name=""bar""") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeTypeParam() As Task Dim text = <File> ''' &lt;$$ Class C(Of T) Sub Foo(Of T)(bar as T) End Sub End Class </File>.Value Await VerifyItemsExistAsync(text, "typeparam name=""T""") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoRepeatParam() As Task Dim text = <File> Class C(Of T) ''' &lt;param name="bar"&gt;&lt;/param;&gt; ''' &lt;$$ Sub Foo(Of T)(bar as T) End Sub End Class </File>.Value Await VerifyItemIsAbsentAsync(text, "param name=""bar""") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeAfterName() As Task Dim text = <File> Class C(Of T) ''' &lt;exception $$ Sub Foo(Of T)(bar as T) End Sub End Class </File>.Value Await VerifyItemExistsAsync(text, "cref") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeAfterNamePartiallyTyped() As Task Dim text = <File> Class C(Of T) ''' &lt;exception c$$ Sub Foo(Of T)(bar as T) End Sub End Class </File>.Value Await VerifyItemExistsAsync(text, "cref") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeAfterAttribute() As Task Dim text = <File> Class C(Of T) ''' &lt;exception name="" $$ Sub Foo(Of T)(bar as T) End Sub End Class </File>.Value Await VerifyItemExistsAsync(text, "cref") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterNameInsideAttribute() As Task Dim text = <File> Class C(Of T) ''' &lt;param name = "$$" Sub Foo(Of T)(bar as T) End Sub End Class </File>.Value Await VerifyItemExistsAsync(text, "bar") End Function <WorkItem(623219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/623219")> <WorkItem(746919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/746919")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommitParam() As Task Dim text = <File> Class C(Of T) ''' &lt;param$$ Sub Foo(Of T)(bar As T) End Sub End Class </File>.NormalizedValue Dim expected = <File> Class C(Of T) ''' &lt;param name="bar"$$ Sub Foo(Of T)(bar As T) End Sub End Class </File>.NormalizedValue Await VerifyCustomCommitProviderAsync(text, "param name=""bar""", expected) End Function <WorkItem(623158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/623158")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCloseTag() As Task Dim text = <File> Class C ''' &lt;foo&gt;&lt;/$$ Sub Foo() End Sub End Class </File>.Value Await VerifyItemExistsAsync(text, "foo", usePreviousCharAsTrigger:=True) End Function <WorkItem(638805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638805")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoParentElement() As Task Dim text = <File><![CDATA[ ''' <summary> ''' </summary> ''' $$ Module Program End Module]]></File>.Value Await VerifyItemsExistAsync(text, "see", "seealso", "![CDATA[", "!--") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNestedTagsOnSameLineAsCompletedTag() As Task Dim text = <File><![CDATA[ ''' <summary> ''' <foo></foo>$$ ''' ''' </summary> Module Program End Module]]></File>.Value Await VerifyItemsExistAsync(text, "code", "list", "para", "paramref", "typeparamref") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNotInCref() As Task Dim text = <File><![CDATA[ ''' <summary> ''' <see cref="$$ ''' </summary> Module Program End Module]]></File>.Value Await VerifyNoItemsExistAsync(text) End Function <WorkItem(638653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638653")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowTypingDoubleQuote() As Task Dim text = <File> Class C(Of T) ''' &lt;param$$ Sub Foo(Of T)(bar as T) End Sub End Class </File>.NormalizedValue Dim expected = <File>$$ Class C(Of T) ''' &lt;param Sub Foo(Of T)(bar as T) End Sub End Class </File>.NormalizedValue Await VerifyCustomCommitProviderAsync(text, "param name=""bar""", expected, Microsoft.CodeAnalysis.SourceCodeKind.Regular, commitChar:=""""c) End Function <WorkItem(638653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638653")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowTypingSpace() As Task Dim text = <File> Class C(Of T) ''' &lt;param$$ Sub Foo(Of T)(bar as T) End Sub End Class </File>.NormalizedValue Dim expected = <File>$$ Class C(Of T) ''' &lt;param Sub Foo(Of T)(bar as T) End Sub End Class </File>.NormalizedValue Await VerifyCustomCommitProviderAsync(text, "param name=""bar""", expected, Microsoft.CodeAnalysis.SourceCodeKind.Regular, commitChar:=" "c) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompletionList() As Task Dim text = <File> Class C ''' &lt;$$ Sub Foo() End Sub End Class </File>.Value Await VerifyItemsExistAsync(text, "completionlist") End Function End Class End Namespace
thomaslevesque/roslyn
src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/XmlDocCommentCompletionProviderTests.vb
Visual Basic
apache-2.0
12,893
' 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.IO Imports System.Reflection.PortableExecutable Imports System.Runtime.InteropServices Imports System.Text Imports System.Threading Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Imports CS = Microsoft.CodeAnalysis.CSharp Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CompilationAPITests Inherits BasicTestBase <WorkItem(8360, "https://github.com/dotnet/roslyn/issues/8360")> <WorkItem(9153, "https://github.com/dotnet/roslyn/issues/9153")> <Fact> Public Sub PublicSignWithRelativeKeyPath() Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary). WithPublicSign(True).WithCryptoKeyFile("test.snk") AssertTheseDiagnostics(VisualBasicCompilation.Create("test", options:=options), <errors> BC37254: Public sign was specified and requires a public key, but no public key was specified BC37257: Option 'CryptoKeyFile' must be an absolute path. </errors>) End Sub <Fact> Public Sub LocalizableErrorArgumentToStringDoesntStackOverflow() ' Error ID is arbitrary Dim arg = New LocalizableErrorArgument(ERRID.IDS_ProjectSettingsLocationName) Assert.NotNull(arg.ToString()) End Sub <WorkItem(538778, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538778")> <WorkItem(537623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537623")> <Fact> Public Sub CompilationName() ' report an error, rather then silently ignoring the directory ' (see cli partition II 22.30) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create("C:/foo/Test.exe")) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create("C:\foo\Test.exe")) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create("\foo/Test.exe")) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create("C:Test.exe")) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create("Te" & ChrW(0) & "st.exe")) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create(" " & vbTab & " ")) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create(ChrW(&HD800))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create("")) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create(" a")) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create("\u2000a")) ' // U+2000 is whitespace ' other characters than directory separators are ok: VisualBasicCompilation.Create(";,*?<>#!@&") VisualBasicCompilation.Create("foo") VisualBasicCompilation.Create(".foo") VisualBasicCompilation.Create("foo ") ' can end with whitespace VisualBasicCompilation.Create("....") VisualBasicCompilation.Create(Nothing) End Sub <Fact> Public Sub CreateAPITest() Dim listSyntaxTree = New List(Of SyntaxTree) Dim listRef = New List(Of MetadataReference) Dim s1 = "using Foo" Dim t1 As SyntaxTree = VisualBasicSyntaxTree.ParseText(s1) listSyntaxTree.Add(t1) ' System.dll listRef.Add(TestReferences.NetFx.v4_0_30319.System) Dim ops = TestOptions.ReleaseExe ' Create Compilation with Option is not Nothing Dim comp = VisualBasicCompilation.Create("Compilation", listSyntaxTree, listRef, ops) Assert.Equal(ops, comp.Options) Assert.NotNull(comp.SyntaxTrees) Assert.NotNull(comp.References) Assert.Equal(1, comp.SyntaxTrees.Count) Assert.Equal(1, comp.References.Count) ' Create Compilation with PreProcessorSymbols of Option is empty Dim ops1 = TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"System", "Microsoft.VisualBasic"})).WithRootNamespace("") ' Create Compilation with Assembly name contains invalid char Dim asmname = "楽聖いち にÅÅ€" comp = VisualBasicCompilation.Create(asmname, listSyntaxTree, listRef, ops1) Assert.Equal(asmname, comp.Assembly.Name) Assert.Equal(asmname + ".exe", comp.SourceModule.Name) Dim compOpt = VisualBasicCompilation.Create("Compilation", Nothing, Nothing, Nothing) Assert.NotNull(compOpt.Options) ' Not Implemented code ' comp = comp.ChangeOptions(options:=null) ' Assert.Equal(CompilationOptions.Default, comp.Options) ' comp = comp.ChangeOptions(ops1) ' Assert.Equal(ops1, comp.Options) ' comp = comp.ChangeOptions(comp1.Options) ' ssert.Equal(comp1.Options, comp.Options) ' comp = comp.ChangeOptions(CompilationOptions.Default) ' Assert.Equal(CompilationOptions.Default, comp.Options) End Sub <Fact> Public Sub GetSpecialType() Dim comp = VisualBasicCompilation.Create("compilation", Nothing, Nothing, Nothing) ' Get Special Type by enum Dim ntSmb = comp.GetSpecialType(typeId:=SpecialType.Count) Assert.Equal(SpecialType.Count, ntSmb.SpecialType) ' Get Special Type by integer ntSmb = comp.GetSpecialType(CType(31, SpecialType)) Assert.Equal(31, CType(ntSmb.SpecialType, Integer)) End Sub <Fact> Public Sub GetTypeByMetadataName() Dim comp = VisualBasicCompilation.Create("compilation", Nothing, Nothing, Nothing) ' Get Type Name And Arity Assert.Null(comp.GetTypeByMetadataName("`1")) Assert.Null(comp.GetTypeByMetadataName("中文`1")) ' Throw exception when the parameter of GetTypeByNameAndArity is NULL 'Assert.Throws(Of Exception)( ' Sub() ' comp.GetTypeByNameAndArity(fullName:=Nothing, arity:=1) ' End Sub) ' Throw exception when the parameter of GetTypeByNameAndArity is less than 0 'Assert.Throws(Of Exception)( ' Sub() ' comp.GetTypeByNameAndArity(String.Empty, -4) ' End Sub) Dim compilationDef = <compilation name="compilation"> <file name="a.vb"> Namespace A.B Class C Class D Class E End Class End Class End Class Class G(Of T) Class Q(Of S1,S2) ENd Class End Class Class G(Of T1,T2) End Class End Namespace Class C Class D Class E End Class End Class End Class </file> </compilation> comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) 'IsCaseSensitive Assert.Equal(Of Boolean)(False, comp.IsCaseSensitive) Assert.Equal("D", comp.GetTypeByMetadataName("C+D").Name) Assert.Equal("E", comp.GetTypeByMetadataName("C+D+E").Name) Assert.Null(comp.GetTypeByMetadataName("")) Assert.Null(comp.GetTypeByMetadataName("+")) Assert.Null(comp.GetTypeByMetadataName("++")) Assert.Equal("C", comp.GetTypeByMetadataName("A.B.C").Name) Assert.Equal("D", comp.GetTypeByMetadataName("A.B.C+D").Name) Assert.Null(comp.GetTypeByMetadataName("A.B.C+F")) Assert.Equal("E", comp.GetTypeByMetadataName("A.B.C+D+E").Name) Assert.Null(comp.GetTypeByMetadataName("A.B.C+D+E+F")) Assert.Equal(1, comp.GetTypeByMetadataName("A.B.G`1").Arity) Assert.Equal(2, comp.GetTypeByMetadataName("A.B.G`1+Q`2").Arity) Assert.Equal(2, comp.GetTypeByMetadataName("A.B.G`2").Arity) Assert.Null(comp.GetTypeByMetadataName("c")) Assert.Null(comp.GetTypeByMetadataName("A.b.C")) Assert.Null(comp.GetTypeByMetadataName("C+d")) Assert.Equal(SpecialType.System_Array, comp.GetTypeByMetadataName("System.Array").SpecialType) Assert.Null(comp.Assembly.GetTypeByMetadataName("System.Array")) Assert.Equal("E", comp.Assembly.GetTypeByMetadataName("A.B.C+D+E").Name) End Sub <Fact> Public Sub EmitToMemoryStreams() Dim comp = VisualBasicCompilation.Create("Compilation", options:=TestOptions.ReleaseDll) Using output = New MemoryStream() Using outputPdb = New MemoryStream() Using outputxml = New MemoryStream() Dim result = comp.Emit(output, outputPdb, Nothing) Assert.True(result.Success) result = comp.Emit(output, outputPdb) Assert.True(result.Success) result = comp.Emit(peStream:=output, pdbStream:=outputPdb, xmlDocumentationStream:=Nothing, cancellationToken:=Nothing) Assert.True(result.Success) result = comp.Emit(peStream:=output, pdbStream:=outputPdb, cancellationToken:=Nothing) Assert.True(result.Success) result = comp.Emit(output, outputPdb) Assert.True(result.Success) result = comp.Emit(output, outputPdb) Assert.True(result.Success) result = comp.Emit(output, outputPdb, outputxml) Assert.True(result.Success) result = comp.Emit(output, Nothing, Nothing, Nothing) Assert.True(result.Success) result = comp.Emit(output) Assert.True(result.Success) result = comp.Emit(output, Nothing, outputxml) Assert.True(result.Success) result = comp.Emit(output, xmlDocumentationStream:=outputxml) Assert.True(result.Success) result = comp.Emit(output, Nothing, outputxml) Assert.True(result.Success) result = comp.Emit(output, xmlDocumentationStream:=outputxml) Assert.True(result.Success) End Using End Using End Using End Sub <Fact> Public Sub EmitOptionsDiagnostics() Dim c = CreateCompilationWithMscorlib({"class C {}"}) Dim stream = New MemoryStream() Dim options = New EmitOptions( debugInformationFormat:=CType(-1, DebugInformationFormat), outputNameOverride:=" ", fileAlignment:=513, subsystemVersion:=SubsystemVersion.Create(1000000, -1000000)) Dim result = c.Emit(stream, options:=options) result.Diagnostics.Verify( Diagnostic(ERRID.ERR_InvalidDebugInformationFormat).WithArguments("-1"), Diagnostic(ERRID.ERR_InvalidOutputName).WithArguments(CodeAnalysisResources.NameCannotStartWithWhitespace), Diagnostic(ERRID.ERR_InvalidFileAlignment).WithArguments("513"), Diagnostic(ERRID.ERR_InvalidSubsystemVersion).WithArguments("1000000.-1000000")) Assert.False(result.Success) End Sub <Fact> Public Sub ReferenceAPITest() ' Create Compilation takes two args Dim comp = VisualBasicCompilation.Create("Compilation") Dim ref1 = TestReferences.NetFx.v4_0_30319.mscorlib Dim ref2 = TestReferences.NetFx.v4_0_30319.System Dim ref3 = New TestMetadataReference(fullPath:="c:\xml.bms") Dim ref4 = New TestMetadataReference(fullPath:="c:\aaa.dll") ' Add a new empty item comp = comp.AddReferences(Enumerable.Empty(Of MetadataReference)()) Assert.Equal(0, comp.References.Count) ' Add a new valid item comp = comp.AddReferences(ref1) Dim assemblySmb = comp.GetReferencedAssemblySymbol(ref1) Assert.NotNull(assemblySmb) Assert.Equal("mscorlib", assemblySmb.Name, StringComparer.OrdinalIgnoreCase) Assert.Equal(1, comp.References.Count) Assert.Equal(MetadataImageKind.Assembly, comp.References(0).Properties.Kind) Assert.Same(ref1, comp.References(0)) ' Replace an existing item with another valid item comp = comp.ReplaceReference(ref1, ref2) Assert.Equal(1, comp.References.Count) Assert.Equal(MetadataImageKind.Assembly, comp.References(0).Properties.Kind) Assert.Equal(ref2, comp.References(0)) ' Remove an existing item comp = comp.RemoveReferences(ref2) Assert.Equal(0, comp.References.Count) 'WithReferences Dim hs1 As New HashSet(Of MetadataReference) From {ref1, ref2, ref3} Dim compCollection1 = VisualBasicCompilation.Create("Compilation") Assert.Equal(Of Integer)(0, Enumerable.Count(Of MetadataReference)(compCollection1.References)) Dim c2 As Compilation = compCollection1.WithReferences(hs1) Assert.Equal(Of Integer)(3, Enumerable.Count(Of MetadataReference)(c2.References)) 'WithReferences Dim compCollection2 = VisualBasicCompilation.Create("Compilation") Assert.Equal(Of Integer)(0, Enumerable.Count(Of MetadataReference)(compCollection2.References)) Dim c3 As Compilation = compCollection1.WithReferences(ref1, ref2, ref3) Assert.Equal(Of Integer)(3, Enumerable.Count(Of MetadataReference)(c3.References)) 'ReferencedAssemblyNames Dim RefAsm_Names As IEnumerable(Of AssemblyIdentity) = c2.ReferencedAssemblyNames Assert.Equal(Of Integer)(2, Enumerable.Count(Of AssemblyIdentity)(RefAsm_Names)) Dim ListNames As New List(Of String) Dim I As AssemblyIdentity For Each I In RefAsm_Names ListNames.Add(I.Name) Next Assert.Contains(Of String)("mscorlib", ListNames) Assert.Contains(Of String)("System", ListNames) 'RemoveAllReferences c2 = c2.RemoveAllReferences Assert.Equal(Of Integer)(0, Enumerable.Count(Of MetadataReference)(c2.References)) ' Overload with Hashset Dim hs = New HashSet(Of MetadataReference)() From {ref1, ref2, ref3} Dim compCollection = VisualBasicCompilation.Create("Compilation", references:=hs) compCollection = compCollection.AddReferences(ref1, ref2, ref3, ref4).RemoveReferences(hs) Assert.Equal(1, compCollection.References.Count) compCollection = compCollection.AddReferences(hs).RemoveReferences(ref1, ref2, ref3, ref4) Assert.Equal(0, compCollection.References.Count) ' Overload with Collection Dim col = New ObjectModel.Collection(Of MetadataReference)() From {ref1, ref2, ref3} compCollection = VisualBasicCompilation.Create("Compilation", references:=col) compCollection = compCollection.AddReferences(col).RemoveReferences(ref1, ref2, ref3) Assert.Equal(0, compCollection.References.Count) compCollection = compCollection.AddReferences(ref1, ref2, ref3).RemoveReferences(col) Assert.Equal(0, comp.References.Count) ' Overload with ConcurrentStack Dim stack = New Concurrent.ConcurrentStack(Of MetadataReference) stack.Push(ref1) stack.Push(ref2) stack.Push(ref3) compCollection = VisualBasicCompilation.Create("Compilation", references:=stack) compCollection = compCollection.AddReferences(stack).RemoveReferences(ref1, ref3, ref2) Assert.Equal(0, compCollection.References.Count) compCollection = compCollection.AddReferences(ref2, ref1, ref3).RemoveReferences(stack) Assert.Equal(0, compCollection.References.Count) ' Overload with ConcurrentQueue Dim queue = New Concurrent.ConcurrentQueue(Of MetadataReference) queue.Enqueue(ref1) queue.Enqueue(ref2) queue.Enqueue(ref3) compCollection = VisualBasicCompilation.Create("Compilation", references:=queue) compCollection = compCollection.AddReferences(queue).RemoveReferences(ref3, ref2, ref1) Assert.Equal(0, compCollection.References.Count) compCollection = compCollection.AddReferences(ref2, ref1, ref3).RemoveReferences(queue) Assert.Equal(0, compCollection.References.Count) End Sub <WorkItem(537826, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537826")> <Fact> Public Sub SyntreeAPITest() Dim s1 = "using System.Linq;" Dim s2 = <![CDATA[Class foo sub main Public Operator End Operator End Class ]]>.Value Dim s3 = "Imports s$ = System.Text" Dim s4 = <text> Module Module1 Sub Foo() for i = 0 to 100 next end sub End Module </text>.Value Dim t1 = VisualBasicSyntaxTree.ParseText(s4) Dim withErrorTree = VisualBasicSyntaxTree.ParseText(s2) Dim withErrorTree1 = VisualBasicSyntaxTree.ParseText(s3) Dim withErrorTreeCS = VisualBasicSyntaxTree.ParseText(s1) Dim withExpressionRootTree = SyntaxFactory.ParseExpression("0").SyntaxTree ' Create compilation takes three args Dim comp = VisualBasicCompilation.Create("Compilation", {t1}, {MscorlibRef, MsvbRef}, TestOptions.ReleaseDll) Dim tree = comp.SyntaxTrees.AsEnumerable() comp.VerifyDiagnostics() ' Add syntaxtree with error comp = comp.AddSyntaxTrees(withErrorTreeCS) Assert.Equal(2, comp.GetDiagnostics().Length()) ' Remove syntaxtree without error comp = comp.RemoveSyntaxTrees(tree) Assert.Equal(2, comp.GetDiagnostics(cancellationToken:=CancellationToken.None).Length()) ' Remove syntaxtree with error comp = comp.RemoveSyntaxTrees(withErrorTreeCS) Assert.Equal(0, comp.GetDiagnostics().Length()) Assert.Equal(0, comp.GetDeclarationDiagnostics().Length()) ' Get valid binding Dim bind = comp.GetSemanticModel(syntaxTree:=t1) Assert.NotNull(bind) ' Get Binding with tree is not exist bind = comp.GetSemanticModel(withErrorTree) Assert.NotNull(bind) ' Add syntaxtree which is CS language comp = comp.AddSyntaxTrees(withErrorTreeCS) Assert.Equal(2, comp.GetDiagnostics().Length()) comp = comp.RemoveSyntaxTrees(withErrorTreeCS) Assert.Equal(0, comp.GetDiagnostics().Length()) comp = comp.AddSyntaxTrees(t1, withErrorTree, withErrorTree1, withErrorTreeCS) comp = comp.RemoveSyntaxTrees(t1, withErrorTree, withErrorTree1, withErrorTreeCS) ' Add a new empty item comp = comp.AddSyntaxTrees(Enumerable.Empty(Of SyntaxTree)) Assert.Equal(0, comp.SyntaxTrees.Length) ' Add a new valid item comp = comp.AddSyntaxTrees(t1) Assert.Equal(1, comp.SyntaxTrees.Length) comp = comp.AddSyntaxTrees(VisualBasicSyntaxTree.ParseText(s4)) Assert.Equal(2, comp.SyntaxTrees.Length) ' Replace an existing item with another valid item comp = comp.ReplaceSyntaxTree(t1, VisualBasicSyntaxTree.ParseText(s4)) Assert.Equal(2, comp.SyntaxTrees.Length) ' Replace an existing item with same item comp = comp.AddSyntaxTrees(t1).ReplaceSyntaxTree(t1, t1) Assert.Equal(3, comp.SyntaxTrees.Length) ' Replace with existing and verify that it throws Assert.Throws(Of ArgumentException)(Sub() comp.ReplaceSyntaxTree(t1, comp.SyntaxTrees(0))) Assert.Throws(Of ArgumentException)(Sub() comp.AddSyntaxTrees(t1)) ' SyntaxTrees have reference equality. This removal should fail. Assert.Throws(Of ArgumentException)(Sub() comp = comp.RemoveSyntaxTrees(VisualBasicSyntaxTree.ParseText(s4))) Assert.Equal(3, comp.SyntaxTrees.Length) ' Remove non-existing item Assert.Throws(Of ArgumentException)(Sub() comp = comp.RemoveSyntaxTrees(withErrorTree)) Assert.Equal(3, comp.SyntaxTrees.Length) Dim t4 = VisualBasicSyntaxTree.ParseText("Using System;") Dim t5 = VisualBasicSyntaxTree.ParseText("Usingsssssssssssss System;") Dim t6 = VisualBasicSyntaxTree.ParseText("Import System") ' Overload with Hashset Dim hs = New HashSet(Of SyntaxTree) From {t4, t5, t6} Dim compCollection = VisualBasicCompilation.Create("Compilation", syntaxTrees:=hs) compCollection = compCollection.RemoveSyntaxTrees(hs) Assert.Equal(0, compCollection.SyntaxTrees.Length) compCollection = compCollection.AddSyntaxTrees(hs).RemoveSyntaxTrees(t4, t5, t6) Assert.Equal(0, compCollection.SyntaxTrees.Length) ' Overload with Collection Dim col = New ObjectModel.Collection(Of SyntaxTree) From {t4, t5, t6} compCollection = VisualBasicCompilation.Create("Compilation", syntaxTrees:=col) compCollection = compCollection.RemoveSyntaxTrees(t4, t5, t6) Assert.Equal(0, compCollection.SyntaxTrees.Length) Assert.Throws(Of ArgumentException)(Sub() compCollection = compCollection.AddSyntaxTrees(t4, t5).RemoveSyntaxTrees(col)) Assert.Equal(0, compCollection.SyntaxTrees.Length) ' Overload with ConcurrentStack Dim stack = New Concurrent.ConcurrentStack(Of SyntaxTree) stack.Push(t4) stack.Push(t5) stack.Push(t6) compCollection = VisualBasicCompilation.Create("Compilation", syntaxTrees:=stack) compCollection = compCollection.RemoveSyntaxTrees(t4, t6, t5) Assert.Equal(0, compCollection.SyntaxTrees.Length) Assert.Throws(Of ArgumentException)(Sub() compCollection = compCollection.AddSyntaxTrees(t4, t6).RemoveSyntaxTrees(stack)) Assert.Equal(0, compCollection.SyntaxTrees.Length) ' Overload with ConcurrentQueue Dim queue = New Concurrent.ConcurrentQueue(Of SyntaxTree) queue.Enqueue(t4) queue.Enqueue(t5) queue.Enqueue(t6) compCollection = VisualBasicCompilation.Create("Compilation", syntaxTrees:=queue) compCollection = compCollection.RemoveSyntaxTrees(t4, t6, t5) Assert.Equal(0, compCollection.SyntaxTrees.Length) Assert.Throws(Of ArgumentException)(Sub() compCollection = compCollection.AddSyntaxTrees(t4, t6).RemoveSyntaxTrees(queue)) Assert.Equal(0, compCollection.SyntaxTrees.Length) ' VisualBasicCompilation.Create with syntaxtree with a non-CompilationUnit root node: should throw an ArgumentException. Assert.False(withExpressionRootTree.HasCompilationUnitRoot, "how did we get a CompilationUnit root?") Assert.Throws(Of ArgumentException)(Sub() VisualBasicCompilation.Create("Compilation", syntaxTrees:={withExpressionRootTree})) ' AddSyntaxTrees with a non-CompilationUnit root node: should throw an ArgumentException. Assert.Throws(Of ArgumentException)(Sub() comp.AddSyntaxTrees(withExpressionRootTree)) ' ReplaceSyntaxTrees syntaxtree with a non-CompilationUnit root node: should throw an ArgumentException. Assert.Throws(Of ArgumentException)(Sub() comp.ReplaceSyntaxTree(comp.SyntaxTrees(0), withExpressionRootTree)) End Sub <Fact> Public Sub ChainedOperations() Dim s1 = "using System.Linq;" Dim s2 = "" Dim s3 = "Import System" Dim t1 = VisualBasicSyntaxTree.ParseText(s1) Dim t2 = VisualBasicSyntaxTree.ParseText(s2) Dim t3 = VisualBasicSyntaxTree.ParseText(s3) Dim listSyntaxTree = New List(Of SyntaxTree) listSyntaxTree.Add(t1) listSyntaxTree.Add(t2) ' Remove second SyntaxTree Dim comp = VisualBasicCompilation.Create("Compilation") comp = comp.AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees(t2) Assert.Equal(1, comp.SyntaxTrees.Length) 'ContainsSyntaxTree Dim b1 As Boolean = comp.ContainsSyntaxTree(t2) Assert.Equal(Of Boolean)(False, b1) comp = comp.AddSyntaxTrees({t2}) b1 = comp.ContainsSyntaxTree(t2) Assert.Equal(Of Boolean)(True, b1) Dim xt As SyntaxTree = Nothing Assert.Throws(Of ArgumentNullException)(Sub() b1 = comp.ContainsSyntaxTree(xt) End Sub) comp = comp.RemoveSyntaxTrees({t2}) Assert.Equal(1, comp.SyntaxTrees.Length) comp = comp.AddSyntaxTrees({t2}) Assert.Equal(2, comp.SyntaxTrees.Length) 'RemoveAllSyntaxTrees comp = comp.RemoveAllSyntaxTrees Assert.Equal(0, comp.SyntaxTrees.Length) comp = VisualBasicCompilation.Create("Compilation").AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees({t2}) Assert.Equal(Of Integer)(1, comp.SyntaxTrees.Length) Assert.Equal(Of String)("Object", comp.ObjectType.Name) ' Remove mid SyntaxTree listSyntaxTree.Add(t3) comp = comp.RemoveSyntaxTrees(t1).AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees(t2) Assert.Equal(2, comp.SyntaxTrees.Length) ' remove list listSyntaxTree.Remove(t2) comp = comp.AddSyntaxTrees().RemoveSyntaxTrees(listSyntaxTree) comp = comp.AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees(listSyntaxTree) Assert.Equal(0, comp.SyntaxTrees.Length) listSyntaxTree.Clear() listSyntaxTree.Add(t1) ' Chained operation count > 2 comp = comp.AddSyntaxTrees(listSyntaxTree).AddReferences().ReplaceSyntaxTree(t1, t2) Assert.Equal(1, comp.SyntaxTrees.Length) Assert.Equal(0, comp.References.Count) ' Create compilation with args is disordered Dim comp1 = VisualBasicCompilation.Create("Compilation") Dim Err = "c:\file_that_does_not_exist" Dim ref1 = TestReferences.NetFx.v4_0_30319.mscorlib Dim listRef = New List(Of MetadataReference) ' this is NOT testing Roslyn listRef.Add(ref1) listRef.Add(ref1) ' Remove with no args comp1 = comp1.AddReferences(listRef).AddSyntaxTrees(listSyntaxTree).RemoveReferences().RemoveSyntaxTrees() 'should have only added one reference since ref1.Equals(ref1) and Equal references are added only once. Assert.Equal(1, comp1.References.Count) Assert.Equal(1, comp1.SyntaxTrees.Length) End Sub <WorkItem(713356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713356")> <Fact()> Public Sub MissedModuleA() Dim netModule1 = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="missing1"> <file name="a.vb"> Class C1 End Class </file> </compilation>, options:=TestOptions.ReleaseModule) netModule1.VerifyDiagnostics() Dim netModule2 = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="missing2"> <file name="a.vb"> Class C2 Public Shared Sub M() Dim a As New C1() End Sub End Class </file> </compilation>, additionalRefs:={netModule1.EmitToImageReference()}, options:=TestOptions.ReleaseModule) netModule2.VerifyDiagnostics() Dim assembly = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="missing"> <file name="a.vb"> Class C3 Public Shared Sub Main(args() As String) Dim a As New C2() End Sub End Class </file> </compilation>, additionalRefs:={netModule2.EmitToImageReference()}) assembly.VerifyDiagnostics(Diagnostic(ERRID.ERR_MissingNetModuleReference).WithArguments("missing1.netmodule")) assembly = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="MissedModuleA"> <file name="a.vb"> Class C3 Public Shared Sub Main(args() As String) Dim a As New C2() End Sub End Class </file> </compilation>, additionalRefs:={netModule1.EmitToImageReference(), netModule2.EmitToImageReference()}) assembly.VerifyDiagnostics() CompileAndVerify(assembly) End Sub <WorkItem(713356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713356")> <Fact()> Public Sub MissedModuleB_OneError() Dim netModule1 = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="a1"> <file name="a.vb"> Class C1 End Class </file> </compilation>, options:=TestOptions.ReleaseModule) CompilationUtils.AssertNoDiagnostics(netModule1) Dim netModule2 = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="a2"> <file name="a.vb"> Class C2 Public Shared Sub M() Dim a As New C1() End Sub End Class </file> </compilation>, additionalRefs:={netModule1.EmitToImageReference()}, options:=TestOptions.ReleaseModule) CompilationUtils.AssertNoDiagnostics(netModule2) Dim netModule3 = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="a3"> <file name="a.vb"> Class C22 Public Shared Sub M() Dim a As New C1() End Sub End Class </file> </compilation>, additionalRefs:={netModule1.EmitToImageReference()}, options:=TestOptions.ReleaseModule) CompilationUtils.AssertNoDiagnostics(netModule3) Dim assembly = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="a"> <file name="a.vb"> Class C3 Public Shared Sub Main(args() As String) Dim a As New C2() Dim b As New C22() End Sub End Class </file> </compilation>, additionalRefs:={netModule2.EmitToImageReference(), netModule3.EmitToImageReference()}) CompilationUtils.AssertTheseDiagnostics(assembly, <errors> BC37221: Reference to 'a1.netmodule' netmodule missing. </errors>) End Sub <WorkItem(718500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718500")> <WorkItem(716762, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716762")> <Fact()> Public Sub MissedModuleB_NoErrorForUnmanagedModules() Dim netModule1 = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="a1"> <file name="a.vb"> Imports System.Runtime.InteropServices Public Class ClassDLLImports Declare Function getUserName Lib "advapi32.dll" Alias "GetUserNameA" ( ByVal lpBuffer As String, ByRef nSize As Integer) As Integer End Class </file> </compilation>, options:=TestOptions.ReleaseModule) CompilationUtils.AssertNoDiagnostics(netModule1) Dim assembly = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="a"> <file name="a.vb"> Class C3 Public Shared Sub Main(args() As String) End Sub End Class </file> </compilation>, additionalRefs:={netModule1.EmitToImageReference(expectedWarnings:={ Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports System.Runtime.InteropServices")})}) assembly.AssertNoDiagnostics() End Sub <WorkItem(715872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715872")> <Fact()> Public Sub MissedModuleC() Dim netModule1 = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="a1"> <file name="a.vb"> Class C1 End Class </file> </compilation>, options:=TestOptions.ReleaseModule) CompilationUtils.AssertNoDiagnostics(netModule1) Dim netModule2 = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="a1"> <file name="a.vb"> Class C2 Public Shared Sub M() End Sub End Class </file> </compilation>, additionalRefs:={netModule1.EmitToImageReference()}, options:=TestOptions.ReleaseModule) CompilationUtils.AssertNoDiagnostics(netModule2) Dim assembly = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="a"> <file name="a.vb"> Class C3 Public Shared Sub Main(args() As String) Dim a As New C2() End Sub End Class </file> </compilation>, additionalRefs:={netModule1.EmitToImageReference(), netModule2.EmitToImageReference()}) CompilationUtils.AssertTheseDiagnostics(assembly, <errors> BC37224: Module 'a1.netmodule' is already defined in this assembly. Each module must have a unique filename. </errors>) End Sub <Fact> Public Sub MixedRefType() ' Create compilation takes three args Dim csComp = CS.CSharpCompilation.Create("CompilationVB") Dim comp = VisualBasicCompilation.Create("Compilation") ' this is NOT right path, ' please don't use VB dll (there is a change to the location in Dev11; you test will fail then) csComp = csComp.AddReferences(SystemRef) ' Add VB reference to C# compilation For Each item In csComp.References comp = comp.AddReferences(item) comp = comp.ReplaceReference(item, item) Next Assert.Equal(1, comp.References.Count) Dim text1 = "Imports System" Dim comp1 = VisualBasicCompilation.Create("Test1", {VisualBasicSyntaxTree.ParseText(text1)}) Dim comp2 = VisualBasicCompilation.Create("Test2", {VisualBasicSyntaxTree.ParseText(text1)}) Dim compRef1 = comp1.ToMetadataReference() Dim compRef2 = comp2.ToMetadataReference() Dim csCompRef = csComp.ToMetadataReference(embedInteropTypes:=True) Dim ref1 = TestReferences.NetFx.v4_0_30319.mscorlib Dim ref2 = TestReferences.NetFx.v4_0_30319.System ' Add VisualBasicCompilationReference comp = VisualBasicCompilation.Create("Test1", {VisualBasicSyntaxTree.ParseText(text1)}, {compRef1, compRef2}) Assert.Equal(2, comp.References.Count) Assert.Equal(MetadataImageKind.Assembly, comp.References(0).Properties.Kind) Assert.Contains(compRef1, comp.References) Assert.Contains(compRef2, comp.References) Dim smb = comp.GetReferencedAssemblySymbol(compRef1) Assert.Equal(smb.Kind, SymbolKind.Assembly) Assert.Equal("Test1", smb.Identity.Name, StringComparer.OrdinalIgnoreCase) ' Mixed reference type comp = comp.AddReferences(ref1) Assert.Equal(3, comp.References.Count) Assert.Contains(ref1, comp.References) ' Replace Compilation reference with Assembly file reference comp = comp.ReplaceReference(compRef2, ref2) Assert.Equal(3, comp.References.Count) Assert.Contains(ref2, comp.References) ' Replace Assembly file reference with Compilation reference comp = comp.ReplaceReference(ref1, compRef2) Assert.Equal(3, comp.References.Count) Assert.Contains(compRef2, comp.References) Dim modRef1 = ModuleMetadata.CreateFromImage(TestResources.MetadataTests.NetModule01.ModuleCS00).GetReference() ' Add Module file reference comp = comp.AddReferences(modRef1) ' Not Implemented 'Dim modSmb = comp.GetReferencedModuleSymbol(modRef1) 'Assert.Equal("ModuleCS00.mod", modSmb.Name) 'Assert.Equal(4, comp.References.Count) 'Assert.True(comp.References.Contains(modRef1)) ' Get Referenced Assembly Symbol 'smb = comp.GetReferencedAssemblySymbol(reference:=modRef1) 'Assert.Equal(smb.Kind, SymbolKind.Assembly) 'Assert.True(String.Equals(smb.AssemblyName.Name, "Test1", StringComparison.OrdinalIgnoreCase)) ' Get Referenced Module Symbol 'Dim moduleSmb = comp.GetReferencedModuleSymbol(reference:=modRef1) 'Assert.Equal(moduleSmb.Kind, SymbolKind.NetModule) 'Assert.True(String.Equals(moduleSmb.Name, "ModuleCS00.mod", StringComparison.OrdinalIgnoreCase)) ' Not implemented ' Get Compilation Namespace 'Dim nsSmb = comp.GlobalNamespace 'Dim ns = comp.GetCompilationNamespace(ns:=nsSmb) 'Assert.Equal(ns.Kind, SymbolKind.Namespace) 'Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)) ' Not implemented ' GetCompilationNamespace (Derived Class MergedNamespaceSymbol) 'Dim merged As NamespaceSymbol = MergedNamespaceSymbol.Create(New NamespaceExtent(New MockAssemblySymbol("Merged")), Nothing, Nothing) 'ns = comp.GetCompilationNamespace(ns:=merged) 'Assert.Equal(ns.Kind, SymbolKind.Namespace) 'Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)) ' Not implemented ' GetCompilationNamespace (Derived Class PENamespaceSymbol) 'Dim pensSmb As Metadata.PE.PENamespaceSymbol = CType(nsSmb, Metadata.PE.PENamespaceSymbol) 'ns = comp.GetCompilationNamespace(ns:=pensSmb) 'Assert.Equal(ns.Kind, SymbolKind.Namespace) 'Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)) ' Replace Module file reference with compilation reference comp = comp.RemoveReferences(compRef1).ReplaceReference(modRef1, compRef1) Assert.Equal(3, comp.References.Count) ' Check the reference order after replace Assert.Equal(MetadataImageKind.Assembly, comp.References(2).Properties.Kind) Assert.Equal(compRef1, comp.References(2)) ' Replace compilation Module file reference with Module file reference comp = comp.ReplaceReference(compRef1, modRef1) ' Check the reference order after replace Assert.Equal(3, comp.References.Count) Assert.Equal(MetadataImageKind.Module, comp.References(2).Properties.Kind) Assert.Equal(modRef1, comp.References(2)) ' Add CS compilation ref Assert.Throws(Of ArgumentException)(Function() comp.AddReferences(csCompRef)) For Each item In comp.References comp = comp.RemoveReferences(item) Next Assert.Equal(0, comp.References.Count) ' Not Implemented ' Dim asmByteRef = MetadataReference.CreateFromImage(New Byte(4) {}, "AssemblyBytesRef1", embedInteropTypes:=True) 'Dim asmObjectRef = New AssemblyObjectReference(assembly:=System.Reflection.Assembly.GetAssembly(GetType(Object)), embedInteropTypes:=True) 'comp = comp.AddReferences(asmByteRef, asmObjectRef) 'Assert.Equal(2, comp.References.Count) 'Assert.Equal(ReferenceKind.AssemblyBytes, comp.References(0).Kind) 'Assert.Equal(ReferenceKind.AssemblyObject, comp.References(1).Kind) 'Assert.Equal(asmByteRef, comp.References(0)) 'Assert.Equal(asmObjectRef, comp.References(1)) 'Assert.True(comp.References(0).EmbedInteropTypes) 'Assert.True(comp.References(1).EmbedInteropTypes) End Sub <Fact> Public Sub ModuleSuppliedAsAssembly() Dim comp = VisualBasicCompilation.Create("Compilation", references:={AssemblyMetadata.CreateFromImage(TestResources.MetadataTests.NetModule01.ModuleVB01).GetReference()}) Assert.Equal(comp.GetDiagnostics().First().Code, ERRID.ERR_MetaDataIsNotAssembly) End Sub <Fact> Public Sub AssemblySuppliedAsModule() Dim comp = VisualBasicCompilation.Create("Compilation", references:={ModuleMetadata.CreateFromImage(TestResources.NetFX.v4_0_30319.System).GetReference()}) Assert.Equal(comp.GetDiagnostics().First().Code, ERRID.ERR_MetaDataIsNotModule) End Sub '' Get nonexistent Referenced Assembly Symbol <WorkItem(537637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537637")> <Fact> Public Sub NegReference1() Dim comp = VisualBasicCompilation.Create("Compilation") Assert.Null(comp.GetReferencedAssemblySymbol(TestReferences.NetFx.v4_0_30319.System)) Dim modRef1 = ModuleMetadata.CreateFromImage(TestResources.MetadataTests.NetModule01.ModuleVB01).GetReference() Assert.Null(comp.GetReferencedModuleSymbol(modRef1)) End Sub '' Add already existing item <WorkItem(537617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537617")> <Fact> Public Sub NegReference2() Dim comp = VisualBasicCompilation.Create("Compilation") Dim ref1 = TestReferences.NetFx.v4_0_30319.System Dim ref2 = New TestMetadataReference(fullPath:="c:\a\xml.bms") Dim ref3 = ref2 Dim ref4 = New TestMetadataReference(fullPath:="c:\aaa.dll") comp = comp.AddReferences(ref1, ref1) Assert.Equal(1, comp.References.Count) Assert.Equal(ref1, comp.References(0)) ' Remove non-existing item Assert.Throws(Of ArgumentException)(Function() comp.RemoveReferences(ref2)) Dim listRef = New List(Of MetadataReference) From {ref1, ref2, ref3, ref4} comp = comp.AddReferences(listRef).AddReferences(ref2).ReplaceReference(ref2, ref2) Assert.Equal(3, comp.References.Count) comp = comp.RemoveReferences(listRef).AddReferences(ref1) Assert.Equal(1, comp.References.Count) Assert.Equal(ref1, comp.References(0)) End Sub '' Add a new invalid item <WorkItem(537575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537575")> <Fact> Public Sub NegReference3() Dim comp = VisualBasicCompilation.Create("Compilation") Dim ref1 = New TestMetadataReference(fullPath:="c:\xml.bms") Dim ref2 = TestReferences.NetFx.v4_0_30319.System comp = comp.AddReferences(ref1) Assert.Equal(1, comp.References.Count) ' Replace an non-existing item with another invalid item Assert.Throws(Of ArgumentException)(Sub() comp = comp.ReplaceReference(ref2, ref1) End Sub) Assert.Equal(1, comp.References.Count) End Sub '' Replace an non-existing item with null <WorkItem(537567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537567")> <Fact> Public Sub NegReference4() Dim opt = TestOptions.ReleaseExe Dim comp = VisualBasicCompilation.Create("Compilation") Dim ref1 = New TestMetadataReference(fullPath:="c:\xml.bms") Assert.Throws(Of ArgumentException)( Sub() comp.ReplaceReference(ref1, Nothing) End Sub) ' Replace null and the arg order of replace is vise Assert.Throws(Of ArgumentNullException)( Sub() comp.ReplaceReference(newReference:=ref1, oldReference:=Nothing) End Sub) End Sub '' Replace an non-existing item with another valid item <WorkItem(537566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537566")> <Fact> Public Sub NegReference5() Dim comp = VisualBasicCompilation.Create("Compilation") Dim ref1 = TestReferences.NetFx.v4_0_30319.mscorlib Dim ref2 = TestReferences.NetFx.v4_0_30319.System Assert.Throws(Of ArgumentException)( Sub() comp = comp.ReplaceReference(ref1, ref2) End Sub) Dim s1 = "Imports System.Text" Dim t1 = Parse(s1) ' Replace an non-existing item with another valid item and disorder the args Assert.Throws(Of ArgumentException)(Sub() comp.ReplaceSyntaxTree(newTree:=VisualBasicSyntaxTree.ParseText("Imports System"), oldTree:=t1) End Sub) Assert.Equal(0, comp.References.Count) End Sub '' Throw exception when add Nothing references <WorkItem(537618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537618")> <Fact> Public Sub NegReference6() Dim opt = TestOptions.ReleaseExe Dim comp = VisualBasicCompilation.Create("Compilation") Assert.Throws(Of ArgumentNullException)(Sub() comp = comp.AddReferences(Nothing)) End Sub '' Throw exception when remove Nothing references <WorkItem(537621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537621")> <Fact> Public Sub NegReference7() Dim opt = TestOptions.ReleaseExe Dim comp = VisualBasicCompilation.Create("Compilation") Dim RemoveNothingRefEx = Assert.Throws(Of ArgumentNullException)(Sub() comp = comp.RemoveReferences(Nothing)) End Sub '' Add already existing item <WorkItem(537576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537576")> <Fact> Public Sub NegSyntaxTree1() Dim opt = TestOptions.ReleaseExe Dim comp = VisualBasicCompilation.Create("Compilation") Dim t1 = VisualBasicSyntaxTree.ParseText("Using System;") Assert.Throws(Of ArgumentException)(Sub() comp.AddSyntaxTrees(t1, t1)) Assert.Equal(0, comp.SyntaxTrees.Length) End Sub ' Throw exception when the parameter of ContainsSyntaxTrees is null <WorkItem(527256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527256")> <Fact> Public Sub NegContainsSyntaxTrees() Dim opt = TestOptions.ReleaseExe Dim comp = VisualBasicCompilation.Create("Compilation") Assert.False(comp.SyntaxTrees.Contains(Nothing)) End Sub ' Throw exception when the parameter of AddReferences is CSharpCompilationReference <WorkItem(537778, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537778")> <Fact> Public Sub NegGetSymbol() Dim opt = TestOptions.ReleaseExe Dim comp = VisualBasicCompilation.Create("Compilation") Dim csComp = CS.CSharpCompilation.Create("CompilationCS") Dim compRef = csComp.ToMetadataReference() Assert.Throws(Of ArgumentException)(Function() comp.AddReferences(compRef)) '' Throw exception when the parameter of GetReferencedAssemblySymbol is null 'Assert.Throws(Of ArgumentNullException)(Sub() comp.GetReferencedAssemblySymbol(Nothing)) '' Throw exception when the parameter of GetReferencedModuleSymbol is null 'Assert.Throws(Of ArgumentNullException)( ' Sub() ' comp.GetReferencedModuleSymbol(Nothing) ' End Sub) End Sub '' Throw exception when the parameter of GetSpecialType is 'SpecialType.None' <WorkItem(537784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537784")> <Fact> Public Sub NegGetSpecialType() Dim comp = VisualBasicCompilation.Create("Compilation") Assert.Throws(Of ArgumentOutOfRangeException)( Sub() comp.GetSpecialType((SpecialType.None)) End Sub) ' Throw exception when the parameter of GetSpecialType is '0' Assert.Throws(Of ArgumentOutOfRangeException)( Sub() comp.GetSpecialType(CType(0, SpecialType)) End Sub) ' Throw exception when the parameter of GetBinding is out of range Assert.Throws(Of ArgumentOutOfRangeException)( Sub() comp.GetSpecialType(CType(100, SpecialType)) End Sub) ' Throw exception when the parameter of GetCompilationNamespace is null Assert.Throws(Of ArgumentNullException)( Sub() comp.GetCompilationNamespace(namespaceSymbol:=Nothing) End Sub) Dim bind = comp.GetSemanticModel(Nothing) Assert.NotNull(bind) End Sub <Fact> Public Sub NegSynTree() Dim comp = VisualBasicCompilation.Create("Compilation") Dim s1 = "Imports System.Text" Dim tree = VisualBasicSyntaxTree.ParseText(s1) ' Throw exception when add Nothing SyntaxTree Assert.Throws(Of ArgumentNullException)(Sub() comp.AddSyntaxTrees(Nothing)) ' Throw exception when Remove Nothing SyntaxTree Assert.Throws(Of ArgumentNullException)(Sub() comp.RemoveSyntaxTrees(Nothing)) ' Replace a tree with nothing (aka removing it) comp = comp.AddSyntaxTrees(tree).ReplaceSyntaxTree(tree, Nothing) Assert.Equal(0, comp.SyntaxTrees.Count) ' Throw exception when remove Nothing SyntaxTree Assert.Throws(Of ArgumentNullException)(Sub() comp = comp.ReplaceSyntaxTree(Nothing, tree)) Dim t1 = CS.SyntaxFactory.ParseSyntaxTree(s1) Dim t2 As SyntaxTree = t1 Dim t3 = t2 Dim csComp = CS.CSharpCompilation.Create("CompilationVB") csComp = csComp.AddSyntaxTrees(t1, CS.SyntaxFactory.ParseSyntaxTree("Imports Foo")) ' Throw exception when cast SyntaxTree For Each item In csComp.SyntaxTrees t3 = item Dim invalidCastSynTreeEx = Assert.Throws(Of InvalidCastException)(Sub() comp = comp.AddSyntaxTrees(CType(t3, VisualBasicSyntaxTree))) invalidCastSynTreeEx = Assert.Throws(Of InvalidCastException)(Sub() comp = comp.RemoveSyntaxTrees(CType(t3, VisualBasicSyntaxTree))) invalidCastSynTreeEx = Assert.Throws(Of InvalidCastException)(Sub() comp = comp.ReplaceSyntaxTree(CType(t3, VisualBasicSyntaxTree), CType(t3, VisualBasicSyntaxTree))) Next End Sub <Fact> Public Sub RootNSIllegalIdentifiers() AssertTheseDiagnostics(TestOptions.ReleaseExe.WithRootNamespace("[[Global]]").Errors, <expected> BC2014: the value '[[Global]]' is invalid for option 'RootNamespace' </expected>) AssertTheseDiagnostics(TestOptions.ReleaseExe.WithRootNamespace("From()").Errors, <expected> BC2014: the value 'From()' is invalid for option 'RootNamespace' </expected>) AssertTheseDiagnostics(TestOptions.ReleaseExe.WithRootNamespace("x$").Errors, <expected> BC2014: the value 'x$' is invalid for option 'RootNamespace' </expected>) AssertTheseDiagnostics(TestOptions.ReleaseExe.WithRootNamespace("Foo.").Errors, <expected> BC2014: the value 'Foo.' is invalid for option 'RootNamespace' </expected>) AssertTheseDiagnostics(TestOptions.ReleaseExe.WithRootNamespace("_").Errors, <expected> BC2014: the value '_' is invalid for option 'RootNamespace' </expected>) End Sub <Fact> Public Sub AmbiguousNestedTypeSymbolFromMetadata() Dim code = "Class A : Class B : End Class : End Class" Dim c1 = VisualBasicCompilation.Create("Asm1", syntaxTrees:={VisualBasicSyntaxTree.ParseText(code)}) Dim c2 = VisualBasicCompilation.Create("Asm2", syntaxTrees:={VisualBasicSyntaxTree.ParseText(code)}) Dim c3 = VisualBasicCompilation.Create("Asm3", references:={c1.ToMetadataReference(), c2.ToMetadataReference()}) Assert.Null(c3.GetTypeByMetadataName("A+B")) End Sub <Fact> Public Sub DuplicateNestedTypeSymbol() Dim code = "Class A : Class B : End Class : Class B : End Class : End Class" Dim c1 = VisualBasicCompilation.Create("Asm1", syntaxTrees:={VisualBasicSyntaxTree.ParseText(code)}) Assert.Equal("A.B", c1.GetTypeByMetadataName("A+B").ToDisplayString()) End Sub <Fact()> <WorkItem(543211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543211")> Public Sub TreeDiagnosticsShouldNotIncludeEntryPointDiagnostics() Dim code1 = "Module M : Sub Main : End Sub : End Module" Dim code2 = " " Dim tree1 = VisualBasicSyntaxTree.ParseText(code1) Dim tree2 = VisualBasicSyntaxTree.ParseText(code2) Dim comp = VisualBasicCompilation.Create( "Test", syntaxTrees:={tree1, tree2}) Dim semanticModel2 = comp.GetSemanticModel(tree2) Dim diagnostics2 = semanticModel2.GetDiagnostics() Assert.Equal(0, diagnostics2.Length()) End Sub <Fact()> <WorkItem(543292, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543292")> Public Sub CompilationStackOverflow() Dim compilation = VisualBasicCompilation.Create("HelloWorld") Assert.Throws(Of NotSupportedException)(Function() compilation.DynamicType) Assert.Throws(Of NotSupportedException)(Function() compilation.CreatePointerTypeSymbol(Nothing)) End Sub <Fact()> Public Sub GetEntryPoint_Exe() Dim source = <compilation name="Name1"> <file name="a.vb"><![CDATA[ Class A Shared Sub Main() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, OutputKind.ConsoleApplication) compilation.VerifyDiagnostics() Dim mainMethod = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A").GetMember(Of MethodSymbol)("Main") Assert.Equal(mainMethod, compilation.GetEntryPoint(Nothing)) Dim entryPointAndDiagnostics = compilation.GetEntryPointAndDiagnostics(Nothing) Assert.Equal(mainMethod, entryPointAndDiagnostics.MethodSymbol) entryPointAndDiagnostics.Diagnostics.Verify() End Sub <Fact()> Public Sub GetEntryPoint_Dll() Dim source = <compilation name="Name1"> <file name="a.vb"><![CDATA[ Class A Shared Sub Main() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, OutputKind.DynamicallyLinkedLibrary) compilation.VerifyDiagnostics() Assert.Null(compilation.GetEntryPoint(Nothing)) Assert.Null(compilation.GetEntryPointAndDiagnostics(Nothing)) End Sub <Fact()> Public Sub GetEntryPoint_Module() Dim source = <compilation name="Name1"> <file name="a.vb"><![CDATA[ Class A Shared Sub Main() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, OutputKind.NetModule) compilation.VerifyDiagnostics() Assert.Null(compilation.GetEntryPoint(Nothing)) Assert.Null(compilation.GetEntryPointAndDiagnostics(Nothing)) End Sub <Fact> Public Sub CreateCompilationForModule() Dim source = <text> Class A Shared Sub Main() End Sub End Class </text>.Value ' equivalent of vbc with no /moduleassemblyname specified: Dim c = VisualBasicCompilation.Create(assemblyName:=Nothing, options:=TestOptions.ReleaseModule, syntaxTrees:={Parse(source)}, references:={MscorlibRef}) c.VerifyDiagnostics() Assert.Null(c.AssemblyName) Assert.Equal("?", c.Assembly.Name) Assert.Equal("?", c.Assembly.Identity.Name) ' no name is allowed for assembly as well, although it isn't useful: c = VisualBasicCompilation.Create(assemblyName:=Nothing, options:=TestOptions.ReleaseModule, syntaxTrees:={Parse(source)}, references:={MscorlibRef}) c.VerifyDiagnostics() Assert.Null(c.AssemblyName) Assert.Equal("?", c.Assembly.Name) Assert.Equal("?", c.Assembly.Identity.Name) ' equivalent of vbc with /moduleassemblyname specified: c = VisualBasicCompilation.Create(assemblyName:="ModuleAssemblyName", options:=TestOptions.ReleaseModule, syntaxTrees:={Parse(source)}, references:={MscorlibRef}) c.VerifyDiagnostics() Assert.Equal("ModuleAssemblyName", c.AssemblyName) Assert.Equal("ModuleAssemblyName", c.Assembly.Name) Assert.Equal("ModuleAssemblyName", c.Assembly.Identity.Name) End Sub <WorkItem(3719, "https://github.com/dotnet/roslyn/issues/3719")> <Fact()> Public Sub GetEntryPoint_Script() Dim source = <![CDATA[System.Console.WriteLine(1)]]> Dim compilation = CreateCompilationWithMscorlib45({VisualBasicSyntaxTree.ParseText(source.Value, options:=TestOptions.Script)}, options:=TestOptions.ReleaseDll) compilation.VerifyDiagnostics() Dim scriptMethod = compilation.GetMember("Script.<Main>") Assert.NotNull(scriptMethod) Dim method = compilation.GetEntryPoint(Nothing) Assert.Equal(method, scriptMethod) Dim entryPoint = compilation.GetEntryPointAndDiagnostics(Nothing) Assert.Equal(entryPoint.MethodSymbol, scriptMethod) End Sub <Fact()> Public Sub GetEntryPoint_Script_MainIgnored() Dim source = <![CDATA[ Class A Shared Sub Main() End Sub End Class ]]> Dim compilation = CreateCompilationWithMscorlib45({VisualBasicSyntaxTree.ParseText(source.Value, options:=TestOptions.Script)}, options:=TestOptions.ReleaseDll) compilation.VerifyDiagnostics(Diagnostic(ERRID.WRN_MainIgnored, "Main").WithArguments("Public Shared Sub Main()").WithLocation(3, 20)) Dim scriptMethod = compilation.GetMember("Script.<Main>") Assert.NotNull(scriptMethod) Dim entryPoint = compilation.GetEntryPointAndDiagnostics(Nothing) Assert.Equal(entryPoint.MethodSymbol, scriptMethod) entryPoint.Diagnostics.Verify(Diagnostic(ERRID.WRN_MainIgnored, "Main").WithArguments("Public Shared Sub Main()").WithLocation(3, 20)) End Sub <Fact()> Public Sub GetEntryPoint_Submission() Dim source = "? 1 + 1" Dim compilation = VisualBasicCompilation.CreateScriptCompilation( "sub", references:={MscorlibRef}, syntaxTree:=Parse(source, options:=TestOptions.Script)) compilation.VerifyDiagnostics() Dim scriptMethod = compilation.GetMember("Script.<Factory>") Assert.NotNull(scriptMethod) Dim method = compilation.GetEntryPoint(Nothing) Assert.Equal(method, scriptMethod) Dim entryPoint = compilation.GetEntryPointAndDiagnostics(Nothing) Assert.Equal(entryPoint.MethodSymbol, scriptMethod) entryPoint.Diagnostics.Verify() End Sub <Fact()> Public Sub GetEntryPoint_Submission_MainIgnored() Dim source = " Class A Shared Sub Main() End Sub End Class " Dim compilation = VisualBasicCompilation.CreateScriptCompilation( "Sub", references:={MscorlibRef}, syntaxTree:=Parse(source, options:=TestOptions.Script)) compilation.VerifyDiagnostics(Diagnostic(ERRID.WRN_MainIgnored, "Main").WithArguments("Public Shared Sub Main()").WithLocation(3, 20)) Dim scriptMethod = compilation.GetMember("Script.<Factory>") Assert.NotNull(scriptMethod) Dim entryPoint = compilation.GetEntryPointAndDiagnostics(Nothing) Assert.Equal(entryPoint.MethodSymbol, scriptMethod) entryPoint.Diagnostics.Verify(Diagnostic(ERRID.WRN_MainIgnored, "Main").WithArguments("Public Shared Sub Main()").WithLocation(3, 20)) End Sub <Fact()> Public Sub GetEntryPoint_MainType() Dim source = <compilation name="Name1"> <file name="a.vb"><![CDATA[ Class A Shared Sub Main() End Sub End Class Class B Shared Sub Main() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseExe.WithMainTypeName("B")) compilation.VerifyDiagnostics() Dim mainMethod = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B").GetMember(Of MethodSymbol)("Main") Assert.Equal(mainMethod, compilation.GetEntryPoint(Nothing)) Dim entryPointAndDiagnostics = compilation.GetEntryPointAndDiagnostics(Nothing) Assert.Equal(mainMethod, entryPointAndDiagnostics.MethodSymbol) entryPointAndDiagnostics.Diagnostics.Verify() End Sub <Fact> Public Sub ReferenceManagerReuse_WithOptions() Dim c1 = VisualBasicCompilation.Create("c", options:=TestOptions.ReleaseDll) Dim c2 = c1.WithOptions(TestOptions.ReleaseExe) Assert.True(c1.ReferenceManagerEquals(c2)) c2 = c1.WithOptions(New VisualBasicCompilationOptions(OutputKind.WindowsApplication)) Assert.True(c1.ReferenceManagerEquals(c2)) c2 = c1.WithOptions(TestOptions.ReleaseModule) Assert.False(c1.ReferenceManagerEquals(c2)) c1 = VisualBasicCompilation.Create("c", options:=TestOptions.ReleaseModule) c2 = c1.WithOptions(TestOptions.ReleaseExe) Assert.False(c1.ReferenceManagerEquals(c2)) c2 = c1.WithOptions(TestOptions.ReleaseDll) Assert.False(c1.ReferenceManagerEquals(c2)) c2 = c1.WithOptions(New VisualBasicCompilationOptions(OutputKind.WindowsApplication)) Assert.False(c1.ReferenceManagerEquals(c2)) End Sub <Fact> Public Sub ReferenceManagerReuse_WithPreviousSubmission() Dim s1 = VisualBasicCompilation.CreateScriptCompilation("s1") Dim s2 = VisualBasicCompilation.CreateScriptCompilation("s2") Dim s3 = s2.WithScriptCompilationInfo(s2.ScriptCompilationInfo.WithPreviousScriptCompilation(s1)) Assert.True(s2.ReferenceManagerEquals(s3)) End Sub <Fact> Public Sub ReferenceManagerReuse_WithXmlFileResolver() Dim c1 = VisualBasicCompilation.Create("c", options:=TestOptions.ReleaseDll) Dim c2 = c1.WithOptions(TestOptions.ReleaseDll.WithXmlReferenceResolver(New XmlFileResolver(Nothing))) Assert.False(c1.ReferenceManagerEquals(c2)) Dim c3 = c1.WithOptions(TestOptions.ReleaseDll.WithXmlReferenceResolver(c1.Options.XmlReferenceResolver)) Assert.True(c1.ReferenceManagerEquals(c3)) End Sub <Fact> Public Sub ReferenceManagerReuse_WithMetadataReferenceResolver() Dim c1 = VisualBasicCompilation.Create("c", options:=TestOptions.ReleaseDll) Dim c2 = c1.WithOptions(TestOptions.ReleaseDll.WithMetadataReferenceResolver(New TestMetadataReferenceResolver())) Assert.False(c1.ReferenceManagerEquals(c2)) Dim c3 = c1.WithOptions(TestOptions.ReleaseDll.WithMetadataReferenceResolver(c1.Options.MetadataReferenceResolver)) Assert.True(c1.ReferenceManagerEquals(c3)) End Sub <Fact> Public Sub ReferenceManagerReuse_WithName() Dim c1 = VisualBasicCompilation.Create("c1") Dim c2 = c1.WithAssemblyName("c2") Assert.False(c1.ReferenceManagerEquals(c2)) Dim c3 = c1.WithAssemblyName("c1") Assert.True(c1.ReferenceManagerEquals(c3)) Dim c4 = c1.WithAssemblyName(Nothing) Assert.False(c1.ReferenceManagerEquals(c4)) Dim c5 = c4.WithAssemblyName(Nothing) Assert.True(c4.ReferenceManagerEquals(c5)) End Sub <Fact> Public Sub ReferenceManagerReuse_WithReferences() Dim c1 = VisualBasicCompilation.Create("c1") Dim c2 = c1.WithReferences({MscorlibRef}) Assert.False(c1.ReferenceManagerEquals(c2)) Dim c3 = c2.WithReferences({MscorlibRef, SystemCoreRef}) Assert.False(c3.ReferenceManagerEquals(c2)) c3 = c2.AddReferences(SystemCoreRef) Assert.False(c3.ReferenceManagerEquals(c2)) c3 = c2.RemoveAllReferences() Assert.False(c3.ReferenceManagerEquals(c2)) c3 = c2.ReplaceReference(MscorlibRef, SystemCoreRef) Assert.False(c3.ReferenceManagerEquals(c2)) c3 = c2.RemoveReferences(MscorlibRef) Assert.False(c3.ReferenceManagerEquals(c2)) End Sub <Fact> Public Sub ReferenceManagerReuse_WithSyntaxTrees() Dim ta = Parse("Imports System") Dim tb = Parse("Imports System", options:=TestOptions.Script) Dim tc = Parse("#r ""bar"" ' error: #r in regular code") Dim tr = Parse("#r ""foo""", options:=TestOptions.Script) Dim ts = Parse("#r ""bar""", options:=TestOptions.Script) Dim a = VisualBasicCompilation.Create("c", syntaxTrees:={ta}) ' add: Dim ab = a.AddSyntaxTrees(tb) Assert.True(a.ReferenceManagerEquals(ab)) Dim ac = a.AddSyntaxTrees(tc) Assert.True(a.ReferenceManagerEquals(ac)) Dim ar = a.AddSyntaxTrees(tr) Assert.False(a.ReferenceManagerEquals(ar)) Dim arc = ar.AddSyntaxTrees(tc) Assert.True(ar.ReferenceManagerEquals(arc)) ' remove: Dim ar2 = arc.RemoveSyntaxTrees(tc) Assert.True(arc.ReferenceManagerEquals(ar2)) Dim c = arc.RemoveSyntaxTrees(ta, tr) Assert.False(arc.ReferenceManagerEquals(c)) Dim none1 = c.RemoveSyntaxTrees(tc) Assert.True(c.ReferenceManagerEquals(none1)) Dim none2 = arc.RemoveAllSyntaxTrees() Assert.False(arc.ReferenceManagerEquals(none2)) Dim none3 = ac.RemoveAllSyntaxTrees() Assert.True(ac.ReferenceManagerEquals(none3)) ' replace: Dim asc = arc.ReplaceSyntaxTree(tr, ts) Assert.False(arc.ReferenceManagerEquals(asc)) Dim brc = arc.ReplaceSyntaxTree(ta, tb) Assert.True(arc.ReferenceManagerEquals(brc)) Dim abc = arc.ReplaceSyntaxTree(tr, tb) Assert.False(arc.ReferenceManagerEquals(abc)) Dim ars = arc.ReplaceSyntaxTree(tc, ts) Assert.False(arc.ReferenceManagerEquals(ars)) End Sub Private Class EvolvingTestReference Inherits PortableExecutableReference Private ReadOnly _metadataSequence As IEnumerator(Of Metadata) Public QueryCount As Integer Public Sub New(metadataSequence As IEnumerable(Of Metadata)) MyBase.New(MetadataReferenceProperties.Assembly) Me._metadataSequence = metadataSequence.GetEnumerator() End Sub Protected Overrides Function CreateDocumentationProvider() As DocumentationProvider Return DocumentationProvider.Default End Function Protected Overrides Function GetMetadataImpl() As Metadata QueryCount = QueryCount + 1 _metadataSequence.MoveNext() Return _metadataSequence.Current End Function Protected Overrides Function WithPropertiesImpl(properties As MetadataReferenceProperties) As PortableExecutableReference Throw New NotImplementedException() End Function End Class <Fact> Public Sub MetadataConsistencyWhileEvolvingCompilation() Dim md1 = AssemblyMetadata.CreateFromImage(CreateCompilationWithMscorlib({"Public Class C : End Class"}, options:=TestOptions.ReleaseDll).EmitToArray()) Dim md2 = AssemblyMetadata.CreateFromImage(CreateCompilationWithMscorlib({"Public Class D : End Class"}, options:=TestOptions.ReleaseDll).EmitToArray()) Dim reference = New EvolvingTestReference({md1, md2}) Dim c1 = CreateCompilationWithMscorlib({"Public Class Main : Public Shared C As C : End Class"}, {reference, reference}, options:=TestOptions.ReleaseDll) Dim c2 = c1.WithAssemblyName("c2") Dim c3 = c2.AddSyntaxTrees(Parse("Public Class Main2 : Public Shared A As Integer : End Class")) Dim c4 = c3.WithOptions(New VisualBasicCompilationOptions(OutputKind.NetModule)) Dim c5 = c4.WithReferences({MscorlibRef, reference}) c3.VerifyDiagnostics() c1.VerifyDiagnostics() c4.VerifyDiagnostics() c2.VerifyDiagnostics() Assert.Equal(1, reference.QueryCount) c5.VerifyDiagnostics(Diagnostic(ERRID.ERR_UndefinedType1, "C").WithArguments("C").WithLocation(1, 40)) Assert.Equal(2, reference.QueryCount) End Sub <Fact> Public Sub LinkedNetmoduleMetadataMustProvideFullPEImage() Dim moduleBytes = TestResources.MetadataTests.NetModule01.ModuleCS00 Dim headers = New PEHeaders(New MemoryStream(moduleBytes)) Dim pinnedPEImage = GCHandle.Alloc(moduleBytes.ToArray(), GCHandleType.Pinned) Try Using mdModule = ModuleMetadata.CreateFromMetadata(pinnedPEImage.AddrOfPinnedObject() + headers.MetadataStartOffset, headers.MetadataSize) Dim c = VisualBasicCompilation.Create("Foo", references:={MscorlibRef, mdModule.GetReference(display:="ModuleCS00")}, options:=TestOptions.ReleaseDll) c.VerifyDiagnostics(Diagnostic(ERRID.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage).WithArguments("ModuleCS00").WithLocation(1, 1)) End Using Finally pinnedPEImage.Free() End Try End Sub <Fact> <WorkItem(797640, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797640")> Public Sub GetMetadataReferenceAPITest() Dim comp = VisualBasicCompilation.Create("Compilation") Dim metadata = TestReferences.NetFx.v4_0_30319.mscorlib comp = comp.AddReferences(metadata) Dim assemblySmb = comp.GetReferencedAssemblySymbol(metadata) Dim reference = comp.GetMetadataReference(assemblySmb) Assert.NotNull(reference) Dim comp2 = VisualBasicCompilation.Create("Compilation") comp2 = comp.AddReferences(metadata) Dim reference2 = comp2.GetMetadataReference(assemblySmb) Assert.NotNull(reference2) End Sub <Fact()> Public Sub EqualityOfMergedNamespaces() Dim moduleComp = CompilationUtils.CreateCompilationWithoutReferences( <compilation> <file name="a.vb"> Namespace NS1 Namespace NS3 Interface T1 End Interface End Namespace End Namespace Namespace NS2 Namespace NS3 Interface T2 End Interface End Namespace End Namespace </file> </compilation>, TestOptions.ReleaseModule) Dim compilation = CompilationUtils.CreateCompilationWithReferences( <compilation> <file name="a.vb"> Namespace NS1 Namespace NS3 Interface T3 End Interface End Namespace End Namespace Namespace NS2 Namespace NS3 Interface T4 End Interface End Namespace End Namespace </file> </compilation>, {moduleComp.EmitToImageReference()}) TestEqualityRecursive(compilation.GlobalNamespace, compilation.GlobalNamespace, NamespaceKind.Compilation, Function(ns) compilation.GetCompilationNamespace(ns)) TestEqualityRecursive(compilation.Assembly.GlobalNamespace, compilation.Assembly.GlobalNamespace, NamespaceKind.Assembly, Function(ns) compilation.Assembly.GetAssemblyNamespace(ns)) End Sub Private Shared Sub TestEqualityRecursive(testNs1 As NamespaceSymbol, testNs2 As NamespaceSymbol, kind As NamespaceKind, factory As Func(Of NamespaceSymbol, NamespaceSymbol)) Assert.Equal(kind, testNs1.NamespaceKind) Assert.Same(testNs1, testNs2) Dim children1 = testNs1.GetMembers().OrderBy(Function(m) m.Name).ToArray() Dim children2 = testNs2.GetMembers().OrderBy(Function(m) m.Name).ToArray() For i = 0 To children1.Count - 1 Assert.Same(children1(i), children2(i)) If children1(i).Kind = SymbolKind.Namespace Then TestEqualityRecursive(DirectCast(testNs1.GetMembers(children1(i).Name).Single(), NamespaceSymbol), DirectCast(testNs1.GetMembers(children1(i).Name).Single(), NamespaceSymbol), kind, factory) End If Next Assert.Same(testNs1, factory(testNs1)) For Each constituent In testNs1.ConstituentNamespaces Assert.Same(testNs1, factory(constituent)) Next End Sub <Fact> Public Sub ConsistentParseOptions() Dim tree1 = SyntaxFactory.ParseSyntaxTree("", VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) Dim tree2 = SyntaxFactory.ParseSyntaxTree("", VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)) Dim tree3 = SyntaxFactory.ParseSyntaxTree("", VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic11)) Dim assemblyName = GetUniqueName() Dim CompilationOptions = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary) VisualBasicCompilation.Create(assemblyName, {tree1, tree2}, {MscorlibRef}, CompilationOptions) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.Create(assemblyName, {tree1, tree3}, {MscorlibRef}, CompilationOptions)) End Sub <Fact> Public Sub SubmissionCompilation_Errors() Dim genericParameter = GetType(List(Of)).GetGenericArguments()(0) Dim open = GetType(Dictionary(Of,)).MakeGenericType(GetType(Integer), genericParameter) Dim ptr = GetType(Integer).MakePointerType() Dim byRefType = GetType(Integer).MakeByRefType() Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", returnType:=genericParameter)) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", returnType:=open)) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", returnType:=GetType(Void))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", returnType:=byRefType)) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", globalsType:=genericParameter)) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", globalsType:=open)) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", globalsType:=GetType(Void))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", globalsType:=GetType(Integer))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", globalsType:=ptr)) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", globalsType:=byRefType)) Dim s0 = VisualBasicCompilation.CreateScriptCompilation("a0", globalsType:=GetType(List(Of Integer))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a1", previousScriptCompilation:=s0, globalsType:=GetType(List(Of Boolean)))) ' invalid options Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", options:=TestOptions.ReleaseExe)) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", options:=TestOptions.ReleaseDll.WithOutputKind(OutputKind.NetModule))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", options:=TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeMetadata))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", options:=TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeApplication))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", options:=TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsApplication))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", options:=TestOptions.ReleaseDll.WithCryptoKeyContainer("foo"))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", options:=TestOptions.ReleaseDll.WithCryptoKeyFile("foo.snk"))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", options:=TestOptions.ReleaseDll.WithDelaySign(True))) Assert.Throws(Of ArgumentException)(Function() VisualBasicCompilation.CreateScriptCompilation("a", options:=TestOptions.ReleaseDll.WithDelaySign(False))) End Sub <Fact> Public Sub HasSubmissionResult() Assert.False(VisualBasicCompilation.CreateScriptCompilation("sub").HasSubmissionResult()) Assert.True(CreateSubmission("?1", parseOptions:=TestOptions.Script).HasSubmissionResult()) Assert.False(CreateSubmission("1", parseOptions:=TestOptions.Script).HasSubmissionResult()) ' TODO (https://github.com/dotnet/roslyn/issues/4763): '?' should be optional ' TestSubmissionResult(CreateSubmission("1", parseOptions:=TestOptions.Interactive), expectedType:=SpecialType.System_Int32, expectedHasValue:=True) ' TODO (https://github.com/dotnet/roslyn/issues/4766): ReturnType should not be ignored ' TestSubmissionResult(CreateSubmission("?1", parseOptions:=TestOptions.Interactive, returnType:=GetType(Double)), expectedType:=SpecialType.System_Double, expectedHasValue:=True) Assert.False(CreateSubmission(" Sub Foo() End Sub ").HasSubmissionResult()) Assert.False(CreateSubmission("Imports System", parseOptions:=TestOptions.Script).HasSubmissionResult()) Assert.False(CreateSubmission("Dim i As Integer", parseOptions:=TestOptions.Script).HasSubmissionResult()) Assert.False(CreateSubmission("System.Console.WriteLine()", parseOptions:=TestOptions.Script).HasSubmissionResult()) Assert.True(CreateSubmission("?System.Console.WriteLine()", parseOptions:=TestOptions.Script).HasSubmissionResult()) Assert.True(CreateSubmission("System.Console.ReadLine()", parseOptions:=TestOptions.Script).HasSubmissionResult()) Assert.True(CreateSubmission("?System.Console.ReadLine()", parseOptions:=TestOptions.Script).HasSubmissionResult()) Assert.True(CreateSubmission("?Nothing", parseOptions:=TestOptions.Script).HasSubmissionResult()) Assert.True(CreateSubmission("?AddressOf System.Console.WriteLine", parseOptions:=TestOptions.Script).HasSubmissionResult()) Assert.True(CreateSubmission("?Function(x) x", parseOptions:=TestOptions.Script).HasSubmissionResult()) End Sub ''' <summary> ''' Previous submission has to have no errors. ''' </summary> <Fact> Public Sub PreviousSubmissionWithError() Dim s0 = CreateSubmission("Dim a As X = 1") s0.VerifyDiagnostics( Diagnostic(ERRID.ERR_UndefinedType1, "X").WithArguments("X")) Assert.Throws(Of InvalidOperationException)(Function() CreateSubmission("?a + 1", previous:=s0)) End Sub End Class End Namespace
sharadagrawal/Roslyn
src/Compilers/VisualBasic/Test/Semantic/Compilation/CompilationAPITests.vb
Visual Basic
apache-2.0
83,625
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class frmMining Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.components = New System.ComponentModel.Container() Dim ChartArea1 As System.Windows.Forms.DataVisualization.Charting.ChartArea = New System.Windows.Forms.DataVisualization.Charting.ChartArea() Dim Legend1 As System.Windows.Forms.DataVisualization.Charting.Legend = New System.Windows.Forms.DataVisualization.Charting.Legend() Dim Series1 As System.Windows.Forms.DataVisualization.Charting.Series = New System.Windows.Forms.DataVisualization.Charting.Series() Dim ChartArea2 As System.Windows.Forms.DataVisualization.Charting.ChartArea = New System.Windows.Forms.DataVisualization.Charting.ChartArea() Dim Legend2 As System.Windows.Forms.DataVisualization.Charting.Legend = New System.Windows.Forms.DataVisualization.Charting.Legend() Dim Series2 As System.Windows.Forms.DataVisualization.Charting.Series = New System.Windows.Forms.DataVisualization.Charting.Series() Dim ChartArea3 As System.Windows.Forms.DataVisualization.Charting.ChartArea = New System.Windows.Forms.DataVisualization.Charting.ChartArea() Dim Series3 As System.Windows.Forms.DataVisualization.Charting.Series = New System.Windows.Forms.DataVisualization.Charting.Series() Dim DataGridViewCellStyle1 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle2 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle3 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle4 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle5 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle6 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle7 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle8 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle9 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle10 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmMining)) Me.btnRefresh = New System.Windows.Forms.Button() Me.Chart1 = New System.Windows.Forms.DataVisualization.Charting.Chart() Me.chtCurCont = New System.Windows.Forms.DataVisualization.Charting.Chart() Me.lbltxtAvgCredits = New System.Windows.Forms.Label() Me.lblThanks = New System.Windows.Forms.Label() Me.lblWhitelistedProjects = New System.Windows.Forms.Label() Me.tOneMinute = New System.Windows.Forms.Timer(Me.components) Me.btnHide = New System.Windows.Forms.Button() Me.MenuStrip1 = New System.Windows.Forms.MenuStrip() Me.FileToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.HideToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ConfigurationToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ContractDetailsToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.TabControl1 = New System.Windows.Forms.TabControl() Me.GroupBox4 = New System.Windows.Forms.GroupBox() Me.GroupBox3 = New System.Windows.Forms.GroupBox() Me.RichTextBox1 = New System.Windows.Forms.RichTextBox() Me.GroupBox2 = New System.Windows.Forms.GroupBox() Me.ChartHashRate = New System.Windows.Forms.DataVisualization.Charting.Chart() Me.GroupBox1 = New System.Windows.Forms.GroupBox() Me.pbCgminer = New System.Windows.Forms.PictureBox() Me.TabPage1 = New System.Windows.Forms.TabPage() Me.WebBrowserBoinc = New System.Windows.Forms.WebBrowser() Me.TabPage2 = New System.Windows.Forms.TabPage() Me.dgv = New System.Windows.Forms.DataGridView() Me.lblWarning = New System.Windows.Forms.Label() Me.btnExport = New System.Windows.Forms.Button() Me.txtSearch = New System.Windows.Forms.TextBox() Me.Label1 = New System.Windows.Forms.Label() Me.lblTestnet = New System.Windows.Forms.Label() Me.dgvProjects = New System.Windows.Forms.DataGridView() Me.lblTotalProjects = New System.Windows.Forms.Label() Me.Label3 = New System.Windows.Forms.Label() Me.pbSync = New System.Windows.Forms.ProgressBar() Me.TimerSync = New System.Windows.Forms.Timer(Me.components) Me.lblLastSynced = New System.Windows.Forms.Label() Me.lblCPID = New System.Windows.Forms.Label() Me.lblSuperblockAge = New System.Windows.Forms.Label() Me.lblQuorumHash = New System.Windows.Forms.Label() Me.lblTimestamp = New System.Windows.Forms.Label() Me.lblBlock = New System.Windows.Forms.Label() Me.btnSync = New System.Windows.Forms.Button() Me.lblQueue = New System.Windows.Forms.Label() Me.lblNeuralDetail = New System.Windows.Forms.Label() Me.lblAvgMagnitude = New System.Windows.Forms.Label() CType(Me.Chart1, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.chtCurCont, System.ComponentModel.ISupportInitialize).BeginInit() Me.MenuStrip1.SuspendLayout() Me.TabControl1.SuspendLayout() Me.GroupBox3.SuspendLayout() Me.GroupBox2.SuspendLayout() CType(Me.ChartHashRate, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.pbCgminer, System.ComponentModel.ISupportInitialize).BeginInit() Me.TabPage1.SuspendLayout() Me.TabPage2.SuspendLayout() CType(Me.dgv, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.dgvProjects, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'btnRefresh ' Me.btnRefresh.Location = New System.Drawing.Point(14, 734) Me.btnRefresh.Name = "btnRefresh" Me.btnRefresh.Size = New System.Drawing.Size(60, 35) Me.btnRefresh.TabIndex = 0 Me.btnRefresh.Text = "Refresh" Me.btnRefresh.UseVisualStyleBackColor = False ' 'Chart1 ' Me.Chart1.BackColor = System.Drawing.Color.Transparent Me.Chart1.BackImageTransparentColor = System.Drawing.Color.Transparent Me.Chart1.BackSecondaryColor = System.Drawing.Color.Transparent Me.Chart1.BorderlineColor = System.Drawing.Color.DimGray Me.Chart1.BorderSkin.BorderColor = System.Drawing.Color.DimGray ChartArea1.AxisX.TitleForeColor = System.Drawing.Color.Lime ChartArea1.AxisX2.TitleForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(192, Byte), Integer), CType(CType(0, Byte), Integer)) ChartArea1.AxisY.LineColor = System.Drawing.Color.DimGray ChartArea1.AxisY.TitleForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(192, Byte), Integer), CType(CType(0, Byte), Integer)) ChartArea1.AxisY2.TitleForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(192, Byte), Integer), CType(CType(0, Byte), Integer)) ChartArea1.BackColor = System.Drawing.Color.Black ChartArea1.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.LeftRight ChartArea1.Name = "ChartArea1" Me.Chart1.ChartAreas.Add(ChartArea1) Legend1.BackColor = System.Drawing.Color.Transparent Legend1.BackSecondaryColor = System.Drawing.Color.FromArgb(CType(CType(224, Byte), Integer), CType(CType(224, Byte), Integer), CType(CType(224, Byte), Integer)) Legend1.BorderColor = System.Drawing.Color.FromArgb(CType(CType(192, Byte), Integer), CType(CType(255, Byte), Integer), CType(CType(192, Byte), Integer)) Legend1.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.NotSet Legend1.BorderWidth = 0 Legend1.ForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(192, Byte), Integer), CType(CType(0, Byte), Integer)) Legend1.Name = "Legend1" Legend1.TitleForeColor = System.Drawing.Color.FromArgb(CType(CType(128, Byte), Integer), CType(CType(255, Byte), Integer), CType(CType(128, Byte), Integer)) Legend1.TitleSeparatorColor = System.Drawing.Color.Lime Me.Chart1.Legends.Add(Legend1) Me.Chart1.Location = New System.Drawing.Point(229, 617) Me.Chart1.Name = "Chart1" Me.Chart1.Palette = System.Windows.Forms.DataVisualization.Charting.ChartColorPalette.Fire Series1.BackImageTransparentColor = System.Drawing.Color.Transparent Series1.BackSecondaryColor = System.Drawing.Color.Transparent Series1.ChartArea = "ChartArea1" Series1.LabelBackColor = System.Drawing.Color.Transparent Series1.LabelBorderColor = System.Drawing.Color.Transparent Series1.LabelForeColor = System.Drawing.Color.FromArgb(CType(CType(128, Byte), Integer), CType(CType(255, Byte), Integer), CType(CType(128, Byte), Integer)) Series1.Legend = "Legend1" Series1.Name = "Series1" Series1.Palette = System.Windows.Forms.DataVisualization.Charting.ChartColorPalette.Bright Me.Chart1.Series.Add(Series1) Me.Chart1.Size = New System.Drawing.Size(823, 81) Me.Chart1.SuppressExceptions = True Me.Chart1.TabIndex = 2 Me.Chart1.Text = "Boinc Utilization" ' 'chtCurCont ' Me.chtCurCont.BackColor = System.Drawing.Color.Transparent Me.chtCurCont.BackImageTransparentColor = System.Drawing.Color.Black Me.chtCurCont.BackSecondaryColor = System.Drawing.Color.Black Me.chtCurCont.BorderlineColor = System.Drawing.Color.Black ChartArea2.Area3DStyle.Enable3D = True ChartArea2.BackColor = System.Drawing.Color.FromArgb(CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer)) ChartArea2.Name = "ChartArea1" Me.chtCurCont.ChartAreas.Add(ChartArea2) Legend2.BackColor = System.Drawing.Color.Transparent Legend2.Name = "Legend1" Me.chtCurCont.Legends.Add(Legend2) Me.chtCurCont.Location = New System.Drawing.Point(31, 608) Me.chtCurCont.Name = "chtCurCont" Me.chtCurCont.Palette = System.Windows.Forms.DataVisualization.Charting.ChartColorPalette.Bright Series2.ChartArea = "ChartArea1" Series2.Legend = "Legend1" Series2.Name = "Series1" Me.chtCurCont.Series.Add(Series2) Me.chtCurCont.Size = New System.Drawing.Size(179, 100) Me.chtCurCont.SuppressExceptions = True Me.chtCurCont.TabIndex = 3 Me.chtCurCont.Text = "Chart2" ' 'lbltxtAvgCredits ' Me.lbltxtAvgCredits.AutoSize = True Me.lbltxtAvgCredits.BackColor = System.Drawing.Color.Transparent Me.lbltxtAvgCredits.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!) Me.lbltxtAvgCredits.Location = New System.Drawing.Point(15, 578) Me.lbltxtAvgCredits.Name = "lbltxtAvgCredits" Me.lbltxtAvgCredits.Size = New System.Drawing.Size(129, 16) Me.lbltxtAvgCredits.TabIndex = 7 Me.lbltxtAvgCredits.Text = "Whitelisted Projects:" ' 'lblThanks ' Me.lblThanks.AutoSize = True Me.lblThanks.BackColor = System.Drawing.Color.Transparent Me.lblThanks.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblThanks.Location = New System.Drawing.Point(8, 772) Me.lblThanks.Name = "lblThanks" Me.lblThanks.Size = New System.Drawing.Size(10, 13) Me.lblThanks.TabIndex = 8 Me.lblThanks.Text = " " ' 'lblWhitelistedProjects ' Me.lblWhitelistedProjects.AutoSize = True Me.lblWhitelistedProjects.BackColor = System.Drawing.Color.Transparent Me.lblWhitelistedProjects.Font = New System.Drawing.Font("Microsoft Sans Serif", 14.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblWhitelistedProjects.Location = New System.Drawing.Point(141, 572) Me.lblWhitelistedProjects.Name = "lblWhitelistedProjects" Me.lblWhitelistedProjects.Size = New System.Drawing.Size(20, 24) Me.lblWhitelistedProjects.TabIndex = 11 Me.lblWhitelistedProjects.Text = "0" ' 'tOneMinute ' Me.tOneMinute.Enabled = True Me.tOneMinute.Interval = 60000 ' 'btnHide ' Me.btnHide.Location = New System.Drawing.Point(80, 734) Me.btnHide.Name = "btnHide" Me.btnHide.Size = New System.Drawing.Size(60, 35) Me.btnHide.TabIndex = 23 Me.btnHide.Text = "Hide" Me.btnHide.UseVisualStyleBackColor = False ' 'MenuStrip1 ' Me.MenuStrip1.AllowItemReorder = True Me.MenuStrip1.BackColor = System.Drawing.Color.Transparent Me.MenuStrip1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None Me.MenuStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.FileToolStripMenuItem, Me.ConfigurationToolStripMenuItem}) Me.MenuStrip1.Location = New System.Drawing.Point(0, 0) Me.MenuStrip1.Name = "MenuStrip1" Me.MenuStrip1.Size = New System.Drawing.Size(1071, 24) Me.MenuStrip1.TabIndex = 42 Me.MenuStrip1.Text = "MenuStrip1" ' 'FileToolStripMenuItem ' Me.FileToolStripMenuItem.BackColor = System.Drawing.Color.Transparent Me.FileToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.HideToolStripMenuItem}) Me.FileToolStripMenuItem.Name = "FileToolStripMenuItem" Me.FileToolStripMenuItem.Size = New System.Drawing.Size(37, 20) Me.FileToolStripMenuItem.Text = "File" ' 'HideToolStripMenuItem ' Me.HideToolStripMenuItem.BackColor = System.Drawing.Color.Transparent Me.HideToolStripMenuItem.ForeColor = System.Drawing.Color.Lime Me.HideToolStripMenuItem.Name = "HideToolStripMenuItem" Me.HideToolStripMenuItem.Size = New System.Drawing.Size(99, 22) Me.HideToolStripMenuItem.Text = "Hide" ' 'ConfigurationToolStripMenuItem ' Me.ConfigurationToolStripMenuItem.BackColor = System.Drawing.Color.Transparent Me.ConfigurationToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ContractDetailsToolStripMenuItem}) Me.ConfigurationToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Black Me.ConfigurationToolStripMenuItem.Name = "ConfigurationToolStripMenuItem" Me.ConfigurationToolStripMenuItem.Size = New System.Drawing.Size(54, 20) Me.ConfigurationToolStripMenuItem.Text = "Debug" ' 'ContractDetailsToolStripMenuItem ' Me.ContractDetailsToolStripMenuItem.Name = "ContractDetailsToolStripMenuItem" Me.ContractDetailsToolStripMenuItem.Size = New System.Drawing.Size(158, 22) Me.ContractDetailsToolStripMenuItem.Text = "Contract Details" ' 'TabControl1 ' Me.TabControl1.Controls.Add(Me.TabPage1) Me.TabControl1.Controls.Add(Me.TabPage2) Me.TabControl1.Location = New System.Drawing.Point(14, 39) Me.TabControl1.Name = "TabControl1" Me.TabControl1.SelectedIndex = 0 Me.TabControl1.Size = New System.Drawing.Size(1045, 383) Me.TabControl1.TabIndex = 53 ' 'RichTextBox1 ' Me.RichTextBox1.BackColor = System.Drawing.Color.DimGray Me.RichTextBox1.ForeColor = System.Drawing.Color.Lime Me.RichTextBox1.Location = New System.Drawing.Point(7, 19) Me.RichTextBox1.Name = "RichTextBox1" Me.RichTextBox1.Size = New System.Drawing.Size(880, 100) Me.RichTextBox1.TabIndex = 0 Me.RichTextBox1.Text = "" ' 'TabPage1 ' Me.TabPage1.Controls.Add(Me.WebBrowserBoinc) Me.TabPage1.Location = New System.Drawing.Point(4, 22) Me.TabPage1.Name = "TabPage1" Me.TabPage1.Padding = New System.Windows.Forms.Padding(3) Me.TabPage1.Size = New System.Drawing.Size(1037, 357) Me.TabPage1.TabIndex = 2 Me.TabPage1.Text = "Gridcoin Website" Me.TabPage1.UseVisualStyleBackColor = True ' 'WebBrowserBoinc ' Me.WebBrowserBoinc.Dock = System.Windows.Forms.DockStyle.Fill Me.WebBrowserBoinc.Location = New System.Drawing.Point(3, 3) Me.WebBrowserBoinc.MinimumSize = New System.Drawing.Size(20, 20) Me.WebBrowserBoinc.Name = "WebBrowserBoinc" Me.WebBrowserBoinc.ScriptErrorsSuppressed = True Me.WebBrowserBoinc.Size = New System.Drawing.Size(1031, 351) Me.WebBrowserBoinc.TabIndex = 0 Me.WebBrowserBoinc.Url = New System.Uri("https://gridcoin.us", System.UriKind.Absolute) ' 'TabPage2 ' Me.TabPage2.Controls.Add(Me.dgv) Me.TabPage2.Location = New System.Drawing.Point(4, 22) Me.TabPage2.Name = "TabPage2" Me.TabPage2.Size = New System.Drawing.Size(1037, 357) Me.TabPage2.TabIndex = 3 Me.TabPage2.Text = "Neural Network" Me.TabPage2.UseVisualStyleBackColor = True ' 'dgv ' DataGridViewCellStyle1.BackColor = System.Drawing.Color.Black DataGridViewCellStyle1.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle1.SelectionBackColor = System.Drawing.Color.Gray DataGridViewCellStyle1.SelectionForeColor = System.Drawing.Color.FromArgb(CType(CType(128, Byte), Integer), CType(CType(255, Byte), Integer), CType(CType(128, Byte), Integer)) Me.dgv.AlternatingRowsDefaultCellStyle = DataGridViewCellStyle1 Me.dgv.BackgroundColor = System.Drawing.Color.Black DataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle2.BackColor = System.Drawing.Color.Black DataGridViewCellStyle2.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) DataGridViewCellStyle2.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText DataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.[True] Me.dgv.ColumnHeadersDefaultCellStyle = DataGridViewCellStyle2 Me.dgv.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize DataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle3.BackColor = System.Drawing.Color.Black DataGridViewCellStyle3.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) DataGridViewCellStyle3.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText DataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.[False] Me.dgv.DefaultCellStyle = DataGridViewCellStyle3 Me.dgv.EnableHeadersVisualStyles = False Me.dgv.GridColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer)) Me.dgv.Location = New System.Drawing.Point(0, 0) Me.dgv.Name = "dgv" DataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle4.BackColor = System.Drawing.Color.Black DataGridViewCellStyle4.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) DataGridViewCellStyle4.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle4.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle4.SelectionForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(0, Byte), Integer)) DataGridViewCellStyle4.WrapMode = System.Windows.Forms.DataGridViewTriState.[True] Me.dgv.RowHeadersDefaultCellStyle = DataGridViewCellStyle4 DataGridViewCellStyle5.BackColor = System.Drawing.Color.Black DataGridViewCellStyle5.ForeColor = System.Drawing.Color.Lime Me.dgv.RowsDefaultCellStyle = DataGridViewCellStyle5 Me.dgv.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect Me.dgv.Size = New System.Drawing.Size(1034, 354) Me.dgv.TabIndex = 1 ' 'lblWarning ' Me.lblWarning.AutoSize = True Me.lblWarning.BackColor = System.Drawing.Color.Transparent Me.lblWarning.Font = New System.Drawing.Font("Segoe Print", 15.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblWarning.ForeColor = System.Drawing.Color.Red Me.lblWarning.Location = New System.Drawing.Point(152, 673) Me.lblWarning.Name = "lblWarning" Me.lblWarning.Size = New System.Drawing.Size(25, 37) Me.lblWarning.TabIndex = 55 Me.lblWarning.Text = " " ' 'btnExport ' Me.btnExport.Location = New System.Drawing.Point(146, 734) Me.btnExport.Name = "btnExport" Me.btnExport.Size = New System.Drawing.Size(118, 35) Me.btnExport.TabIndex = 56 Me.btnExport.Text = "Export to CSV" Me.btnExport.UseVisualStyleBackColor = False ' 'txtSearch ' Me.txtSearch.BackColor = System.Drawing.Color.Gainsboro Me.txtSearch.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.txtSearch.ForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(0, Byte), Integer)) Me.txtSearch.Location = New System.Drawing.Point(757, 38) Me.txtSearch.Name = "txtSearch" Me.txtSearch.Size = New System.Drawing.Size(299, 20) Me.txtSearch.TabIndex = 61 ' 'Label1 ' Me.Label1.AutoSize = True Me.Label1.BackColor = System.Drawing.Color.Gainsboro Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!) Me.Label1.ForeColor = System.Drawing.Color.Green Me.Label1.Location = New System.Drawing.Point(700, 40) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(54, 16) Me.Label1.TabIndex = 62 Me.Label1.Text = "Search:" ' 'lblTestnet ' Me.lblTestnet.AutoSize = True Me.lblTestnet.BackColor = System.Drawing.Color.Transparent Me.lblTestnet.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblTestnet.ForeColor = System.Drawing.Color.Red Me.lblTestnet.Location = New System.Drawing.Point(478, 0) Me.lblTestnet.Name = "lblTestnet" Me.lblTestnet.Size = New System.Drawing.Size(13, 20) Me.lblTestnet.TabIndex = 63 Me.lblTestnet.Text = " " ' 'dgvProjects ' DataGridViewCellStyle6.BackColor = System.Drawing.Color.Black DataGridViewCellStyle6.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle6.SelectionBackColor = System.Drawing.Color.Gray DataGridViewCellStyle6.SelectionForeColor = System.Drawing.Color.FromArgb(CType(CType(128, Byte), Integer), CType(CType(255, Byte), Integer), CType(CType(128, Byte), Integer)) Me.dgvProjects.AlternatingRowsDefaultCellStyle = DataGridViewCellStyle6 Me.dgvProjects.BackgroundColor = System.Drawing.Color.Black DataGridViewCellStyle7.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle7.BackColor = System.Drawing.Color.Black DataGridViewCellStyle7.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) DataGridViewCellStyle7.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle7.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle7.SelectionForeColor = System.Drawing.SystemColors.HighlightText DataGridViewCellStyle7.WrapMode = System.Windows.Forms.DataGridViewTriState.[True] Me.dgvProjects.ColumnHeadersDefaultCellStyle = DataGridViewCellStyle7 Me.dgvProjects.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize DataGridViewCellStyle8.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle8.BackColor = System.Drawing.Color.Black DataGridViewCellStyle8.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) DataGridViewCellStyle8.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle8.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle8.SelectionForeColor = System.Drawing.SystemColors.HighlightText DataGridViewCellStyle8.WrapMode = System.Windows.Forms.DataGridViewTriState.[False] Me.dgvProjects.DefaultCellStyle = DataGridViewCellStyle8 Me.dgvProjects.EnableHeadersVisualStyles = False Me.dgvProjects.GridColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer)) Me.dgvProjects.Location = New System.Drawing.Point(14, 428) Me.dgvProjects.Name = "dgvProjects" DataGridViewCellStyle9.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle9.BackColor = System.Drawing.Color.Black DataGridViewCellStyle9.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) DataGridViewCellStyle9.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle9.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle9.SelectionForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(0, Byte), Integer)) DataGridViewCellStyle9.WrapMode = System.Windows.Forms.DataGridViewTriState.[True] Me.dgvProjects.RowHeadersDefaultCellStyle = DataGridViewCellStyle9 DataGridViewCellStyle10.BackColor = System.Drawing.Color.Black DataGridViewCellStyle10.ForeColor = System.Drawing.Color.Lime Me.dgvProjects.RowsDefaultCellStyle = DataGridViewCellStyle10 Me.dgvProjects.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect Me.dgvProjects.Size = New System.Drawing.Size(1045, 138) Me.dgvProjects.TabIndex = 64 ' 'lblTotalProjects ' Me.lblTotalProjects.AutoSize = True Me.lblTotalProjects.BackColor = System.Drawing.Color.Transparent Me.lblTotalProjects.Font = New System.Drawing.Font("Microsoft Sans Serif", 14.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.lblTotalProjects.Location = New System.Drawing.Point(369, 572) Me.lblTotalProjects.Name = "lblTotalProjects" Me.lblTotalProjects.Size = New System.Drawing.Size(20, 24) Me.lblTotalProjects.TabIndex = 66 Me.lblTotalProjects.Text = "0" Me.lblTotalProjects.Visible = False ' 'Label3 ' Me.Label3.AutoSize = True Me.Label3.BackColor = System.Drawing.Color.Transparent Me.Label3.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!) Me.Label3.Location = New System.Drawing.Point(269, 578) Me.Label3.Name = "Label3" Me.Label3.Size = New System.Drawing.Size(94, 16) Me.Label3.TabIndex = 65 Me.Label3.Text = "Total Projects:" Me.Label3.Visible = False ' 'pbSync ' Me.pbSync.Location = New System.Drawing.Point(477, 575) Me.pbSync.Name = "pbSync" Me.pbSync.Size = New System.Drawing.Size(578, 18) Me.pbSync.TabIndex = 67 ' 'TimerSync ' Me.TimerSync.Enabled = True Me.TimerSync.Interval = 2000 ' 'lblLastSynced ' Me.lblLastSynced.AutoSize = True Me.lblLastSynced.BackColor = System.Drawing.Color.Transparent Me.lblLastSynced.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!) Me.lblLastSynced.Location = New System.Drawing.Point(448, 734) Me.lblLastSynced.Name = "lblLastSynced" Me.lblLastSynced.Size = New System.Drawing.Size(85, 16) Me.lblLastSynced.TabIndex = 68 Me.lblLastSynced.Text = "Last Synced:" ' 'lblCPID ' Me.lblCPID.AutoSize = True Me.lblCPID.BackColor = System.Drawing.Color.Transparent Me.lblCPID.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!) Me.lblCPID.Location = New System.Drawing.Point(448, 753) Me.lblCPID.Name = "lblCPID" Me.lblCPID.Size = New System.Drawing.Size(42, 16) Me.lblCPID.TabIndex = 69 Me.lblCPID.Text = "CPID:" ' 'lblSuperblockAge ' Me.lblSuperblockAge.AutoSize = True Me.lblSuperblockAge.BackColor = System.Drawing.Color.Transparent Me.lblSuperblockAge.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!) Me.lblSuperblockAge.Location = New System.Drawing.Point(725, 734) Me.lblSuperblockAge.Name = "lblSuperblockAge" Me.lblSuperblockAge.Size = New System.Drawing.Size(108, 16) Me.lblSuperblockAge.TabIndex = 70 Me.lblSuperblockAge.Text = "Superblock Age:" ' 'lblQuorumHash ' Me.lblQuorumHash.AutoSize = True Me.lblQuorumHash.BackColor = System.Drawing.Color.Transparent Me.lblQuorumHash.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!) Me.lblQuorumHash.Location = New System.Drawing.Point(725, 753) Me.lblQuorumHash.Name = "lblQuorumHash" Me.lblQuorumHash.Size = New System.Drawing.Size(143, 16) Me.lblQuorumHash.TabIndex = 71 Me.lblQuorumHash.Text = "Popular Quorum Hash:" ' 'lblTimestamp ' Me.lblTimestamp.AutoSize = True Me.lblTimestamp.BackColor = System.Drawing.Color.Transparent Me.lblTimestamp.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!) Me.lblTimestamp.Location = New System.Drawing.Point(725, 772) Me.lblTimestamp.Name = "lblTimestamp" Me.lblTimestamp.Size = New System.Drawing.Size(151, 16) Me.lblTimestamp.TabIndex = 72 Me.lblTimestamp.Text = "Superblock Timestamp:" ' 'lblBlock ' Me.lblBlock.AutoSize = True Me.lblBlock.BackColor = System.Drawing.Color.Transparent Me.lblBlock.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!) Me.lblBlock.Location = New System.Drawing.Point(448, 772) Me.lblBlock.Name = "lblBlock" Me.lblBlock.Size = New System.Drawing.Size(127, 16) Me.lblBlock.TabIndex = 73 Me.lblBlock.Text = "Superblock Block #:" ' 'btnSync ' Me.btnSync.Location = New System.Drawing.Point(272, 734) Me.btnSync.Name = "btnSync" Me.btnSync.Size = New System.Drawing.Size(118, 35) Me.btnSync.TabIndex = 74 Me.btnSync.Text = "Sync" Me.btnSync.UseVisualStyleBackColor = False ' 'lblQueue ' Me.lblQueue.AutoSize = True Me.lblQueue.BackColor = System.Drawing.Color.Transparent Me.lblQueue.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!) Me.lblQueue.Location = New System.Drawing.Point(474, 598) Me.lblQueue.Name = "lblQueue" Me.lblQueue.Size = New System.Drawing.Size(61, 16) Me.lblQueue.TabIndex = 75 Me.lblQueue.Text = "Queue: 0" ' 'lblNeuralDetail ' Me.lblNeuralDetail.AutoSize = True Me.lblNeuralDetail.BackColor = System.Drawing.Color.Transparent Me.lblNeuralDetail.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!) Me.lblNeuralDetail.Location = New System.Drawing.Point(815, 596) Me.lblNeuralDetail.Name = "lblNeuralDetail" Me.lblNeuralDetail.Size = New System.Drawing.Size(11, 16) Me.lblNeuralDetail.TabIndex = 76 Me.lblNeuralDetail.Text = " " ' 'lblAvgMagnitude ' Me.lblAvgMagnitude.AutoSize = True Me.lblAvgMagnitude.BackColor = System.Drawing.Color.Transparent Me.lblAvgMagnitude.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!) Me.lblAvgMagnitude.Location = New System.Drawing.Point(15, 715) Me.lblAvgMagnitude.Name = "lblAvgMagnitude" Me.lblAvgMagnitude.Size = New System.Drawing.Size(173, 16) Me.lblAvgMagnitude.TabIndex = 77 Me.lblAvgMagnitude.Text = "Superblock Avg Magnitude:" ' 'frmMining ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.Color.Black Me.BackgroundImage = My.Resources.GradientU Me.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch Me.ClientSize = New System.Drawing.Size(1071, 793) Me.Controls.Add(Me.lblAvgMagnitude) Me.Controls.Add(Me.lblNeuralDetail) Me.Controls.Add(Me.lblQueue) Me.Controls.Add(Me.btnSync) Me.Controls.Add(Me.lblBlock) Me.Controls.Add(Me.lblTimestamp) Me.Controls.Add(Me.lblQuorumHash) Me.Controls.Add(Me.lblSuperblockAge) Me.Controls.Add(Me.lblCPID) Me.Controls.Add(Me.lblLastSynced) Me.Controls.Add(Me.pbSync) Me.Controls.Add(Me.lblTotalProjects) Me.Controls.Add(Me.Label3) Me.Controls.Add(Me.dgvProjects) Me.Controls.Add(Me.lblTestnet) Me.Controls.Add(Me.txtSearch) Me.Controls.Add(Me.Label1) Me.Controls.Add(Me.btnExport) Me.Controls.Add(Me.lblWarning) Me.Controls.Add(Me.TabControl1) Me.Controls.Add(Me.btnHide) Me.Controls.Add(Me.lblWhitelistedProjects) Me.Controls.Add(Me.lblThanks) Me.Controls.Add(Me.lbltxtAvgCredits) Me.Controls.Add(Me.chtCurCont) Me.Controls.Add(Me.Chart1) Me.Controls.Add(Me.btnRefresh) Me.Controls.Add(Me.MenuStrip1) Me.DoubleBuffered = True Me.ForeColor = System.Drawing.Color.Lime Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon) Me.MainMenuStrip = Me.MenuStrip1 Me.Name = "frmMining" Me.Text = "Gridcoin Neural Network 3.4" CType(Me.Chart1, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.chtCurCont, System.ComponentModel.ISupportInitialize).EndInit() Me.MenuStrip1.ResumeLayout(False) Me.MenuStrip1.PerformLayout() Me.TabControl1.ResumeLayout(False) Me.GroupBox3.ResumeLayout(False) Me.GroupBox2.ResumeLayout(False) CType(Me.ChartHashRate, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.pbCgminer, System.ComponentModel.ISupportInitialize).EndInit() Me.TabPage1.ResumeLayout(False) Me.TabPage2.ResumeLayout(False) CType(Me.dgv, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.dgvProjects, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents btnRefresh As System.Windows.Forms.Button Friend WithEvents Chart1 As System.Windows.Forms.DataVisualization.Charting.Chart Friend WithEvents chtCurCont As System.Windows.Forms.DataVisualization.Charting.Chart Friend WithEvents lbltxtAvgCredits As System.Windows.Forms.Label Friend WithEvents lblThanks As System.Windows.Forms.Label Friend WithEvents lblWhitelistedProjects As System.Windows.Forms.Label Friend WithEvents tOneMinute As System.Windows.Forms.Timer Friend WithEvents btnHide As System.Windows.Forms.Button Friend WithEvents MenuStrip1 As System.Windows.Forms.MenuStrip Friend WithEvents FileToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents HideToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents ConfigurationToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents TabControl1 As System.Windows.Forms.TabControl Friend WithEvents pbCgminer As System.Windows.Forms.PictureBox Friend WithEvents GroupBox3 As System.Windows.Forms.GroupBox Friend WithEvents RichTextBox1 As System.Windows.Forms.RichTextBox Friend WithEvents GroupBox2 As System.Windows.Forms.GroupBox Friend WithEvents ChartHashRate As System.Windows.Forms.DataVisualization.Charting.Chart Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox Friend WithEvents lblWarning As System.Windows.Forms.Label Friend WithEvents GroupBox4 As System.Windows.Forms.GroupBox Friend WithEvents TabPage1 As System.Windows.Forms.TabPage Friend WithEvents TabPage2 As System.Windows.Forms.TabPage Friend WithEvents dgv As System.Windows.Forms.DataGridView Friend WithEvents ContractDetailsToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents btnExport As System.Windows.Forms.Button Friend WithEvents txtSearch As System.Windows.Forms.TextBox Friend WithEvents Label1 As System.Windows.Forms.Label Friend WithEvents lblTestnet As System.Windows.Forms.Label Friend WithEvents dgvProjects As System.Windows.Forms.DataGridView Friend WithEvents lblTotalProjects As System.Windows.Forms.Label Friend WithEvents Label3 As System.Windows.Forms.Label Friend WithEvents pbSync As System.Windows.Forms.ProgressBar Friend WithEvents TimerSync As System.Windows.Forms.Timer Friend WithEvents lblLastSynced As System.Windows.Forms.Label Friend WithEvents lblCPID As System.Windows.Forms.Label Friend WithEvents lblSuperblockAge As System.Windows.Forms.Label Friend WithEvents lblQuorumHash As System.Windows.Forms.Label Friend WithEvents lblTimestamp As System.Windows.Forms.Label Friend WithEvents lblBlock As System.Windows.Forms.Label Friend WithEvents btnSync As System.Windows.Forms.Button Friend WithEvents lblQueue As System.Windows.Forms.Label Friend WithEvents lblNeuralDetail As System.Windows.Forms.Label Friend WithEvents WebBrowserBoinc As System.Windows.Forms.WebBrowser Friend WithEvents lblAvgMagnitude As System.Windows.Forms.Label End Class
TheCharlatan/Gridcoin-Research
contrib/Installer/boinc/boinc/frmMining.Designer.vb
Visual Basic
mit
41,191
' 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.Linq Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Roslyn.Test.Utilities Imports Xunit Public MustInherit Class BasicTestBase Inherits BasicTestBaseBase Protected Overloads Function GetCompilationForEmit( source As IEnumerable(Of String), additionalRefs() As MetadataReference, options As VisualBasicCompilationOptions, parseOptions As VisualBasicParseOptions ) As VisualBasicCompilation Return DirectCast(MyBase.GetCompilationForEmit(source, additionalRefs, options, parseOptions), VisualBasicCompilation) End Function Public Function XCDataToString(Optional data As XCData = Nothing) As String Return data?.Value.Replace(vbLf, Environment.NewLine) End Function Private Function Translate(action As Action(Of ModuleSymbol)) As Action(Of IModuleSymbol) If action IsNot Nothing Then Return Sub(m) action(DirectCast(m, ModuleSymbol)) Else Return Nothing End If End Function Friend Shadows Function CompileAndVerify( source As XElement, expectedOutput As XCData, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional additionalRefs As MetadataReference() = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional emitOptions As EmitOptions = Nothing, Optional verify As Verification = Verification.Passes ) As CompilationVerifier Return CompileAndVerify( source, XCDataToString(expectedOutput), expectedReturnCode, args, additionalRefs, dependencies, sourceSymbolValidator, validator, symbolValidator, expectedSignatures, options, parseOptions, emitOptions, verify) End Function Friend Shadows Function CompileAndVerify( compilation As Compilation, Optional manifestResources As IEnumerable(Of ResourceDescription) = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional expectedOutput As String = Nothing, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional emitOptions As EmitOptions = Nothing, Optional verify As Verification = Verification.Passes) As CompilationVerifier Return MyBase.CompileAndVerify( compilation, manifestResources, dependencies, Translate(sourceSymbolValidator), validator, Translate(symbolValidator), expectedSignatures, expectedOutput, expectedReturnCode, args, emitOptions, verify) End Function Friend Shadows Function CompileAndVerify( compilation As Compilation, expectedOutput As XCData, Optional args As String() = Nothing, Optional manifestResources As IEnumerable(Of ResourceDescription) = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional emitOptions As EmitOptions = Nothing, Optional verify As Verification = Verification.Passes) As CompilationVerifier Return CompileAndVerify( compilation, manifestResources, dependencies, sourceSymbolValidator, validator, symbolValidator, expectedSignatures, XCDataToString(expectedOutput), Nothing, args, emitOptions, verify) End Function Friend Shadows Function CompileAndVerify( source As XElement, Optional expectedOutput As String = Nothing, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional additionalRefs As MetadataReference() = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional emitOptions As EmitOptions = Nothing, Optional verify As Verification = Verification.Passes, Optional useLatestFramework As Boolean = False ) As CompilationVerifier Dim defaultRefs = If(useLatestFramework, LatestVbReferences, DefaultVbReferences) Dim allReferences = If(additionalRefs IsNot Nothing, defaultRefs.Concat(additionalRefs), defaultRefs) Return Me.CompileAndVerify(source, allReferences, expectedOutput, expectedReturnCode, args, dependencies, sourceSymbolValidator, validator, symbolValidator, expectedSignatures, options, parseOptions, emitOptions, verify) End Function Friend Shadows Function CompileAndVerify( source As XElement, allReferences As IEnumerable(Of MetadataReference), Optional expectedOutput As String = Nothing, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional emitOptions As EmitOptions = Nothing, Optional verify As Verification = Verification.Passes ) As CompilationVerifier If options Is Nothing Then options = If(expectedOutput Is Nothing, TestOptions.ReleaseDll, TestOptions.ReleaseExe) End If Dim assemblyName As String = Nothing Dim sourceTrees = ParseSourceXml(source, parseOptions, assemblyName) Dim compilation = CreateCompilation(sourceTrees, allReferences, options, assemblyName) Return MyBase.CompileAndVerify( compilation, Nothing, dependencies, Translate(sourceSymbolValidator), validator, Translate(symbolValidator), expectedSignatures, expectedOutput, expectedReturnCode, args, emitOptions, verify) End Function Friend Shadows Function CompileAndVerify( source As String, allReferences As IEnumerable(Of MetadataReference), Optional expectedOutput As String = Nothing, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional emitOptions As EmitOptions = Nothing, Optional assemblyName As String = Nothing, Optional verify As Verification = Verification.Passes ) As CompilationVerifier If options Is Nothing Then options = If(expectedOutput Is Nothing, TestOptions.ReleaseDll, TestOptions.ReleaseExe) End If Dim compilation = CreateCompilation(source, allReferences, options, assemblyName, parseOptions) Return MyBase.CompileAndVerify( compilation, Nothing, dependencies, Translate(sourceSymbolValidator), validator, Translate(symbolValidator), expectedSignatures, expectedOutput, expectedReturnCode, args, emitOptions, verify) End Function Friend Shadows Function CompileAndVerifyOnWin8Only( source As XElement, allReferences As IEnumerable(Of MetadataReference), Optional expectedOutput As String = Nothing, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional verify As Verification = Verification.Passes ) As CompilationVerifier Return Me.CompileAndVerify( source, allReferences, If(OSVersion.IsWin8, expectedOutput, Nothing), If(OSVersion.IsWin8, expectedReturnCode, Nothing), args, dependencies, sourceSymbolValidator, validator, symbolValidator, expectedSignatures, options, parseOptions, verify:=If(OSVersion.IsWin8, verify, Verification.Skipped)) End Function Friend Shadows Function CompileAndVerifyOnWin8Only( source As XElement, expectedOutput As XCData, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional allReferences() As MetadataReference = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional verify As Verification = Verification.Passes ) As CompilationVerifier Return CompileAndVerifyOnWin8Only( source, allReferences, XCDataToString(expectedOutput), expectedReturnCode, args, dependencies, sourceSymbolValidator, validator, symbolValidator, expectedSignatures, options, parseOptions, verify) End Function Friend Shadows Function CompileAndVerifyOnWin8Only( source As XElement, Optional expectedOutput As String = Nothing, Optional additionalRefs() As MetadataReference = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional verify As Verification = Verification.Passes, Optional useLatestFramework As Boolean = False ) As CompilationVerifier Return CompileAndVerify( source, expectedOutput:=If(OSVersion.IsWin8, expectedOutput, Nothing), additionalRefs:=additionalRefs, dependencies:=dependencies, sourceSymbolValidator:=sourceSymbolValidator, validator:=validator, symbolValidator:=symbolValidator, expectedSignatures:=expectedSignatures, options:=options, parseOptions:=parseOptions, verify:=If(OSVersion.IsWin8, verify, Verification.Skipped), useLatestFramework:=useLatestFramework) End Function ''' <summary> ''' Compile sources and adds a custom reference using a custom IL ''' </summary> ''' <param name="sources">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Friend Function CompileWithCustomILSource(sources As XElement, ilSource As XCData) As CompilationVerifier Return CompileWithCustomILSource(sources, ilSource.Value) End Function ''' <summary> ''' Compile sources and adds a custom reference using a custom IL ''' </summary> ''' <param name="sources">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Friend Function CompileWithCustomILSource(sources As XElement, ilSource As String, Optional options As VisualBasicCompilationOptions = Nothing, Optional compilationVerifier As Action(Of VisualBasicCompilation) = Nothing, Optional expectedOutput As String = Nothing) As CompilationVerifier If expectedOutput IsNot Nothing Then options = options.WithOutputKind(OutputKind.ConsoleApplication) End If If ilSource = Nothing Then Return CompileAndVerify(sources) End If Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(sources, {MscorlibRef, MsvbRef, reference}, options) If compilationVerifier IsNot Nothing Then compilationVerifier(compilation) End If Return CompileAndVerify(compilation, expectedOutput:=expectedOutput) End Function Friend Overloads Function CompileAndVerifyFieldMarshal(source As XElement, expectedBlobs As Dictionary(Of String, Byte()), Optional getExpectedBlob As Func(Of String, PEAssembly, Byte()) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional isField As Boolean = True) As CompilationVerifier Return CompileAndVerifyFieldMarshal(source, Function(s, _omitted1) Assert.True(expectedBlobs.ContainsKey(s), "Expecting marshalling blob for " & If(isField, "field ", "parameter ") & s) Return expectedBlobs(s) End Function, expectedSignatures, isField) End Function Friend Overloads Function CompileAndVerifyFieldMarshal(source As XElement, getExpectedBlob As Func(Of String, PEAssembly, Byte()), Optional expectedSignatures As SignatureDescription() = Nothing, Optional isField As Boolean = True) As CompilationVerifier Return CompileAndVerify(source, options:=TestOptions.ReleaseDll, validator:=Sub(assembly) MetadataValidation.MarshalAsMetadataValidator(assembly, getExpectedBlob, isField), expectedSignatures:=expectedSignatures) End Function End Class Public MustInherit Class BasicTestBaseBase Inherits CommonTestBase Protected Overrides ReadOnly Property CompilationOptionsReleaseDll As CompilationOptions Get Return TestOptions.ReleaseDll End Get End Property Protected Overrides Function GetCompilationForEmit( source As IEnumerable(Of String), additionalRefs As IEnumerable(Of MetadataReference), options As CompilationOptions, parseOptions As ParseOptions ) As Compilation Return VisualBasicCompilation.Create( GetUniqueName(), syntaxTrees:=source.Select(Function(t) VisualBasicSyntaxTree.ParseText(t, options:=DirectCast(parseOptions, VisualBasicParseOptions))), references:=If(additionalRefs IsNot Nothing, DefaultVbReferences.Concat(additionalRefs), DefaultVbReferences), options:=DirectCast(options, VisualBasicCompilationOptions)) End Function Public Shared Function CreateSubmission(code As String, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional previous As VisualBasicCompilation = Nothing, Optional returnType As Type = Nothing, Optional hostObjectType As Type = Nothing) As VisualBasicCompilation Return VisualBasicCompilation.CreateScriptCompilation( GetUniqueName(), references:=If(references Is Nothing, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}.Concat(references)), options:=options, syntaxTree:=Parse(code, options:=If(parseOptions, TestOptions.Script)), previousScriptCompilation:=previous, returnType:=returnType, globalsType:=hostObjectType) End Function Friend Shared Function GetAttributeNames(attributes As ImmutableArray(Of SynthesizedAttributeData)) As IEnumerable(Of String) Return attributes.Select(Function(a) a.AttributeClass.Name) End Function Friend Shared Function GetAttributeNames(attributes As ImmutableArray(Of VisualBasicAttributeData)) As IEnumerable(Of String) Return attributes.Select(Function(a) a.AttributeClass.Name) End Function Friend Overrides Function VisualizeRealIL(peModule As IModuleSymbol, methodData As CompilationTestData.MethodData, markers As IReadOnlyDictionary(Of Integer, String)) As String Throw New NotImplementedException() End Function Friend Function GetSymbolsFromBinaryReference(bytes() As Byte) As AssemblySymbol Return MetadataTestHelpers.GetSymbolsForReferences({bytes}).Single() End Function Public Shared Shadows Function GetPdbXml(compilation As VisualBasicCompilation, Optional methodName As String = "") As XElement Return XElement.Parse(PdbValidation.GetPdbXml(compilation, qualifiedMethodName:=methodName)) End Function Public Shared Shadows Function GetPdbXml(source As XElement, Optional options As VisualBasicCompilationOptions = Nothing, Optional methodName As String = "") As XElement Dim compilation = CreateCompilationWithMscorlib(source, options) compilation.VerifyDiagnostics() Return GetPdbXml(compilation, methodName) End Function Public Shared Shadows Function GetSequencePoints(pdbXml As XElement) As XElement Return <sequencePoints> <%= From entry In pdbXml.<methods>.<method>.<sequencePoints>.<entry> Select <entry startLine=<%= entry.@startLine %> startColumn=<%= entry.@startColumn %> endLine=<%= entry.@endLine %> endColumn=<%= entry.@endColumn %>/> %> </sequencePoints> End Function Public Shared ReadOnly ClassesWithReadWriteProperties As XCData = <![CDATA[ .class public auto ansi beforefieldinit B extends [mscorlib]System.Object { .method public hidebysig newslot specialname virtual instance int32 get_P_rw_r_w() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method B::get_P_rw_r_w .method public hidebysig newslot specialname virtual instance void set_P_rw_r_w(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method B::set_P_rw_r_w .method public hidebysig newslot specialname virtual instance int32 get_P_rw_rw_w() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method B::get_P_rw_rw_w .method public hidebysig newslot specialname virtual instance void set_P_rw_rw_w(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method B::set_P_rw_rw_w .method public hidebysig newslot specialname virtual instance int32 get_P_rw_rw_r() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method B::get_P_rw_rw_r .method public hidebysig newslot specialname virtual instance void set_P_rw_rw_r(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method B::set_P_rw_rw_r .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method B::.ctor .property instance int32 P_rw_r_w() { .get instance int32 B::get_P_rw_r_w() .set instance void B::set_P_rw_r_w(int32) } // end of property B::P_rw_r_w .property instance int32 P_rw_rw_w() { .set instance void B::set_P_rw_rw_w(int32) .get instance int32 B::get_P_rw_rw_w() } // end of property B::P_rw_rw_w .property instance int32 P_rw_rw_r() { .get instance int32 B::get_P_rw_rw_r() .set instance void B::set_P_rw_rw_r(int32) } // end of property B::P_rw_rw_r } // end of class B .class public auto ansi beforefieldinit D1 extends B { .method public hidebysig specialname virtual instance int32 get_P_rw_r_w() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method D1::get_P_rw_r_w .method public hidebysig specialname virtual instance int32 get_P_rw_rw_w() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method D1::get_P_rw_rw_w .method public hidebysig specialname virtual instance void set_P_rw_rw_w(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method D1::set_P_rw_rw_w .method public hidebysig specialname virtual instance int32 get_P_rw_rw_r() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method D1::get_P_rw_rw_r .method public hidebysig specialname virtual instance void set_P_rw_rw_r(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method D1::set_P_rw_rw_r .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void B::.ctor() IL_0006: ret } // end of method D1::.ctor .property instance int32 P_rw_r_w() { .get instance int32 D1::get_P_rw_r_w() } // end of property D1::P_rw_r_w .property instance int32 P_rw_rw_w() { .get instance int32 D1::get_P_rw_rw_w() .set instance void D1::set_P_rw_rw_w(int32) } // end of property D1::P_rw_rw_w .property instance int32 P_rw_rw_r() { .get instance int32 D1::get_P_rw_rw_r() .set instance void D1::set_P_rw_rw_r(int32) } // end of property D1::P_rw_rw_r } // end of class D1 .class public auto ansi beforefieldinit D2 extends D1 { .method public hidebysig specialname virtual instance void set_P_rw_r_w(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method D2::set_P_rw_r_w .method public hidebysig specialname virtual instance void set_P_rw_rw_w(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method D2::set_P_rw_rw_w .method public hidebysig specialname virtual instance int32 get_P_rw_rw_r() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method D2::get_P_rw_rw_r .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void D1::.ctor() IL_0006: ret } // end of method D2::.ctor .property instance int32 P_rw_r_w() { .set instance void D2::set_P_rw_r_w(int32) } // end of property D2::P_rw_r_w .property instance int32 P_rw_rw_w() { .set instance void D2::set_P_rw_rw_w(int32) } // end of property D2::P_rw_rw_w .property instance int32 P_rw_rw_r() { .get instance int32 D2::get_P_rw_rw_r() } // end of property D2::P_rw_rw_r } // end of class D2 ]]> Public Class NameSyntaxFinder Inherits VisualBasicSyntaxWalker Private Sub New() MyBase.New(SyntaxWalkerDepth.StructuredTrivia) End Sub Public Overrides Sub DefaultVisit(node As SyntaxNode) Dim name = TryCast(node, NameSyntax) If name IsNot Nothing Then Me._names.Add(name) End If MyBase.DefaultVisit(node) End Sub Private ReadOnly _names As New List(Of NameSyntax) Public Shared Function FindNames(node As SyntaxNode) As List(Of NameSyntax) Dim finder As New NameSyntaxFinder() finder.Visit(node) Return finder._names End Function End Class Public Class ExpressionSyntaxFinder Inherits VisualBasicSyntaxWalker Private Sub New() MyBase.New(SyntaxWalkerDepth.StructuredTrivia) End Sub Public Overrides Sub DefaultVisit(node As SyntaxNode) Dim expr = TryCast(node, ExpressionSyntax) If expr IsNot Nothing Then Me._expressions.Add(expr) End If MyBase.DefaultVisit(node) End Sub Private ReadOnly _expressions As New List(Of ExpressionSyntax) Public Shared Function FindExpression(node As SyntaxNode) As List(Of ExpressionSyntax) Dim finder As New ExpressionSyntaxFinder() finder.Visit(node) Return finder._expressions End Function End Class Public Class SyntaxNodeFinder Inherits VisualBasicSyntaxWalker Private Sub New() MyBase.New(SyntaxWalkerDepth.StructuredTrivia) End Sub Public Overrides Sub DefaultVisit(node As SyntaxNode) If node IsNot Nothing AndAlso Me._kinds.Contains(node.Kind) Then Me._nodes.Add(node) End If MyBase.DefaultVisit(node) End Sub Private ReadOnly _nodes As New List(Of SyntaxNode) Private ReadOnly _kinds As New HashSet(Of SyntaxKind)(SyntaxFacts.EqualityComparer) Public Shared Function FindNodes(Of T As SyntaxNode)(node As SyntaxNode, ParamArray kinds() As SyntaxKind) As List(Of T) Return New List(Of T)(From s In FindNodes(node, kinds) Select DirectCast(s, T)) End Function Public Shared Function FindNodes(node As SyntaxNode, ParamArray kinds() As SyntaxKind) As List(Of SyntaxNode) Dim finder As New SyntaxNodeFinder() finder._kinds.AddAll(kinds) finder.Visit(node) Return finder._nodes End Function End Class Public Class TypeComparer Implements IComparer(Of NamedTypeSymbol) Private Function Compare(x As NamedTypeSymbol, y As NamedTypeSymbol) As Integer Implements IComparer(Of NamedTypeSymbol).Compare Dim result As Integer = StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name) If result <> 0 Then Return result End If Return x.Arity - y.Arity End Function End Class #Region "IOperation tree validation" Friend Shared Function GetOperationTreeForTest(Of TSyntaxNode As SyntaxNode)(compilation As VisualBasicCompilation, fileName As String, Optional which As Integer = 0) As (tree As String, syntax As SyntaxNode, operation As IOperation) Dim node As SyntaxNode = CompilationUtils.FindBindingText(Of TSyntaxNode)(compilation, fileName, which, prefixMatch:=True) If node Is Nothing Then Return Nothing End If Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim operation = semanticModel.GetOperation(node) If operation IsNot Nothing Then Return (OperationTreeVerifier.GetOperationTree(compilation, operation), node, operation) Else Return (Nothing, Nothing, Nothing) End If End Function Friend Shared Function GetOperationTreeForTest(Of TSyntaxNode As SyntaxNode)( testSrc As String, Optional compilationOptions As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional which As Integer = 0, Optional useLatestFrameworkReferences As Boolean = False) As (tree As String, syntax As SyntaxNode, operation As IOperation, compilation As Compilation) Dim fileName = "a.vb" Dim syntaxTree = Parse(testSrc, fileName, parseOptions) Dim defaultRefs = If(useLatestFrameworkReferences, LatestVbReferences, DefaultVbReferences) Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime({syntaxTree}, references:=defaultRefs.Append({ValueTupleRef, SystemRuntimeFacadeRef}), options:=If(compilationOptions, TestOptions.ReleaseDll)) Dim operationTree = GetOperationTreeForTest(Of TSyntaxNode)(compilation, fileName, which) Return (operationTree.tree, operationTree.syntax, operationTree.operation, compilation) End Function Friend Shared Sub VerifyOperationTreeForTest(Of TSyntaxNode As SyntaxNode)(compilation As VisualBasicCompilation, fileName As String, expectedOperationTree As String, Optional which As Integer = 0, Optional additionalOperationTreeVerifier As Action(Of IOperation, Compilation, SyntaxNode) = Nothing) Dim operationTree = GetOperationTreeForTest(Of TSyntaxNode)(compilation, fileName, which) OperationTreeVerifier.Verify(expectedOperationTree, operationTree.tree) If additionalOperationTreeVerifier IsNot Nothing Then additionalOperationTreeVerifier(operationTree.operation, compilation, operationTree.syntax) End If End Sub Friend Shared Sub VerifyOperationTreeForTest(Of TSyntaxNode As SyntaxNode)( testSrc As String, expectedOperationTree As String, Optional compilationOptions As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional which As Integer = 0, Optional additionalOperationTreeVerifier As Action(Of IOperation, Compilation, SyntaxNode) = Nothing, Optional useLatestFrameworkReferences As Boolean = False) Dim operationTree = GetOperationTreeForTest(Of TSyntaxNode)(testSrc, compilationOptions, parseOptions, which, useLatestFrameworkReferences) OperationTreeVerifier.Verify(expectedOperationTree, operationTree.tree) If additionalOperationTreeVerifier IsNot Nothing Then additionalOperationTreeVerifier(operationTree.operation, operationTree.compilation, operationTree.syntax) End If End Sub Friend Shared Sub VerifyNoOperationTreeForTest(Of TSyntaxNode As SyntaxNode)( testSrc As String, Optional compilationOptions As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional which As Integer = 0, Optional useLatestFrameworkReferences As Boolean = False) Dim operationTree = GetOperationTreeForTest(Of TSyntaxNode)(testSrc, compilationOptions, parseOptions, which, useLatestFrameworkReferences) Assert.Null(operationTree.tree) End Sub Friend Shared Sub VerifyOperationTreeAndDiagnosticsForTest(Of TSyntaxNode As SyntaxNode)(compilation As VisualBasicCompilation, fileName As String, expectedOperationTree As String, expectedDiagnostics As String, Optional which As Integer = 0, Optional additionalOperationTreeVerifier As Action(Of IOperation, Compilation, SyntaxNode) = Nothing) compilation.AssertTheseDiagnostics(FilterString(expectedDiagnostics)) VerifyOperationTreeForTest(Of TSyntaxNode)(compilation, fileName, expectedOperationTree, which, additionalOperationTreeVerifier) End Sub Friend Shared Sub VerifyOperationTreeAndDiagnosticsForTest(Of TSyntaxNode As SyntaxNode)( testSrc As String, expectedOperationTree As String, expectedDiagnostics As String, Optional compilationOptions As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional which As Integer = 0, Optional additionalReferences As IEnumerable(Of MetadataReference) = Nothing, Optional additionalOperationTreeVerifier As Action(Of IOperation, Compilation, SyntaxNode) = Nothing, Optional useLatestFramework As Boolean = False) Dim fileName = "a.vb" Dim syntaxTree = Parse(testSrc, fileName, parseOptions) Dim defaultRefs = If(useLatestFramework, LatestVbReferences, DefaultVbReferences) Dim references = defaultRefs.Concat({ValueTupleRef, SystemRuntimeFacadeRef}) references = If(additionalReferences IsNot Nothing, references.Concat(additionalReferences), references) Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime({syntaxTree}, references:=references, options:=If(compilationOptions, TestOptions.ReleaseDll)) VerifyOperationTreeAndDiagnosticsForTest(Of TSyntaxNode)(compilation, fileName, expectedOperationTree, expectedDiagnostics, which, additionalOperationTreeVerifier) End Sub Public Shared Function GetAssertTheseDiagnosticsString(allDiagnostics As ImmutableArray(Of Diagnostic), suppressInfos As Boolean) As String Return DumpAllDiagnostics(allDiagnostics, suppressInfos) End Function Friend Shared Function GetOperationAndSyntaxForTest(Of TSyntaxNode As SyntaxNode)(compilation As Compilation, fileName As String, Optional which As Integer = 0) As (operation As IOperation, syntaxNode As SyntaxNode) Dim node As SyntaxNode = CompilationUtils.FindBindingText(Of TSyntaxNode)(compilation, fileName, which, prefixMatch:=True) If node Is Nothing Then Return (Nothing, Nothing) End If Dim semanticModel = compilation.GetSemanticModel(node.SyntaxTree) Dim operation = semanticModel.GetOperation(node) Return (operation, node) End Function #End Region End Class
orthoxerox/roslyn
src/Compilers/Test/Utilities/VisualBasic/BasicTestBase.vb
Visual Basic
apache-2.0
38,634
' 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.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class Lambda_Relaxation Inherits BasicTestBase <Fact()> Public Sub ArgumentIsVbOrBoxWidening() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Integer) = Sub(x As Object) 'BIND1:"Sub(x As Object)" System.Console.WriteLine(x) End Sub x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWidening", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Integer)" IL_0019: newobj "Sub System.Action(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0024: ldc.i4.2 IL_0025: callvirt "Sub System.Action(Of Integer).Invoke(Integer)" IL_002a: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-1(Object)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0024: ldarg.1 IL_0025: box "Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0006: call "Sub System.Console.WriteLine(Object)" IL_000b: ret } ]]>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub ArgumentIsVbOrBoxWidening2() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Integer) x1 = CType(Sub(x As Object) 'BIND1:"Sub(x As Object)" System.Console.WriteLine(x) End Sub, System.Action(Of Integer)) x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Null(typeInfo.ConvertedType) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Identity", conv.Kind.ToString()) Assert.True(conv.Exists) Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Integer)" IL_0019: newobj "Sub System.Action(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0024: ldc.i4.2 IL_0025: callvirt "Sub System.Action(Of Integer).Invoke(Integer)" IL_002a: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-1(Object)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0024: ldarg.1 IL_0025: box "Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0006: call "Sub System.Console.WriteLine(Object)" IL_000b: ret } ]]>) Next End Sub <Fact()> Public Sub ArgumentIsVbOrBoxWidening3() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Integer) x1 = DirectCast(Sub(x As Object) 'BIND1:"Sub(x As Object)" System.Console.WriteLine(x) End Sub, System.Action(Of Integer)) x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Null(typeInfo.ConvertedType) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Identity", conv.Kind.ToString()) Assert.True(conv.Exists) Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Integer)" IL_0019: newobj "Sub System.Action(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0024: ldc.i4.2 IL_0025: callvirt "Sub System.Action(Of Integer).Invoke(Integer)" IL_002a: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-1(Object)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0024: ldarg.1 IL_0025: box "Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0006: call "Sub System.Console.WriteLine(Object)" IL_000b: ret } ]]>) Next End Sub <Fact()> Public Sub ArgumentIsVbOrBoxWidening4() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Integer) x1 = TryCast(Sub(x As Object) 'BIND1:"Sub(x As Object)" System.Console.WriteLine(x) End Sub, System.Action(Of Integer)) x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Null(typeInfo.ConvertedType) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Identity", conv.Kind.ToString()) Assert.True(conv.Exists) Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Integer)" IL_0019: newobj "Sub System.Action(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Integer)" IL_0024: ldc.i4.2 IL_0025: callvirt "Sub System.Action(Of Integer).Invoke(Integer)" IL_002a: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-1(Object)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0024: ldarg.1 IL_0025: box "Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0006: call "Sub System.Console.WriteLine(Object)" IL_000b: ret } ]]>) Next End Sub <Fact()> Public Sub ArgumentIsNarrowing() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Object) = Sub(x As Integer) 'BIND1:"Sub(x As Integer)" System.Console.WriteLine(x) End Sub x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Object)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Object)" IL_0019: newobj "Sub System.Action(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0024: ldc.i4.2 IL_0025: box "Integer" IL_002a: callvirt "Sub System.Action(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-1(Integer)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0024: ldarg.1 IL_0025: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Integer).Invoke(Integer)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Sub System.Console.WriteLine(Integer)" IL_0006: ret } ]]>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) If True Then Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Object)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42016: Implicit conversion from 'Object' to 'Integer'. Dim x1 As System.Action(Of Object) = Sub(x As Integer) 'BIND1:"Sub(x As Integer)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) If True Then Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Object)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'. Dim x1 As System.Action(Of Object) = Sub(x As Integer) 'BIND1:"Sub(x As Integer)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(543114, "DevDiv")> <Fact()> Public Sub ArgumentIsNarrowing2() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Object) = CType(Sub(x As Integer) System.Console.WriteLine(x) End Sub, System.Action(Of Object)) x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Object)" IL_0019: newobj "Sub System.Action(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0024: ldc.i4.2 IL_0025: box "Integer" IL_002a: callvirt "Sub System.Action(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-1(Integer)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0024: ldarg.1 IL_0025: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Integer).Invoke(Integer)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Sub System.Console.WriteLine(Integer)" IL_0006: ret } ]]>) Next End Sub <WorkItem(543114, "DevDiv")> <Fact()> Public Sub ArgumentIsNarrowing3() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Object) = DirectCast(Sub(x As Integer) System.Console.WriteLine(x) End Sub, System.Action(Of Object)) x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Object)" IL_0019: newobj "Sub System.Action(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0024: ldc.i4.2 IL_0025: box "Integer" IL_002a: callvirt "Sub System.Action(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-1(Integer)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0024: ldarg.1 IL_0025: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Integer).Invoke(Integer)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Sub System.Console.WriteLine(Integer)" IL_0006: ret } ]]>) Next End Sub <WorkItem(543114, "DevDiv")> <Fact()> Public Sub ArgumentIsNarrowing4() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 As System.Action(Of Object) = TryCast(Sub(x As Integer) System.Console.WriteLine(x) End Sub, System.Action(Of Object)) x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(Object)" IL_0019: newobj "Sub System.Action(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action(Of Object)" IL_0024: ldc.i4.2 IL_0025: box "Integer" IL_002a: callvirt "Sub System.Action(Of Object).Invoke(Object)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-1(Integer)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0024: ldarg.1 IL_0025: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_002a: callvirt "Sub VB$AnonymousDelegate_0(Of Integer).Invoke(Integer)" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Sub System.Console.WriteLine(Integer)" IL_0006: ret } ]]>) Next End Sub <Fact()> Public Sub ArgumentIsClrWidening() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Action(Of System.Collections.Generic.IEnumerable(Of Integer)) = Sub(x As System.Collections.IEnumerable) 'BIND1:"Sub(x As System.Collections.IEnumerable)" System.Console.WriteLine(x) End Sub x1(New Integer() {}) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Collections.Generic.IEnumerable(Of System.Int32))", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWidening", conv.Kind.ToString()) Assert.True(conv.Exists) Dim verifier = CompileAndVerify(compilation, expectedOutput:="System.Int32[]") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As System.Action(Of System.Collections.Generic.IEnumerable(Of Integer))" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As System.Action(Of System.Collections.Generic.IEnumerable(Of Integer))" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-1(System.Collections.IEnumerable)" IL_0019: newobj "Sub System.Action(Of System.Collections.Generic.IEnumerable(Of Integer))..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As System.Action(Of System.Collections.Generic.IEnumerable(Of Integer))" IL_0024: ldc.i4.0 IL_0025: newarr "Integer" IL_002a: callvirt "Sub System.Action(Of System.Collections.Generic.IEnumerable(Of Integer)).Invoke(System.Collections.Generic.IEnumerable(Of Integer))" IL_002f: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call "Sub System.Console.WriteLine(Object)" IL_0006: ret } ]]>) Next End Sub <Fact()> Public Sub ArgumentConversionError() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Action(Of Integer) = Sub(x As System.Guid) 'BIND1:"Sub(x As System.Guid)" End Sub End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36670: Nested sub does not have a signature that is compatible with delegate 'Action(Of Integer)'. Dim x1 As Action(Of Integer) = Sub(x As System.Guid) 'BIND1:"Sub(x As System.Guid)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub ArgumentConversionError2() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Action(Of Integer) = ((Sub(x As System.Guid) 'BIND1:"Sub(x As System.Guid)" End Sub)) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36670: Nested sub does not have a signature that is compatible with delegate 'Action(Of Integer)'. Dim x1 As Action(Of Integer) = ((Sub(x As System.Guid) 'BIND1:"Sub(x As System.Guid)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub ReturnValueIsDropped1() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Action = Function() 1 'BIND1:"Function()" Dim x2 As Action = Function() 'BIND2:"Function()" System.Console.WriteLine("x2") Return 2 End Function x1() x2() End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWideningDropReturnOrArgs", conv.Kind.ToString()) Assert.True(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWideningDropReturnOrArgs", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="x2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 85 (0x55) .maxstack 2 .locals init (System.Action V_0) //x1 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Action" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Action" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1()" IL_0019: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Action" IL_0024: stloc.0 IL_0025: ldsfld "Program._Closure$__.$IR0-2 As System.Action" IL_002a: brfalse.s IL_0033 IL_002c: ldsfld "Program._Closure$__.$IR0-2 As System.Action" IL_0031: br.s IL_0049 IL_0033: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0038: ldftn "Sub Program._Closure$__._Lambda$__R0-2()" IL_003e: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_0043: dup IL_0044: stsfld "Program._Closure$__.$IR0-2 As System.Action" IL_0049: ldloc.0 IL_004a: callvirt "Sub System.Action.Invoke()" IL_004f: callvirt "Sub System.Action.Invoke()" IL_0054: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-1() As Integer" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0024: callvirt "Function VB$AnonymousDelegate_0(Of Integer).Invoke() As Integer" IL_0029: pop IL_002a: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-2", <![CDATA[ { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-2 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-2 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-2() As Integer" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-2 As <generated method>" IL_0024: callvirt "Function VB$AnonymousDelegate_0(Of Integer).Invoke() As Integer" IL_0029: pop IL_002a: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-2", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldstr "x2" IL_0005: call "Sub System.Console.WriteLine(String)" IL_000a: ldc.i4.2 IL_000b: ret } ]]>) Next End Sub <Fact()> Public Sub ReturnValueIsDropped2_ReturnTypeInferenceError() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Action = Function() AddressOf Main 'BIND1:"Function()" Dim x2 As Action = Function() 'BIND2:"Function()" Return AddressOf Main End Function End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Action", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30581: 'AddressOf' expression cannot be converted to 'Object' because 'Object' is not a delegate type. Dim x1 As Action = Function() AddressOf Main 'BIND1:"Function()" ~~~~~~~~~~~~~~ BC36751: Cannot infer a return type. Consider adding an 'As' clause to specify the return type. Dim x2 As Action = Function() 'BIND2:"Function()" ~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub SubToFunction() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Integer) = Sub() 'BIND1:"Sub()" End Sub End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36670: Nested sub does not have a signature that is compatible with delegate 'Func(Of Integer)'. Dim x1 As Func(Of Integer) = Sub() 'BIND1:"Sub()" ~~~~~~~~~~~~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub ReturnIsWidening() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Integer) = Function() CObj(1) 'BIND1:"Function()" Dim x2 As Func(Of Integer) = Function() As Object 'BIND2:"Function() As Object" Return 2 End Function System.Console.WriteLine(x1()) System.Console.WriteLine(x2()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="1" & vbCrLf & "2" & vbCrLf) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 95 (0x5f) .maxstack 2 .locals init (System.Func(Of Integer) V_0) //x1 IL_0000: ldsfld "Program._Closure$__.$I0-1 As System.Func(Of Integer)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As System.Func(Of Integer)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-1() As Integer" IL_0019: newobj "Sub System.Func(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As System.Func(Of Integer)" IL_0024: stloc.0 IL_0025: ldsfld "Program._Closure$__.$IR0-1 As System.Func(Of Integer)" IL_002a: brfalse.s IL_0033 IL_002c: ldsfld "Program._Closure$__.$IR0-1 As System.Func(Of Integer)" IL_0031: br.s IL_0049 IL_0033: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0038: ldftn "Function Program._Closure$__._Lambda$__R0-1() As Integer" IL_003e: newobj "Sub System.Func(Of Integer)..ctor(Object, System.IntPtr)" IL_0043: dup IL_0044: stsfld "Program._Closure$__.$IR0-1 As System.Func(Of Integer)" IL_0049: ldloc.0 IL_004a: callvirt "Function System.Func(Of Integer).Invoke() As Integer" IL_004f: call "Sub System.Console.WriteLine(Integer)" IL_0054: callvirt "Function System.Func(Of Integer).Invoke() As Integer" IL_0059: call "Sub System.Console.WriteLine(Integer)" IL_005e: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: box "Integer" IL_0006: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_000b: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 47 (0x2f) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-2 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-2 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-2() As Object" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-2 As <generated method>" IL_0024: callvirt "Function VB$AnonymousDelegate_0(Of Object).Invoke() As Object" IL_0029: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_002e: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-2", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: box "Integer" IL_0006: ret } ]]>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If End If CompileAndVerify(compilation, expectedOutput:="1" & vbCrLf & "2" & vbCrLf) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42016: Implicit conversion from 'Object' to 'Integer'. Dim x1 As Func(Of Integer) = Function() CObj(1) 'BIND1:"Function()" ~~~~~~~ BC42016: Implicit conversion from 'Object' to 'Integer'. Dim x2 As Func(Of Integer) = Function() As Object 'BIND2:"Function() As Object" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'. Dim x1 As Func(Of Integer) = Function() CObj(1) 'BIND1:"Function()" ~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'. Dim x2 As Func(Of Integer) = Function() As Object 'BIND2:"Function() As Object" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub ReturnIsIsVbOrBoxNarrowing1() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Object) = Function() As Integer 'BIND1:"Function() As Integer" Return 2 End Function System.Console.WriteLine(x1()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Object)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWidening", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="2") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 52 (0x34) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Func(Of Object)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Func(Of Object)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__R0-1() As Object" IL_0019: newobj "Sub System.Func(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Func(Of Object)" IL_0024: callvirt "Function System.Func(Of Object).Invoke() As Object" IL_0029: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_002e: call "Sub System.Console.WriteLine(Object)" IL_0033: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 47 (0x2f) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-1() As Integer" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0024: callvirt "Function VB$AnonymousDelegate_0(Of Integer).Invoke() As Integer" IL_0029: box "Integer" IL_002e: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: ret } ]]>) Next End Sub <Fact()> Public Sub ReturnIsClrNarrowing() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Collections.IEnumerable) = Function() As Collections.Generic.IEnumerable(Of Integer) 'BIND1:"Function() As Collections.Generic.IEnumerable(Of Integer)" Return New Integer() {} End Function System.Console.WriteLine(x1()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Collections.IEnumerable)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWidening", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="System.Int32[]") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 47 (0x2f) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As System.Func(Of System.Collections.IEnumerable)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As System.Func(Of System.Collections.IEnumerable)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-1() As System.Collections.Generic.IEnumerable(Of Integer)" IL_0019: newobj "Sub System.Func(Of System.Collections.IEnumerable)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As System.Func(Of System.Collections.IEnumerable)" IL_0024: callvirt "Function System.Func(Of System.Collections.IEnumerable).Invoke() As System.Collections.IEnumerable" IL_0029: call "Sub System.Console.WriteLine(Object)" IL_002e: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: newarr "Integer" IL_0006: ret } ]]>) Next End Sub <Fact()> Public Sub ReturnNoConversion() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Guid) = Function() As Integer 'BIND1:"Function() As Integer" Return 1 End Function End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Guid)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36532: Nested function does not have the same signature as delegate 'Func(Of Guid)'. Dim x1 As Func(Of Guid) = Function() As Integer 'BIND1:"Function() As Integer" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub AllArgumentsIgnored() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Integer, Integer) = Function() 1 'BIND1:"Function()" Dim x2 As Func(Of Integer, Integer) = Function() As Integer 'BIND2:"Function() As Integer" Return 2 End Function System.Console.WriteLine(x1(12)) System.Console.WriteLine(x2(13)) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32, System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWideningDropReturnOrArgs", conv.Kind.ToString()) Assert.True(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32, System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Widening, Lambda, DelegateRelaxationLevelWideningDropReturnOrArgs", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="1" & vbCrLf & "2" & vbCrLf) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 99 (0x63) .maxstack 3 .locals init (System.Func(Of Integer, Integer) V_0) //x1 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As System.Func(Of Integer, Integer)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As System.Func(Of Integer, Integer)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__R0-1(Integer) As Integer" IL_0019: newobj "Sub System.Func(Of Integer, Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As System.Func(Of Integer, Integer)" IL_0024: stloc.0 IL_0025: ldsfld "Program._Closure$__.$IR0-2 As System.Func(Of Integer, Integer)" IL_002a: brfalse.s IL_0033 IL_002c: ldsfld "Program._Closure$__.$IR0-2 As System.Func(Of Integer, Integer)" IL_0031: br.s IL_0049 IL_0033: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0038: ldftn "Function Program._Closure$__._Lambda$__R0-2(Integer) As Integer" IL_003e: newobj "Sub System.Func(Of Integer, Integer)..ctor(Object, System.IntPtr)" IL_0043: dup IL_0044: stsfld "Program._Closure$__.$IR0-2 As System.Func(Of Integer, Integer)" IL_0049: ldloc.0 IL_004a: ldc.i4.s 12 IL_004c: callvirt "Function System.Func(Of Integer, Integer).Invoke(Integer) As Integer" IL_0051: call "Sub System.Console.WriteLine(Integer)" IL_0056: ldc.i4.s 13 IL_0058: callvirt "Function System.Func(Of Integer, Integer).Invoke(Integer) As Integer" IL_005d: call "Sub System.Console.WriteLine(Integer)" IL_0062: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 42 (0x2a) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-1() As Integer" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0024: callvirt "Function VB$AnonymousDelegate_0(Of Integer).Invoke() As Integer" IL_0029: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-2", <![CDATA[ { // Code size 42 (0x2a) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-2 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-2 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Function Program._Closure$__._Lambda$__0-2() As Integer" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-2 As <generated method>" IL_0024: callvirt "Function VB$AnonymousDelegate_0(Of Integer).Invoke() As Integer" IL_0029: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-2", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: ret } ]]>) Next End Sub <Fact()> Public Sub ParameterCountMismatch() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Integer) = Function(y As Integer) 1 'BIND1:"Function(y As Integer)" Dim x2 As Func(Of Integer) = Function(y As Integer) As Integer 'BIND2:"Function(y As Integer) As Integer" Return 2 End Function Dim x3 As Func(Of Integer, Integer, Integer) = Function(y) 1 'BIND3:"Function(y)" Dim x4 As Func(Of Integer, Integer, Integer) = Function(y) As Integer 'BIND4:"Function(y) As Integer" Return 2 End Function End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If If True Then Dim node3 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 3) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node3.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32, System.Int32, System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node3.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If If True Then Dim node4 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 4) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node4.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32, System.Int32, System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node4.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer)'. Dim x1 As Func(Of Integer) = Function(y As Integer) 1 'BIND1:"Function(y As Integer)" ~~~~~~~~~~~~~~~~~~~~~~~~ BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer)'. Dim x2 As Func(Of Integer) = Function(y As Integer) As Integer 'BIND2:"Function(y As Integer) As Integer" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer, Integer)'. Dim x3 As Func(Of Integer, Integer, Integer) = Function(y) 1 'BIND3:"Function(y)" ~~~~~~~~~~~~~ BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer, Integer)'. Dim x4 As Func(Of Integer, Integer, Integer) = Function(y) As Integer 'BIND4:"Function(y) As Integer" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub ByRefMismatch() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Main() Dim x1 As Func(Of Integer, Integer) = Function(ByRef y As Integer) 1 'BIND1:"Function(ByRef y As Integer)" End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("System.Func(Of System.Int32, System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Lambda, DelegateRelaxationLevelInvalid", conv.Kind.ToString()) Assert.False(conv.Exists) End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'. Dim x1 As Func(Of Integer, Integer) = Function(ByRef y As Integer) 1 'BIND1:"Function(ByRef y As Integer)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) Next End Sub <Fact()> Public Sub ByRefArgumentIsWidening() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Delegate Sub d1(ByRef a As String) Module Program Sub Main() Dim x1 As d1 = Sub(ByRef y As Object) 'BIND1:"Sub(ByRef y As Object)" System.Console.WriteLine(y) y = "2" End Sub Dim x2 As String = "1" x1(x2) System.Console.WriteLine(x2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("d1", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="1" & vbCrLf & "2" & vbCrLf) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 56 (0x38) .maxstack 2 .locals init (String V_0) //x2 IL_0000: ldsfld "Program._Closure$__.$IR0-1 As d1" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$IR0-1 As d1" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__R0-1(ByRef String)" IL_0019: newobj "Sub d1..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$IR0-1 As d1" IL_0024: ldstr "1" IL_0029: stloc.0 IL_002a: ldloca.s V_0 IL_002c: callvirt "Sub d1.Invoke(ByRef String)" IL_0031: ldloc.0 IL_0032: call "Sub System.Console.WriteLine(String)" IL_0037: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__R0-1", <![CDATA[ { // Code size 55 (0x37) .maxstack 2 .locals init (Object V_0) IL_0000: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-1(ByRef Object)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Object)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0024: ldarg.1 IL_0025: ldind.ref IL_0026: stloc.0 IL_0027: ldloca.s V_0 IL_0029: callvirt "Sub VB$AnonymousDelegate_0(Of Object).Invoke(ByRef Object)" IL_002e: ldarg.1 IL_002f: ldloc.0 IL_0030: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Object) As String" IL_0035: stind.ref IL_0036: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldind.ref IL_0002: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0007: call "Sub System.Console.WriteLine(Object)" IL_000c: ldarg.1 IL_000d: ldstr "2" IL_0012: stind.ref IL_0013: ret } ]]>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("d1", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If CompileAndVerify(compilation, expectedOutput:="1" & vbCrLf & "2" & vbCrLf) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC41999: Implicit conversion from 'Object' to 'String' in copying the value of 'ByRef' parameter 'y' back to the matching argument. Dim x1 As d1 = Sub(ByRef y As Object) 'BIND1:"Sub(ByRef y As Object)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) If True Then Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("d1", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Narrowing, Lambda, DelegateRelaxationLevelNarrowing", conv.Kind.ToString()) Assert.True(conv.Exists) End If CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32029: Option Strict On disallows narrowing from type 'Object' to type 'String' in copying the value of 'ByRef' parameter 'y' back to the matching argument. Dim x1 As d1 = Sub(ByRef y As Object) 'BIND1:"Sub(ByRef y As Object)" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub NoRelaxation() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Delegate Sub d1(ByRef a As Object) Module Program Sub Main() Dim x1 As d1 = Sub(ByRef y As Object) 'BIND1:"Sub(ByRef y As Object)" System.Console.WriteLine(y) y = "2" End Sub Dim x2 As Object = "1" x1(x2) System.Console.WriteLine(x2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef) For Each optStrict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(optStrict)) Assert.Equal(optStrict, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("d1", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="1" & vbCrLf & "2" & vbCrLf) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 61 (0x3d) .maxstack 2 .locals init (Object V_0) //x2 IL_0000: ldsfld "Program._Closure$__.$I0-1 As d1" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-1 As d1" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-1(ByRef Object)" IL_0019: newobj "Sub d1..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-1 As d1" IL_0024: ldstr "1" IL_0029: stloc.0 IL_002a: ldloca.s V_0 IL_002c: callvirt "Sub d1.Invoke(ByRef Object)" IL_0031: ldloc.0 IL_0032: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0037: call "Sub System.Console.WriteLine(Object)" IL_003c: ret } ]]>) verifier.VerifyIL("Program._Closure$__._Lambda$__0-1", <![CDATA[ { // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldind.ref IL_0002: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0007: call "Sub System.Console.WriteLine(Object)" IL_000c: ldarg.1 IL_000d: ldstr "2" IL_0012: stind.ref IL_0013: ret } ]]>) Next End Sub <Fact()> Public Sub RestrictedTypes1() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Delegate Sub d5(a1 As Object, a2 As ArgIterator) Class Program Sub Main() Dim x1 As d5 = Sub(y1 As Object, y2 As ArgIterator) End Sub Dim x2 As d5 = Sub(y1 As String, y2 As ArgIterator) End Sub End Sub Sub Test123(y2 As ArgIterator) Dim x1 As Action(Of Object) = Function(y1 As Object) As ArgIterator Return y2 '1 End Function '1 Dim x2 As Action(Of Object) = Function(y1 As Object) As ArgIterator End Function '2 Dim x3 As Action(Of Object) = Function(y1 As Object) Return y2 '3 End Function '3 Dim x4 As d6 = Function() Nothing End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(compilationDef, <![CDATA[ .class public auto ansi sealed d6 extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object TargetObject, native int TargetMethod) runtime managed { } // end of method d6::.ctor .method public newslot strict virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(int32 x, class [mscorlib]System.AsyncCallback DelegateCallback, object DelegateAsyncState) runtime managed { } // end of method d6::BeginInvoke .method public newslot strict virtual instance valuetype [mscorlib]System.ArgIterator EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed { } // end of method d6::EndInvoke .method public newslot strict virtual instance valuetype [mscorlib]System.ArgIterator Invoke(int32 x) runtime managed { } // end of method d6::Invoke } // end of class d6 ]]>) 'Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, OptionsExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> <![CDATA[ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x2 As d5 = Sub(y1 As String, y2 As ArgIterator) ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x1 As Action(Of Object) = Function(y1 As Object) As ArgIterator ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x2 As Action(Of Object) = Function(y1 As Object) As ArgIterator ~~~~~~~~~~~ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function '2 ~~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x3 As Action(Of Object) = Function(y1 As Object) ~~~~~~~~~~~~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x4 As d6 = Function() Nothing ~~~~~~~~~~ ]]> </expected>) End Sub <Fact()> Public Sub OverloadResolution1() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Test1(x As Func(Of Func(Of Object, Integer))) System.Console.WriteLine(x) End Sub Sub Test1(x As Func(Of Func(Of Integer, Integer))) System.Console.WriteLine(x) End Sub Function Test2(a As Object) As Integer Return 1 End Function Sub Main() 10: Test1(Function() Function(a As Object) 1) 20: Test1(Function() Return Function(a As Object) 1 End Function) 30: Test1(Function() Return Function(a As Object) Return 1 End Function End Function) 40: Test1(Function() Return Function(a As Object) As Integer Return 1 End Function End Function) 50: Test1(Function() As Func(Of Object, Integer) Return Function(a As Object) Return 1 End Function End Function) Test1(Function() AddressOf Test2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30521: Overload resolution failed because no accessible 'Test1' is most specific for these arguments: 'Public Sub Test1(x As Func(Of Func(Of Object, Integer)))': Not most specific. 'Public Sub Test1(x As Func(Of Func(Of Integer, Integer)))': Not most specific. 10: Test1(Function() Function(a As Object) 1) ~~~~~ BC30521: Overload resolution failed because no accessible 'Test1' is most specific for these arguments: 'Public Sub Test1(x As Func(Of Func(Of Object, Integer)))': Not most specific. 'Public Sub Test1(x As Func(Of Func(Of Integer, Integer)))': Not most specific. 20: Test1(Function() ~~~~~ BC30521: Overload resolution failed because no accessible 'Test1' is most specific for these arguments: 'Public Sub Test1(x As Func(Of Func(Of Object, Integer)))': Not most specific. 'Public Sub Test1(x As Func(Of Func(Of Integer, Integer)))': Not most specific. 30: Test1(Function() ~~~~~ BC30521: Overload resolution failed because no accessible 'Test1' is most specific for these arguments: 'Public Sub Test1(x As Func(Of Func(Of Object, Integer)))': Not most specific. 'Public Sub Test1(x As Func(Of Func(Of Integer, Integer)))': Not most specific. 40: Test1(Function() ~~~~~ BC30521: Overload resolution failed because no accessible 'Test1' is most specific for these arguments: 'Public Sub Test1(x As Func(Of Func(Of Object, Integer)))': Not most specific. 'Public Sub Test1(x As Func(Of Func(Of Integer, Integer)))': Not most specific. Test1(Function() AddressOf Test2) ~~~~~ </expected>) End Sub <Fact()> Public Sub OverloadResolution2() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Test1(x As Func(Of Object, Integer)) System.Console.WriteLine(x) End Sub Sub Test1(x As Func(Of Integer, Integer)) System.Console.WriteLine(x) End Sub Sub Main() Test1(Function(x As Object) 1) Test1(Function(x As Integer) 1) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ System.Func`2[System.Object,System.Int32] System.Func`2[System.Int32,System.Int32] ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub OverloadResolution3() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Test2(x As Func(Of Object, Integer)) System.Console.WriteLine(x) End Sub Sub Test2(x As Func(Of Integer, Integer)) System.Console.WriteLine(x) End Sub Sub Main() Test2(Function(x As String) 1) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30519: Overload resolution failed because no accessible 'Test2' can be called without a narrowing conversion: 'Public Sub Test2(x As Func(Of Object, Integer))': Argument matching parameter 'x' narrows to 'Func(Of Object, Integer)'. 'Public Sub Test2(x As Func(Of Integer, Integer))': Argument matching parameter 'x' narrows to 'Func(Of Integer, Integer)'. Test2(Function(x As String) 1) ~~~~~ </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30518: Overload resolution failed because no accessible 'Test2' can be called with these arguments: 'Public Sub Test2(x As Func(Of Object, Integer))': Option Strict On disallows implicit conversions from 'Object' to 'String'. 'Public Sub Test2(x As Func(Of Integer, Integer))': Option Strict On disallows implicit conversions from 'Integer' to 'String'. Test2(Function(x As String) 1) ~~~~~ </expected>) End Sub <Fact()> Public Sub OverloadResolution4() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module Program Sub Test3(x As Func(Of Object)) System.Console.WriteLine(x) End Sub Sub Test4(x As Func(Of Object)) System.Console.WriteLine(x) End Sub Sub Test3(x As Func(Of Integer)) System.Console.WriteLine(x) End Sub Sub Test5(x As Func(Of Integer)) System.Console.WriteLine(x) End Sub Sub Main() Test3(Function() "a") Test4(Function() "a") Test5(Function() "a") Test3(Function() Return "b" End Function) Test4(Function() Return "b" End Function) Test5(Function() Return "b" End Function) Test3(Function() As String Return "b" End Function) Test4(Function() As String Return "b" End Function) Test5(Function() As String Return "b" End Function) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42016: Implicit conversion from 'String' to 'Integer'. Test5(Function() "a") ~~~ BC42016: Implicit conversion from 'String' to 'Integer'. Return "b" ~~~ BC42016: Implicit conversion from 'String' to 'Integer'. Test5(Function() As String ~~~~~~~~~~~~~~~~~~~~~ </expected>) CompileAndVerify(compilation, <![CDATA[ System.Func`1[System.Object] System.Func`1[System.Object] System.Func`1[System.Int32] System.Func`1[System.Object] System.Func`1[System.Object] System.Func`1[System.Int32] System.Func`1[System.Object] System.Func`1[System.Object] System.Func`1[System.Int32] ]]>) End Sub <Fact()> Public Sub OverloadResolution5() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Option Strict On Imports System Module Program Sub Test6(x As Object) System.Console.WriteLine(x) End Sub Sub Test7(x As Object) System.Console.WriteLine(x) End Sub Sub Test6(x As Func(Of Object)) System.Console.WriteLine(x) End Sub Sub Test8(x As Func(Of Object)) System.Console.WriteLine(x) End Sub Sub Test9(x As Func(Of String)) System.Console.WriteLine(x) End Sub Sub Test10(x As Func(Of String)) System.Console.WriteLine(x) End Sub Sub Test9(x As Func(Of Object)) System.Console.WriteLine(x) End Sub Sub Test11(x As Func(Of String)) System.Console.WriteLine(x) End Sub Sub Main() Test6(Function() "a") Test7(Function() "a") Test8(Function() "a") Test6(Function() Return "b" End Function) Test7(Function() Return "b" End Function) Test8(Function() Return "b" End Function) Test6(Function() As String Return "b" End Function) Test7(Function() As String Return "b" End Function) Test8(Function() As String Return "b" End Function) Test9(Function() "a") Test10(Function() "a") Test11(Function() "a") Test9(Function() Return "b" End Function) Test10(Function() Return "b" End Function) Test11(Function() Return "b" End Function) Test9(Function() As String Return "c" End Function) Test10(Function() As String Return "c" End Function) Test11(Function() As String Return "c" End Function) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) CompileAndVerify(compilation, <![CDATA[ System.Func`1[System.Object] VB$AnonymousDelegate_0`1[System.String] System.Func`1[System.Object] System.Func`1[System.Object] VB$AnonymousDelegate_0`1[System.String] System.Func`1[System.Object] System.Func`1[System.Object] VB$AnonymousDelegate_0`1[System.String] System.Func`1[System.Object] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] System.Func`1[System.String] ]]>) End Sub <Fact()> Public Sub ArgumentIsVbOrBoxWidening5() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim val As Integer = 1 Dim x1 As System.Action(Of Integer) = Sub(x As Object) System.Console.WriteLine("{0}{1}",val,x) End Sub x1(2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) Dim verifier = CompileAndVerify(compilation, expectedOutput:="12") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 30 (0x1e) .maxstack 3 IL_0000: newobj "Sub Program._Closure$__0-0..ctor()" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: stfld "Program._Closure$__0-0.$VB$Local_val As Integer" IL_000c: ldftn "Sub Program._Closure$__0-0._Lambda$__R1(Integer)" IL_0012: newobj "Sub System.Action(Of Integer)..ctor(Object, System.IntPtr)" IL_0017: ldc.i4.2 IL_0018: callvirt "Sub System.Action(Of Integer).Invoke(Integer)" IL_001d: ret } ]]>) verifier.VerifyIL("Program._Closure$__0-0._Lambda$__R1", <![CDATA[ { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: box "Integer" IL_0007: call "Sub Program._Closure$__0-0._Lambda$__1(Object)" IL_000c: ret } ]]>) verifier.VerifyIL("Program._Closure$__0-0._Lambda$__1", <![CDATA[ { // Code size 28 (0x1c) .maxstack 3 IL_0000: ldstr "{0}{1}" IL_0005: ldarg.0 IL_0006: ldfld "Program._Closure$__0-0.$VB$Local_val As Integer" IL_000b: box "Integer" IL_0010: ldarg.1 IL_0011: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0016: call "Sub System.Console.WriteLine(String, Object, Object)" IL_001b: ret } ]]>) End Sub <Fact()> Public Sub CustomModifiers1() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Class Program Shared Sub Main() Dim d As TestCustomModifiers Dim a(-1) As Integer d = AddressOf F1 d(a) d = Function(x) System.Console.WriteLine("L1") Return x End Function d(a) d = Function(x As Integer()) As Integer() System.Console.WriteLine("L2") Return x End Function d(a) End Sub Shared Function F1(x As Integer()) As Integer() System.Console.WriteLine("F1") Return x End Function End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(compilationDef, <![CDATA[ .class public auto ansi sealed TestCustomModifiers extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object TargetObject, native int TargetMethod) runtime managed { } // end of method TestCustomModifiers::.ctor .method public newslot strict virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) [] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) x, class [mscorlib]System.AsyncCallback DelegateCallback, object DelegateAsyncState) runtime managed { } // end of method TestCustomModifiers::BeginInvoke .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) [] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed { } // end of method TestCustomModifiers::EndInvoke .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) [] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) Invoke(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) [] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) x) runtime managed { } // end of method TestCustomModifiers::Invoke } // end of class TestCustomModifiers ]]>.Value, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) CompileAndVerify(compilation, expectedOutput:="F1" & vbCrLf & "L1" & vbCrLf & "L2") End Sub <WorkItem(543647, "DevDiv")> <Fact()> Public Sub BaseMethodParamIntegerDelegateParamShort() Dim compilationDef = <compilation name="Test"> <file name="a.vb"> Imports System Delegate Function DelShort(ByVal s As Short) As String MustInherit Class BaseClass Overridable Function MethodThatIsVirtual(ByVal i As Integer) As String Return "Base Method" End Function End Class Class DerivedClass Inherits BaseClass Overrides Function MethodThatIsVirtual(ByVal i As Integer) As String Return "Derived Method" End Function Function TC2() As String Dim dS As DelShort = AddressOf MyBase.MethodThatIsVirtual Return dS(1) End Function End Class Module Program Sub Main(args As String()) Dim d = New DerivedClass() Console.WriteLine(d.TC2()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim verifier = CompileAndVerify(compilation, expectedOutput:="Base Method") End Sub <WorkItem(531532, "DevDiv")> <Fact()> Public Sub Bug18258() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.CompilerServices Friend Module Program <Extension> Sub Bar(Of T)(x As T) Dim d As New Action(Of Action(Of T))(Sub(y) End Sub) d.Invoke(AddressOf x.Bar) End Sub Sub Main() End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(compilationDef, {SystemCoreRef}, TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim verifier = CompileAndVerify(compilation) End Sub <WorkItem(1096576, "DevDiv")> <Fact()> Public Sub Bug1096576() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Imports System Class Thing Sub Foo() End Sub Public t As New Thing Public tcb As AsyncCallback = AddressOf t.Foo End Class ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(compilationDef, TestOptions.DebugDll) Dim verifier = CompileAndVerify(compilation).VerifyDiagnostics() End Sub End Class End Namespace
DavidKarlas/roslyn
src/Compilers/VisualBasic/Test/Semantic/Semantics/Lambda_Relaxation.vb
Visual Basic
apache-2.0
117,712
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp Public Class ExternalCodeFunctionTests Inherits AbstractCodeFunctionTests #Region "FullName tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName1() Dim code = <Code> class C { void $$Goo(string s) { } } </Code> TestFullName(code, "C.Goo") End Sub #End Region #Region "Name tests" <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName1() Dim code = <Code> class C { void $$Goo(string s) { } } </Code> TestName(code, "Goo") End Sub #End Region Protected Overrides ReadOnly Property LanguageName As String = LanguageNames.CSharp Protected Overrides ReadOnly Property TargetExternalCodeElements As Boolean = True End Class End Namespace
mmitche/roslyn
src/VisualStudio/Core/Test/CodeModel/CSharp/ExternalCodeFunctionTests.vb
Visual Basic
apache-2.0
1,243
' Licensed to the .NET Foundation under one or more 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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend Enum RequiredConversion ' "ConversionRequired" in Dev10 compiler '// When we do type inference, we have to unify the types supplied and infer generic parameters. '// e.g. if we have Sub f(ByVal x as T(), ByVal y as T) and invoke it with x=AnimalArray, y=Mammal, '// then we have to figure out that T should be an Animal. The way that's done: '// (1) All the requirements on T are gathered together, e.g. '// T:{Mammal+vb, Animal+arr} means '// (+vb) "T is something such that argument Mammal can be supplied to parameter T" '// (+arr) "T is something such that argument Animal() can be supplied to parameter T()" '// (2) We'll go through each candidate type to see if they work. First T=Mammal. Does it work for each requirement? '// (+vb) Yes, argument Mammal can be supplied to parameter Mammal through identity '// (+arr) Sort-of, argument Animal() can be supplied to parameter Mammal() only through narrowing '// (3) Now try the next candidate, T=Animal. Does it work for each requirement? '// (+vb) Yes, argument Mammal can be supplied to parameter Animal through widening '// (+arr) Yes, argument Animal() can be supplied to parameter Animal() through identity '// (4) At the end, we pick out the one that worked "best". In this case T=Animal worked best. '// The criteria for "best" are documented and implemented in ConversionResolution.cpp/FindDominantType. '// This enumeration contains the different kinds of requirements... '// Each requirement is that some X->Y be a conversion. Inside FindDominantType we will grade each candidate '// on whether it could satisfy that requirement with an Identity, a Widening, a Narrowing, or not at all. '// Identity: '// This restriction requires that req->candidate be an identity conversion according to the CLR. '// e.g. supplying "New List(Of Mammal)" to parameter "List(Of T)", we require that Mammal->T be identity '// e.g. supplying "New List(Of Mammal)" to a parameter "List(Of T)" we require that Mammal->T be identity '// e.g. supplying "Dim ml as ICovariant(Of Mammal) = Nothing" to a parameter "*ByRef* ICovariant(Of T)" we require that Mammal->T be identity '// (but for non-ByRef covariance see "ReferenceConversion" below.) '// Note that CLR does not include lambda->delegate, and doesn't include user-defined conversions. Identity '// Any: '// This restriction requires that req->candidate be a conversion according to VB. '// e.g. supplying "New Mammal" to parameter "T", we require that Mammal->T be a VB conversion '// It includes user-defined conversions and all the VB-specific conversions. Any '// AnyReverse: '// This restriction requires that candidate->req be a conversion according to VB. '// It might hypothetically be used for "out" parameters if VB ever gets them: '// e.g. supplying "Dim m as Mammal" to parameter "Out T" we require that T->Mammal be a VB conversion. '// But the actual reason it's included now is as be a symmetric form of AnyConversion: '// this simplifies the implementation of InvertConversionRequirement and CombineConversionRequirements AnyReverse '// AnyAndReverse: '// This restriction requires that req->candidate and candidate->hint be conversions according to VB. '// e.g. supplying "Dim m as New Mammal" to "ByRef T", we require that Mammal->T be a conversion, and also T->Mammal for the copyback. '// Again, each direction includes user-defined conversions and all the VB-specific conversions. AnyAndReverse '// ArrayElement: '// This restriction requires that req->candidate be a array element conversion. '// e.g. supplying "new Mammal(){}" to "ByVal T()", we require that Mammal->T be an array-element-conversion. '// It consists of the subset of CLR-array-element-conversions that are also allowed by VB. '// Note: ArrayElementConversion gives us array covariance, and also by enum()->underlying_integral(). ArrayElement '// Reference: '// This restriction requires that req->candidate be a reference conversion. '// e.g. supplying "Dim x as ICovariant(Of Mammal)" to "ICovariant(Of T)", we require that Mammal->T be a reference conversion. '// It consists of the subset of CLR-reference-conversions that are also allowed by VB. Reference '// ReverseReference: '// This restriction requires that candidate->req be a reference conversion. '// e.g. supplying "Dim x as IContravariant(Of Animal)" to "IContravariant(Of T)", we require that T->Animal be a reference conversion. '// Note that just because T->U is a widening reference conversion, it doesn't mean that U->T is narrowing, nor vice versa. '// Again it consists of the subset of CLR-reference-conversions that are also allowed by VB. ReverseReference '// None: '// This is not a restriction. It allows for the candidate to have any relation, even be completely unrelated, '// to the hint type. It is used as a way of feeding in candidate suggestions into the algorithm, but leaving '// them purely as suggestions, without any requirement to be satisfied. (e.g. you might add the restriction '// that there be a conversion from some literal "1L", and add the type hint "Long", so that Long can be used '// as a candidate but it's not required. This is used in computing the dominant type of an array literal.) None '// These restrictions form a partial order composed of three chains: from less strict to more strict, we have: '// [reverse chain] [None] < AnyReverse < ReverseReference < Identity '// [middle chain] None < [Any,AnyReverse] < AnyConversionAndReverse < Identity '// [forward chain] [None] < Any < ArrayElement < Reference < Identity '// '// = KEY: '// / | \ = Identity '// / | \ +r Reference '// -r | +r -r ReverseReference '// | +-any | +-any AnyConversionAndReverse '// | /|\ +arr +arr ArrayElement '// | / | \ | +any Any '// -any | +any -any AnyReverse '// \ | / none None '// \ | / '// none '// '// The routine "CombineConversionRequirements" finds the least upper bound of two elements. '// The routine "StrengthenConversionRequirementToReference" walks up the current chain to a reference conversion. '// The routine "InvertConversionRequirement" switches from reverse chain to forwards chain or vice versa, '// and asserts if given ArrayElementConversion since this has no counterparts in the reverse chain. '// These three routines are called by InferTypeArgumentsFromArgumentDirectly, as it matches an '// argument type against a parameter. '// The routine "CheckHintSatisfaction" is what actually implements the satisfaction-of-restriction check. '// '// If you make any changes to this enum or the partial order, you'll have to change all the above functions. '// They do "VSASSERT(Count==8)" to help remind you to change them, should you make any additions to this enum. Count End Enum End Namespace
physhi/roslyn
src/Compilers/VisualBasic/Portable/Semantics/TypeInference/RequiredConversion.vb
Visual Basic
apache-2.0
8,119
Public Class Node(Of T As IHasRect) Public bound As Rectangle Private contents As New List(Of T) Public nodes As New List(Of Node(Of T))(4) Public Sub New(ByVal b As Rectangle) bound = b End Sub Public ReadOnly Property Count As Integer Get Dim cnt As Integer = 0 For Each n As Node(Of T) In nodes cnt += n.Count Next cnt += contents.Count Return cnt End Get End Property Public ReadOnly Property SubTreeContents As List(Of T) Get Dim results As New List(Of T) For Each n As Node(Of T) In nodes results.AddRange(n.SubTreeContents) Next results.AddRange(contents) Return results End Get End Property Public ReadOnly Property IsEmpty As Boolean Get Return IIf(bound.IsEmpty OrElse nodes.Count = 0, True, False) End Get End Property Public Function Query(ByVal queryArea As Rectangle) As List(Of T) Dim results As New List(Of T) ' this quad contains items that are not entirely contained by ' it's four sub-quads. Iterate through the items in this quad ' to see if they intersect. For Each item As T In contents If queryArea.IntersectsWith(item.Rect) Then results.Add(item) Next For Each node As Node(Of T) In nodes If node.IsEmpty Then Continue For ' Case 1: search area completely contained by sub-quad ' if a node completely contains the query area, go down that branch ' and skip the remaining nodes (break this loop) If node.bound.Contains(queryArea) Then results.AddRange(node.Query(queryArea)) Exit For End If ' Case 2: Sub-quad completely contained by search area ' if the query area completely contains a sub-quad, ' just add all the contents of that quad and it's children ' to the result set. You need to continue the loop to test ' the other quads If queryArea.Contains(node.bound) Then results.AddRange(node.SubTreeContents) Continue For End If ' Case 3: search area intersects with sub-quad ' traverse into this quad, continue the loop to search other ' quads If node.bound.IntersectsWith(queryArea) Then results.AddRange(node.Query(queryArea)) Next Return results End Function Public Sub Insert(ByVal item As T) ' if the item is not contained in this quad, there's a problem If Not bound.Contains(item.Rect) Then 'Trace.TraceWarning("feature is out of the bounds of this quadtree node"); Return End If ' if the subnodes are null create them. may not be sucessfull: see below ' we may be at the smallest allowed size in which case the subnodes will not be created If nodes.Count = 0 Then CreateSubNodes() ' for each subnode: ' if the node contains the item, add the item to that node and return ' this recurses into the node that is just large enough to fit this item For Each node As Node(Of T) In nodes If node.bound.Contains(item.Rect) Then node.Insert(item) Return End If Next ' if we make it to here, either ' 1) none of the subnodes completely contained the item. or ' 2) we're at the smallest subnode size allowed ' add the item to this node's contents. contents.Add(item) End Sub Public Sub ForEach(ByVal action As QuadTree(Of T).QTAction) action(Me) ' draw the child quads For Each node As Node(Of T) In nodes node.ForEach(action) Next End Sub Private Sub CreateSubNodes() ' the smallest subnode has an area If (bound.Height * bound.Width) <= 10 Then Return Dim halfWidth As Single = (bound.Width / 2.0F) Dim halfHeight As Single = (bound.Height / 2.0F) nodes.Add(New Node(Of T)(New Rectangle(bound.Location, New Size(halfWidth, halfHeight)))) nodes.Add(New Node(Of T)(New Rectangle(New Point(bound.Left, bound.Top + halfHeight), New Size(halfWidth, halfHeight)))) nodes.Add(New Node(Of T)(New Rectangle(New Point(bound.Left + halfWidth, bound.Top), New Size(halfWidth, halfHeight)))) nodes.Add(New Node(Of T)(New Rectangle(New Point(bound.Left + halfWidth, bound.Top + halfHeight), New Size(halfWidth, halfHeight)))) End Sub End Class
thekoushik/Darker-Unknown
WindowsApplication3/WindowsApplication3/WindowsApplication3/Node.vb
Visual Basic
mit
4,741
Imports Owl.Core.Structures Imports Owl.Core.Tensors Namespace Convolutions ''' <summary> ''' Scales values to conform to 0-1 range. ''' </summary> Public Class Normalizer Inherits ImageModifier Public Overrides Function Duplicate() As ImageModifier Return New Normalizer() End Function Public Overrides Sub Apply(ByRef Image As Tensor) Image.Remap(New Range(0, 1)) End Sub Public Shared Function Create() As Normalizer Return New Normalizer End Function End Class End Namespace
mateuszzwierzycki/Owl
Owl.Learning/Images/Normalizer.vb
Visual Basic
mit
600
Namespace Models Public Class CachedField Inherits GenericEntity Public Overrides Property ID As String Get Return FieldName End Get Set(value As String) FieldName = value End Set End Property Private _DataType As String = "" Public Property DataType As String Get Return _DataType End Get Set(value As String) SetProperty(_DataType, value, "DataType") End Set End Property Private _FieldName As String = "" Public Property FieldName As String Get Return _FieldName End Get Set(value As String) SetProperty(_FieldName, value, "FieldName", {"ID"}) End Set End Property Private _FieldAlias As String = "" Public Property FieldAlias As String Get Return _FieldAlias End Get Set(value As String) SetProperty(_FieldAlias, value, "FieldAlias") End Set End Property Private _FieldOptions As New List(Of Models.CachedFieldOption) Public ReadOnly Property FieldOptions As List(Of Models.CachedFieldOption) Get Return _FieldOptions End Get End Property Public ReadOnly Property HasAlias As Boolean Get If FieldName.ToLower.StartsWith("userdef") Then If FieldName.Equals(FieldAlias, StringComparison.OrdinalIgnoreCase) Then Return False End If End If Return True End Get End Property Public Overrides Function GetParameters() As System.Collections.Generic.IDictionary(Of String, Object) Throw New NotImplementedException End Function Public Overrides Sub LoadFromEntity(genericEntity As GenericEntity) If Me Is genericEntity Then Return End If If TypeOf (genericEntity) Is CachedField Then Else Return End If Dim Entity As CachedField = DirectCast(genericEntity, CachedField) Me.DataType = Entity.DataType Me.FieldName = Entity.FieldName Me.FieldAlias = Entity.FieldAlias _FieldOptions.Clear() _FieldOptions.AddRange(Entity.FieldOptions) End Sub Public Overrides Sub LoadFromReader(dataReader As System.Data.IDataReader) Throw New NotImplementedException End Sub Public Overrides Sub PopulateDataRow(ByRef dataRow As System.Data.DataRow) Throw New NotImplementedException End Sub End Class End Namespace
nublet/DMS
DMS.Base/Models/Extensions/CachedField.vb
Visual Basic
mit
2,915
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.18444 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <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.Softeis.My.MySettings Get Return Global.Softeis.My.MySettings.Default End Get End Property End Module End Namespace
lbischof/gibb
303_Softeis/Softeis/My Project/Settings.Designer.vb
Visual Basic
mit
2,920
Namespace Inspection ''' <summary>Query Part for Visibility (e.g. Public, Friend + Private etc).</summary> ''' <autogenerated>Generated from a T4 template. Modifications will be lost, if applicable use a partial class instead.</autogenerated> ''' <generator-date>10/02/2014 15:53:34</generator-date> ''' <generator-functions>1</generator-functions> ''' <generator-source>Leviathan\_Inspection\Querying\Generated\VisibilityPart.tt</generator-source> ''' <generator-template>Text-Templates\Classes\VB_Object.tt</generator-template> ''' <generator-version>1</generator-version> <System.CodeDom.Compiler.GeneratedCode("Leviathan\_Inspection\Querying\Generated\VisibilityPart.tt", "1")> _ Partial Public Class VisibilityPart Inherits System.Object #Region " Public Constructors " ''' <summary>Default Constructor</summary> Public Sub New() MyBase.New() m_Visibility = MemberVisibility.All End Sub ''' <summary>Parametered Constructor (1 Parameters)</summary> Public Sub New( _ ByVal _Visibility As MemberVisibility _ ) MyBase.New() Visibility = _Visibility End Sub #End Region #Region " Class Plumbing/Interface Code " #Region " Hashable Implementation " #Region " Public Methods " ''' <summary>Method to Generate a HashCode</summary> ''' <remarks></remarks> Public Overrides Function GetHashCode() As System.Int32 Return Leviathan.Caching.Simple.CombineHashCodes(GetType(VisibilityPart), Visibility) End Function #End Region #End Region #Region " Settable Implementation " #Region " Public Methods " Public Function SetVisibility(_Visibility As MemberVisibility) As VisibilityPart Visibility = _Visibility Return Me End Function #End Region #End Region #End Region #Region " Public Constants " ''' <summary>Public Shared Reference to the Name of the Property: Visibility</summary> ''' <remarks></remarks> Public Const PROPERTY_VISIBILITY As String = "Visibility" #End Region #Region " Private Variables " ''' <summary>Private Data Storage Variable for Property: Visibility</summary> ''' <remarks></remarks> Private m_Visibility As MemberVisibility #End Region #Region " Public Properties " ''' <summary>Provides Access to the Property: Visibility</summary> ''' <remarks></remarks> Public Property Visibility() As MemberVisibility Get Return m_Visibility End Get Set(value As MemberVisibility) m_Visibility = value End Set End Property #End Region End Class End Namespace
thiscouldbejd/Leviathan
_Inspection/Querying/Generated/VisibilityPart.vb
Visual Basic
mit
2,606
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.1 ' ' 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("Circles.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
morphx666/Circles
Circles/My Project/Resources.Designer.vb
Visual Basic
mit
2,709
'------------------------------------------------------------------------------ ' <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.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("jogos.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
reillysiemens/jogos
visualBasic/jogos/jogos/My Project/Resources.Designer.vb
Visual Basic
mit
2,714
'------------------------------------------------------------------------------ ' <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.OpenSaveLogExtensionVB.My.MySettings Get Return Global.OpenSaveLogExtensionVB.My.MySettings.Default End Get End Property End Module End Namespace
Esri/arcobjects-sdk-community-samples
Net/Framework/OpenSaveLogExtension/VBNet/My Project/Settings.Designer.vb
Visual Basic
apache-2.0
2,934
' 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.Diagnostics Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Threading 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.Symbols Friend NotInheritable Class SourcePropertySymbol Inherits PropertySymbol Implements IAttributeTargetSymbol Private ReadOnly _containingType As SourceMemberContainerTypeSymbol Private ReadOnly _name As String Private _lazyMetadataName As String Private ReadOnly _syntaxRef As SyntaxReference Private ReadOnly _blockRef As SyntaxReference Private ReadOnly _location As Location Private ReadOnly _flags As SourceMemberFlags Private _lazyType As TypeSymbol Private _lazyParameters As ImmutableArray(Of ParameterSymbol) Private _getMethod As MethodSymbol Private _setMethod As MethodSymbol Private _backingField As FieldSymbol Private _lazyDocComment As String Private _lazyExpandedDocComment As String Private _lazyMeParameter As ParameterSymbol ' Attributes on property. Set once after construction. IsNull means not set. Private _lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData) ' Attributes on return type of the property. Set once after construction. IsNull means not set. Private _lazyReturnTypeCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData) ' The explicitly implemented interface properties, or Empty if none. Private _lazyImplementedProperties As ImmutableArray(Of PropertySymbol) ' The overridden or hidden property. Private _lazyOverriddenProperties As OverriddenMembersResult(Of PropertySymbol) Private _lazyState As Integer <Flags> Private Enum StateFlags As Integer SymbolDeclaredEvent = &H1 ' Bit value for generating SymbolDeclaredEvent End Enum Private Sub New(container As SourceMemberContainerTypeSymbol, name As String, flags As SourceMemberFlags, syntaxRef As SyntaxReference, blockRef As SyntaxReference, location As Location) Debug.Assert(container IsNot Nothing) Debug.Assert(syntaxRef IsNot Nothing) Debug.Assert(location IsNot Nothing) _containingType = container _name = name _syntaxRef = syntaxRef _blockRef = blockRef _location = location _flags = flags _lazyState = 0 End Sub Friend Shared Function Create(containingType As SourceMemberContainerTypeSymbol, bodyBinder As Binder, syntax As PropertyStatementSyntax, blockSyntaxOpt As PropertyBlockSyntax, diagnostics As DiagnosticBag) As SourcePropertySymbol ' Decode the flags. Dim modifiers = DecodeModifiers(syntax.Modifiers, containingType, bodyBinder, diagnostics) Dim identifier = syntax.Identifier Dim name = identifier.ValueText Dim omitFurtherDiagnostics As Boolean = String.IsNullOrEmpty(name) Dim location = identifier.GetLocation() Dim syntaxRef = bodyBinder.GetSyntaxReference(syntax) Dim blockRef = If(blockSyntaxOpt Is Nothing, Nothing, bodyBinder.GetSyntaxReference(blockSyntaxOpt)) Dim prop = New SourcePropertySymbol(containingType, name, modifiers.AllFlags, syntaxRef, blockRef, location) bodyBinder = New LocationSpecificBinder(BindingLocation.PropertySignature, prop, bodyBinder) If syntax.AttributeLists.Count = 0 Then prop.SetCustomAttributeData(CustomAttributesBag(Of VisualBasicAttributeData).Empty) End If Dim accessorFlags = modifiers.AllFlags And (Not SourceMemberFlags.AccessibilityMask) Dim getMethod As SourcePropertyAccessorSymbol = Nothing Dim setMethod As SourcePropertyAccessorSymbol = Nothing If blockSyntaxOpt IsNot Nothing Then For Each accessor In blockSyntaxOpt.Accessors Dim accessorKind = accessor.BlockStatement.Kind If accessorKind = SyntaxKind.GetAccessorStatement Then Dim accessorMethod = CreateAccessor(prop, SourceMemberFlags.MethodKindPropertyGet, accessorFlags, bodyBinder, accessor, diagnostics) If getMethod Is Nothing Then getMethod = accessorMethod Else diagnostics.Add(ERRID.ERR_DuplicatePropertyGet, accessorMethod.Locations(0)) End If ElseIf accessorKind = SyntaxKind.SetAccessorStatement Then Dim accessorMethod = CreateAccessor(prop, SourceMemberFlags.MethodKindPropertySet, accessorFlags, bodyBinder, accessor, diagnostics) If setMethod Is Nothing Then setMethod = accessorMethod Else diagnostics.Add(ERRID.ERR_DuplicatePropertySet, accessorMethod.Locations(0)) End If End If Next End If Dim isReadOnly = (modifiers.FoundFlags And SourceMemberFlags.ReadOnly) <> 0 Dim isWriteOnly = (modifiers.FoundFlags And SourceMemberFlags.WriteOnly) <> 0 If Not prop.IsMustOverride Then If isReadOnly Then If getMethod IsNot Nothing Then If getMethod.LocalAccessibility <> Accessibility.NotApplicable Then diagnostics.Add(ERRID.ERR_ReadOnlyNoAccessorFlag, GetAccessorBlockBeginLocation(getMethod)) End If ElseIf blockSyntaxOpt IsNot Nothing Then diagnostics.Add(ERRID.ERR_ReadOnlyHasNoGet, location) End If If setMethod IsNot Nothing Then diagnostics.Add(ERRID.ERR_ReadOnlyHasSet, setMethod.Locations(0)) End If End If If isWriteOnly Then If setMethod IsNot Nothing Then If setMethod.LocalAccessibility <> Accessibility.NotApplicable Then diagnostics.Add(ERRID.ERR_WriteOnlyNoAccessorFlag, GetAccessorBlockBeginLocation(setMethod)) End If ElseIf blockSyntaxOpt IsNot Nothing Then diagnostics.Add(ERRID.ERR_WriteOnlyHasNoWrite, location) End If If getMethod IsNot Nothing Then diagnostics.Add(ERRID.ERR_WriteOnlyHasGet, getMethod.Locations(0)) End If End If If (getMethod IsNot Nothing) AndAlso (setMethod IsNot Nothing) Then If (getMethod.LocalAccessibility <> Accessibility.NotApplicable) AndAlso (setMethod.LocalAccessibility <> Accessibility.NotApplicable) Then ' Both accessors have explicit accessibility. Report an error on the second. Dim accessor = If(getMethod.Locations(0).SourceSpan.Start < setMethod.Locations(0).SourceSpan.Start, setMethod, getMethod) diagnostics.Add(ERRID.ERR_OnlyOneAccessorForGetSet, GetAccessorBlockBeginLocation(accessor)) ElseIf prop.IsOverridable AndAlso ((getMethod.LocalAccessibility = Accessibility.Private) OrElse (setMethod.LocalAccessibility = Accessibility.Private)) Then ' If either accessor is Private, property cannot be Overridable. bodyBinder.ReportModifierError(syntax.Modifiers, ERRID.ERR_BadPropertyAccessorFlags3, diagnostics, s_overridableModifierKinds) End If End If If (Not isReadOnly) AndAlso (Not isWriteOnly) AndAlso ((getMethod Is Nothing) OrElse (setMethod Is Nothing)) AndAlso (blockSyntaxOpt IsNot Nothing) AndAlso (Not prop.IsMustOverride) Then diagnostics.Add(ERRID.ERR_PropMustHaveGetSet, location) End If End If If blockSyntaxOpt Is Nothing Then ' Generate backing field for auto property. If Not prop.IsMustOverride Then If isWriteOnly Then diagnostics.Add(ERRID.ERR_AutoPropertyCantBeWriteOnly, location) End If Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)) Dim fieldName = "_" + prop._name prop._backingField = New SynthesizedPropertyBackingFieldSymbol(prop, fieldName, isShared:=prop.IsShared) End If Dim flags = prop._flags And Not SourceMemberFlags.MethodKindMask ' Generate accessors for auto property or abstract property. If Not isWriteOnly Then prop._getMethod = New SourcePropertyAccessorSymbol( prop, Binder.GetAccessorName(prop.Name, MethodKind.PropertyGet, isWinMd:=False), flags Or SourceMemberFlags.MethodKindPropertyGet, prop._syntaxRef, prop.Locations) End If If Not isReadOnly Then prop._setMethod = New SourcePropertyAccessorSymbol( prop, Binder.GetAccessorName(prop.Name, MethodKind.PropertySet, isWinMd:=prop.IsCompilationOutputWinMdObj()), flags Or SourceMemberFlags.MethodKindPropertySet Or SourceMemberFlags.MethodIsSub, prop._syntaxRef, prop.Locations) End If Else prop._getMethod = getMethod prop._setMethod = setMethod End If Debug.Assert((prop._getMethod Is Nothing) OrElse prop._getMethod.ImplicitlyDefinedBy Is prop) Debug.Assert((prop._setMethod Is Nothing) OrElse prop._setMethod.ImplicitlyDefinedBy Is prop) Return prop End Function Friend Shared Function CreateWithEvents( containingType As SourceMemberContainerTypeSymbol, bodyBinder As Binder, identifier As SyntaxToken, syntaxRef As SyntaxReference, modifiers As MemberModifiers, firstFieldDeclarationOfType As Boolean, diagnostics As DiagnosticBag) As SourcePropertySymbol Dim name = identifier.ValueText ' we will require AccessedThroughPropertyAttribute bodyBinder.ReportUseSiteErrorForSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_AccessedThroughPropertyAttribute__ctor, DirectCast(identifier.Parent, VisualBasicSyntaxNode), diagnostics) Dim omitFurtherDiagnostics As Boolean = String.IsNullOrEmpty(name) Dim location = identifier.GetLocation() ' WithEvents instance property is always overridable Dim memberFlags = modifiers.AllFlags If (memberFlags And SourceMemberFlags.Shared) = 0 Then memberFlags = modifiers.AllFlags Or SourceMemberFlags.Overridable End If If firstFieldDeclarationOfType Then memberFlags = memberFlags Or SourceMemberFlags.FirstFieldDeclarationOfType End If Dim prop = New SourcePropertySymbol(containingType, name, memberFlags, syntaxRef, Nothing, location) ' no implements. prop._lazyImplementedProperties = ImmutableArray(Of PropertySymbol).Empty prop.SetCustomAttributeData(CustomAttributesBag(Of VisualBasicAttributeData).Empty) Dim fieldName = "_" + prop._name prop._backingField = New SourceWithEventsBackingFieldSymbol(prop, syntaxRef, fieldName) ' Generate synthesized accessors for auto property or abstract property. prop._getMethod = New SynthesizedWithEventsGetAccessorSymbol( containingType, prop) prop._setMethod = New SynthesizedWithEventsSetAccessorSymbol( containingType, prop, bodyBinder.GetSpecialType(SpecialType.System_Void, identifier, diagnostics), valueParameterName:=StringConstants.WithEventsValueParameterName) Debug.Assert((prop._getMethod Is Nothing) OrElse prop._getMethod.ImplicitlyDefinedBy Is prop) Debug.Assert((prop._setMethod Is Nothing) OrElse prop._setMethod.ImplicitlyDefinedBy Is prop) Return prop End Function Friend Sub CloneParametersForAccessor(method As MethodSymbol, parameterBuilder As ArrayBuilder(Of ParameterSymbol)) Dim overriddenMethod As MethodSymbol = method.OverriddenMethod For Each parameter In Me.Parameters Dim clone As ParameterSymbol = New SourceClonedParameterSymbol(DirectCast(parameter, SourceParameterSymbol), method, parameter.Ordinal) If overriddenMethod IsNot Nothing Then CustomModifierUtils.CopyParameterCustomModifiers(overriddenMethod.Parameters(parameter.Ordinal), clone) End If parameterBuilder.Add(clone) Next End Sub ''' <summary> ''' Property declaration syntax node. ''' It is either PropertyStatement for normal properties or FieldDeclarationSyntax for WithEvents ones. ''' </summary> Friend ReadOnly Property DeclarationSyntax As DeclarationStatementSyntax Get Dim syntax = _syntaxRef.GetVisualBasicSyntax() If syntax.Kind = SyntaxKind.PropertyStatement Then Return DirectCast(syntax, PropertyStatementSyntax) Else Debug.Assert(syntax.Kind = SyntaxKind.ModifiedIdentifier) Return DirectCast(syntax.Parent.Parent, FieldDeclarationSyntax) End If End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property Type As TypeSymbol Get EnsureSignature() Return _lazyType End Get End Property Private Function ComputeType(diagnostics As DiagnosticBag) As TypeSymbol Dim binder = CreateBinderForTypeDeclaration() If IsWithEvents Then Dim syntax = DirectCast(_syntaxRef.GetSyntax(), ModifiedIdentifierSyntax) Return SourceMemberFieldSymbol.ComputeWithEventsFieldType( Me, syntax, binder, ignoreTypeSyntaxDiagnostics:=(_flags And SourceMemberFlags.FirstFieldDeclarationOfType) = 0, diagnostics:=diagnostics) Else Dim syntax = DirectCast(_syntaxRef.GetSyntax(), PropertyStatementSyntax) Dim asClause = syntax.AsClause If asClause IsNot Nothing AndAlso asClause.Kind = SyntaxKind.AsNewClause AndAlso (DirectCast(asClause, AsNewClauseSyntax).NewExpression.Kind = SyntaxKind.AnonymousObjectCreationExpression) Then Return ErrorTypeSymbol.UnknownResultType Else Dim getErrorInfo As Func(Of DiagnosticInfo) = Nothing Dim omitFurtherDiagnostics As Boolean = String.IsNullOrEmpty(_name) If Not omitFurtherDiagnostics Then If binder.OptionStrict = OptionStrict.On Then getErrorInfo = ErrorFactory.GetErrorInfo_ERR_StrictDisallowsImplicitProc ElseIf binder.OptionStrict = OptionStrict.Custom Then getErrorInfo = ErrorFactory.GetErrorInfo_WRN_ObjectAssumedProperty1_WRN_MissingAsClauseinProperty End If End If Dim identifier = syntax.Identifier Dim type = binder.DecodeIdentifierType(identifier, asClause, getErrorInfo, diagnostics) Debug.Assert(type IsNot Nothing) If Not type.IsErrorType() Then Dim errorLocation = SourceSymbolHelpers.GetAsClauseLocation(identifier, asClause) AccessCheck.VerifyAccessExposureForMemberType(Me, errorLocation, type, diagnostics) Dim restrictedType As TypeSymbol = Nothing If type.IsRestrictedTypeOrArrayType(restrictedType) Then Binder.ReportDiagnostic(diagnostics, errorLocation, ERRID.ERR_RestrictedType1, restrictedType) End If Dim getMethod = Me.GetMethod If getMethod IsNot Nothing AndAlso getMethod.IsIterator Then Dim originalRetTypeDef = type.OriginalDefinition If originalRetTypeDef.SpecialType <> SpecialType.System_Collections_Generic_IEnumerable_T AndAlso originalRetTypeDef.SpecialType <> SpecialType.System_Collections_Generic_IEnumerator_T AndAlso type.SpecialType <> SpecialType.System_Collections_IEnumerable AndAlso type.SpecialType <> SpecialType.System_Collections_IEnumerator Then Binder.ReportDiagnostic(diagnostics, errorLocation, ERRID.ERR_BadIteratorReturn) End If End If End If Return type End If End If End Function Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Public Overrides ReadOnly Property MetadataName As String Get If _lazyMetadataName Is Nothing Then OverloadingHelper.SetMetadataNameForAllOverloads(_name, SymbolKind.Property, _containingType) Debug.Assert(_lazyMetadataName IsNot Nothing) End If Return _lazyMetadataName End Get End Property Friend Overrides Sub SetMetadataName(metadataName As String) Dim old = Interlocked.CompareExchange(_lazyMetadataName, metadataName, Nothing) Debug.Assert(old Is Nothing OrElse old = metadataName) End Sub Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingType End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return _containingType End Get End Property Public ReadOnly Property ContainingSourceType As SourceMemberContainerTypeSymbol Get Return _containingType End Get End Property Friend Overrides Function GetLexicalSortKey() As LexicalSortKey ' WARNING: this should not allocate memory! Return New LexicalSortKey(_location, Me.DeclaringCompilation) End Function Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray.Create(_location) End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return GetDeclaringSyntaxReferenceHelper(_syntaxRef) End Get End Property Friend Overrides Function IsDefinedInSourceTree(tree As SyntaxTree, definedWithinSpan As TextSpan?, Optional cancellationToken As CancellationToken = Nothing) As Boolean Dim propertyStatementSyntax = Me.Syntax Return propertyStatementSyntax IsNot Nothing AndAlso IsDefinedInSourceTree(propertyStatementSyntax.Parent, tree, definedWithinSpan, cancellationToken) End Function Public ReadOnly Property DefaultAttributeLocation As AttributeLocation Implements IAttributeTargetSymbol.DefaultAttributeLocation Get Return AttributeLocation.Property End Get End Property Private Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) If Me.IsWithEvents Then Return Nothing End If Return OneOrMany.Create(DirectCast(_syntaxRef.GetSyntax, PropertyStatementSyntax).AttributeLists) End Function Private Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) If Me.IsWithEvents Then Return Nothing End If Dim asClauseOpt = DirectCast(Me.Syntax, PropertyStatementSyntax).AsClause If asClauseOpt Is Nothing Then Return Nothing End If Return OneOrMany.Create(asClauseOpt.Attributes) End Function Friend Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) If _lazyCustomAttributesBag Is Nothing OrElse Not _lazyCustomAttributesBag.IsSealed Then LoadAndValidateAttributes(Me.GetAttributeDeclarations(), _lazyCustomAttributesBag) End If Return _lazyCustomAttributesBag End Function Friend Function GetReturnTypeAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) If _lazyReturnTypeCustomAttributesBag Is Nothing OrElse Not _lazyReturnTypeCustomAttributesBag.IsSealed Then LoadAndValidateAttributes(GetReturnTypeAttributeDeclarations(), _lazyReturnTypeCustomAttributesBag, symbolPart:=AttributeLocation.Return) End If Return _lazyReturnTypeCustomAttributesBag End Function ''' <summary> ''' Gets the attributes applied on this symbol. ''' Returns an empty array if there are no attributes. ''' </summary> ''' <remarks> ''' NOTE: This method should always be kept as a NotOverridable method. ''' If you want to override attribute binding logic for a sub-class, then override <see cref="GetAttributesBag"/> method. ''' </remarks> Public Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me.GetAttributesBag().Attributes End Function Private Function GetDecodedWellKnownAttributeData() As CommonPropertyWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me._lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonPropertyWellKnownAttributeData) End Function Private Function GetDecodedReturnTypeWellKnownAttributeData() As CommonReturnTypeWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me._lazyReturnTypeCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetReturnTypeAttributesBag() End If Return DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonReturnTypeWellKnownAttributeData) End Function Friend Overrides Function EarlyDecodeWellKnownAttribute(ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData Debug.Assert(arguments.AttributeType IsNot Nothing) Debug.Assert(Not arguments.AttributeType.IsErrorType()) Dim boundAttribute As VisualBasicAttributeData = Nothing Dim obsoleteData As ObsoleteAttributeData = Nothing If EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(arguments, boundAttribute, obsoleteData) Then If obsoleteData IsNot Nothing Then arguments.GetOrCreateData(Of CommonPropertyEarlyWellKnownAttributeData)().ObsoleteAttributeData = obsoleteData End If Return boundAttribute End If Return MyBase.EarlyDecodeWellKnownAttribute(arguments) End Function Friend Overrides Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing) Dim attrData = arguments.Attribute If attrData.IsTargetAttribute(Me, AttributeDescription.TupleElementNamesAttribute) Then arguments.Diagnostics.Add(ERRID.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location) End If If arguments.SymbolPart = AttributeLocation.Return Then Dim isMarshalAs = attrData.IsTargetAttribute(Me, AttributeDescription.MarshalAsAttribute) ' write-only property doesn't accept any return type attributes other than MarshalAs ' MarshalAs is applied on the "Value" parameter of the setter if the property has no parameters and the containing type is an interface . If _getMethod Is Nothing AndAlso _setMethod IsNot Nothing AndAlso (Not isMarshalAs OrElse Not SynthesizedParameterSymbol.IsMarshalAsAttributeApplicable(_setMethod)) Then arguments.Diagnostics.Add(ERRID.WRN_ReturnTypeAttributeOnWriteOnlyProperty, arguments.AttributeSyntaxOpt.GetLocation()) Return End If If isMarshalAs Then MarshalAsAttributeDecoder(Of CommonReturnTypeWellKnownAttributeData, AttributeSyntax, VisualBasicAttributeData, AttributeLocation). Decode(arguments, AttributeTargets.Field, MessageProvider.Instance) Return End If Else If attrData.IsTargetAttribute(Me, AttributeDescription.SpecialNameAttribute) Then arguments.GetOrCreateData(Of CommonPropertyWellKnownAttributeData).HasSpecialNameAttribute = True Return ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.ExcludeFromCodeCoverageAttribute) Then arguments.GetOrCreateData(Of CommonPropertyWellKnownAttributeData).HasExcludeFromCodeCoverageAttribute = True Return ElseIf Not IsWithEvents AndAlso attrData.IsTargetAttribute(Me, AttributeDescription.DebuggerHiddenAttribute) Then ' if neither getter or setter is marked by DebuggerHidden Dev11 reports a warning If Not (_getMethod IsNot Nothing AndAlso DirectCast(_getMethod, SourcePropertyAccessorSymbol).HasDebuggerHiddenAttribute OrElse _setMethod IsNot Nothing AndAlso DirectCast(_setMethod, SourcePropertyAccessorSymbol).HasDebuggerHiddenAttribute) Then arguments.Diagnostics.Add(ERRID.WRN_DebuggerHiddenIgnoredOnProperties, arguments.AttributeSyntaxOpt.GetLocation()) End If Return End If End If MyBase.DecodeWellKnownAttribute(arguments) End Sub Friend Overrides ReadOnly Property IsDirectlyExcludedFromCodeCoverage As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasExcludeFromCodeCoverageAttribute End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasSpecialNameAttribute End Get End Property Friend ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData Get Dim data = GetDecodedReturnTypeWellKnownAttributeData() Return If(data IsNot Nothing, data.MarshallingInformation, Nothing) End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return (_flags And SourceMemberFlags.MustOverride) <> 0 End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return (_flags And SourceMemberFlags.NotOverridable) <> 0 End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return (_flags And SourceMemberFlags.Overridable) <> 0 End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return (_flags And SourceMemberFlags.Overrides) <> 0 End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return (_flags And SourceMemberFlags.Shared) <> 0 End Get End Property Public Overrides ReadOnly Property IsDefault As Boolean Get Return (_flags And SourceMemberFlags.Default) <> 0 End Get End Property Public Overrides ReadOnly Property IsWriteOnly As Boolean Get Return (_flags And SourceMemberFlags.WriteOnly) <> 0 End Get End Property Public Overrides ReadOnly Property IsReadOnly As Boolean Get Return (_flags And SourceMemberFlags.ReadOnly) <> 0 End Get End Property Public Overrides ReadOnly Property GetMethod As MethodSymbol Get Return _getMethod End Get End Property Public Overrides ReadOnly Property SetMethod As MethodSymbol Get Return _setMethod End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get If (_flags And SourceMemberFlags.Shadows) <> 0 Then Return False ElseIf (_flags And SourceMemberFlags.Overloads) <> 0 Then Return True Else Return (_flags And SourceMemberFlags.Overrides) <> 0 End If End Get End Property Public Overrides ReadOnly Property IsWithEvents As Boolean Get Return (_flags And SourceMemberFlags.WithEvents) <> 0 End Get End Property Friend Overrides ReadOnly Property ShadowsExplicitly As Boolean Get Return (_flags And SourceMemberFlags.Shadows) <> 0 End Get End Property ''' <summary> True if 'Overloads' is explicitly specified in method's declaration </summary> Friend ReadOnly Property OverloadsExplicitly As Boolean Get Return (_flags And SourceMemberFlags.Overloads) <> 0 End Get End Property ''' <summary> True if 'Overrides' is explicitly specified in method's declaration </summary> Friend ReadOnly Property OverridesExplicitly As Boolean Get Return (_flags And SourceMemberFlags.Overrides) <> 0 End Get End Property Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention Get Return (If(IsShared, Microsoft.Cci.CallingConvention.Default, Microsoft.Cci.CallingConvention.HasThis)) End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get EnsureSignature() Return _lazyParameters End Get End Property Private Sub EnsureSignature() If _lazyParameters.IsDefault Then Dim diagnostics = DiagnosticBag.GetInstance() Dim sourceModule = DirectCast(ContainingModule, SourceModuleSymbol) Dim params As ImmutableArray(Of ParameterSymbol) = ComputeParameters(diagnostics) Dim retType As TypeSymbol = ComputeType(diagnostics) ' For an overriding property, we need to copy custom modifiers from the property we override. Dim overriddenMembers As OverriddenMembersResult(Of PropertySymbol) If Not Me.IsOverrides OrElse Not OverrideHidingHelper.CanOverrideOrHide(Me) Then overriddenMembers = OverriddenMembersResult(Of PropertySymbol).Empty Else ' Since we cannot expose parameters and return type to the outside world yet, ' let's create a fake symbol to use for overriding resolution Dim fakeParamsBuilder = ArrayBuilder(Of ParameterSymbol).GetInstance(params.Length) For Each param As ParameterSymbol In params fakeParamsBuilder.Add(New SignatureOnlyParameterSymbol( param.Type, ImmutableArray(Of CustomModifier).Empty, ImmutableArray(Of CustomModifier).Empty, defaultConstantValue:=Nothing, isParamArray:=False, isByRef:=param.IsByRef, isOut:=False, isOptional:=param.IsOptional)) Next overriddenMembers = OverrideHidingHelper(Of PropertySymbol). MakeOverriddenMembers(New SignatureOnlyPropertySymbol(Me.Name, _containingType, Me.IsReadOnly, Me.IsWriteOnly, fakeParamsBuilder.ToImmutableAndFree(), returnsByRef:=False, [type]:=retType, typeCustomModifiers:=ImmutableArray(Of CustomModifier).Empty, refCustomModifiers:=ImmutableArray(Of CustomModifier).Empty, isOverrides:=True, isWithEvents:=Me.IsWithEvents)) End If Debug.Assert(IsDefinition) Dim overridden = overriddenMembers.OverriddenMember If overridden IsNot Nothing Then ' Copy custom modifiers Dim returnTypeWithCustomModifiers As TypeSymbol = overridden.Type ' We do an extra check before copying the return type to handle the case where the overriding ' property (incorrectly) has a different return type than the overridden property. In such cases, ' we want to retain the original (incorrect) return type to avoid hiding the return type ' given in source. If retType.IsSameType(returnTypeWithCustomModifiers, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds) Then retType = CustomModifierUtils.CopyTypeCustomModifiers(returnTypeWithCustomModifiers, retType) End If params = CustomModifierUtils.CopyParameterCustomModifiers(overridden.Parameters, params) End If ' Unlike PropertySymbol, in SourcePropertySymbol we cache the result of MakeOverriddenOfHiddenMembers, because we use ' it heavily while validating methods and emitting. Interlocked.CompareExchange(_lazyOverriddenProperties, overriddenMembers, Nothing) Interlocked.CompareExchange(_lazyType, retType, Nothing) sourceModule.AtomicStoreArrayAndDiagnostics( _lazyParameters, params, diagnostics, CompilationStage.Declare) diagnostics.Free() End If End Sub Public Overrides ReadOnly Property ParameterCount As Integer Get If Not Me._lazyParameters.IsDefault Then Return Me._lazyParameters.Length End If Dim decl = Me.DeclarationSyntax If decl.Kind = SyntaxKind.PropertyStatement Then Dim paramList As ParameterListSyntax = DirectCast(decl, PropertyStatementSyntax).ParameterList Return If(paramList Is Nothing, 0, paramList.Parameters.Count) End If Return MyBase.ParameterCount End Get End Property Private Function ComputeParameters(diagnostics As DiagnosticBag) As ImmutableArray(Of ParameterSymbol) If Me.IsWithEvents Then ' no parameters Return ImmutableArray(Of ParameterSymbol).Empty End If Dim binder = CreateBinderForTypeDeclaration() Dim syntax = DirectCast(_syntaxRef.GetSyntax(), PropertyStatementSyntax) Dim parameters = binder.DecodePropertyParameterList(Me, syntax.ParameterList, diagnostics) If IsDefault Then ' Default properties must have required parameters. If Not HasRequiredParameters(parameters) Then diagnostics.Add(ERRID.ERR_DefaultPropertyWithNoParams, _location) End If ' 'touch' System_Reflection_DefaultMemberAttribute__ctor to make sure all diagnostics are reported binder.ReportUseSiteErrorForSynthesizedAttribute(WellKnownMember.System_Reflection_DefaultMemberAttribute__ctor, syntax, diagnostics) End If Return parameters End Function Friend Overrides ReadOnly Property MeParameter As ParameterSymbol Get If IsShared Then Return Nothing Else If _lazyMeParameter Is Nothing Then Interlocked.CompareExchange(Of ParameterSymbol)(_lazyMeParameter, New MeParameterSymbol(Me), Nothing) End If Return _lazyMeParameter End If End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of PropertySymbol) Get If _lazyImplementedProperties.IsDefault Then Dim diagnostics = DiagnosticBag.GetInstance() Dim sourceModule = DirectCast(Me.ContainingModule, SourceModuleSymbol) sourceModule.AtomicStoreArrayAndDiagnostics(_lazyImplementedProperties, ComputeExplicitInterfaceImplementations(diagnostics), diagnostics, CompilationStage.Declare) diagnostics.Free() End If Return _lazyImplementedProperties End Get End Property Private Function ComputeExplicitInterfaceImplementations(diagnostics As DiagnosticBag) As ImmutableArray(Of PropertySymbol) Dim binder = CreateBinderForTypeDeclaration() Dim syntax = DirectCast(_syntaxRef.GetSyntax(), PropertyStatementSyntax) Return BindImplementsClause(_containingType, binder, Me, syntax, diagnostics) End Function ''' <summary> ''' Helper method for accessors to get the overridden accessor methods. Should only be called by the ''' accessor method symbols. ''' </summary> ''' <param name="getter">True to get implemented getters, False to get implemented setters</param> ''' <returns>All the accessors of the given kind implemented by this property.</returns> Friend Function GetAccessorImplementations(getter As Boolean) As ImmutableArray(Of MethodSymbol) Dim implementedProperties = ExplicitInterfaceImplementations Debug.Assert(Not implementedProperties.IsDefault) If implementedProperties.IsEmpty Then Return ImmutableArray(Of MethodSymbol).Empty Else Dim builder As ArrayBuilder(Of MethodSymbol) = ArrayBuilder(Of MethodSymbol).GetInstance() For Each implementedProp In implementedProperties Dim accessor = If(getter, implementedProp.GetMethod, implementedProp.SetMethod) If accessor IsNot Nothing AndAlso accessor.RequiresImplementation() Then builder.Add(accessor) End If Next Return builder.ToImmutableAndFree() End If End Function Friend Overrides ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of PropertySymbol) Get EnsureSignature() Return Me._lazyOverriddenProperties End Get End Property Public Overrides ReadOnly Property TypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Dim overridden = Me.OverriddenProperty If overridden Is Nothing Then Return ImmutableArray(Of CustomModifier).Empty Else Return overridden.TypeCustomModifiers End If End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return CType((_flags And SourceMemberFlags.AccessibilityMask), Accessibility) End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return _containingType.AreMembersImplicitlyDeclared End Get End Property Friend ReadOnly Property IsCustomProperty As Boolean Get ' Auto and WithEvents properties have backing fields Return _backingField Is Nothing AndAlso Not IsMustOverride End Get End Property Friend ReadOnly Property IsAutoProperty As Boolean Get Return Not IsWithEvents AndAlso _backingField IsNot Nothing End Get End Property Friend Overrides ReadOnly Property AssociatedField As FieldSymbol Get Return _backingField End Get End Property ''' <summary> ''' Property declaration syntax node. ''' It is either PropertyStatement for normal properties or ModifiedIdentifier for WithEvents ones. ''' </summary> Friend ReadOnly Property Syntax As VisualBasicSyntaxNode Get Return If(_syntaxRef IsNot Nothing, _syntaxRef.GetVisualBasicSyntax(), Nothing) End Get End Property Friend ReadOnly Property SyntaxReference As SyntaxReference Get Return Me._syntaxRef End Get End Property Friend ReadOnly Property BlockSyntaxReference As SyntaxReference Get Return Me._blockRef End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get ' If there are no attributes then this symbol is not Obsolete. If (Not Me._containingType.AnyMemberHasAttributes) Then Return Nothing End If Dim lazyCustomAttributesBag = Me._lazyCustomAttributesBag If (lazyCustomAttributesBag IsNot Nothing AndAlso lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed) Then Dim data = DirectCast(_lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData, CommonPropertyEarlyWellKnownAttributeData) Return If(data IsNot Nothing, data.ObsoleteAttributeData, Nothing) End If Return ObsoleteAttributeData.Uninitialized End Get End Property ' Get the location of the implements name for an explicit implemented property, for later error reporting. Friend Function GetImplementingLocation(implementedProperty As PropertySymbol) As Location Debug.Assert(ExplicitInterfaceImplementations.Contains(implementedProperty)) Dim propertySyntax = TryCast(_syntaxRef.GetSyntax(), PropertyStatementSyntax) If propertySyntax IsNot Nothing AndAlso propertySyntax.ImplementsClause IsNot Nothing Then Dim binder = CreateBinderForTypeDeclaration() Dim implementingSyntax = FindImplementingSyntax(Of PropertySymbol)(propertySyntax.ImplementsClause, Me, implementedProperty, _containingType, binder) Return implementingSyntax.GetLocation() End If Return If(Locations.FirstOrDefault(), NoLocation.Singleton) End Function Private Function CreateBinderForTypeDeclaration() As Binder Dim binder = BinderBuilder.CreateBinderForType(DirectCast(ContainingModule, SourceModuleSymbol), _syntaxRef.SyntaxTree, _containingType) Return New LocationSpecificBinder(BindingLocation.PropertySignature, Me, binder) End Function Private Shared Function CreateAccessor([property] As SourcePropertySymbol, kindFlags As SourceMemberFlags, propertyFlags As SourceMemberFlags, bodyBinder As Binder, syntax As AccessorBlockSyntax, diagnostics As DiagnosticBag) As SourcePropertyAccessorSymbol Dim accessor = SourcePropertyAccessorSymbol.CreatePropertyAccessor([property], kindFlags, propertyFlags, bodyBinder, syntax, diagnostics) Debug.Assert(accessor IsNot Nothing) Dim localAccessibility = accessor.LocalAccessibility If Not IsAccessibilityMoreRestrictive([property].DeclaredAccessibility, localAccessibility) Then ReportAccessorAccessibilityError(bodyBinder, syntax, ERRID.ERR_BadPropertyAccessorFlagsRestrict, diagnostics) ElseIf [property].IsNotOverridable AndAlso localAccessibility = Accessibility.Private Then ReportAccessorAccessibilityError(bodyBinder, syntax, ERRID.ERR_BadPropertyAccessorFlags1, diagnostics) ElseIf [property].IsDefault AndAlso localAccessibility = Accessibility.Private Then ReportAccessorAccessibilityError(bodyBinder, syntax, ERRID.ERR_BadPropertyAccessorFlags2, diagnostics) End If Return accessor End Function ''' <summary> ''' Return true if the accessor accessibility is more restrictive ''' than the property accessibility, otherwise false. ''' </summary> Private Shared Function IsAccessibilityMoreRestrictive([property] As Accessibility, accessor As Accessibility) As Boolean If accessor = Accessibility.NotApplicable Then Return True End If Return (accessor < [property]) AndAlso ((accessor <> Accessibility.Protected) OrElse ([property] <> Accessibility.Friend)) End Function Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String If expandIncludes Then Return GetAndCacheDocumentationComment(Me, preferredCulture, expandIncludes, _lazyExpandedDocComment, cancellationToken) Else Return GetAndCacheDocumentationComment(Me, preferredCulture, expandIncludes, _lazyDocComment, cancellationToken) End If End Function Private Shared Function DecodeModifiers(modifiers As SyntaxTokenList, container As SourceMemberContainerTypeSymbol, binder As Binder, diagBag As DiagnosticBag) As MemberModifiers ' Decode the flags. Dim propertyModifiers = binder.DecodeModifiers(modifiers, SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Default Or SourceMemberFlags.Overloads Or SourceMemberFlags.Shadows Or SourceMemberFlags.Shared Or SourceMemberFlags.Overridable Or SourceMemberFlags.NotOverridable Or SourceMemberFlags.Overrides Or SourceMemberFlags.MustOverride Or SourceMemberFlags.ReadOnly Or SourceMemberFlags.Iterator Or SourceMemberFlags.WriteOnly, ERRID.ERR_BadPropertyFlags1, Accessibility.Public, diagBag) ' Diagnose Shared with an overriding modifier. Dim flags = propertyModifiers.FoundFlags If (flags And SourceMemberFlags.Default) <> 0 AndAlso (flags And SourceMemberFlags.InvalidIfDefault) <> 0 Then binder.ReportModifierError(modifiers, ERRID.ERR_BadFlagsWithDefault1, diagBag, InvalidModifiersIfDefault) flags = flags And Not SourceMemberFlags.InvalidIfDefault propertyModifiers = New MemberModifiers(flags, propertyModifiers.ComputedFlags) End If propertyModifiers = binder.ValidateSharedPropertyAndMethodModifiers(modifiers, propertyModifiers, True, container, diagBag) Return propertyModifiers End Function Private Shared Function BindImplementsClause(containingType As SourceMemberContainerTypeSymbol, bodyBinder As Binder, prop As SourcePropertySymbol, syntax As PropertyStatementSyntax, diagnostics As DiagnosticBag) As ImmutableArray(Of PropertySymbol) If syntax.ImplementsClause IsNot Nothing Then If prop.IsShared And Not containingType.IsModuleType Then ' Implementing with shared methods is illegal. ' Module case is caught inside ProcessImplementsClause and has different message. Binder.ReportDiagnostic(diagnostics, syntax.Modifiers.First(SyntaxKind.SharedKeyword), ERRID.ERR_SharedOnProcThatImpl, syntax.Identifier.ToString()) Else Return ProcessImplementsClause(Of PropertySymbol)(syntax.ImplementsClause, prop, containingType, bodyBinder, diagnostics) End If End If Return ImmutableArray(Of PropertySymbol).Empty End Function ''' <summary> ''' Returns the location (span) of the accessor begin block. ''' (Used for consistency with the native compiler that ''' highlights the entire begin block for certain diagnostics.) ''' </summary> Private Shared Function GetAccessorBlockBeginLocation(accessor As SourcePropertyAccessorSymbol) As Location Dim syntaxTree = accessor.SyntaxTree Dim block = DirectCast(accessor.BlockSyntax, AccessorBlockSyntax) Debug.Assert(syntaxTree IsNot Nothing) Debug.Assert(block IsNot Nothing) Debug.Assert(block.BlockStatement IsNot Nothing) Return syntaxTree.GetLocation(block.BlockStatement.Span) End Function Private Shared ReadOnly s_overridableModifierKinds() As SyntaxKind = { SyntaxKind.OverridableKeyword } Private Shared ReadOnly s_accessibilityModifierKinds() As SyntaxKind = { SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.FriendKeyword, SyntaxKind.PublicKeyword } ''' <summary> ''' Report an error associated with the accessor accessibility modifier. ''' </summary> Private Shared Sub ReportAccessorAccessibilityError(binder As Binder, syntax As AccessorBlockSyntax, errorId As ERRID, diagnostics As DiagnosticBag) binder.ReportModifierError(syntax.BlockStatement.Modifiers, errorId, diagnostics, s_accessibilityModifierKinds) End Sub Private Shared Function HasRequiredParameters(parameters As ImmutableArray(Of ParameterSymbol)) As Boolean For Each parameter In parameters If Not parameter.IsOptional AndAlso Not parameter.IsParamArray Then Return True End If Next Return False End Function ''' <summary> ''' Gets the syntax tree. ''' </summary> Friend ReadOnly Property SyntaxTree As SyntaxTree Get Return _syntaxRef.SyntaxTree End Get End Property ' This should be called at most once after the attributes are bound. Attributes must be bound after the class ' and members are fully declared to avoid infinite recursion. Private Sub SetCustomAttributeData(attributeData As CustomAttributesBag(Of VisualBasicAttributeData)) Debug.Assert(attributeData IsNot Nothing) Debug.Assert(_lazyCustomAttributesBag Is Nothing) _lazyCustomAttributesBag = attributeData End Sub Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) MyBase.GenerateDeclarationErrors(cancellationToken) ' Ensure return type attributes are bound Dim unusedType = Me.Type Dim unusedParameters = Me.Parameters Me.GetReturnTypeAttributesBag() Dim unusedImplementations = Me.ExplicitInterfaceImplementations If DeclaringCompilation.EventQueue IsNot Nothing Then DirectCast(Me.ContainingModule, SourceModuleSymbol).AtomicSetFlagAndRaiseSymbolDeclaredEvent(_lazyState, StateFlags.SymbolDeclaredEvent, 0, Me) End If End Sub Friend Overrides ReadOnly Property IsMyGroupCollectionProperty 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) If Me.Type.ContainsTupleNames() Then AddSynthesizedAttribute(attributes, DeclaringCompilation.SynthesizeTupleNamesAttribute(Type)) End If End Sub End Class End Namespace
aelij/roslyn
src/Compilers/VisualBasic/Portable/Symbols/Source/SourcePropertySymbol.vb
Visual Basic
apache-2.0
59,478
Public Class StringForm ' Executes the editor. Public Shared Function GetString(ByVal value As String) As String Dim instance As New StringForm() instance.TextBox1.Text = value If instance.ShowDialog() = Windows.Forms.DialogResult.OK Then Return instance.TextBox1.Text Else Return value End If End Function End Class
QMDevTeam/QMDesigner
BO/Editor Classes/Forms/StringForm.vb
Visual Basic
apache-2.0
394
Imports MonitoringAgent.Agent.AgentParameters Namespace Agent Public Class Database Public Shared Property AgentSystemList As New List(Of AgentSystem) Public Shared Property AgentDataList As New List(Of AgentData) Public Shared Property AgentStateList As New List(Of AgentState) Public Shared Property AgentConfigList As New List(Of AgentConfiguration) End Class End Namespace
philipcwhite/MonitoringAgent
MonitoringAgent/Agent/Database/Database.vb
Visual Basic
apache-2.0
424
Imports BVSoftware.Bvc5.Core Partial Class BVAdmin_Configuration_Shipping_EditMethod Inherits BaseAdminPage Private m As Shipping.ShippingMethod Private WithEvents editor As Content.BVShippingModule Protected Sub Page_Load1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then LoadCountries() LoadNOTCountries() LoadRegions() LoadNOTRegions() End If End Sub Protected Sub Page_PreInit1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit Me.PageTitle = "Edit Shipping Method" Me.CurrentTab = AdminTabType.Configuration ValidateCurrentUserHasPermission(Membership.SystemPermissions.SettingsView) End Sub Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init If Request.QueryString("id") IsNot Nothing Then Me.BlockIDField.Value = Request.QueryString("id") End If m = Shipping.ShippingMethod.FindByBvin(Me.BlockIDField.Value) LoadEditor() End Sub Private Function FindProvider(ByVal bvin As String) As Shipping.ShippingProvider Dim result As Shipping.ShippingProvider = New Shipping.Provider.NullProvider Dim found As Boolean = False For Each p As Shipping.ShippingProvider In Shipping.AvailableProviders.Providers If p.ProviderId = bvin Then result = p found = True Exit For End If Next Return result End Function Private Sub LoadEditor() Dim tempControl As System.Web.UI.Control = Nothing Dim p As Shipping.ShippingProvider = FindProvider(m.ShippingProviderId) tempControl = Content.ModuleController.LoadShippingEditor(p.Name, Me) If TypeOf tempControl Is Content.BVShippingModule Then editor = CType(tempControl, Content.BVShippingModule) If Not editor Is Nothing Then editor.BlockId = m.Bvin editor.ShippingMethod = m Me.phEditor.Controls.Add(editor) End If Else Me.phEditor.Controls.Add(New LiteralControl("Error, editor is not based on Content.BVShippingModule class")) End If End Sub Protected Sub editor_EditingComplete(ByVal sender As Object, ByVal e As BVSoftware.Bvc5.Core.Content.BVModuleEventArgs) Handles editor.EditingComplete If (e.Info.ToUpper = "CANCELED") Then If (Request.QueryString("doc") = 1) Then Shipping.ShippingMethod.Delete(m.Bvin) End If Else If e.Info <> String.Empty Then m.Name = e.Info Shipping.ShippingMethod.Update(m) End If End If Response.Redirect("Shipping.aspx") End Sub Protected Sub btnAddCountry_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnAddCountry.Click Dim li As ListItem For Each li In inNOTCountries.Items If li.Selected = True Then Shipping.ShippingMethod.DeleteCountryRestriction(Me.BlockIDField.Value, li.Value) End If Next LoadCountries() LoadNOTCountries() LoadRegions() LoadNOTRegions() End Sub Protected Sub btnDelCountry_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnDelCountry.Click Dim li As ListItem For Each li In inCountries.Items If li.Selected = True Then Shipping.ShippingMethod.AddCountryRestriction(Me.BlockIDField.Value, li.Value) End If Next LoadCountries() LoadNOTCountries() LoadRegions() LoadNOTRegions() End Sub Protected Sub btnAddRegion_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnAddRegion.Click Dim li As ListItem For Each li In inNOTRegions.Items If li.Selected = True Then Shipping.ShippingMethod.DeleteRegionRestriction(Me.BlockIDField.Value, li.Value) End If Next LoadRegions() LoadNOTRegions() End Sub Protected Sub btnDelRegion_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnDelRegion.Click Dim li As ListItem For Each li In inRegions.Items If li.Selected = True Then Shipping.ShippingMethod.AddRegionRestriction(Me.BlockIDField.Value, li.Value) End If Next LoadRegions() LoadNOTRegions() End Sub Sub LoadRegions() inRegions.Items.Clear() inRegions.DataSource = Shipping.ShippingMethod.FindRegions(Me.BlockIDField.Value) inRegions.DataTextField = "Name" inRegions.DataValueField = "Bvin" inRegions.DataBind() End Sub Sub LoadNOTRegions() inNOTRegions.Items.Clear() inNOTRegions.DataSource = Shipping.ShippingMethod.FindNotRegions(Me.BlockIDField.Value) inNOTRegions.DataTextField = "Name" inNOTRegions.DataValueField = "Bvin" inNOTRegions.DataBind() End Sub Sub LoadCountries() inCountries.Items.Clear() inCountries.DataSource = Shipping.ShippingMethod.FindCountries(Me.BlockIDField.Value) inCountries.DataTextField = "DisplayName" inCountries.DataValueField = "Bvin" inCountries.DataBind() End Sub Sub LoadNOTCountries() inNOTCountries.Items.Clear() inNOTCountries.DataSource = Shipping.ShippingMethod.FindNotCountries(Me.BlockIDField.Value) inNOTCountries.DataTextField = "DisplayName" inNOTCountries.DataValueField = "Bvin" inNOTCountries.DataBind() End Sub End Class
ajaydex/Scopelist_2015
BVAdmin/Configuration/Shipping_EditMethod.aspx.vb
Visual Basic
apache-2.0
5,905
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("SampleLibraryVB")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("Offwhite.net LLC")> <Assembly: AssemblyProduct("SampleLibraryVB")> <Assembly: AssemblyCopyright("Copyright © Offwhite.net LLC 2008")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("cce16e7e-8cb0-43d4-9815-0d7a18886f5f")> ' 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")>
smallsharptools/SmallSharpToolsDotNet
VSX/Sample/SampleLibraryVB/My Project/AssemblyInfo.vb
Visual Basic
apache-2.0
1,215
' 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.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Editor.Commands Imports Microsoft.CodeAnalysis.Editor.CSharp.Formatting Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Differencing Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Text.Projection Imports Microsoft.VisualStudio.Utilities Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense Public Class CSharpCompletionCommandHandlerTests <WorkItem(541201, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541201")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TabCommitsWithoutAUniqueMatch() As Task Using state = TestState.CreateCSharpTestState( <Document> $$ </Document>) state.SendTypeChars("using System.Ne") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Net", isHardSelected:=True) state.SendTypeChars("x") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Net", isSoftSelected:=True) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("using System.Net", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAtEndOfFile() As Task Using state = TestState.CreateCSharpTestState( <Document>$$</Document>) state.SendTypeChars("us") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("using", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNotAtStartOfExistingWord() As Task Using state = TestState.CreateCSharpTestState( <Document>$$using</Document>) state.SendTypeChars("u") Await state.AssertNoCompletionSession() Assert.Contains("using", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMSCorLibTypes() As Task Using state = TestState.CreateCSharpTestState( <Document> using System; class c : $$ </Document>) state.SendTypeChars("A") Await state.AssertCompletionSession() Assert.True(state.CompletionItemsContainsAll(displayText:={"Attribute", "Exception", "IDisposable"})) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFiltering1() As Task Using state = TestState.CreateCSharpTestState( <Document> using System; class c { $$ </Document>) state.SendTypeChars("Sy") Await state.AssertCompletionSession() Assert.True(state.CompletionItemsContainsAll(displayText:={"OperatingSystem", "System", "SystemException"})) Assert.False(state.CompletionItemsContainsAny(displayText:={"Exception", "Activator"})) End Using End Function ' NOTE(cyrusn): This should just be a unit test for SymbolCompletionProvider. However, I'm ' just porting the integration tests to here for now. <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMultipleTypes() As Task Using state = TestState.CreateCSharpTestState( <Document> class C { $$ } struct S { } enum E { } interface I { } delegate void D(); </Document>) state.SendTypeChars("C") Await state.AssertCompletionSession() Assert.True(state.CompletionItemsContainsAll(displayText:={"C", "S", "E", "I", "D"})) End Using End Function ' NOTE(cyrusn): This should just be a unit test for KeywordCompletionProvider. However, I'm ' just porting the integration tests to here for now. <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInEmptyFile() As Task Using state = TestState.CreateCSharpTestState( <Document> $$ </Document>) state.SendInvokeCompletionList() Await state.AssertCompletionSession() Assert.True(state.CompletionItemsContainsAll(displayText:={"abstract", "class", "namespace"})) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNotAfterTypingDotAfterIntegerLiteral() As Task Using state = TestState.CreateCSharpTestState( <Document> class c { void M() { 3$$ } } </Document>) state.SendTypeChars(".") Await state.AssertNoCompletionSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterExplicitInvokeAfterDotAfterIntegerLiteral() As Task Using state = TestState.CreateCSharpTestState( <Document> class c { void M() { 3.$$ } } </Document>) state.SendInvokeCompletionList() Await state.AssertCompletionSession() Assert.True(state.CompletionItemsContainsAll({"ToString"})) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEnterIsConsumed() As Task Using state = TestState.CreateCSharpTestState( <Document> class Class1 { void Main(string[] args) { $$ } }</Document>) state.SendTypeChars("System.TimeSpan.FromMin") state.SendReturn() Await state.WaitForAsynchronousOperationsAsync() Assert.Equal(<text> class Class1 { void Main(string[] args) { System.TimeSpan.FromMinutes } }</text>.NormalizedValue, state.GetDocumentText()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDescription1() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; /// <summary> /// TestDocComment /// </summary> class TestException : Exception { } class MyException : $$]]></Document>) state.SendTypeChars("Test") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(description:="class TestException" & vbCrLf & "TestDocComment") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestObjectCreationPreselection1() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System.Collections.Generic; class C { public void Foo() { List<int> list = new$$ } }]]></Document>) state.SendTypeChars(" ") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="List<int>", isHardSelected:=True) Assert.True(state.CompletionItemsContainsAll(displayText:={"LinkedList<>", "List<>", "System"})) state.SendTypeChars("Li") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="List<int>", isHardSelected:=True) Assert.True(state.CompletionItemsContainsAll(displayText:={"LinkedList<>", "List<>"})) Assert.False(state.CompletionItemsContainsAny(displayText:={"System"})) state.SendTypeChars("n") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="LinkedList<>", isHardSelected:=True) state.SendBackspace() Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="List<int>", isHardSelected:=True) state.SendTab() Assert.Contains("new List<int>", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(543268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543268")> Public Async Function TestTypePreselection1() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ partial class C { } partial class C { $$ }]]></Document>) state.SendTypeChars("C") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="C", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(543519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543519")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNewPreselectionAfterVar() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void M() { var c = $$ } }]]></Document>) state.SendTypeChars("new ") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(543559, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543559")> <WorkItem(543561, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543561")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEscapedIdentifiers() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class @return { void foo() { $$ } } ]]></Document>) state.SendTypeChars("@") Await state.AssertNoCompletionSession() state.SendTypeChars("r") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="@return", isHardSelected:=True) state.SendTab() Assert.Contains("@return", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(543771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543771")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommitUniqueItem1() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class Program { static void Main(string[] args) { Console.WriteL$$(); } }]]></Document>) state.SendCommitUniqueCompletionListItem() Await state.AssertNoCompletionSession() Assert.Contains("WriteLine()", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(543771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543771")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommitUniqueItem2() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class Program { static void Main(string[] args) { Console.WriteL$$ine(); } }]]></Document>) state.SendCommitUniqueCompletionListItem() Await state.AssertNoCompletionSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitForUsingDirective1() As Task Using state = TestState.CreateCSharpTestState( <Document> $$ </Document>) state.SendTypeChars("using Sys") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True) state.SendTypeChars("(") Await state.AssertNoCompletionSession() Assert.Contains("using Sys(", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitForUsingDirective2() As Task Using state = TestState.CreateCSharpTestState( <Document> $$ </Document>) state.SendTypeChars("using Sys") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True) state.SendTypeChars(".") Await state.AssertCompletionSession() Assert.Contains("using System.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitForUsingDirective3() As Task Using state = TestState.CreateCSharpTestState( <Document> $$ </Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendTypeChars("using Sys") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True) state.SendTypeChars(";") Await state.AssertNoCompletionSession() state.AssertMatchesTextStartingAtLine(1, "using System;") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitForUsingDirective4() As Task Using state = TestState.CreateCSharpTestState( <Document> $$ </Document>) state.SendTypeChars("using Sys") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="System", isHardSelected:=True) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() Assert.Contains("using Sys ", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function KeywordsIncludedInObjectCreationCompletion() As Task Using state = TestState.CreateCSharpTestState( <Document> class C { void Foo() { string s = new$$ } } </Document>) state.SendTypeChars(" ") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="string", isHardSelected:=True) Assert.True(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(c) c.DisplayText = "int")) End Using End Function <WorkItem(544293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544293")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NoKeywordsOrSymbolsAfterNamedParameter() As Task Using state = TestState.CreateCSharpTestState( <Document> class Foo { void Test() { object m = null; Method(obj:m, $$ } void Method(object obj, int num = 23, string str = "") { } } </Document>) state.SendTypeChars("a") Await state.AssertCompletionSession() Assert.True(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "num:")) Assert.False(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "System")) Assert.False(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(c) c.DisplayText = "int")) End Using End Function <WorkItem(544017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544017")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionTriggeredOnSpace() As Task Using state = TestState.CreateCSharpTestState( <Document> enum Numeros { Uno, Dos } class Foo { void Bar(int a, Numeros n) { } void Baz() { Bar(0$$ } } </Document>) state.SendTypeChars(", ") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Numeros", isHardSelected:=True) Assert.Equal(1, state.CurrentCompletionPresenterSession.CompletionItems.Where(Function(c) c.DisplayText = "Numeros").Count()) End Using End Function <WorkItem(479078, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/479078")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionTriggeredOnSpaceForNullables() As Task Using state = TestState.CreateCSharpTestState( <Document> enum Numeros { Uno, Dos } class Foo { void Bar(int a, Numeros? n) { } void Baz() { Bar(0$$ } } </Document>) state.SendTypeChars(", ") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Numeros", isHardSelected:=True) Assert.Equal(1, state.CurrentCompletionPresenterSession.CompletionItems.Where(Function(c) c.DisplayText = "Numeros").Count()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionTriggeredOnDot() As Task Using state = TestState.CreateCSharpTestState( <Document> enum Numeros { Uno, Dos } class Foo { void Bar() { Numeros num = $$ } } </Document>) state.SendTypeChars("Nu.") Await state.WaitForAsynchronousOperationsAsync() Assert.Contains("Numeros num = Numeros.", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumCompletionNotTriggeredOnOtherCommitCharacters() As Task Await EnumCompletionNotTriggeredOn("+"c) Await EnumCompletionNotTriggeredOn("{"c) Await EnumCompletionNotTriggeredOn(" "c) Await EnumCompletionNotTriggeredOn(";"c) End Function Private Async Function EnumCompletionNotTriggeredOn(c As Char) As Task Using state = TestState.CreateCSharpTestState( <Document> enum Numeros { Uno, Dos } class Foo { void Bar() { Numeros num = $$ } } </Document>) state.SendTypeChars("Nu") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Numeros", isHardSelected:=True) state.SendTypeChars(c.ToString()) Await state.AssertNoCompletionSession() Assert.Contains(String.Format("Numeros num = Nu{0}", c), state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(544296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544296")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestVerbatimNamedIdentifierFiltering() As Task Using state = TestState.CreateCSharpTestState( <Document> class Program { void Foo(int @int) { Foo($$ } } </Document>) state.SendTypeChars("i") Await state.AssertCompletionSession() Assert.True(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "@int:")) state.SendTypeChars("n") Await state.WaitForAsynchronousOperationsAsync() Assert.True(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "@int:")) state.SendTypeChars("t") Await state.WaitForAsynchronousOperationsAsync() Assert.True(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "@int:")) End Using End Function <WorkItem(543687, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543687")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoPreselectInInvalidObjectCreationLocation() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class Program { void Test() { $$ } } class Bar { } class Foo<T> : IFoo<T> { } interface IFoo<T> { }]]> </Document>) state.SendTypeChars("IFoo<Bar> a = new ") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(544925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544925")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestQualifiedEnumSelection() As Task Using state = TestState.CreateCSharpTestState( <Document> using System; class Program { void Main() { Environment.GetFolderPath$$ } } </Document>) state.SendTypeChars("(") state.SendTab() Await state.WaitForAsynchronousOperationsAsync() Assert.Contains("Environment.SpecialFolder", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WorkItem(545070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545070")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTextChangeSpanWithAtCharacter() As Task Using state = TestState.CreateCSharpTestState( <Document> public class @event { $$@event() { } } </Document>) state.SendTypeChars("public ") Await state.AssertNoCompletionSession() Assert.Contains("public @event", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDoNotInsertColonSoThatUserCanCompleteOutAVariableNameThatDoesNotCurrentlyExist_IE_TheCyrusCase() As Task Using state = TestState.CreateCSharpTestState( <Document> using System.Threading; class Program { static void Main(string[] args) { Foo($$) } void Foo(CancellationToken cancellationToken) { } } </Document>) state.SendTypeChars("can") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("Foo(cancellationToken)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function #If False Then <Scenario Name="Verify correct intellisense selection on ENTER"> <SetEditorText> <![CDATA[class Class1 { void Main(string[] args) { // } }]]> </SetEditorText> <PlaceCursor Marker="//" /> <SendKeys>var a = System.TimeSpan.FromMin{ENTER}{(}</SendKeys> <VerifyEditorContainsText> <![CDATA[class Class1 { void Main(string[] args) { var a = System.TimeSpan.FromMinutes( } }]]> </VerifyEditorContainsText> </Scenario> #End If <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeNamedPropertyCompletionCommitWithTab() As Task Using state = TestState.CreateCSharpTestState( <Document> class MyAttribute : System.Attribute { public string Name { get; set; } } [MyAttribute($$ public class Foo { } </Document>) state.SendTypeChars("Nam") state.SendTab() Await state.AssertNoCompletionSession() Assert.Equal("[MyAttribute(Name =", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeNamedPropertyCompletionCommitWithEquals() As Task Using state = TestState.CreateCSharpTestState( <Document> class MyAttribute : System.Attribute { public string Name { get; set; } } [MyAttribute($$ public class Foo { } </Document>) state.SendTypeChars("Nam=") Await state.AssertNoCompletionSession() Assert.Equal("[MyAttribute(Name =", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(544940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544940")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeNamedPropertyCompletionCommitWithSpace() As Task Using state = TestState.CreateCSharpTestState( <Document> class MyAttribute : System.Attribute { public string Name { get; set; } } [MyAttribute($$ public class Foo { } </Document>) state.SendTypeChars("Nam ") Await state.AssertNoCompletionSession() Assert.Equal("[MyAttribute(Name ", state.GetLineTextFromCaretPosition()) End Using End Function <WorkItem(545590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545590")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOverrideDefaultParameter() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public virtual void Foo<S>(S x = default(S)) { } } class D : C { override $$ } ]]></Document>) state.SendTypeChars(" Foo") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("public override void Foo<S>(S x = default(S))", state.SubjectBuffer.CurrentSnapshot.GetText(), StringComparison.Ordinal) End Using End Function <WorkItem(545664, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545664")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestArrayAfterOptionalParameter() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class A { public virtual void Foo(int x = 0, int[] y = null) { } } class B : A { public override void Foo(int x = 0, params int[] y) { } } class C : B { override$$ } ]]></Document>) state.SendTypeChars(" Foo") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains(" public override void Foo(int x = 0, int[] y = null)", state.SubjectBuffer.CurrentSnapshot.GetText(), StringComparison.Ordinal) End Using End Function <WorkItem(545967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545967")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestVirtualSpaces() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public string P { get; set; } void M() { var v = new C {$$ }; } } ]]></Document>) state.SendReturn() Assert.True(state.TextView.Caret.InVirtualSpace) Assert.Equal(12, state.TextView.Caret.Position.VirtualSpaces) state.SendInvokeCompletionList() Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("P", isSoftSelected:=True) state.SendDownKey() Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("P", isHardSelected:=True) state.SendTab() Await state.WaitForAsynchronousOperationsAsync() Assert.Equal(" P", state.GetLineFromCurrentCaretPosition().GetText()) Dim bufferPosition = state.TextView.Caret.Position.BufferPosition Assert.Equal(13, bufferPosition.Position - bufferPosition.GetContainingLine().Start.Position) Assert.False(state.TextView.Caret.InVirtualSpace) End Using End Function <WorkItem(546561, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546561")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNamedParameterAgainstMRU() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Program { void Foo(string s) { } static void Main() { $$ } } ]]></Document>) ' prime the MRU state.SendTypeChars("string") state.SendTab() Await state.AssertNoCompletionSession() ' Delete what we just wrote. state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendEscape() Await state.AssertNoCompletionSession() ' ensure we still select the named param even though 'string' is in the MRU. state.SendTypeChars("Foo(s") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("s:") End Using End Function <WorkItem(546403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546403")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMissingOnObjectCreationAfterVar1() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class A { void Foo() { var v = new$$ } } ]]></Document>) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(546403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546403")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMissingOnObjectCreationAfterVar2() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class A { void Foo() { var v = new $$ } } ]]></Document>) state.SendTypeChars("X") Await state.AssertCompletionSession() Assert.False(state.CurrentCompletionPresenterSession.CompletionItems.Any(Function(i) i.DisplayText = "X")) End Using End Function <WorkItem(546917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546917")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEnumInSwitch() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ enum Numeros { } class C { void M() { Numeros n; switch (n) { case$$ } } } ]]></Document>) state.SendTypeChars(" ") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Numeros") End Using End Function <WorkItem(547016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547016")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAmbiguityInLocalDeclaration() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public int W; public C() { $$ W = 0; } } ]]></Document>) state.SendTypeChars("w") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="W") End Using End Function <WorkItem(530835, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530835")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompletionFilterSpanCaretBoundary() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public void Method() { $$ } } ]]></Document>) state.SendTypeChars("Met") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Method") state.SendLeftKey() state.SendLeftKey() state.SendLeftKey() state.SendTypeChars("new") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem(displayText:="Method", isSoftSelected:=True) End Using End Function <WorkItem(5487, "https://github.com/dotnet/roslyn/issues/5487")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommitCharTypedAtTheBeginingOfTheFilterSpan() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { public bool Method() { if ($$ } } ]]></Document>) state.SendTypeChars("Met") Await state.AssertCompletionSession() state.SendLeftKey() state.SendLeftKey() state.SendLeftKey() Await state.AssertSelectedCompletionItem(isSoftSelected:=True) state.SendTypeChars("!") Await state.AssertNoCompletionSession() Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("if (!Met", state.GetLineTextFromCaretPosition().Trim()) Assert.Equal("M", state.GetCaretPoint().BufferPosition.GetChar()) End Using End Function <WorkItem(622957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/622957")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBangFiltersInDocComment() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; /// $$ /// TestDocComment /// </summary> class TestException : Exception { } ]]></Document>) state.SendTypeChars("<") Await state.AssertCompletionSession() state.SendTypeChars("!") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("!--") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function InvokeCompletionDoesNotFilter() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Method() { string$$ } } ]]></Document>) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("string") state.CompletionItemsContainsAll({"integer", "Method"}) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function InvokeBeforeWordDoesNotSelect() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Method() { $$string } } ]]></Document>) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("AccessViolationException") state.CompletionItemsContainsAll({"integer", "Method"}) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function InvokeCompletionSelectsWithoutRegardToCaretPosition() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Method() { s$$tring } } ]]></Document>) state.SendInvokeCompletionList() Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("string") state.CompletionItemsContainsAll({"integer", "Method"}) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TabAfterQuestionMark() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Method() { ?$$ } } ]]></Document>) state.SendTab() Await state.WaitForAsynchronousOperationsAsync() Assert.Equal(state.GetLineTextFromCaretPosition(), " ?" + vbTab) End Using End Function <WorkItem(657658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/657658")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PreselectionIgnoresBrackets() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { $$ static void Main(string[] args) { } }]]></Document>) state.SendTypeChars("static void F<T>(int a, Func<T, int> b) { }") state.SendEscape() state.TextView.Caret.MoveTo(New VisualStudio.Text.SnapshotPoint(state.SubjectBuffer.CurrentSnapshot, 220)) state.SendTypeChars("F") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("F<>") End Using End Function <WorkItem(672474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672474")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInvokeSnippetCommandDismissesCompletion() As Task Using state = TestState.CreateCSharpTestState( <Document>$$</Document>) state.SendTypeChars("us") Await state.AssertCompletionSession() state.SendInsertSnippetCommand() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(672474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672474")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSurroundWithCommandDismissesCompletion() As Task Using state = TestState.CreateCSharpTestState( <Document>$$</Document>) state.SendTypeChars("us") Await state.AssertCompletionSession() state.SendSurroundWithCommand() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(737239, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737239")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function LetEditorHandleOpenParen() As Task Dim expected = <Document><![CDATA[ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { List<int> x = new List<int>( } }]]></Document>.Value.Replace(vbLf, vbCrLf) Using state = TestState.CreateCSharpTestState(<Document><![CDATA[ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { List<int> x = new$$ } }]]></Document>) state.SendTypeChars(" ") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("List<int>") state.SendTypeChars("(") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal(expected, state.GetDocumentText()) End Using End Function <WorkItem(785637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/785637")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitMovesCaretToWordEnd() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Main() { M$$ain } } ]]></Document>) state.SendCommitUniqueCompletionListItem() Await state.WaitForAsynchronousOperationsAsync() Assert.Equal(state.GetLineFromCurrentCaretPosition().End, state.GetCaretPoint().BufferPosition) End Using End Function <WorkItem(775370, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775370")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function MatchingConsidersAtSign() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class C { public void Main() { $$ } } ]]></Document>) state.SendTypeChars("var @this = ""foo""") state.SendReturn() state.SendTypeChars("string str = this.ToString();") state.SendReturn() state.SendTypeChars("str = @th") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("@this") End Using End Function <WorkItem(865089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/865089")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeFilterTextRemovesAttributeSuffix() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ [$$] class AtAttribute : System.Attribute { }]]></Document>) state.SendTypeChars("At") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("At") Assert.Equal("At", state.CurrentCompletionPresenterSession.SelectedItem.FilterText) End Using End Function <WorkItem(852578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/852578")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PreselectExceptionOverSnippet() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using System; class C { Exception foo() { return new $$ } }]]></Document>) state.SendTypeChars(" ") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("Exception") End Using End Function <WorkItem(868286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/868286")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitNameAfterAlias() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ using foo = System$$]]></Document>) state.SendTypeChars(".act<") Await state.WaitForAsynchronousOperationsAsync() state.AssertMatchesTextStartingAtLine(1, "using foo = System.Action<") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCompletionInLinkedFiles() As Task Using state = TestState.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Thing2"> <Document FilePath="C.cs"> class C { void M() { $$ } #if Thing1 void Thing1() { } #elif Thing2 void Thing2() { } #endif } </Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Thing1"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>) Dim documents = state.Workspace.Documents Dim linkDocument = documents.Single(Function(d) d.IsLinkFile) state.SendTypeChars("Thing1") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("Thing1") state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendEscape() state.Workspace.SetDocumentContext(linkDocument.Id) state.SendTypeChars("Thing1") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("Thing1") Assert.True(state.CurrentCompletionPresenterSession.SelectedItem.ShowsWarningIcon) state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendBackspace() state.SendTypeChars("M") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("M") Assert.False(state.CurrentCompletionPresenterSession.SelectedItem.ShowsWarningIcon) End Using End Function <WorkItem(951726, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951726")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function DismissUponSave() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { $$ }]]></Document>) state.SendTypeChars("voi") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("void") state.SendSave() Await state.AssertNoCompletionSession() state.AssertMatchesTextStartingAtLine(3, " voi") End Using End Function <WorkItem(930254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930254")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NoCompletionWithBoxSelection() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { {|Selection:$$int x;|} {|Selection:int y;|} }]]></Document>) state.SendInvokeCompletionList() Await state.AssertNoCompletionSession() state.SendTypeChars("foo") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(839555, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839555")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TriggeredOnHash() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ $$]]></Document>) state.SendTypeChars("#") Await state.AssertCompletionSession() End Using End Function <WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function RegionCompletionCommitTriggersFormatting_1() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { $$ }]]></Document>) state.SendTypeChars("#reg") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("region") state.SendReturn() Await state.WaitForAsynchronousOperationsAsync() state.AssertMatchesTextStartingAtLine(3, " #region") End Using End Function <WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function RegionCompletionCommitTriggersFormatting_2() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { $$ }]]></Document>) state.SendTypeChars("#reg") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("region") state.SendTypeChars(" ") Await state.WaitForAsynchronousOperationsAsync() state.AssertMatchesTextStartingAtLine(3, " #region ") End Using End Function <WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EndRegionCompletionCommitTriggersFormatting_2() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { #region NameIt $$ }]]></Document>) state.SendTypeChars("#endreg") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("endregion") state.SendReturn() Await state.WaitForAsynchronousOperationsAsync() state.AssertMatchesTextStartingAtLine(4, " #endregion ") End Using End Function Private Class SlowProvider Inherits CompletionListProvider Public checkpoint As Checkpoint = New Checkpoint() Public Overrides Async Function ProduceCompletionListAsync(context As CompletionListContext) As Task Await checkpoint.Task.ConfigureAwait(False) End Function Public Overrides Function IsTriggerCharacter(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean Return True End Function End Class <WorkItem(1015893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1015893")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function BackspaceDismissesIfComputationIsIncomplete() As Task Dim slowProvider = New SlowProvider() Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void foo() { foo($$ } }]]></Document>, {slowProvider}) state.SendTypeChars("f") state.SendBackspace() ' Send a backspace that goes beyond the session's applicable span ' before the model computation has finished. Then, allow the ' computation to complete. There should still be no session. state.SendBackspace() slowProvider.checkpoint.Release() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(1065600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1065600")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitUniqueItemWithBoxSelection() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void foo(int x) { [|$$ |] } }]]></Document>) state.SendReturn() state.TextView.Selection.Mode = VisualStudio.Text.Editor.TextSelectionMode.Box state.SendCommitUniqueCompletionListItem() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(1594, "https://github.com/dotnet/roslyn/issues/1594")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NoPreselectionOnSpaceWhenAbuttingWord() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Program { void Main() { Program p = new $$Program(); } }]]></Document>) state.SendTypeChars(" ") Await state.AssertNoCompletionSession() End Using End Function <WorkItem(1594, "https://github.com/dotnet/roslyn/issues/1594")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function SpacePreselectionAtEndOfFile() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class Program { void Main() { Program p = new $$]]></Document>) state.SendTypeChars(" ") Await state.AssertCompletionSession() End Using End Function <WorkItem(1659, "https://github.com/dotnet/roslyn/issues/1659")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function DismissOnSelectAllCommand() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void foo(int x) { $$]]></Document>) ' Note: the caret is at the file, so the Select All command's movement ' of the caret to the end of the selection isn't responsible for ' dismissing the session. state.SendInvokeCompletionList() Await state.AssertCompletionSession() state.SendSelectAll() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(588, "https://github.com/dotnet/roslyn/issues/588")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionCommitAndFormatAreSeparateUndoTransactions() As Task Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void foo(int x) { int doodle; $$]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendTypeChars("doo;") Await state.WaitForAsynchronousOperationsAsync() state.AssertMatchesTextStartingAtLine(6, " doodle;") state.SendUndo() Await state.WaitForAsynchronousOperationsAsync() state.AssertMatchesTextStartingAtLine(6, "doodle;") state.SendUndo() Await state.WaitForAsynchronousOperationsAsync() state.AssertMatchesTextStartingAtLine(6, "doo;") End Using End Function <WorkItem(4978, "https://github.com/dotnet/roslyn/issues/4978")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function SessionNotStartedWhenCaretNotMappableIntoSubjectBuffer() As Task ' In inline diff view, typing delete next to a "deletion", ' can cause our CommandChain to be called with a subjectbuffer ' and TextView such that the textView's caret can't be mapped ' into our subject buffer. ' ' To test this, we create a projection buffer with 2 source ' spans: one of "text" content type and one based on a C# ' buffer. We create a TextView with that projection as ' its buffer, setting the caret such that it maps only ' into the "text" buffer. We then call the completion ' command handlers with commandargs based on that TextView ' but with the C# buffer as the SubjectBuffer. Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void foo(int x) {$$ /********/ int doodle; } }]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) Dim textBufferFactoryService = state.GetExportedValue(Of ITextBufferFactoryService)() Dim contentTypeService = state.GetExportedValue(Of IContentTypeRegistryService)() Dim contentType = contentTypeService.GetContentType(ContentTypeNames.CSharpContentType) Dim textViewFactory = state.GetExportedValue(Of ITextEditorFactoryService)() Dim editorOperationsFactory = state.GetExportedValue(Of IEditorOperationsFactoryService)() Dim otherBuffer = textBufferFactoryService.CreateTextBuffer("text", contentType) Dim otherExposedSpan = otherBuffer.CurrentSnapshot.CreateTrackingSpan(0, 4, SpanTrackingMode.EdgeExclusive, TrackingFidelityMode.Forward) Dim subjectBufferExposedSpan = state.SubjectBuffer.CurrentSnapshot.CreateTrackingSpan(0, state.SubjectBuffer.CurrentSnapshot.Length, SpanTrackingMode.EdgeExclusive, TrackingFidelityMode.Forward) Dim projectionBufferFactory = state.GetExportedValue(Of IProjectionBufferFactoryService)() Dim projection = projectionBufferFactory.CreateProjectionBuffer(Nothing, New Object() {otherExposedSpan, subjectBufferExposedSpan}.ToList(), ProjectionBufferOptions.None) Using disposableView As DisposableTextView = textViewFactory.CreateDisposableTextView(projection) disposableView.TextView.Caret.MoveTo(New SnapshotPoint(disposableView.TextView.TextBuffer.CurrentSnapshot, 0)) Dim editorOperations = editorOperationsFactory.GetEditorOperations(disposableView.TextView) state.CompletionCommandHandler.ExecuteCommand(New DeleteKeyCommandArgs(disposableView.TextView, state.SubjectBuffer), Sub() editorOperations.Delete()) Await state.AssertNoCompletionSession() End Using End Using End Function <WorkItem(588, "https://github.com/dotnet/roslyn/issues/588")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround1() As Task Using New CultureContext("tr-TR") Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void foo(int x) { string.$$]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendTypeChars("is") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("IsInterned") End Using End Using End Function <WorkItem(588, "https://github.com/dotnet/roslyn/issues/588")> <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMatchWithTurkishIWorkaround2() As Task Using New CultureContext("tr-TR") Using state = TestState.CreateCSharpTestState( <Document><![CDATA[ class C { void foo(int x) { string.$$]]></Document>, extraExportedTypes:={GetType(CSharpEditorFormattingService)}.ToList()) state.SendTypeChars("ı") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem() End Using End Using End Function End Class End Namespace
basoundr/roslyn
src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb
Visual Basic
apache-2.0
64,453
Imports Newtonsoft.Json Partial Public Module Models <JsonObject(MemberSerialization:=MemberSerialization.OptIn)> Public Class Role <JsonProperty(PropertyName:="name", Required:=Required.AllowNull)> Public Name As String <JsonProperty(PropertyName:="rate", Required:=Required.AllowNull)> Public Rate As Double Public Overrides Function ToString() As String Return Name End Function End Class End Module
dewster/lol-mastery-manager-new-client
LoLMasteryManager/Models/Role.vb
Visual Basic
mit
487
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers Imports Microsoft.CodeAnalysis.PickMembers Imports Microsoft.CodeAnalysis.VisualBasic.GenerateEqualsAndGetHashCodeFromMembers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.GenerateConstructorFromMembers Public Class GenerateEqualsAndGetHashCodeFromMembersTests Inherits AbstractVisualBasicCodeActionTest Private Const GenerateOperatorsId = AbstractGenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId Private Const ImplementIEquatableId = AbstractGenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicGenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider( DirectCast(parameters.fixProviderData, IPickMembersService)) End Function <WorkItem(541991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541991")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestEqualsOnSingleField() As Task Await TestInRegularAndScriptAsync( "Class Z [|Private a As Integer|] End Class", "Class Z Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a End Function End Class") End Function <WorkItem(541991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541991")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestGetHashCodeOnSingleField() As Task Await TestInRegularAndScriptAsync( "Class Z [|Private a As Integer|] End Class", "Class Z Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a End Function Public Overrides Function GetHashCode() As Integer Dim hashCode As Long = -468965076 hashCode = (hashCode * -1521134295 + a.GetHashCode()).GetHashCode() Return hashCode End Function End Class", index:=1) End Function <WorkItem(541991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541991")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestBothOnSingleField() As Task Await TestInRegularAndScriptAsync( "Class Z [|Private a As Integer|] End Class", "Class Z Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a End Function Public Overrides Function GetHashCode() As Integer Dim hashCode As Long = -468965076 hashCode = (hashCode * -1521134295 + a.GetHashCode()).GetHashCode() Return hashCode End Function End Class", index:=1) End Function <WorkItem(545205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545205")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestTypeWithNumberInName() As Task Await TestInRegularAndScriptAsync( "Partial Class c1(Of V As {New}, U) [|Dim x As New V|] End Class", "Imports System.Collections.Generic Partial Class c1(Of V As {New}, U) Dim x As New V Public Overrides Function Equals(obj As Object) As Boolean Dim c = TryCast(obj, c1(Of V, U)) Return c IsNot Nothing AndAlso EqualityComparer(Of V).Default.Equals(x, c.x) End Function End Class") End Function <WorkItem(17643, "https://github.com/dotnet/roslyn/issues/17643")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestWithDialogNoBackingField() As Task Await TestWithPickMembersDialogAsync( " Class Program Public Property F() As Integer [||] End Class", " Class Program Public Property F() As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim program = TryCast(obj, Program) Return program IsNot Nothing AndAlso F = program.F End Function End Class", chosenSymbols:=Nothing) End Function <WorkItem(25690, "https://github.com/dotnet/roslyn/issues/25690")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestWithDialogNoParameterizedProperty() As Task Await TestWithPickMembersDialogAsync( " Class Program Public ReadOnly Property P() As Integer Get Return 0 End Get End Property Public ReadOnly Property I(index As Integer) As Integer Get Return 0 End Get End Property [||] End Class", " Class Program Public ReadOnly Property P() As Integer Get Return 0 End Get End Property Public ReadOnly Property I(index As Integer) As Integer Get Return 0 End Get End Property Public Overrides Function Equals(obj As Object) As Boolean Dim program = TryCast(obj, Program) Return program IsNot Nothing AndAlso P = program.P End Function End Class", chosenSymbols:=Nothing) End Function <WorkItem(25690, "https://github.com/dotnet/roslyn/issues/25690")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestWithDialogNoIndexer() As Task Await TestWithPickMembersDialogAsync( " Class Program Public ReadOnly Property P() As Integer Get Return 0 End Get End Property Default Public ReadOnly Property I(index As Integer) As Integer Get Return 0 End Get End Property [||] End Class", " Class Program Public ReadOnly Property P() As Integer Get Return 0 End Get End Property Default Public ReadOnly Property I(index As Integer) As Integer Get Return 0 End Get End Property Public Overrides Function Equals(obj As Object) As Boolean Dim program = TryCast(obj, Program) Return program IsNot Nothing AndAlso P = program.P End Function End Class", chosenSymbols:=Nothing) End Function <WorkItem(25707, "https://github.com/dotnet/roslyn/issues/25707")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestWithDialogNoSetterOnlyProperty() As Task Await TestWithPickMembersDialogAsync( " Class Program Public ReadOnly Property P() As Integer Get Return 0 End Get End Property Public WriteOnly Property S() As Integer Set End Set End Property [||] End Class", " Class Program Public ReadOnly Property P() As Integer Get Return 0 End Get End Property Public WriteOnly Property S() As Integer Set End Set End Property Public Overrides Function Equals(obj As Object) As Boolean Dim program = TryCast(obj, Program) Return program IsNot Nothing AndAlso P = program.P End Function End Class", chosenSymbols:=Nothing) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestGenerateOperators1() As Task Await TestWithPickMembersDialogAsync( " Imports System.Collections.Generic Class Program Public s As String [||] End Class", " Imports System.Collections.Generic Class Program Public s As String Public Overrides Function Equals(obj As Object) As Boolean Dim program = TryCast(obj, Program) Return program IsNot Nothing AndAlso s = program.s End Function Public Shared Operator =(program1 As Program, program2 As Program) As Boolean Return EqualityComparer(Of Program).Default.Equals(program1, program2) End Operator Public Shared Operator <>(program1 As Program, program2 As Program) As Boolean Return Not program1 = program2 End Operator End Class", chosenSymbols:=Nothing, optionsCallback:=Sub(options) EnableOption(options, GenerateOperatorsId)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestGenerateOperators3() As Task Await TestWithPickMembersDialogAsync( " Imports System.Collections.Generic Class Program Public s As String [||] Public Shared Operator =(program1 As Program, program2 As Program) As Boolean Return True End Operator End Class", " Imports System.Collections.Generic Class Program Public s As String Public Overrides Function Equals(obj As Object) As Boolean Dim program = TryCast(obj, Program) Return program IsNot Nothing AndAlso s = program.s End Function Public Shared Operator =(program1 As Program, program2 As Program) As Boolean Return True End Operator End Class", chosenSymbols:=Nothing, optionsCallback:=Sub(Options) Assert.Null(Options.FirstOrDefault(Function(o) o.Id = GenerateOperatorsId))) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestGenerateOperators4() As Task Await TestWithPickMembersDialogAsync( " Imports System.Collections.Generic Structure Program Public s As String [||] End Structure", " Imports System.Collections.Generic Structure Program Public s As String Public Overrides Function Equals(obj As Object) As Boolean If Not (TypeOf obj Is Program) Then Return False End If Dim program = DirectCast(obj, Program) Return s = program.s End Function Public Shared Operator =(program1 As Program, program2 As Program) As Boolean Return program1.Equals(program2) End Operator Public Shared Operator <>(program1 As Program, program2 As Program) As Boolean Return Not program1 = program2 End Operator End Structure", chosenSymbols:=Nothing, optionsCallback:=Sub(options) EnableOption(options, GenerateOperatorsId)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestImplementIEquatable1() As Task Await TestWithPickMembersDialogAsync( " Imports System.Collections.Generic structure Program Public s As String [||] End structure", " Imports System Imports System.Collections.Generic structure Program Implements IEquatable(Of Program) Public s As String Public Overrides Function Equals(obj As Object) As Boolean Return (TypeOf obj Is Program) AndAlso Equals(DirectCast(obj, Program)) End Function Public Function Equals(other As Program) As Boolean Implements IEquatable(Of Program).Equals Return s = other.s End Function End structure", chosenSymbols:=Nothing, optionsCallback:=Sub(Options) EnableOption(Options, ImplementIEquatableId)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestImplementIEquatable2() As Task Await TestWithPickMembersDialogAsync( " Imports System.Collections.Generic Class Program Public s As String [||] End Class", " Imports System Imports System.Collections.Generic Class Program Implements IEquatable(Of Program) Public s As String Public Overrides Function Equals(obj As Object) As Boolean Return Equals(TryCast(obj, Program)) End Function Public Function Equals(other As Program) As Boolean Implements IEquatable(Of Program).Equals Return other IsNot Nothing AndAlso s = other.s End Function End Class", chosenSymbols:=Nothing, optionsCallback:=Sub(Options) EnableOption(Options, ImplementIEquatableId)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestGetHashCodeWithOverflowChecking() As Task Await TestInRegularAndScriptAsync( "Option Strict On Class Z [|Private a As Integer Private b As Integer|] End Class", "Option Strict On Class Z Private a As Integer Private b As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a AndAlso b = z.b End Function Public Overrides Function GetHashCode() As Integer Dim hashCode As Long = 2118541809 hashCode = (hashCode * -1521134295 + a.GetHashCode()).GetHashCode() hashCode = (hashCode * -1521134295 + b.GetHashCode()).GetHashCode() Return CType(hashCode, Integer) End Function End Class", index:=1, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, checkOverflow:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestGetHashCodeWithoutOverflowChecking() As Task Await TestInRegularAndScriptAsync( "Class Z [|Private a As Integer|] End Class", "Class Z Private a As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a End Function Public Overrides Function GetHashCode() As Integer Return -1757793268 + a.GetHashCode() End Function End Class", index:=1, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, checkOverflow:=False)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestMultipleValuesWithoutValueTuple() As Task Await TestInRegularAndScriptAsync( "Class Z [|Private a As Integer Private b As Integer|] End Class", "Class Z Private a As Integer Private b As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a AndAlso b = z.b End Function Public Overrides Function GetHashCode() As Integer Dim hashCode As Long = 2118541809 hashCode = (hashCode * -1521134295 + a.GetHashCode()).GetHashCode() hashCode = (hashCode * -1521134295 + b.GetHashCode()).GetHashCode() Return hashCode End Function End Class", index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestMultipleValuesWithValueTupleOneValue() As Task Await TestInRegularAndScriptAsync( " Namespace System Public Structure ValueTuple End Structure End Namespace Class Z [|Private a As Integer|] Private b As Integer End Class", " Namespace System Public Structure ValueTuple End Structure End Namespace Class Z Private a As Integer Private b As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a End Function Public Overrides Function GetHashCode() As Integer Dim hashCode As Long = -468965076 hashCode = (hashCode * -1521134295 + a.GetHashCode()).GetHashCode() Return hashCode End Function End Class", index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)> Public Async Function TestMultipleValuesWithValueTupleTwoValues() As Task Await TestInRegularAndScriptAsync( " Namespace System Public Structure ValueTuple End Structure End Namespace Class Z [|Private a As Integer Private b As Integer|] End Class", " Namespace System Public Structure ValueTuple End Structure End Namespace Class Z Private a As Integer Private b As Integer Public Overrides Function Equals(obj As Object) As Boolean Dim z = TryCast(obj, Z) Return z IsNot Nothing AndAlso a = z.a AndAlso b = z.b End Function Public Overrides Function GetHashCode() As Integer Return (a, b).GetHashCode() End Function End Class", index:=1) End Function End Class End Namespace
OmarTawfik/roslyn
src/EditorFeatures/VisualBasicTest/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.vb
Visual Basic
apache-2.0
17,488
' Licensed to the .NET Foundation under one or more 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.CodeStyle Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Test.Utilities.Formatting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Formatting Public Class VisualBasicNewDocumentFormattingServiceTests Inherits AbstractNewDocumentFormattingServiceTests Protected Overrides ReadOnly Property Language As String = LanguageNames.VisualBasic Protected Overrides Function CreateTestWorkspace(testCode As String, parseOptions As ParseOptions) As TestWorkspace Return TestWorkspace.CreateVisualBasic(testCode, parseOptions) End Function <Fact> Public Async Function TestFileBanners() As Task Await TestAsync( testCode:="Imports System Namespace Goo End Namespace", expected:="' This is a banner. Imports System Namespace Goo End Namespace", options:={(CodeStyleOptions2.FileHeaderTemplate, "This is a banner.")}) End Function <Fact> Public Async Function TestOrganizeUsings() As Task Await TestAsync( testCode:="Imports Aaa Imports System Namespace Goo End Namespace", expected:="Imports System Imports Aaa Namespace Goo End Namespace") End Function End Class End Namespace
CyrusNajmabadi/roslyn
src/EditorFeatures/VisualBasicTest/Formatting/VisualBasicNewDocumentFormattingServiceTests.vb
Visual Basic
mit
1,614
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Statements Public Class ElseKeywordRecommenderTests <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ElseNotInMethodBody() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ElseInMultiLineIf() VerifyRecommendationsContain(<MethodBody>If True Then | End If</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ElseInMultiLineElseIf1() VerifyRecommendationsContain(<MethodBody>If True Then ElseIf True Then | End If</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ElseInMultiLineElseIf2() VerifyRecommendationsContain(<MethodBody>If True Then Else If True Then | End If</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ElseNotInMultiLineElse() VerifyRecommendationsMissing(<MethodBody>If True Then Else | End If</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterInvocation() VerifyRecommendationsContain(<MethodBody>If True Then System.Console.Write("Foo") |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterExpression() VerifyRecommendationsContain(<MethodBody>If True Then q = q + 3 |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterDeclaration() VerifyRecommendationsContain(<MethodBody>If True Then Dim q = 3 |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterStop() VerifyRecommendationsContain(<MethodBody>If True Then Stop |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterEnd() VerifyRecommendationsContain(<MethodBody>If True Then End |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterReDim() VerifyRecommendationsContain(<MethodBody>If True Then ReDim array(1, 1, 1) |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterErase() VerifyRecommendationsContain(<MethodBody>If True Then Erase foo, quux |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterError() VerifyRecommendationsContain(<MethodBody>If True Then Error 23 |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterExit() VerifyRecommendationsContain(<MethodBody>If True Then Exit Do |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterGoTo() VerifyRecommendationsContain(<MethodBody>If True Then GoTo foo |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterResume() VerifyRecommendationsContain(<MethodBody>If True Then Resume |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterResumeNext() VerifyRecommendationsContain(<MethodBody>If True Then Resume Next |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterContinue() VerifyRecommendationsContain(<MethodBody>If True Then Continue Do |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterReturn() VerifyRecommendationsContain(<MethodBody>If True Then Return |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterReturnExpressionInPropertyGet() VerifyRecommendationsContain( <ClassDeclaration> ReadOnly Property Foo As Integer Get If True Then Return | </ClassDeclaration>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterReturnExpression() VerifyRecommendationsContain(<ClassDeclaration>Function Foo as String If True Then Return foo |</ClassDeclaration>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterThrow() VerifyRecommendationsContain(<MethodBody>Try If True Then Throw | Catch</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterThrowExpression() VerifyRecommendationsContain(<MethodBody>Try If True Then Throw foo | Catch</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterAddHandler() VerifyRecommendationsContain(<MethodBody>If True Then AddHandler Obj.Ev_Event, AddressOf EventHandler |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterRaiseEvent() VerifyRecommendationsContain(<MethodBody>If True Then RaiseEvent Ev_Event() |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SingleLineIfElseAfterColonSeparatedStatements() VerifyRecommendationsContain(<MethodBody>If True Then Console.WriteLine("foo") : Console.WriteLine("bar") |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ElseNotInSingleLineIf1() VerifyRecommendationsMissing(<MethodBody>If True Then |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ElseNotInSingleLineIf2() VerifyRecommendationsMissing(<MethodBody>If True Then Stop Else |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ElseNotSingleLineIfNoStatements() VerifyRecommendationsMissing(<MethodBody>If True Then Else |</MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ElseAfterCase() VerifyRecommendationsContain( <MethodBody> Select Case x Case | </MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoElseAfterCaseIfExists() VerifyRecommendationsMissing( <MethodBody> Select Case x Case Else End Case | </MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoElseAfterCaseIfNotLastCase() VerifyRecommendationsMissing( <MethodBody> Select Case x Case | Case 1 </MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ElseWithinIfWithinElse() VerifyRecommendationsContain( <MethodBody> If True Then Else If False Then | End If End If </MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ElseWithinElseIfWithinElse() VerifyRecommendationsContain( <MethodBody> If True Then Else If False Then ElseIf True | End If End If </MethodBody>, "Else") End Sub <WpfFact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ElseNotWithinDo() VerifyRecommendationsMissing( <MethodBody> If True Then Do While True | End While End If </MethodBody>, "Else") End Sub End Class End Namespace
VPashkov/roslyn
src/EditorFeatures/VisualBasicTest/Recommendations/Statements/ElseKeywordRecommenderTests.vb
Visual Basic
apache-2.0
9,947