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.
' This code is licensed under the MIT License (MIT).
' THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
' ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
' IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
' PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
'
'*********************************************************
Imports System
Imports System.Threading.Tasks
Imports Windows.Devices.Sensors
Imports Windows.Foundation
Imports Windows.UI.Core
Imports Windows.UI.Xaml
Imports Windows.UI.Xaml.Controls
Imports Windows.UI.Xaml.Navigation
Namespace Global.SDKTemplate
Public NotInheritable Partial Class Scenario1_DataEvents
Inherits Page
Dim rootPage As MainPage = MainPage.Current
Private sensor As Altimeter
Private desiredReportIntervalMs As UInteger
Public Sub New()
Me.InitializeComponent()
sensor = Altimeter.GetDefault()
If Nothing IsNot sensor Then
' Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
' This value will be used later to activate the sensor.
Dim minReportIntervalMs As UInteger = sensor.MinimumReportInterval
desiredReportIntervalMs = If(minReportIntervalMs > 1000, minReportIntervalMs, 1000)
Else
rootPage.NotifyUser("No altimeter found", NotifyType.ErrorMessage)
End If
End Sub
''' <summary>
''' Invoked when this page is about to be displayed in a Frame.
''' </summary>
''' <param name="e">Event data that describes how this page was reached. The Parameter
''' property is typically used to configure the page.</param>
Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs)
ScenarioEnableButton.IsEnabled = True
ScenarioDisableButton.IsEnabled = False
End Sub
''' <summary>
''' Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.
''' </summary>
''' <param name="e">
''' Event data that can be examined by overriding code. The event data is representative
''' of the navigation that will unload the current Page unless canceled. The
''' navigation can potentially be canceled by setting Cancel.
''' </param>
Protected Overrides Sub OnNavigatingFrom(e As NavigatingCancelEventArgs)
If ScenarioDisableButton.IsEnabled Then
RemoveHandler Window.Current.VisibilityChanged, New WindowVisibilityChangedEventHandler(AddressOf VisibilityChanged)
RemoveHandler sensor.ReadingChanged, New TypedEventHandler(Of Altimeter, AltimeterReadingChangedEventArgs)(AddressOf ReadingChanged)
sensor.ReportInterval = 0
End If
MyBase.OnNavigatingFrom(e)
End Sub
''' <summary>
''' This is the event handler for VisibilityChanged events. You would register for these notifications
''' if handling sensor data when the app is not visible could cause unintended actions in the app.
''' </summary>
''' <param name="sender"></param>
''' <param name="e">
''' Event data that can be examined for the current visibility state.
''' </param>
Private Sub VisibilityChanged(sender As Object, e As VisibilityChangedEventArgs)
If ScenarioDisableButton.IsEnabled Then
If e.Visible Then
AddHandler sensor.ReadingChanged, New TypedEventHandler(Of Altimeter, AltimeterReadingChangedEventArgs)(AddressOf ReadingChanged)
Else
RemoveHandler sensor.ReadingChanged, New TypedEventHandler(Of Altimeter, AltimeterReadingChangedEventArgs)(AddressOf ReadingChanged)
End If
End If
End Sub
''' <summary>
''' This is the event handler for ReadingChanged events.
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Async Private Sub ReadingChanged(sender As Object, e As AltimeterReadingChangedEventArgs)
Await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Sub()
Dim reading As AltimeterReading = e.Reading
ScenarioOutput_M.Text = String.Format("{0,5:0.00}", reading.AltitudeChangeInMeters)
End Sub)
End Sub
''' <summary>
''' This is the click handler for the 'Enable' button.
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub ScenarioEnable(sender As Object, e As RoutedEventArgs)
If Nothing IsNot sensor Then
sensor.ReportInterval = desiredReportIntervalMs
AddHandler Window.Current.VisibilityChanged, New WindowVisibilityChangedEventHandler(AddressOf VisibilityChanged)
AddHandler sensor.ReadingChanged, New TypedEventHandler(Of Altimeter, AltimeterReadingChangedEventArgs)(AddressOf ReadingChanged)
ScenarioEnableButton.IsEnabled = False
ScenarioDisableButton.IsEnabled = True
Else
rootPage.NotifyUser("No altimeter found", NotifyType.ErrorMessage)
End If
End Sub
''' <summary>
''' This is the click handler for the 'Disable' button.
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub ScenarioDisable(sender As Object, e As RoutedEventArgs)
RemoveHandler Window.Current.VisibilityChanged, New WindowVisibilityChangedEventHandler(AddressOf VisibilityChanged)
RemoveHandler sensor.ReadingChanged, New TypedEventHandler(Of Altimeter, AltimeterReadingChangedEventArgs)(AddressOf ReadingChanged)
sensor.ReportInterval = 0
ScenarioEnableButton.IsEnabled = True
ScenarioDisableButton.IsEnabled = False
End Sub
End Class
End Namespace
|
japf/Windows-universal-samples
|
Samples/Altimeter/vb/Scenario1_DataEvents.xaml.vb
|
Visual Basic
|
mit
| 6,195
|
' 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.Xml.Linq
Imports Microsoft.CodeAnalysis.Text
Public Structure BasicTestSource
Public ReadOnly Property Value As Object
Private Sub New(value As Object)
Me.Value = value
End Sub
Public Function GetSyntaxTrees(
Optional parseOptions As VisualBasicParseOptions = Nothing,
Optional ByRef assemblyName As String = Nothing,
Optional ByRef spans As IEnumerable(Of IEnumerable(Of TextSpan)) = Nothing) As SyntaxTree()
If Value Is Nothing Then
Debug.Assert(parseOptions Is Nothing)
Return Array.Empty(Of SyntaxTree)
End If
Dim xmlSource = TryCast(Value, XElement)
If xmlSource IsNot Nothing Then
Return ParseSourceXml(xmlSource, parseOptions, assemblyName, spans).ToArray()
End If
Dim source = TryCast(Value, String)
If source IsNot Nothing Then
Return New SyntaxTree() {VisualBasicSyntaxTree.ParseText(source, parseOptions)}
End If
Dim sources = TryCast(Value, String())
If sources IsNot Nothing Then
Return sources.Select(Function(s) VisualBasicSyntaxTree.ParseText(s, parseOptions)).ToArray()
End If
Dim tree = TryCast(Value, SyntaxTree)
If tree IsNot Nothing Then
Debug.Assert(parseOptions Is Nothing)
Return New SyntaxTree() {tree}
End If
Dim trees = TryCast(Value, SyntaxTree())
If trees IsNot Nothing Then
Debug.Assert(parseOptions Is Nothing)
Return trees
End If
Throw New Exception($"Unexpected value: {Value}")
End Function
''' <summary>
'''
''' </summary>
''' <param name="source">The sources compile according to the following schema
''' <compilation name="assemblyname[optional]">
''' <file name="file1.vb[optional]">
''' source
''' </file>
''' </compilation>
''' </param>
Public Shared Widening Operator CType(source As XElement) As BasicTestSource
Return New BasicTestSource(source)
End Operator
Public Shared Widening Operator CType(source As String) As BasicTestSource
Return New BasicTestSource(source)
End Operator
Public Shared Widening Operator CType(source As String()) As BasicTestSource
Return New BasicTestSource(source)
End Operator
Public Shared Widening Operator CType(source As SyntaxTree) As BasicTestSource
Return New BasicTestSource(source)
End Operator
Public Shared Widening Operator CType(source As SyntaxTree()) As BasicTestSource
Return New BasicTestSource(source)
End Operator
End Structure
|
shyamnamboodiripad/roslyn
|
src/Compilers/Test/Utilities/VisualBasic/BasicTestSource.vb
|
Visual Basic
|
apache-2.0
| 2,912
|
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("First Name")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("University of Hartford")>
<Assembly: AssemblyProduct("First Name")>
<Assembly: AssemblyCopyright("Copyright © University of Hartford 2013")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("b9f60aca-3109-456c-860d-a8d2e9e083ab")>
' 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")>
|
patkub/visual-basic-intro
|
First Name/First Name/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,182
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
Imports System.Composition
Imports Microsoft.NetCore.Analyzers.Runtime
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Namespace Microsoft.NetCore.VisualBasic.Analyzers.Runtime
''' <summary>
''' CA1307: Specify StringComparison
''' </summary>
<ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]>
Public NotInheritable Class BasicSpecifyStringComparisonFixer
Inherits SpecifyStringComparisonFixer
End Class
End Namespace
|
dotnet/roslyn-analyzers
|
src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicSpecifyStringComparison.Fixer.vb
|
Visual Basic
|
mit
| 631
|
Imports SistFoncreagro.BussinessEntities
Imports SistFoncreagro.DataAccess
Public Class VehiculoBL : Implements IVehiculoBL
Dim factoryrepository As IVehiculoRepository
Public Sub New()
factoryrepository = New VehiculoRepository
End Sub
Public Sub DeleteVEHICULO(ByVal IdVehiculo As Integer) Implements IVehiculoBL.DeleteVEHICULO
factoryrepository.DeleteVEHICULO(IdVehiculo)
End Sub
Public Function GetVEHICULOByIdDetalleEje(ByVal IdDetalleEje As Integer) As System.Collections.Generic.List(Of BussinessEntities.Vehiculo) Implements IVehiculoBL.GetVEHICULOByIdDetalleEje
Return factoryrepository.GetVEHICULOByIdDetalleEje(IdDetalleEje)
End Function
Public Function GetVEHICULOByIdVehiculo(ByVal IdVehiculo As Object) As BussinessEntities.Vehiculo Implements IVehiculoBL.GetVEHICULOByIdVehiculo
Return factoryrepository.GetVEHICULOByIdVehiculo(IdVehiculo)
End Function
Public Sub SaveVEHICULO(ByVal _Vehiculo As BussinessEntities.Vehiculo) Implements IVehiculoBL.SaveVEHICULO
factoryrepository.SaveVEHICULO(_Vehiculo)
End Sub
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.BussinesLogic/VehiculoBL.vb
|
Visual Basic
|
mit
| 1,126
|
Public Class NewMissionForm
Public MissionObjController As MissionObjectController
Public TransporterObjController As TransporterObjectController
Public MaxAnalyzers As Integer
Public MaxScans As Integer
Public MaxSwitchDrivers As Integer
Public MaxPositioners As Integer
Public SurveyNumber As Integer = 0
Public AddSurvey As Boolean = False
Public Sub New(ByRef aMissionObjController As MissionObjectController, Optional ByVal add As Boolean = False, Optional ByVal index As Integer = 0)
Me.MissionObjController = aMissionObjController
Me.maxAnalyzers = Me.MissionObjController.aMain.missionObj.getMaxMissionObjects
Me.maxScans = Me.MissionObjController.aMain.missionObj.getMaxMissionObjects
Me.maxSwitchDrivers = Me.MissionObjController.aMain.missionObj.getmaxSwitchDrivers
Me.maxPositioners = Me.MissionObjController.aMain.missionObj.getmaxPositioners
Me.addSurvey = add
'This call is required by the designer.
InitializeComponent()
'populate the analyzer combo box drop down
With Me.MissionObjController.aMain.missionObj
For ii As Integer = 0 To .getNumberAnalyzersDefined
If .getAnalyzer(ii) Is Nothing Then
Exit For
Else
Me.cmbBxAzr.Items.Add("Analyzer " & ii)
End If
Next
End With
If add = True Then
Me.GroupBoxAnalyzers.Visible = False
Me.GroupBoxScan.Visible = True
Me.grpBxMissions.Visible = False
Me.numUpDwnScans.Maximum = Me.maxScans
Me.numUpDwnNumSwitchDrivers.Maximum = Me.maxSwitchDrivers
Me.numUpDwnNumPositoners.Maximum = Me.maxPositioners
Me.surveyNumber = index
Me.lblSurveyNumber.Text = Me.surveyNumber
Me.txtBxSurveyName.Text = "Survey " & Me.surveyNumber
End If
' Add any initialization after the InitializeComponent() call.
Me.StartPosition = FormStartPosition.Manual
Me.Left = 300
Me.Top = 300
Me.Visible = True
End Sub
Private Sub Button1_Click_1(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Me.MissionObjController.defineParameters(Me.txtBxMissionName.Text, Me.NumUpDwnNumOfAnalyzers.Value)
Me.GroupBoxAnalyzers.Visible = False
Me.GroupBoxScan.Visible = True
Me.numUpDwnScans.Maximum = Me.maxScans
Me.numUpDwnNumSwitchDrivers.Maximum = Me.maxSwitchDrivers
Me.numUpDwnNumPositoners.Maximum = Me.maxPositioners
Me.lblSurveyNumber.Text = Me.surveyNumber
Me.txtBxSurveyName.Text = "Survey " & Me.surveyNumber
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDefineAnalyzers.Click
If Me.cmbBxAzr.SelectedIndex < 0 Then
Me.cmbBxAzr.SelectedIndex = 0
End If
Me.MissionObjController.defineSurvey(Me.surveyNumber, Me.txtBxSurveyName.Text, Me.numUpDwnScans.Value, Me.numUpDwnNumSwitchDrivers.Value, Me.numUpDwnNumSwitches.Value, Me.numUpDwnNumPositoners.Value, Me.cmbBxAzr.SelectedIndex)
Me.surveyNumber += 1
Me.lblSurveyNumber.Text = Me.surveyNumber
Me.txtBxSurveyName.Text = "Survey " & Me.surveyNumber
Me.numUpDwnScans.Value = 0
Me.numUpDwnNumSwitchDrivers.Value = 0
Me.numUpDwnNumPositoners.Value = 0
' If Me.surveyNumber >= Me.MissionObjController.editDeleteExistingMissionForm.EditTransporterController.aTransport.getNumSurveysDefined Then
If Me.surveyNumber >= Me.MissionObjController.aMain.NewTransporterObject.getNumSurveysDefined Then
Me.Close()
End If
'add this new survey back into the editTransport cmbBx of surveys
If Me.addSurvey = True Then
With Me.MissionObjController.editDeleteExistingMissionForm.EditTransporterController.EditTransporterForm
.cmbBxScanNames.Items.Clear()
'changed 7/6
'For ii As Integer = 0 To Me.MissionObjController.aMain.TransporterObj.getNumSurveysDefined - 1
' .cmbBxScanNames.Items.Add(Me.MissionObjController.aMain.TransporterObj.getSurveyObject(ii).getName)
'Next
For ii As Integer = 0 To Me.MissionObjController.editDeleteExistingMissionForm.EditTransporterController.aTransport.getNumSurveysDefined - 1
.cmbBxScanNames.Items.Add(Me.MissionObjController.editDeleteExistingMissionForm.EditTransporterController.aTransport.getSurveyObject(ii).getName)
Next
End With
End If
End Sub
End Class
|
wboxx1/85-EIS-PUMA
|
puma/src/Supporting Forms/zzz - Legacy Forms/NewMissionForm.vb
|
Visual Basic
|
mit
| 4,735
|
Sub CreateIndexSheet()
Dim Sheet As Worksheet
ActiveWorkbook.Sheets.Add(Before:=Worksheets(1)).Name = "Index Sheet" 'Call whatever you like
Range("A1").Select
Selection.Value = "Index Sheet"
ActiveCell.Offset(1, 0).Select 'Moves down a row
For Each Sheet In Worksheets
If Sheet.Name <> "Index Sheet" Then
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:="'" & Sheet.Name & "'" & "!A1", TextToDisplay:=Sheet.Name
ActiveCell.Offset(1, 0).Select 'Moves down a row
End If
Next Sheet
Range("A1").EntireColumn.AutoFit
Range("A1").EntireRow.Delete 'Remove content Sheet from content list
End Sub
|
Jonnokc/Excel_VBA
|
Validation_Form/Other/Creates_And_Fills_Out_Index_Sheet.vb
|
Visual Basic
|
mit
| 730
|
Option Infer On
Imports System
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim documents As SolidEdgeFramework.Documents = Nothing
Dim draftDocument As SolidEdgeDraft.DraftDocument = Nothing
Dim sheet As SolidEdgeDraft.Sheet = Nothing
Dim boundaries2d As SolidEdgeFrameworkSupport.Boundaries2d = Nothing
Dim boundary2d As SolidEdgeFrameworkSupport.Boundary2d = Nothing
Dim circles2d As SolidEdgeFrameworkSupport.Circles2d = Nothing
Dim circle2d As SolidEdgeFrameworkSupport.Circle2d = Nothing
Try
' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register()
' Attempt to connect to a running instance of Solid Edge.
application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application)
documents = application.Documents
draftDocument = CType(documents.Add("SolidEdge.DraftDocument"), SolidEdgeDraft.DraftDocument)
sheet = draftDocument.ActiveSheet
circles2d = sheet.Circles2d
boundaries2d = sheet.Boundaries2d
circle2d = circles2d.AddByCenterRadius(0.1, 0.1, 0.02)
Dim Points = CType(New Double(), System.Array) { 0.1, 0.1, 0.1, 0.2, 0.2, 0.2, 0.2, 0.1 }
Dim Objects = New Object() { circle2d }
boundary2d = boundaries2d.AddByObjects(Objects.Length, Objects, 0.1, 0.1)
Dim boundingObjects = boundary2d.BoundingObjects
Catch ex As System.Exception
Console.WriteLine(ex)
Finally
OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgeFrameworkSupport.Boundary2d.BoundingObjects.vb
|
Visual Basic
|
mit
| 2,063
|
Imports SistFoncreagro.BussinessEntities
Imports System.Data.SqlClient
Imports System.Data
Public Class ResponsableRepository : Inherits MasterDataAccess : Implements IResponsableRepository
Private Function SelectObjectFactory(ByVal command As SqlCommand) As List(Of Responsable)
Dim lista As New List(Of Responsable)
Using reader As SqlDataReader = MyBase.ExecuteReader(command)
While reader.Read
Dim _Responsable As New Responsable() With
{
.IdResponsable = reader.GetValue(0),
.IdPersonal = reader.GetValue(1),
.IdControl = reader.GetValue(3)
}
If Not reader.IsDBNull(2) Then
_Responsable.Observaciones = reader.GetValue(2)
End If
lista.Add(_Responsable)
End While
End Using
Return lista
End Function
Public Sub DeleteRESPONSABLE(ByVal IdResponsable As Integer) Implements IResponsableRepository.DeleteRESPONSABLE
Dim command As SqlCommand = MyBase.CreateSPCommand("DeleteRESPONSABLE")
command.Parameters.AddWithValue("IdResponsable", IdResponsable)
MyBase.ExecuteNonQuery(command)
End Sub
Public Function GetRESPONSABLEByIdControl(ByVal IdControl As Integer) As System.Collections.Generic.List(Of BussinessEntities.Responsable) Implements IResponsableRepository.GetRESPONSABLEByIdControl
Dim command As SqlCommand = MyBase.CreateSPCommand("GetRESPONSABLEByIdControl")
command.Parameters.AddWithValue("IdControl", IdControl)
Return SelectObjectFactory(command)
End Function
Public Function GetRESPONSABLEByIdResponsable(ByVal IdResponsable As Integer) As BussinessEntities.Responsable Implements IResponsableRepository.GetRESPONSABLEByIdResponsable
Dim command As SqlCommand = MyBase.CreateSPCommand("GetRESPONSABLEByIdResponsable")
command.Parameters.AddWithValue("IdResponsable", IdResponsable)
Return SelectObjectFactory(command).SingleOrDefault
End Function
Public Sub SaveRESPONSABLE(ByVal _Responsable As BussinessEntities.Responsable) Implements IResponsableRepository.SaveRESPONSABLE
Dim command As SqlCommand = MyBase.CreateSPCommand("SaveRESPONSABLE")
command.Parameters.AddWithValue("IdControl", _Responsable.IdControl)
command.Parameters.AddWithValue("IdPersonal", _Responsable.IdPersonal)
command.Parameters.AddWithValue("IdResponsable", _Responsable.IdResponsable)
command.Parameters.AddWithValue("Observaciones", _Responsable.Observaciones)
MyBase.ExecuteNonQuery(command)
End Sub
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.DataAccess/ResponsableRepository.vb
|
Visual Basic
|
mit
| 2,709
|
'------------------------------------------------------------------------------
' <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
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.Shapes.Form1
End Sub
End Class
End Namespace
|
tima-t/codesCSharp
|
C#OOP/OOP-Principles - Part 2/Shapes/My Project/Application.Designer.vb
|
Visual Basic
|
mit
| 1,472
|
Imports System
Imports Microsoft.SPOT
Imports Toolbox.NETMF.Hardware
' Copyright 2012-2014 Stefan Thoolen (http://www.netmftoolbox.com/)
'
' 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.
Namespace Games
Public Module HD44780_Snake
' Constants that compile all characters
Private Const FRUIT_BOTTOM As Byte = &H1 ' b0001
Private Const FRUIT_TOP As Byte = &H2 ' b0010
Private Const SNAKE_TOP As Byte = &H5 ' b0101
Private Const SNAKE_BOTTOM As Byte = &H8 ' b1000
''' <summary>Reference to the display</summary>
Private _disp As Hd44780Lcd
''' <summary>Start button</summary>
Private _btnStart As IGPIPort
''' <summary>Left button</summary>
Private _btnLeft As IGPIPort
''' <summary>Right button</summary>
Private _btnRight As IGPIPort
''' <summary>Up button</summary>
Private _btnUp As IGPIPort
''' <summary>Down button</summary>
Private _btnDown As IGPIPort
''' <summary>Random helper</summary>
Private _rand As Random
''' <summary>Max. width of the game</summary>
Public Width As Integer = 16
''' <summary>Max. height of the game</summary>
Public Height As Integer = 4
''' <summary>Storage for the position of the snake (y * Height + x). The integer size is the max. length of the snake</summary>
Private _snake(40) As Integer
''' <summary>The position for the food</summary>
Private _FoodPosition As Integer = -1
''' <summary>The direction we're moving into (-1 = left, 1 = right, -Width = up, +Width = down)</summary>
Private _Direction As Integer = -1
''' <summary>Each tick this will be increased</summary>
Private _Timer As Integer = 0
''' <summary>The current game speed</summary>
Private _Speed As Integer = 40
''' <summary>
''' Shows the splash screen
''' </summary>
Public Sub Splash()
_disp.ClearDisplay()
_NetduinoLogo()
_disp.Write(" HD44780 Snake")
_disp.ChangePosition(1, 2)
_disp.Write("for ")
_disp.Write(New Byte() {0, 1, 2, 3, 4, 5, 0, 6}, False)
End Sub
''' <summary>
''' Initializes the hardware
''' </summary>
''' <param name="Display">Reference to the LCD</param>
''' <param name="ButtonStart">Start button</param>
''' <param name="ButtonLeft">Left button</param>
''' <param name="ButtonRight">Right button</param>
''' <param name="ButtonUp">Up button</param>
''' <param name="ButtonDown">Down button</param>
Public Sub Init(Display As Hd44780Lcd, ButtonStart As IGPIPort, ButtonLeft As IGPIPort, ButtonRight As IGPIPort, ButtonUp As IGPIPort, ButtonDown As IGPIPort)
' Copies the parameters to local values
_disp = Display
_btnStart = ButtonStart
_btnLeft = ButtonLeft
_btnRight = ButtonRight
_btnUp = ButtonUp
_btnDown = ButtonDown
_rand = New Random()
End Sub
''' <summary>
''' Changes the custom characters to the Netduino-logo
''' </summary>
Private Sub _NetduinoLogo()
' To show the Netduino-logo on a 2x16 LCD, we need 7 custom characters (0x00 to 0x06):
_CustomizeCharacter(&H0, New Byte() {&H0, &H0, &H0, &HE, &H11, &H11, &H11, &H11}) ' n
_CustomizeCharacter(&H1, New Byte() {&H0, &H0, &H0, &HE, &H13, &H14, &H19, &HE}) ' e
_CustomizeCharacter(&H2, New Byte() {&H0, &H10, &H10, &H1E, &H10, &H10, &H10, &HE}) ' t
_CustomizeCharacter(&H3, New Byte() {&H1, &H1, &H1, &HF, &H13, &H11, &H11, &HE}) ' d
_CustomizeCharacter(&H4, New Byte() {&H0, &H0, &H0, &H11, &H11, &H11, &H11, &HE}) ' u
_CustomizeCharacter(&H5, New Byte() {&H0, &H4, &H0, &H4, &H4, &H4, &H4, &H4}) ' i
_CustomizeCharacter(&H6, New Byte() {&H0, &H0, &H0, &HE, &H11, &H11, &H11, &HE}) ' o
End Sub
''' <summary>
''' Changes the custom characters to the snake
''' </summary>
Private Sub _SnakeChars()
' To play snake on a 2x16 LCD, we need 7 custom characters (0x00 to 0x06):
_CustomizeCharacter(&H0, New Byte() {&H0, &H0, &H0, &H0, &H0, &HE, &HE, &H0}) ' b000: ₒ (fruit at the bottom)
_CustomizeCharacter(&H1, New Byte() {&H0, &HE, &HE, &H0, &H0, &H0, &H0, &H0}) ' b001: ° (fruit at the top)
_CustomizeCharacter(&H2, New Byte() {&H1F, &H1F, &H1F, &H1F, &H0, &H0, &H0, &H0}) ' b010: ▀ (snake at the top)
_CustomizeCharacter(&H3, New Byte() {&H1F, &H1F, &H1F, &H1F, &H0, &HE, &HE, &H0}) ' b011: ▀ + ₒ (snake at the top + fruit at the bottom)
_CustomizeCharacter(&H4, New Byte() {&H0, &H0, &H0, &H0, &H1F, &H1F, &H1F, &H1F}) ' b100: ▄ (snake at the bottom)
_CustomizeCharacter(&H5, New Byte() {&H0, &HE, &HE, &H0, &H1F, &H1F, &H1F, &H1F}) ' b101: ▄ + ° (snake at the bottom + fruit at the top)
_CustomizeCharacter(&H6, New Byte() {&H1F, &H1F, &H1F, &H1F, &H1F, &H1F, &H1F, &H1F}) ' b110: █ (snake at the bottom + snake at the top)
End Sub
''' <summary>Screen line 1 buffer</summary>
Private _Line1Buffer() As Byte = New Byte() {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
''' <summary>Screen line 2 buffer</summary>
Private _Line2Buffer() As Byte = New Byte() {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
''' <summary>
''' Draws the screen
''' </summary>
Private Sub _DrawScreen()
' Lets start with 2 empty lines
Dim Line1() As Byte = New Byte() {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
Dim Line2() As Byte = New Byte() {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
' Adds the fruit
If _FoodPosition < 16 Then ' line 1
Line1(_FoodPosition) += FRUIT_TOP
ElseIf _FoodPosition < 32 Then ' line 2
Line1(_FoodPosition - 16) += FRUIT_BOTTOM
ElseIf _FoodPosition < 48 Then ' line 3
Line2(_FoodPosition - 32) += FRUIT_TOP
Else ' line 4
Line2(_FoodPosition - 48) += FRUIT_BOTTOM
End If
' Adds the snake
For Pos As Integer = 0 To _snake.Length - 1
If _snake(Pos) = -1 Then Continue For
If _snake(Pos) < 16 Then ' line 1
Line1(_snake(Pos)) += SNAKE_TOP
ElseIf _snake(Pos) < 32 Then ' line 2
Line1(_snake(Pos) - 16) += SNAKE_BOTTOM
ElseIf _snake(Pos) < 48 Then ' line 3
Line2(_snake(Pos) - 32) += SNAKE_TOP
Else ' line 4
Line2(_snake(Pos) - 48) += SNAKE_BOTTOM
End If
Next
For Pos As Byte = 0 To 15
If Line1(Pos) <> _Line1Buffer(Pos) Then
_disp.ChangePosition(0, Pos)
If Line1(Pos) = 0 Then
_disp.Write(" ")
Else
_disp.Write(CByte(Line1(Pos) >> 1))
End If
End If
If Line2(Pos) <> _Line2Buffer(Pos) Then
_disp.ChangePosition(1, Pos)
If Line2(Pos) = 0 Then
_disp.Write(" ")
Else
_disp.Write(CByte(Line2(Pos) >> 1))
End If
End If
Next
_Line1Buffer = Line1
_Line2Buffer = Line2
End Sub
''' <summary>
''' Starts the game
''' </summary>
Public Sub Start()
_disp.ClearDisplay()
' Enables the snake characters
_SnakeChars()
' Sets the snake for the first time
_ResetSnake()
_ResetFood()
' Starts the main loop
Do
_MainLoop()
Loop
End Sub
''' <summary>
''' Main game loop
''' </summary>
Private Sub _MainLoop()
' Draws out the display
_DrawScreen()
' Joystick control changes the direction
If _btnLeft.Read() And _Direction <> 1 Then _Direction = -1
If _btnRight.Read() And _Direction <> -1 Then _Direction = 1
If _btnDown.Read() And _Direction <> 0 - Width Then _Direction = Width
If _btnUp.Read() And _Direction <> Width Then _Direction = 0 - Width
' Increases the timer
_Timer = _Timer + 1
' Do we need to move?
If _Timer >= _Speed Then
_DoMovement()
_Timer = 0
End If
End Sub
''' <summary>
''' Resets the snake, placing it at a random position
''' </summary>
Private Sub _ResetSnake()
' The rest of the snake pixels is empty
For Counter As Integer = 0 To _snake.Length - 1
_snake(Counter) = -1 ' No position
Next
' Starts at the middle
_snake(0) = CInt(Height * Width / 2 - Width / 2)
End Sub
''' <summary>
''' Will place food on the matrix
''' </summary>
Private Sub _ResetFood()
Dim NewPos As Integer = -1
Dim Found As Boolean
' Checks if this position isn't currently occupied by the snake
Do
NewPos = _rand.Next(Width * Height)
Found = False
For Counter As Integer = 0 To _snake.Length - 1
If _snake(Counter) = NewPos Then Found = True
Next
Loop While Found
_FoodPosition = NewPos
End Sub
''' <summary>
''' Moves the snake one position
''' </summary>
Private Sub _DoMovement()
' The next position
Dim NextPos As Integer = _snake(0) + _Direction
' We went out of the screen
If NextPos < 0 Then NextPos += (Height * Width) ' At the top
If NextPos >= (Height * Width) Then NextPos -= (Height * Width) ' At the bottom
If Floor(NextPos / Width) < Floor(_snake(0) / Width) And (_Direction = -1) Then NextPos += Width ' At the left
If Floor(NextPos / Width) > Floor(_snake(0) / Width) And (_Direction = 1) Then NextPos -= Width ' At the right
' Are we eating?
Dim Grow As Boolean = False
If NextPos = _FoodPosition Then
Grow = True
_ResetFood()
End If
' The next list of positions will be stored in here
Dim NewSnake() As Integer = CType(_snake.Clone(), Integer())
' Some checks
For Counter As Integer = 0 To _snake.Length - 1
' We ate ourself!
If _snake(Counter) = NextPos Then Throw New Exception(" Game over!")
' Is this our length?
If _snake(Counter) = -1 And Not Grow Then
Exit For
' Do we need to grow?
ElseIf _snake(Counter) = -1 Then
Grow = False
End If
' Moves up one spot
If Counter > 0 Then NewSnake(Counter) = _snake(Counter - 1)
Next
' New position
NewSnake(0) = NextPos
_snake = NewSnake
' Did we win?
If _snake(_snake.Length - 1) <> -1 Then
Throw New Exception(" Next level!")
'this._ResetSnake();
'this._ResetSnake();
'this._Speed = (int)(this._Speed * .9) - 1;
End If
End Sub
''' <summary>
''' Creates a customized character on a HD44780 LCD
''' </summary>
''' <param name="Index">Character index (0 to 7)</param>
''' <param name="Character">Character bitmap</param>
Private Sub _CustomizeCharacter(Index As Integer, CharacterBitmap() As Byte)
If Index < 0 Or Index > 7 Then Throw New IndexOutOfRangeException("Index must be a value from 0 to 7")
If CharacterBitmap.Length <> 8 Then Throw New ArgumentOutOfRangeException("CharacterBitmap must have 8 byte values")
_disp.Write(CByte(&H40 + 8 * Index), True) ' Set CGRAM Address
_disp.Write(CharacterBitmap) ' Writes the character
_disp.Write(CByte(&H80), True) ' Set DDRAM Address
End Sub
''' <summary>
''' Since VB.NETMF lacks Math.Floor, I made this method
''' </summary>
''' <param name="Value">Full value</param>
''' <return>Value rounded down</return>
Private Function Floor(ByVal Value As Double) As Integer
Dim RetValue = CInt(Value)
If RetValue > Value Then RetValue = RetValue - 1
Return RetValue
End Function
End Module
End Namespace
|
JakeLardinois/NetMF.Toolbox
|
Samples/Visual Basic/Hd44780LcdSnake/Games/HD44780_Snake.vb
|
Visual Basic
|
apache-2.0
| 13,955
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators
Friend NotInheritable Class TryCastExpressionDocumentation
Inherits AbstractCastExpressionDocumentation
Public Overrides ReadOnly Property DocumentationText As String
Get
Return VBWorkspaceResources.Introduces_a_type_conversion_operation_that_does_not_throw_an_exception_If_an_attempted_conversion_fails_TryCast_returns_Nothing_which_your_program_can_test_for
End Get
End Property
Public Overrides ReadOnly Property PrefixParts As IEnumerable(Of SymbolDisplayPart)
Get
Return {
New SymbolDisplayPart(SymbolDisplayPartKind.Keyword, Nothing, "TryCast"),
New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "(")
}
End Get
End Property
End Class
End Namespace
|
leppie/roslyn
|
src/Workspaces/VisualBasic/Portable/Utilities/IntrinsicOperators/TryCastExpressionDocumentation.vb
|
Visual Basic
|
apache-2.0
| 1,328
|
Imports Aspose.Email.Examples.VisualBasic.Email
Imports Aspose.Email.Examples.VisualBasic.Email.IMAP
Imports Aspose.Email.Examples.VisualBasic.Email.Knowledge.Base
Imports Aspose.Email.Examples.VisualBasic.Email.Outlook
Imports Aspose.Email.Examples.VisualBasic.Email.POP3
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Text
Imports Aspose.Email.Examples.VisualBasic.Email.Exchange
Imports Aspose.Email.Examples.VisualBasic.Email.SMTP
Imports Aspose.Email.Examples.VisualBasic.Email.Thunderbird
Namespace Aspose.Email.Examples.VisualBasic.Email
Class RunExamples
Public Shared Sub Main()
Console.WriteLine("Open RunExamples.vb " & vbLf & "In Main() method uncomment the example that you want to run.")
Console.WriteLine("=====================================================")
' Uncomment the one you want to try out
' =====================================================
' =====================================================
' Email
' =====================================================
' =====================================================
'DraftAppointmentRequest.Run()
'DisplayEmailInformation.Run()
'ExtractingEmailHeaders.Run()
'ProcessBouncedMsgs.Run()
'CreateNewEmail.Run()
'SaveMessageAsDraft.Run()
'SpecifyRecipientAddresses.Run()
'DisplayEmailAddressesNames.Run()
'SetHTMLBody.Run()
'SetAlternateText.Run()
'ManagingEmailAttachments.Run()
'RemoveAttachments.Run()
'EmbeddedObjects.Run()
'LoadMessageWithLoadOptions.Run()
'SetEmailHeaders.Run()
'ExtractAttachments.Run()
'CreateNewMailMessage.Run()
'ReadMessageByPreservingTNEFAttachments.Run()
'CreatingTNEFFromMSG.Run()
'LoadAndSaveFileAsEML.Run()
'PreserveOriginalBoundaries.Run()
'PreserveTNEFAttachment.Run()
'ExtractEmbeddObjects.Run()
'EncryptAndDecryptMessage.Run()
'PrintHeaderUsingMhtFormatOptions.Run()
'ExtraPrintHeaderUsingHideExtraPrintHeader.Run()
'BayesianSpamAnalyzer.Run()
'GetDeliveryStatusNotificationMessages.Run()
'DetectDifferentFileFormats.Run()
'ExtractEmbeddedObjectsFromEmail.Run()
'EncryptAndDecryptMessage.Run()
'AddMapiNoteToPST.Run()
'ExtractEmbeddObjects.Run()
'DetectTNEFMessage.Run()
'DetermineAttachmentEmbeddedMessage.Run()
'IdentifyInlineAndRegularAttachments.Run()
'ReceiveNotifications.Run()
'SetDefaultTextEncoding.Run()
'SendIMAPasynchronousEmail.Run()
'/ =====================================================
'/ =====================================================
'/ Outlook
'/ =====================================================
'/ =====================================================
'NewPSTAddSubfolders.Run()
'CreateSaveOutlookFiles.Run()
'DeleteBulkItemsFromPSTFile.Run()
'UpdateBulkMessagesInPSTFile.Run()
'LoadMSGFiles.Run()
'LoadingFromStream.Run()
'GetMAPIProperty.Run()
'SetMAPIProperties.Run()
'ReadNamedMAPIProperties.Run()
'ReadiNamedMAPIPropertyFromAttachment.Run()
'ReadingNamedMAPIPropertyFromAttachment.Run()
'RemovePropertiesFromMSGAndAttachments.Run()
'ConvertEMLToMSG.Run()
'CreatEMLFileAndConvertToMSG.Run()
'ReadAndWritingOutlookTemplateFile.Run()
'DeleteMessagesFromPSTFiles.Run()
'SetFollowUpflag.Run()
'SetFollowUpForRecipients.Run()
'MarkFollowUpFlagAsCompleted.Run()
'RemoveFollowUpflag.Run()
'ReadFollowupFlagOptionsForMessage.Run()
'CreateAndSaveOutlookContact.Run()
'CreatingAndSavingOutlookTasks.Run()
'AddReminderInformationToMapiTask.Run()
'AddAttachmentsToMapiTask.Run()
'AddRecurrenceToMapiTask.Run()
'CreatAndSaveAnOutlookNote.Run()
'ReadMapiNote.Run()
'ConvertMIMEMessagesFromMSGToEML.Run()
'ConvertMIMEMessageToEML.Run()
'SetColorCategories.Run()
'SetReminderByAddingTags.Run()
'CreatAndSaveCalendaritems.Run()
'AddDisplayReminderToACalendar.Run()
'AddAudioReminderToCalendar.Run()
'ManageAttachmentsFromCalendarFiles.Run()
'CreatePollUsingMapiMessage.Run()
'ReadVotingOptionsFromMapiMessage.Run()
'AddVotingButtonToExistingMessage.Run()
'DeleteVotingButtonFromMessage.Run()
'CreateAndSaveDistributionList.Run()
'CreatReplyMessage.Run()
'CreateForwardMessage.Run()
'EndAfterNoccurrences.Run()
'WeeklyEndAfterNoccurrences.Run()
'EndAfterNoccurrenceSelectMultipleDaysInweek.Run()
'MonthlyEndAfterNoccurrences.Run()
'YearlyEndAfterNoccurrences.Run()
'GenerateRecurrenceFromRecurrenceRule.Run()
'Exposeproperties.Run()
'GetTheTextAndRTFBodies.Run()
'ParseOutlookMessageFile.Run()
'CreateMeetingRequestWithRecurrence.Run()
'CreateNewMapiCalendarAndAddToCalendarSubfolder.Run()
'ConvertMSGToMIMEMessage.Run()
' Working with Outlook Personal Storage (PST) files
'SplitSinglePSTInToMultiplePST.Run()
'MergeMultiplePSTsInToSinglePST.Run()
'MergeFolderFromAnotherPSTFile.Run()
'ConvertOSTToPST.Run()
'ExtractNumberOfMessages.Run()
'ExtractAttachmentsFromPSTMessages.Run()
'AddMessagesToPSTFiles.Run()
'ReadandConvertOSTFiles.Run()
'SaveCalendarItems.Run()
'RetreiveParentFolderInformationFromMessageInfo.Run()
'ParseSearchableFolders.Run()
'AccessContactInformation.Run()
'GetMessageInformation.Run()
'ChangeFolderContainerClass.Run()
'CheckPasswordProtection.Run()
'SetPasswordOnPST.Run()
'CreateNewPSTFileAndAddingSubfolders.Run()
'CreateNewMapiContactAndAddToContactsSubfolder.Run()
'ExtractMessagesFromPSTFile.Run()
'RemovingPaswordProperty.Run()
'AddMapiTaskToPST.Run()
'CreateNewMapiJournalAndAddToSubfolder.Run()
'AddAttachmentsToMapiJournal.Run()
'AddMapiCalendarToPST.Run()
'CreateDistributionListInPST.Run()
'SaveMessagesDirectlyFromPSTToStream.Run()
'SearchStringInPSTWithIgnoreCaseParameter.Run()
'AddFilesToPST.Run()
'SearchMessagesAndFoldersInPST.Run()
'MoveItemsToOtherFolders.Run()
'AddMapiNoteToPST.Run()
'UpdatePSTCustomProperites.Run()
'SaveContactInformation.Run()
'DisplayInformationOfPSTFile.Run()
'SpecificCriterionSplitPST.Run()
'/ =====================================================
'/ =====================================================
'/ Knowledge-Base
'/ =====================================================
'/ =====================================================
' PrintEmail.Run()
'/ =====================================================
'/ =====================================================
'/ Exchange
'/ =====================================================
'/ =====================================================
'GetMailboxInformationFromExchangeWebServices.Run()
'GetMailboxInformationFromExchangeServer.Run()
'GetMailboxInformationFromExchangeServer.Run()
'ListExchangeServerMessages.Run()
'ProgrammingSamplesUsingEWS.Run()
'ListMessagesFromDifferentFolders.Run()
'ExchangeServerUsingEWS.Run()
'ListMessagesByID.Run()
'EnumeratMessagesWithPaginginEWS.Run()
'SaveMessagesFromExchangeServerMailboxToEML.Run()
'SaveMessagesUsingExchangeWebServices.Run()
'SaveMessagesToMemoryStream.Run()
'SaveMessagesToMemoryStreamUsingEWS.Run()
'ExchangeClientSaveMessagesInMSGFormat.Run()
'SendEmailMessagesUsingExchangeServer.Run()
'SendEmailMessagesUsingExchangeWebServices.Run()
'MoveMessageFromOneFolderToAnotherUsingExchangeClient.Run()
'MoveMessageFromOneFolderToAnotherusingEWS.Run()
'DeleteMessagesFromExchangeServer.Run()
'DeleteMessagesFromusingEWS.Run()
'DownloadMessagesFromExchangeServerFoldersRecursively.Run()
'DownloadMessagesFromPublicFolders.Run()
'ConnectExchangeServerUsingIMAP.Run()
'ExchangeServerUsesSSL.Run()
'SendMeetingRequestsUsingExchangeServer.Run()
'SendMeetingRequestsUsingEWS.Run()
'FilterMessagesFromExchangeMailbox.Run()
'ExchangeServerReadRules.Run()
'CreateNewRuleOntheExchangeServer.Run()
'UpdateRuleOntheExchangeServer.Run()
'ReadUserConfiguration.Run()
'UpdateUserConfiguration.Run()
'DeleteUserConfiguration.Run()
'FindConversationsOnExchangeServer.Run()
'CopyConversations.Run()
'MoveConversations.Run()
'DeleteConversations.Run()
'GetMailTips.Run()
'AccessAnotherMailboxUsingExchangeClient.Run()
'AccessAnotherMailboxUsingExchangeWebServiceClient.Run()
'AccessCustomFolderUsingExchangeWebServiceClient.Run()
'ExchangeImpersonationUsingEWS.Run()
'RetrieveFolderPermissionsUsingExchangeWebServiceClient.Run()
'SendTaskRequestUsingIEWSClient.Run()
'ExchangeFoldersBackupToPST.Run()
'CreateREAndFWMessages.Run()
'CreateAndSendingMessageWithVotingOptions.Run()
'PreFetchMessageSizeUsingIEWSClient.Run()
'SynchronizeFolderItems.Run()
'SecondaryCalendarEvents.Run()
'SaveExchangeTaskToDisc.Run()
'CreateExchangeTask.Run()
'DeleteExchangeTask.Run()
'SendExchangeTask.Run()
'UpdateExchangeTask.Run()
'SendCalendarInvitation.Run()
'/ =====================================================
'/ =====================================================
'/ POP3
'/ =====================================================
'/ =====================================================
'ParseMessageAndSave.Run()
'RecipientInformation.Run()
'RetrievingEmailHeaders.Run()
'RetrievingEmailMessages.Run()
'SaveToDiskWithoutParsing.Run()
'ConnectingToPOP3.Run()
'GettingMailboxInfo.Run()
'SSLEnabledPOP3Server.Run()
'FilterMessagesFromPOP3Mailbox.Run()
'RetrieveEmailViaPop3ClientProxyServer.Run()
'GetServerExtensionsUsingPop3Client.Run()
'RetrievMessagesAsynchronously.Run()
'RetrieveMessageSummaryInformationUsingUniqueId.Run()
'/ =====================================================
'/ =====================================================
'/ IMAP
'/ =====================================================
'/ =====================================================
'InsertHeaderAtSpecificLocation.Run()
'DeletingFolders.Run()
'RenamingFolders.Run()
'AddingNewMessage.Run()
'ConnectingWithIMAPServer.Run()
'GettingFoldersInformation.Run()
'MessagesFromIMAPServerToDisk.Run()
'RemovingMessageFlags.Run()
'ReadMessagesRecursively.Run()
'SettingMessageFlags.Run()
'SSLEnabledIMAPServer.Run()
'IMAP4IDExtensionSupport.Run()
'IMAP4ExtendedListCommand.Run()
'CopyMultipleMessagesFromOneFoldertoAnother.Run()
'DeleteSingleMessage.Run()
'DeleteMultipleMessages.Run()
'SavingMessagesFromIMAPServer.Run()
'ListMessagesWithMaximumNumberOfMessages.Run()
'ListingMessagesRecursively.Run()
'GetMessageIdUsingImapMessageInfo.Run()
'FilteringMessagesFromIMAPMailbox.Run()
'InternalDateFilter.Run()
'ProxyServerAccessMailbox.Run()
'RetrievingMessagesAsynchronously.Run()
'RetreivingServerExtensions.Run()
'SupportIMAPIdleCommand.Run()
'/ =====================================================
'/ =====================================================
'/ SMTP
'/ =====================================================
'/ =====================================================
'SetSpecificIpAddress.Run()
'ExportAsEML.Run()
'ImportEML.Run()
'CustomizingEmailHeader.Run()
'DeliveryNotifications.Run()
'SetEmailInfo.Run()
'SettingHTMLBody.Run()
'SettingTextBody.Run()
'AppointmentInICSFormat.Run()
'CustomizingEmailHeaders.Run()
'EmbeddedObjects.Run()
'LoadSmtpConfigFile.Run()
'MailMerge.Run()
'ManagingEmailAttachments.Run()
'MeetingRequests.Run()
'MultipleRecipients.Run()
'SendingEMLFilesWithSMTP.Run()
'SSLEnabledSMTPServer.Run()
'SendEmailUsingSMTP.Run()
'SendEmailAsynchronously.Run()
'SendingBulkEmails.Run()
'SendMessageAsTNEF.Run()
'SendEmailViaProxyServer.Run()
'SendPlainTextEmailMessage.Run()
'SendEmailWithAlternateText.Run()
'ForwardEmail.Run()
'SignEmailsWithDKIM.Run()
'/ =====================================================
'/ =====================================================
'/ Thunderbird
'/ =====================================================
'/ =====================================================
'ReadMessagesFromThunderbird.Run()
'CreateNewMessagesToThunderbird.Run()
' Stop before exiting
Console.WriteLine(Environment.NewLine + "Program Finished. Press any key to exit....")
Console.ReadKey()
End Sub
Friend Shared Function GetDataDir_KnowledgeBase() As String
Return Path.GetFullPath(GetDataDir_Data() + "KnowledgeBase/")
End Function
Friend Shared Function Thunderbird() As String
Return Path.GetFullPath(GetDataDir_Data() & Convert.ToString("Thunderbird/"))
End Function
Friend Shared Function GetDataDir_Email() As String
Return Path.GetFullPath(GetDataDir_Data() & Convert.ToString("Email/"))
End Function
Friend Shared Function GetDataDir_Exchange() As String
Return Path.GetFullPath(GetDataDir_Data() & Convert.ToString("/Exchange/"))
End Function
Friend Shared Function GetDataDir_Outlook() As String
Return Path.GetFullPath(GetDataDir_Data() & Convert.ToString("Outlook/"))
End Function
Friend Shared Function GetDataDir_POP3() As String
Return Path.GetFullPath(GetDataDir_Data() & Convert.ToString("POP3/"))
End Function
Friend Shared Function GetDataDir_IMAP() As String
Return Path.GetFullPath(GetDataDir_Data() & Convert.ToString("IMAP/"))
End Function
Friend Shared Function GetDataDir_SMTP() As String
Return Path.GetFullPath(GetDataDir_Data() & Convert.ToString("SMTP/"))
End Function
Private Shared Function GetDataDir_Data() As String
Dim parent = Directory.GetParent(Directory.GetCurrentDirectory()).Parent
Dim startDirectory As String = Nothing
If parent IsNot Nothing Then
Dim directoryInfo = parent.Parent
If directoryInfo IsNot Nothing Then
startDirectory = directoryInfo.FullName
End If
Else
startDirectory = parent.FullName
End If
Return If(startDirectory IsNot Nothing, Path.Combine(startDirectory, "Data\"), Nothing)
End Function
End Class
End Namespace
|
maria-shahid-aspose/Aspose.Email-for-.NET
|
Examples/VisualBasic/RunExamples.vb
|
Visual Basic
|
mit
| 17,085
|
' Copyright (c) Microsoft Corporation. All rights reserved.
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports Microsoft.WindowsAPICodePack.DirectX.WindowsImagingComponent
Imports Microsoft.WindowsAPICodePack.DirectX.Direct2D1
Imports System.IO
Namespace Microsoft.WindowsAPICodePack.Samples
Friend Class BitmapUtilities
Friend Shared Function LoadBitmapFromFile(ByVal renderTarget As RenderTarget, ByVal wicFactory As ImagingFactory, ByVal fileName As String) As D2DBitmap
Dim decoder As BitmapDecoder = wicFactory.CreateDecoderFromFileName(fileName, DesiredAccess.Read, DecodeMetadataCacheOption.OnLoad)
Return CreateBitmapFromDecoder(renderTarget, wicFactory, decoder)
End Function
Friend Shared Function LoadBitmapFromStream(ByVal renderTarget As RenderTarget, ByVal wicFactory As ImagingFactory, ByVal ioStream As Stream) As D2DBitmap
Dim decoder As BitmapDecoder = wicFactory.CreateDecoderFromStream(ioStream, DecodeMetadataCacheOption.OnLoad)
Return CreateBitmapFromDecoder(renderTarget, wicFactory, decoder)
End Function
Private Shared Function CreateBitmapFromDecoder(ByVal renderTarget As RenderTarget, ByVal wicFactory As ImagingFactory, ByVal decoder As BitmapDecoder) As D2DBitmap
Dim source As BitmapFrameDecode
Dim converter As FormatConverter
' Create the initial frame.
source = decoder.GetFrame(0)
' Convert the image format to 32bppPBGRA -- which Direct2D expects.
converter = wicFactory.CreateFormatConverter()
converter.Initialize(source.ToBitmapSource(), PixelFormats.Pbgra32Bpp, BitmapDitherType.None, BitmapPaletteType.MedianCut)
' Create a Direct2D bitmap from the WIC bitmap.
Return renderTarget.CreateBitmapFromWicBitmap(converter.ToBitmapSource())
End Function
End Class
End Namespace
|
devkimchi/Windows-API-Code-Pack-1.1
|
source/Samples/DirectX/VB/Direct2D/TextInlineImage/BitmapUtilities.vb
|
Visual Basic
|
mit
| 1,848
|
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
Public Class FullNameTests : Inherits VisualBasicResultProviderTestBase
<Fact>
Public Sub RootComment()
Dim source = "
Class C
Public F As Integer
End Class
"
Dim assembly = GetAssembly(source)
Dim type = assembly.GetType("C")
Dim value = CreateDkmClrValue(type.Instantiate())
Dim root = FormatResult("a ' Comment", value)
Assert.Equal("a.F", GetChildren(root).Single().FullName)
root = FormatResult(" a ' Comment", value)
Assert.Equal("a.F", GetChildren(root).Single().FullName)
root = FormatResult("a' Comment", value)
Assert.Equal("a.F", GetChildren(root).Single().FullName)
root = FormatResult("a +c '' Comment", value)
Assert.Equal("(a +c).F", GetChildren(root).Single().FullName)
root = FormatResult("a + c' Comment", value)
Assert.Equal("(a + c).F", GetChildren(root).Single().FullName)
' The result provider should never see a value like this in the "real-world"
root = FormatResult("''a' Comment", value)
Assert.Equal(".F", GetChildren(root).Single().FullName)
End Sub
<Fact>
Public Sub RootFormatSpecifiers()
Dim source = "
Class C
Public F As Integer
End Class
"
Dim assembly = GetAssembly(source)
Dim type = assembly.GetType("C")
Dim value = CreateDkmClrValue(type.Instantiate())
Dim root = FormatResult("a, raw", value) ' simple
Assert.Equal("a, raw", root.FullName)
Assert.Equal("a.F", GetChildren(root).Single().FullName)
root = FormatResult("a, raw, ac, h", value) ' multiple specifiers
Assert.Equal("a, raw, ac, h", root.FullName)
Assert.Equal("a.F", GetChildren(root).Single().FullName)
root = FormatResult("M(a, b), raw", value) ' non - specifier comma
Assert.Equal("M(a, b), raw", root.FullName)
Assert.Equal("(M(a, b)).F", GetChildren(root).Single().FullName) ' parens not required
root = FormatResult("a, raw1", value) ' alpha - numeric
Assert.Equal("a, raw1", root.FullName)
Assert.Equal("a.F", GetChildren(root).Single().FullName)
root = FormatResult("a, $raw", value) ' other punctuation
Assert.Equal("a, $raw", root.FullName)
Assert.Equal("(a, $raw).F", GetChildren(root).Single().FullName) ' Not ideal
End Sub
<Fact>
Public Sub RootParentheses()
Dim source = "
Class C
Public F As Integer
End Class
"
Dim assembly = GetAssembly(source)
Dim type = assembly.GetType("C")
Dim value = CreateDkmClrValue(type.Instantiate())
Dim root = FormatResult("a + b", value)
Assert.Equal("(a + b).F", GetChildren(root).Single().FullName) ' required
root = FormatResult("new C()", value)
Assert.Equal("(new C()).F", GetChildren(root).Single().FullName) ' documentation
root = FormatResult("A.B", value)
Assert.Equal("A.B.F", GetChildren(root).Single().FullName) ' desirable
root = FormatResult("Global.A.B", value)
Assert.Equal("Global.A.B.F", GetChildren(root).Single().FullName) ' desirable
End Sub
<Fact>
Public Sub RootTrailingSemicolons()
Dim source = "
Class C
Public F As Integer
End Class
"
Dim assembly = GetAssembly(source)
Dim type = assembly.GetType("C")
Dim value = CreateDkmClrValue(type.Instantiate())
' The result provider should never see a values like these in the "real-world"
Dim root = FormatResult("a;", value)
Assert.Equal("(a;).F", GetChildren(root).Single().FullName)
root = FormatResult("a + b;", value)
Assert.Equal("(a + b;).F", GetChildren(root).Single().FullName)
root = FormatResult(" M( ) ; ", value)
Assert.Equal("(M( ) ;).F", GetChildren(root).Single().FullName)
End Sub
<Fact>
Public Sub RootMixedExtras()
Dim source = "
Class C
Public F As Integer
End Class
"
Dim assembly = GetAssembly(source)
Dim type = assembly.GetType("C")
Dim value = CreateDkmClrValue(type.Instantiate())
' Comment, then format specifier.
Dim root = FormatResult("a', ac", value)
Assert.Equal("a", root.FullName)
' Format specifier, then comment.
root = FormatResult("a, ac , raw ', h", value)
Assert.Equal("a, ac, raw", root.FullName)
End Sub
<Fact, WorkItem(1022165)>
Public Sub Keywords_Root()
Dim source = "
Class C
Sub M()
Dim [Namespace] As Integer = 3
End Sub
End Class
"
Dim assembly = GetAssembly(source)
Dim value = CreateDkmClrValue(3)
Dim root = FormatResult("[Namespace]", value)
Verify(root,
EvalResult("[Namespace]", "3", "Integer", "[Namespace]"))
value = CreateDkmClrValue(assembly.GetType("C").Instantiate())
root = FormatResult("Me", value)
Verify(root,
EvalResult("Me", "{C}", "C", "Me"))
' Verify that keywords aren't escaped by the ResultProvider at the
' root level (we would never expect to see "Namespace" passed as a
' resultName, but this check verifies that we leave them "as is").
root = FormatResult("Namespace", CreateDkmClrValue(New Object()))
Verify(root,
EvalResult("Namespace", "{Object}", "Object", "Namespace"))
End Sub
End Class
End Namespace
|
JohnHamby/roslyn
|
src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/FullNameTests.vb
|
Visual Basic
|
apache-2.0
| 6,021
|
Namespace Common
''' <summary>
'''
''' </summary>
''' <remarks></remarks>
Public Class RelayCommand
Implements ICommand
Private ReadOnly _execute As Action
Private ReadOnly _canExecute As Func(Of Boolean)
Public Sub New(execute As Action)
Me.New(execute, Nothing)
End Sub
Public Sub New(execute As Action, canExecute As Func(Of Boolean))
If execute Is Nothing Then
Throw New ArgumentNullException("execute")
End If
_execute = execute
_canExecute = canExecute
End Sub
Public Event CanExecuteChanged As EventHandler Implements ICommand.CanExecuteChanged
Public Sub RaiseCanExecuteChanged()
RaiseEvent CanExecuteChanged(Me, EventArgs.Empty)
End Sub
Public Function CanExecute(parameter As Object) As Boolean Implements ICommand.CanExecute
Return If(_canExecute Is Nothing, True, _canExecute())
End Function
Public Sub Execute(parameter As Object) Implements ICommand.Execute
_execute()
End Sub
End Class
End Namespace
|
jaksg82/XtfViewer
|
XtfViewer_Win8/Common/RelayCommand.vb
|
Visual Basic
|
mit
| 1,170
|
' Copyright 2013, Google Inc. All Rights Reserved.
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
' Author: api.anash@gmail.com (Anash P. Oommen)
Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201309
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Net
Imports System.Threading
Namespace Google.Api.Ads.AdWords.Examples.VB.v201309
''' <summary>
''' This code example shows how to handle RateExceededError in your
''' application. To trigger the rate exceeded error, this code example runs
''' 100 threads in parallel, each thread attempting to validate 100 keywords
''' in a single request. Note that spawning 100 parallel threads is for
''' illustrative purposes only, you shouldn't do this in your application.
'''
''' Tags: AdGroupAdService.mutate
''' </summary>
Public Class HandleRateExceededError
Inherits ExampleBase
''' <summary>
''' Main method, to run this code example as a standalone application.
''' </summary>
''' <param name="args">The command line arguments.</param>
Public Shared Sub Main(ByVal args As String())
Dim codeExample As New HandleRateExceededError
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 shows how to handle RateExceededError in your application. " & _
"To trigger the rate exceeded error, this code example runs 100 threads in " & _
"parallel, each thread attempting to validate 100 keywords in a single request. " & _
"Note that spawning 100 parallel threads is for illustrative purposes only, you " & _
"shouldn't do this in your application."
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)
Const NUM_THREADS As Integer = 100
' Increase the maximum number of parallel HTTP connections that .NET
' framework allows. By default, this is set to 2 by the .NET framework.
ServicePointManager.DefaultConnectionLimit = NUM_THREADS
Dim threads As New List(Of Thread)
For i As Integer = 0 To NUM_THREADS
Dim thread As New Thread(AddressOf New KeywordThread(user, i, adGroupId).Run)
threads.Add(thread)
Next i
For i As Integer = 0 To threads.Count - 1
threads.Item(i).Start(i)
Next i
For i As Integer = 0 To threads.Count - 1
threads.Item(i).Join()
Next i
End Sub
''' <summary>
''' Thread class for validating keywords.
''' </summary>
Public Class KeywordThread
''' <summary>
''' Index of this thread, for identifying and debugging.
''' </summary>
Dim threadIndex As Integer
''' <summary>
''' The ad group id to which keywords are added.
''' </summary>
Dim adGroupId As Long
''' <summary>
''' The AdWords user who owns this ad group.
''' </summary>
Dim user As AdWordsUser
''' <summary>
''' Number of keywords to be validated in each API call.
''' </summary>
Const NUM_KEYWORDS As Integer = 100
''' <summary>
''' Initializes a new instance of the <see cref="KeywordThread" /> class.
''' </summary>
''' <param name="threadIndex">Index of the thread.</param>
''' <param name="adGroupId">The ad group id.</param>
''' <param name="user">The AdWords user who owns the ad group.</param>
Public Sub New(ByVal user As AdWordsUser, ByVal threadIndex As Integer, _
ByVal adGroupId As Long)
Me.user = user
Me.threadIndex = threadIndex
Me.adGroupId = adGroupId
End Sub
''' <summary>
''' Main method for the thread.
''' </summary>
''' <param name="obj">The thread parameter.</param>
Public Sub Run(ByVal obj As Object)
' Create the operations.
Dim operations As New List(Of AdGroupCriterionOperation)
For j As Integer = 0 To NUM_KEYWORDS
' Create the keyword.
Dim keyword As New Keyword
keyword.text = "mars cruise thread " & threadIndex.ToString & " seed " & j.ToString
keyword.matchType = KeywordMatchType.BROAD
' Create the biddable ad group criterion.
Dim keywordCriterion As AdGroupCriterion = New BiddableAdGroupCriterion
keywordCriterion.adGroupId = adGroupId
keywordCriterion.criterion = keyword
' Create the operations.
Dim keywordOperation As New AdGroupCriterionOperation
keywordOperation.operator = [Operator].ADD
keywordOperation.operand = keywordCriterion
operations.Add(keywordOperation)
Next j
' Get the AdGroupCriterionService. This should be done within the
' thread, since a service can only handle one outgoing HTTP request
' at a time.
Dim service As AdGroupCriterionService = user.GetService( _
AdWordsService.v201309.AdGroupCriterionService)
service.RequestHeader.validateOnly = True
Dim retryCount As Integer = 0
Const NUM_RETRIES As Integer = 3
Try
While (retryCount < NUM_RETRIES)
Try
' Validate the keywords.
Dim retval As AdGroupCriterionReturnValue = service.mutate(operations.ToArray)
Exit While
Catch ex As AdWordsApiException
' Handle API errors.
Dim innerException As ApiException = TryCast(ex.ApiException, ApiException)
If (innerException Is Nothing) Then
Throw New Exception("Failed to retrieve ApiError. See inner exception for more " & _
"details.", ex)
End If
For Each apiError As ApiError In innerException.errors
If Not TypeOf apiError Is RateExceededError Then
' Rethrow any errors other than RateExceededError.
Throw
End If
' Handle rate exceeded errors.
Dim rateExceededError As RateExceededError = DirectCast(apiError, RateExceededError)
Console.WriteLine("Got Rate exceeded error - rate name = '{0}', scope = '{1}', " & _
"retry After {2} seconds.", rateExceededError.rateScope, _
rateExceededError.rateName, rateExceededError.retryAfterSeconds)
Thread.Sleep(rateExceededError.retryAfterSeconds)
retryCount = retryCount + 1
Next
Finally
If (retryCount = NUM_RETRIES) Then
Throw New Exception(String.Format("Could not recover after making {0} attempts.", _
retryCount))
End If
End Try
End While
Catch ex As Exception
Throw New System.ApplicationException("Failed to validate keywords.", ex)
End Try
End Sub
End Class
End Class
End Namespace
|
akilb/googleads-adwords-dotnet-lib
|
examples/adxbuyer/VB/v201309/ErrorHandling/HandleRateExceededError.vb
|
Visual Basic
|
apache-2.0
| 8,159
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports InternalSyntax = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Imports PreprocessorState = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.Scanner.PreprocessorState
Imports Scanner = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.Scanner
Namespace Microsoft.CodeAnalysis.VisualBasic
Public Partial Class VisualBasicSyntaxTree
''' <summary>
''' Map containing information about all conditional symbol definitions in the source file corresponding to a parsed syntax tree.
''' </summary>
Private Class ConditionalSymbolsMap
''' <summary>
''' Conditional symbols map, where each key-value pair indicates:
''' Key: Conditional symbol name.
''' Value: Stack of all active conditional symbol definitions, i.e. #Const directives, in the source file corresponding to a parsed syntax tree.
''' All the defining #Const directives for a conditional symbol are pushed onto this stack in source code order.
''' Each stack entry is a tuple {InternalSyntax.CConst, Integer} where:
''' InternalSyntax.CConst: Constant value of the symbol.
''' Integer: Source position of the defining #Const directive.
''' </summary>
Private ReadOnly _conditionalsMap As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer)))
Friend Shared ReadOnly Uninitialized As ConditionalSymbolsMap = New ConditionalSymbolsMap()
' Only used by Uninitialized instance
Private Sub New()
End Sub
Private Sub New(conditionalsMap As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer))))
Debug.Assert(conditionalsMap IsNot Nothing)
Debug.Assert(conditionalsMap.Any())
#If DEBUG Then
For Each kvPair In conditionalsMap
Dim conditionalStack As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = kvPair.Value
Debug.Assert(conditionalStack.Any())
' Ensure that all the defining #Const directives for this conditional symbol are pushed onto the stack in source code order.
Dim prevPosition As Integer = Int32.MaxValue
For i = 0 To conditionalStack.Count - 1
Dim position As Integer = conditionalStack(i).Item2
Debug.Assert(prevPosition >= position)
prevPosition = position
Next
Next
#End If
Me._conditionalsMap = conditionalsMap
End Sub
#Region "Build conditional symbols map"
Friend Shared Function Create(syntaxRoot As VisualBasicSyntaxNode, options As VisualBasicParseOptions) As ConditionalSymbolsMap
Dim symbolsMapBuilder = New ConditionalSymbolsMapBuilder()
Dim conditionalSymbolsMap As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer))) = symbolsMapBuilder.Build(syntaxRoot, options)
Debug.Assert(conditionalSymbolsMap Is Nothing OrElse conditionalSymbolsMap.Count > 0)
Return If(conditionalSymbolsMap IsNot Nothing, New ConditionalSymbolsMap(conditionalSymbolsMap), Nothing)
End Function
Private Class ConditionalSymbolsMapBuilder
Private _conditionalsMap As Dictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer)))
Private _preprocessorState As PreprocessorState
Friend Function Build(root As SyntaxNodeOrToken, options As VisualBasicParseOptions) As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer)))
Me._conditionalsMap = New Dictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer)))(IdentifierComparison.Comparer)
' Process command line preprocessor symbol definitions.
Dim preprocessorSymbolsMap As ImmutableDictionary(Of String, InternalSyntax.CConst) = Scanner.GetPreprocessorConstants(options)
Me.ProcessCommandLinePreprocessorSymbols(preprocessorSymbolsMap)
Me._preprocessorState = New PreprocessorState(preprocessorSymbolsMap)
' Get and process source directives.
Dim directives As IEnumerable(Of DirectiveTriviaSyntax) = root.GetDirectives(Of DirectiveTriviaSyntax)()
Debug.Assert(directives IsNot Nothing)
ProcessSourceDirectives(directives)
Return If(Me._conditionalsMap.Any(), ImmutableDictionary.CreateRange(IdentifierComparison.Comparer, Me._conditionalsMap), Nothing)
End Function
Private Sub ProcessCommandLinePreprocessorSymbols(preprocessorSymbolsMap As ImmutableDictionary(Of String, InternalSyntax.CConst))
For Each kvPair In preprocessorSymbolsMap
Me.ProcessConditionalSymbolDefinition(kvPair.Key, kvPair.Value, 0)
Next
End Sub
Private Sub ProcessConditionalSymbolDefinition(name As String, value As InternalSyntax.CConst, position As Integer)
Dim values As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = Nothing
If Not _conditionalsMap.TryGetValue(name, values) Then
' First definition for this conditional symbol in this source file, create a new key-value pair.
values = New Stack(Of Tuple(Of InternalSyntax.CConst, Integer))
_conditionalsMap.Add(name, values)
End If
values.Push(Tuple.Create(value, position))
End Sub
Private Sub ProcessSourceDirectives(directives As IEnumerable(Of DirectiveTriviaSyntax))
For Each directive In directives
ProcessDirective(directive)
Next
End Sub
' Process all active conditional directives under trivia, in source code order.
Private Sub ProcessDirective(directive As DirectiveTriviaSyntax)
Debug.Assert(_conditionalsMap IsNot Nothing)
Debug.Assert(directive IsNot Nothing)
Select Case directive.Kind
Case SyntaxKind.ConstDirectiveTrivia
Dim prevPreprocessorSymbols = _preprocessorState.SymbolsMap
_preprocessorState = Scanner.ApplyDirective(_preprocessorState, DirectCast(directive.Green(), InternalSyntax.DirectiveTriviaSyntax))
Dim newPreprocessorSymbols = _preprocessorState.SymbolsMap
If Not prevPreprocessorSymbols Is newPreprocessorSymbols Then
Dim name As String = DirectCast(directive, ConstDirectiveTriviaSyntax).Name.ValueText
#If DEBUG Then
Dim values As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = Nothing
If Not _conditionalsMap.TryGetValue(name, values) Then
' First definition for this conditional symbol in this source file, create a new key-value pair.
Debug.Assert(Not prevPreprocessorSymbols.ContainsKey(name))
Else
' Not the first definition for this conditional symbol in this source file.
' We must have an existing entry for this conditional symbol in prevPreprocessorSymbols map.
Debug.Assert(values IsNot Nothing)
Debug.Assert(prevPreprocessorSymbols.ContainsKey(name))
Debug.Assert(Object.Equals(prevPreprocessorSymbols(name).ValueAsObject, values.Peek().Item1.ValueAsObject))
End If
#End If
ProcessConditionalSymbolDefinition(name, newPreprocessorSymbols(name), directive.SpanStart)
End If
Case Else
_preprocessorState = Scanner.ApplyDirective(_preprocessorState, DirectCast(directive.Green(), InternalSyntax.DirectiveTriviaSyntax))
End Select
End Sub
End Class
#End Region
Friend Function GetPreprocessingSymbolInfo(conditionalSymbolName As String, node As IdentifierNameSyntax) As VisualBasicPreprocessingSymbolInfo
Dim constValue As InternalSyntax.CConst = GetPreprocessorSymbolValue(conditionalSymbolName, node)
If constValue Is Nothing Then
Return VisualBasicPreprocessingSymbolInfo.None
End If
' Get symbol name at preprocessor definition, i.e. #Const directive.
' NOTE: symbolName and conditionalSymbolName might have different case, we want the definition name.
Dim symbolName = _conditionalsMap.Keys.First(Function(key) IdentifierComparison.Equals(key, conditionalSymbolName))
Return New VisualBasicPreprocessingSymbolInfo(New PreprocessingSymbol(name:=symbolName), constantValueOpt:=constValue.ValueAsObject, isDefined:=True)
End Function
Private Function GetPreprocessorSymbolValue(conditionalSymbolName As String, node As SyntaxNodeOrToken) As InternalSyntax.CConst
Dim values As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = Nothing
If _conditionalsMap.TryGetValue(conditionalSymbolName, values) Then
' All the defining #Const directives for a conditional symbol are pushed onto the stack in source code order.
' Get the first entry from the top end of the stack with source position less then the source position of 'node'.
' If there is none, then the given conditional symbol is undefined at 'node'
Dim position As Integer = node.SpanStart
For Each valueTuple In values
If valueTuple.Item2 < position Then
Return valueTuple.Item1
End If
Next
End If
Return Nothing
End Function
' Returns a flag indicating whether the given conditional symbol is defined prior to the given node in source code order in this parsed syntax tree and
' it has a non-zero integral value or non-null string value.
' NOTE: These criteria are used by the native VB compiler.
Friend Function IsConditionalSymbolDefined(conditionalSymbolName As String, node As SyntaxNodeOrToken) As Boolean
If conditionalSymbolName IsNot Nothing Then
Dim constValue As InternalSyntax.CConst = GetPreprocessorSymbolValue(conditionalSymbolName, node)
If constValue IsNot Nothing AndAlso Not constValue.IsBad Then
Select Case constValue.SpecialType
Case SpecialType.System_Boolean
Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Boolean))
Return value.Value
Case SpecialType.System_Byte
Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Byte))
Return value.Value <> 0
Case SpecialType.System_Int16
Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Int16))
Return value.Value <> 0
Case SpecialType.System_Int32
Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Int32))
Return value.Value <> 0
Case SpecialType.System_Int64
Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Int64))
Return value.Value <> 0
Case SpecialType.System_SByte
Dim value = DirectCast(constValue, InternalSyntax.CConst(Of SByte))
Return value.Value <> 0
Case SpecialType.System_UInt16
Dim value = DirectCast(constValue, InternalSyntax.CConst(Of UInt16))
Return value.Value <> 0
Case SpecialType.System_UInt32
Dim value = DirectCast(constValue, InternalSyntax.CConst(Of UInt32))
Return value.Value <> 0
Case SpecialType.System_UInt64
Dim value = DirectCast(constValue, InternalSyntax.CConst(Of UInt64))
Return value.Value <> 0
Case SpecialType.System_String
Debug.Assert(DirectCast(constValue, InternalSyntax.CConst(Of String)).Value IsNot Nothing)
Return True
End Select
End If
End If
Return False
End Function
End Class
End Class
End Namespace
|
jmarolf/roslyn
|
src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxTree.ConditionalSymbolsMap.vb
|
Visual Basic
|
mit
| 14,037
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Editor.Shared.Options
Imports Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
Imports Microsoft.CodeAnalysis.Snippets
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Completion
<[UseExportProvider]>
Public Class CSharpCompletionSnippetNoteTests
Private _markup As XElement = <document>
<![CDATA[using System;
class C
{
$$
void M() { }
}]]></document>
Public Shared ReadOnly Property AllCompletionImplementations() As IEnumerable(Of Object())
Get
Return TestStateFactory.GetAllCompletionImplementations()
End Get
End Property
<WorkItem(726497, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/726497")>
<MemberData(NameOf(AllCompletionImplementations))>
<WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function SnippetExpansionNoteAddedToDescription_ExactMatch(completionImplementation As CompletionImplementation) As Task
Using state = CreateCSharpSnippetExpansionNoteTestState(completionImplementation, _markup, "interface")
state.SendTypeChars("interfac")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(description:="title" & vbCrLf &
"description" & vbCrLf &
String.Format(FeaturesResources.Note_colon_Tab_twice_to_insert_the_0_snippet, "interface"))
End Using
End Function
<MemberData(NameOf(AllCompletionImplementations))>
<WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function ColonDoesntTriggerSnippetInTupleLiteral(completionImplementation As CompletionImplementation) As Task
Using state = CreateCSharpSnippetExpansionNoteTestState(completionImplementation, _markup, "interface")
state.SendTypeChars("var t = (interfac")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="interface", isHardSelected:=True)
state.SendTypeChars(":")
Assert.Contains("(interfac:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<MemberData(NameOf(AllCompletionImplementations))>
<WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function ColonDoesntTriggerSnippetInTupleLiteralAfterComma(completionImplementation As CompletionImplementation) As Task
Using state = CreateCSharpSnippetExpansionNoteTestState(completionImplementation, _markup, "interface")
state.SendTypeChars("var t = (1, interfac")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="interface", isHardSelected:=True)
state.SendTypeChars(":")
Assert.Contains("(1, interfac:", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WorkItem(726497, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/726497")>
<MemberData(NameOf(AllCompletionImplementations))>
<WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function SnippetExpansionNoteAddedToDescription_DifferentSnippetShortcutCasing(completionImplementation As CompletionImplementation) As Task
Using state = CreateCSharpSnippetExpansionNoteTestState(completionImplementation, _markup, "intErfaCE")
state.SendTypeChars("interfac")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(description:=$"{String.Format(FeaturesResources._0_Keyword, "interface")}
{String.Format(FeaturesResources.Note_colon_Tab_twice_to_insert_the_0_snippet, "interface")}")
End Using
End Function
<WorkItem(726497, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/726497")>
<MemberData(NameOf(AllCompletionImplementations))>
<WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Sub SnippetExpansionNoteNotAddedToDescription_ShortcutIsProperSubstringOfInsertedText(completionImplementation As CompletionImplementation)
Using state = CreateCSharpSnippetExpansionNoteTestState(completionImplementation, _markup, "interfac")
state.SendTypeChars("interfac")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(description:="title" & vbCrLf &
"description" & vbCrLf &
String.Format(FeaturesResources.Note_colon_Tab_twice_to_insert_the_0_snippet, "interfac"))
End Using
End Sub
<WorkItem(726497, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/726497")>
<MemberData(NameOf(AllCompletionImplementations))>
<WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Sub SnippetExpansionNoteNotAddedToDescription_ShortcutIsProperSuperstringOfInsertedText(completionImplementation As CompletionImplementation)
Using state = CreateCSharpSnippetExpansionNoteTestState(completionImplementation, _markup, "interfaces")
state.SendTypeChars("interfac")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(description:=String.Format(FeaturesResources._0_Keyword, "interface"))
End Using
End Sub
<WorkItem(726497, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/726497")>
<MemberData(NameOf(AllCompletionImplementations))>
<WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Sub SnippetExpansionNoteAddedToDescription_DisplayTextDoesNotMatchShortcutButInsertionTextDoes(completionImplementation As CompletionImplementation)
Using state = CreateCSharpSnippetExpansionNoteTestState(completionImplementation, _markup, "InsertionText")
state.SendTypeChars("DisplayTex")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(description:=String.Format(FeaturesResources.Note_colon_Tab_twice_to_insert_the_0_snippet, "InsertionText"))
End Using
End Sub
<MemberData(NameOf(AllCompletionImplementations))>
<WpfTheory, Trait(Traits.Feature, Traits.Features.Completion), Trait(Traits.Feature, Traits.Features.Interactive)>
Public Async Function SnippetExpansionNoteNotAddedToDescription_Interactive(completionImplementation As CompletionImplementation) As Task
Dim workspaceXml =
<Workspace>
<Submission Language="C#" CommonReferences="true">
$$
</Submission>
</Workspace>
Using state = TestStateFactory.CreateTestStateFromWorkspace(
completionImplementation,
workspaceXml,
New CompletionProvider() {New MockCompletionProvider()},
New List(Of Type) From {GetType(TestCSharpSnippetInfoService)},
WorkspaceKind.Interactive)
Dim testSnippetInfoService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetService(Of ISnippetInfoService)(), TestCSharpSnippetInfoService)
testSnippetInfoService.SetSnippetShortcuts({"for"})
state.Workspace.Options = state.Workspace.Options.WithChangedOption(InternalFeatureOnOffOptions.Snippets, False)
state.SendTypeChars("for")
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(
description:=String.Format(FeaturesResources._0_Keyword, "for") & vbCrLf &
String.Format(FeaturesResources.Note_colon_Tab_twice_to_insert_the_0_snippet, "for"))
End Using
End Function
Private Function CreateCSharpSnippetExpansionNoteTestState(completionImplementation As CompletionImplementation, xElement As XElement, ParamArray snippetShortcuts As String()) As ITestState
Dim state = TestStateFactory.CreateCSharpTestState(
completionImplementation,
xElement,
New CompletionProvider() {New MockCompletionProvider()},
extraExportedTypes:=New List(Of Type) From {GetType(TestCSharpSnippetInfoService)})
Dim testSnippetInfoService = DirectCast(state.Workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetService(Of ISnippetInfoService)(), TestCSharpSnippetInfoService)
testSnippetInfoService.SetSnippetShortcuts(snippetShortcuts)
Return state
End Function
End Class
End Namespace
|
DustinCampbell/roslyn
|
src/VisualStudio/Core/Test/Completion/CSharpCompletionSnippetNoteTests.vb
|
Visual Basic
|
apache-2.0
| 9,389
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
' This portion of the binder converts an ExpressionSyntax into a BoundExpression
Partial Friend Class Binder
Private Function BindAnonymousObjectCreationExpression(node As AnonymousObjectCreationExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
Return AnonymousTypeCreationBinder.BindAnonymousObjectInitializer(Me, node, node.Initializer, node.NewKeyword, diagnostics)
End Function
Private Function BindAnonymousObjectCreationExpression(node As VisualBasicSyntaxNode,
typeDescr As AnonymousTypeDescriptor,
initExpressions As ImmutableArray(Of BoundExpression),
diagnostics As BindingDiagnosticBag) As BoundExpression
' Check for restricted types.
For Each field As AnonymousTypeField In typeDescr.Fields
Dim restrictedType As TypeSymbol = Nothing
If field.Type.IsRestrictedTypeOrArrayType(restrictedType) Then
ReportDiagnostic(diagnostics, field.Location, ERRID.ERR_RestrictedType1, restrictedType)
End If
Next
Return CreateAnonymousObjectCreationExpression(node, typeDescr, initExpressions)
End Function
Private Function CreateAnonymousObjectCreationExpression(node As VisualBasicSyntaxNode,
typeDescr As AnonymousTypeDescriptor,
initExpressions As ImmutableArray(Of BoundExpression),
Optional hasErrors As Boolean = False) As BoundExpression
' Get or create an anonymous type
Dim anonymousType As AnonymousTypeManager.AnonymousTypePublicSymbol =
Me.Compilation.AnonymousTypeManager.ConstructAnonymousTypeSymbol(typeDescr)
' get constructor
Dim constructor As MethodSymbol = anonymousType.InstanceConstructors.First()
Debug.Assert(constructor IsNot Nothing)
Debug.Assert(constructor.ParameterCount = initExpressions.Length)
Return CreateAnonymousObjectCreationExpression(node, anonymousType, initExpressions, hasErrors)
End Function
Protected Overridable Function CreateAnonymousObjectCreationExpression(node As VisualBasicSyntaxNode,
anonymousType As AnonymousTypeManager.AnonymousTypePublicSymbol,
initExpressions As ImmutableArray(Of BoundExpression),
Optional hasErrors As Boolean = False) As BoundAnonymousTypeCreationExpression
' By default BoundAnonymousTypeCreationExpression is created without
' locals and bound nodes for 'declarations' of properties
Return New BoundAnonymousTypeCreationExpression(node, Nothing,
ImmutableArray(Of BoundAnonymousTypePropertyAccess).Empty,
initExpressions, anonymousType, hasErrors)
End Function
''' <summary>
''' Binder to be used for binding New With { ... } expressions.
''' </summary>
Friend Class AnonymousTypeCreationBinder
Inherits Binder
' NOTE: field descriptors in 'Fields' array are mutable, field types are being assigned
' in successfully processed fields as we go through the field initializers
Private ReadOnly _fields() As AnonymousTypeField
' NOTE: after the binder is initialized, some elements in 'Fields' may remain empty because
' errors in field declaration; '_fieldName2index' map actually stores the list of
' 'good' fields into corresponding slots in 'Fields', those slots must not be empty
Private ReadOnly _fieldName2index As Dictionary(Of String, Integer)
' field declaration bound node is created for fields with implicitly
' specified name to provide semantic info on those identifier;
' the array builder is being created lazily if needed
Private _fieldDeclarations As ArrayBuilder(Of BoundAnonymousTypePropertyAccess)
' '_locals' field points to an array which holds locals introduced during binding
' for each field which is being used in other field initialization;
' Thus while binding 'New With { .a = 1, .b = 1 + .a }' a local will be created to
' hold the value of '1' and to be used as '.a = <local_a>' and '.b = 1 + <local_a>'
' Note that no local is created for not referenced fields (like '.b' in the example
' above) leaving correspondent slots in '_locals' empty.
Private ReadOnly _locals() As LocalSymbol
Private ReadOnly _propertySymbols() As PropertySymbol
''' <summary>
''' If set, the state of the binder shouldn't be modified by subsequent binding operations,
''' which could be performed by SemanticModel in context of this binder.
''' </summary>
Private _freeze As Boolean
Friend Shared Function BindAnonymousObjectInitializer(containingBinder As Binder,
owningSyntax As VisualBasicSyntaxNode,
initializerSyntax As ObjectMemberInitializerSyntax,
typeLocationToken As SyntaxToken,
diagnostics As BindingDiagnosticBag) As BoundExpression
Dim fieldsCount = initializerSyntax.Initializers.Count
If fieldsCount = 0 Then
' ERR_AnonymousTypeNeedField must have been reported in Parser
Return BadExpression(owningSyntax, ImmutableArray(Of BoundExpression).Empty, ErrorTypeSymbol.UnknownResultType)
End If
Return New AnonymousTypeCreationBinder(containingBinder, initializerSyntax, diagnostics).
BindInitializersAndCreateBoundNode(owningSyntax, initializerSyntax, diagnostics, typeLocationToken)
End Function
#Region "Binder Creation and Initial Analysis"
Private Sub New(containingBinder As Binder,
initializerSyntax As ObjectMemberInitializerSyntax,
diagnostics As BindingDiagnosticBag)
MyBase.New(containingBinder)
Dim objectType As TypeSymbol = GetSpecialType(SpecialType.System_Object, initializerSyntax, diagnostics)
' Examine 'initializerSyntax' node and builds the list of anonymous type field declarations
' with no type assigned to fields yet (those will be assigned when the binder binds field
' initializers one-by-one). Some diagnostics may be reported as we go...
Dim initializers = initializerSyntax.Initializers
Dim initializersCount As Integer = initializers.Count
Debug.Assert(initializersCount > 0)
' Initialize binder fields
Me._fieldName2index = New Dictionary(Of String, Integer)(initializersCount, CaseInsensitiveComparison.Comparer)
Me._fields = New AnonymousTypeField(initializersCount - 1) {}
Me._fieldDeclarations = Nothing
Me._locals = New LocalSymbol(initializersCount - 1) {}
Me._propertySymbols = New PropertySymbol(initializersCount - 1) {}
' Process field initializers
For fieldIndex = 0 To initializersCount - 1
Dim fieldSyntax As FieldInitializerSyntax = initializers(fieldIndex)
Dim fieldName As String = Nothing
Dim fieldNode As VisualBasicSyntaxNode = Nothing
Dim fieldIsKey As Boolean = False
' get field's name
If fieldSyntax.Kind = SyntaxKind.InferredFieldInitializer Then
Dim inferredFieldInitializer = DirectCast(fieldSyntax, InferredFieldInitializerSyntax)
Dim fieldNameToken As SyntaxToken = inferredFieldInitializer.Expression.ExtractAnonymousTypeMemberName(Nothing)
If fieldNameToken.Kind = SyntaxKind.None Then
' failed to infer field name, create a dummy field descriptor
' NOTE: errors are supposed to be reported by parser
fieldName = Nothing
fieldNode = inferredFieldInitializer.Expression
fieldIsKey = False
Else
' field name successfully inferred
fieldName = fieldNameToken.ValueText
fieldNode = DirectCast(fieldNameToken.Parent, VisualBasicSyntaxNode)
fieldIsKey = inferredFieldInitializer.KeyKeyword.Kind = SyntaxKind.KeyKeyword
End If
Else
' field name is specified implicitly
Dim namedFieldInitializer = DirectCast(fieldSyntax, NamedFieldInitializerSyntax)
fieldNode = namedFieldInitializer.Name
fieldIsKey = namedFieldInitializer.KeyKeyword.Kind = SyntaxKind.KeyKeyword
fieldName = namedFieldInitializer.Name.Identifier.ValueText
End If
' check type character
Dim typeChar As TypeCharacter = ExtractTypeCharacter(fieldNode)
If typeChar <> TypeCharacter.None Then
' report the error and proceed to the next field initializer
ReportDiagnostic(diagnostics, fieldSyntax, ERRID.ERR_AnonymousTypeDisallowsTypeChar)
End If
If String.IsNullOrEmpty(fieldName) Then
' since the field does not have name, we generate a pseudo name to be used in template
fieldName = "$"c & fieldIndex.ToString()
Else
' check the name for duplications (in System.Object and in the list of fields)
If objectType.GetMembers(fieldName).Any() OrElse Me._fieldName2index.ContainsKey(fieldName) Then
' report the error
ReportDiagnostic(diagnostics, fieldSyntax, ErrorFactory.ErrorInfo(ERRID.ERR_DuplicateAnonTypeMemberName1, fieldName))
End If
End If
' build anonymous type field descriptor
Me._fields(fieldIndex) = New AnonymousTypeField(fieldName, fieldNode.GetLocation(), fieldIsKey)
Me._fieldName2index(fieldName) = fieldIndex ' This might overwrite fields in error-cases
Next
End Sub
#End Region
#Region "Binding of anonymous type creation field initializers"
Private Function BindInitializersAndCreateBoundNode(owningSyntax As VisualBasicSyntaxNode,
initializerSyntax As ObjectMemberInitializerSyntax,
diagnostics As BindingDiagnosticBag,
typeLocationToken As SyntaxToken) As BoundExpression
Dim fieldsCount As Integer = Me._fields.Length
' Try to bind expressions from field initializers one-by-one; after each of the
' expression is bound successfully assign the type of the field in 'fields'.
Dim boundInitializers(fieldsCount - 1) As BoundExpression
' WARNING: Note that SemanticModel.GetDeclaredSymbol for field initializer node relies on
' the fact that the order of properties in anonymous type template corresponds
' 1-to-1 to the appropriate filed initializer syntax nodes; This means such
' correspondence must be preserved all the time including erroneous scenarios
' NOTE: if one field initializer references another, the binder creates an
' BoundAnonymousTypePropertyAccess node to represent the value of the field,
' if the field referenced is not processed yet an error will be generated
For index = 0 To fieldsCount - 1
Dim initializer As FieldInitializerSyntax = initializerSyntax.Initializers(index)
' to be used if we need to create BoundAnonymousTypePropertyAccess node
Dim namedFieldInitializer As NamedFieldInitializerSyntax = Nothing
Dim initExpression As ExpressionSyntax = Nothing
If initializer.Kind = SyntaxKind.InferredFieldInitializer Then
initExpression = DirectCast(initializer, InferredFieldInitializerSyntax).Expression
Else
namedFieldInitializer = DirectCast(initializer, NamedFieldInitializerSyntax)
initExpression = namedFieldInitializer.Expression
End If
Dim initializerBinder As New AnonymousTypeFieldInitializerBinder(Me, index)
Dim boundExpression As BoundExpression = initializerBinder.BindRValue(initExpression, diagnostics)
boundExpression = New BoundAnonymousTypeFieldInitializer(initializer, initializerBinder, boundExpression, boundExpression.Type).MakeCompilerGenerated()
boundInitializers(index) = boundExpression
Dim fieldType As TypeSymbol = boundExpression.Type
' check for restricted type
Dim restrictedType As TypeSymbol = Nothing
If fieldType.IsRestrictedTypeOrArrayType(restrictedType) Then
ReportDiagnostic(diagnostics, initExpression, ERRID.ERR_RestrictedType1, restrictedType)
End If
' always assign the type, event if there were errors in binding and/or
' the type is an error type, we are going to use it for anonymous type fields
Me._fields(index).AssignFieldType(fieldType)
If namedFieldInitializer IsNot Nothing Then
' create an instance of BoundAnonymousTypePropertyAccess to
' guarantee semantic info on the identifier
If Me._fieldDeclarations Is Nothing Then
Me._fieldDeclarations = ArrayBuilder(Of BoundAnonymousTypePropertyAccess).GetInstance()
End If
Me._fieldDeclarations.Add(
New BoundAnonymousTypePropertyAccess(
namedFieldInitializer.Name,
Me, index, fieldType))
End If
' TODO: when Dev10 reports ERR_BadOrCircularInitializerReference (BC36555) ??
Next
' just return a new bound anonymous type creation node
Dim result As BoundExpression = Me.CreateAnonymousObjectCreationExpression(owningSyntax,
New AnonymousTypeDescriptor(
Me._fields.AsImmutableOrNull(),
typeLocationToken.GetLocation(),
False),
boundInitializers.AsImmutableOrNull())
Me._freeze = True
Return result
End Function
Protected Overrides Function CreateAnonymousObjectCreationExpression(node As VisualBasicSyntaxNode,
anonymousType As AnonymousTypeManager.AnonymousTypePublicSymbol,
initExpressions As ImmutableArray(Of BoundExpression),
Optional hasErrors As Boolean = False) As BoundAnonymousTypeCreationExpression
' cache anonymous type property symbols created
For index = 0 To Me._fields.Length - 1
Dim name As String = Me._fields(index).Name
' NOTE: we use the following criteria as an indicator of the fact that
' the name of the field is not correct, so we don't want to return
' symbols of such fields to semantic API
If name(0) <> "$"c Then
Me._propertySymbols(index) = anonymousType.Properties(index)
End If
Next
' create a node
Return New BoundAnonymousTypeCreationExpression(node, Me,
If(Me._fieldDeclarations Is Nothing,
ImmutableArray(Of BoundAnonymousTypePropertyAccess).Empty,
Me._fieldDeclarations.ToImmutableAndFree()),
initExpressions, anonymousType, hasErrors)
End Function
#End Region
#Region "Accessors for anonymous type creation bound nodes "
Friend Function GetAnonymousTypePropertySymbol(index As Integer) As PropertySymbol
Return Me._propertySymbols(index)
End Function
Friend Function GetAnonymousTypePropertyLocal(index As Integer) As LocalSymbol
Return Me._locals(index)
End Function
Friend Function TryGetField(name As String, <Out()> ByRef field As AnonymousTypeField, <Out()> ByRef fieldIndex As Integer) As Boolean
If Me._fieldName2index.TryGetValue(name, fieldIndex) Then
field = Me._fields(fieldIndex)
Return True
End If
field = Nothing
Return False
End Function
Friend Sub RegisterFieldReference(fieldIndex As Integer)
Debug.Assert(Me._fields(fieldIndex).Type IsNot Nothing)
If Not _freeze Then
' check if there is already a local symbol created for this field
Dim local = Me._locals(fieldIndex)
If local Is Nothing Then
' create a local
local = New SynthesizedLocal(Me.ContainingMember, Me._fields(fieldIndex).Type, SynthesizedLocalKind.LoweringTemp)
Me._locals(fieldIndex) = local
End If
End If
End Sub
#End Region
End Class
''' <summary>
''' Having this binder, which is created for each field initializer within AnonymousObjectCreationExpressionSyntax
''' gives us the following advantages:
''' - We no longer rely on transient state of AnonymousTypeField objects to detect out of order field references
''' within initializers. This way we can be sure that result of binding performed by SemanticModel is consistent
''' with result of initial binding of the entire node.
''' - AnonymousTypeCreationBinder overrides CreateAnonymousObjectCreationExpression in such a way that it mutates
''' its state. That overridden method shouldn't be called while we are binding each initializer (by queries, for example),
''' it should be called only by AnonymousTypeCreationBinder itself after all initializers are bound and we are producing
''' the resulting node. So having an extra binder in between takes care of that.
''' </summary>
Friend Class AnonymousTypeFieldInitializerBinder
Inherits Binder
Private ReadOnly _initializerOrdinal As Integer
Public Sub New(creationBinder As AnonymousTypeCreationBinder, initializerOrdinal As Integer)
MyBase.New(creationBinder)
_initializerOrdinal = initializerOrdinal
End Sub
#Region "Binding of member access with omitted left like '.fieldName'"
Protected Friend Overrides Function TryBindOmittedLeftForMemberAccess(node As MemberAccessExpressionSyntax,
diagnostics As BindingDiagnosticBag,
accessingBinder As Binder,
<Out> ByRef wholeMemberAccessExpressionBound As Boolean) As BoundExpression
wholeMemberAccessExpressionBound = True
Dim creationBinder = DirectCast(ContainingBinder, AnonymousTypeCreationBinder)
' filter out parser errors
If node.ContainsDiagnostics Then
Return BadExpression(node, ErrorTypeSymbol.UnknownResultType)
End If
Dim nameSyntax As SimpleNameSyntax = node.Name
Dim name As String = nameSyntax.Identifier.ValueText
' 'nameSyntax' points to '.<nameSyntax>' which is supposed to be either
' a property name or a name inherited from System.Object
Dim fieldIndex As Integer = 0
Dim field As AnonymousTypeField = Nothing
If creationBinder.TryGetField(name, field, fieldIndex) Then
' Field is found
Dim hasErrors As Boolean = False
' check for type arguments
If nameSyntax.Kind = SyntaxKind.GenericName Then
' referencing a field, but with type arguments specified
' NOTE: since we don't have the symbol of the anonymous type's
' property, we mock property name to be used in this message
' TODO: revise
ReportDiagnostic(diagnostics, DirectCast(nameSyntax, GenericNameSyntax).TypeArgumentList,
ERRID.ERR_TypeOrMemberNotGeneric1,
String.Format(
"Public {0}Property {1} As T{2}",
If(field.IsKey, "Readonly ", ""),
name, fieldIndex))
hasErrors = True
End If
' check if the field referenced is already processed, and is 'good', e.g. has type assigned
If fieldIndex >= _initializerOrdinal Then
' referencing a field which is not processed yet or has an error
' report an error and return a bad expression
If Not hasErrors Then
' don't report this error if other diagnostics are already reported
ReportDiagnostic(diagnostics, node, ERRID.ERR_AnonymousTypePropertyOutOfOrder1, name)
End If
Return BadExpression(node, ErrorTypeSymbol.UnknownResultType)
Else
creationBinder.RegisterFieldReference(fieldIndex)
If Me.ContainingMember IsNot accessingBinder.ContainingMember Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_CannotLiftAnonymousType1, node.Name.Identifier.ValueText)
hasErrors = True
End If
' return bound anonymous type access
Debug.Assert(field.Type IsNot Nothing)
Return New BoundAnonymousTypePropertyAccess(node, creationBinder, fieldIndex, field.Type, hasErrors)
End If
Else
' NOTE: Dev10 allows references to methods defined of anonymous type, which boils
' down to those defined on System.Object AND extension methods defined
' for System.Object:
'
' - In case an instance method of System.Object is being called, the result of
' Dev10 compilation with throw an exception in runtime
' - In case a shared method of System.Object is being called, like
' New With {.a = .ReferenceEquals(Nothing, Nothing)}, the call finishes fine
' - The result of calling extension methods depends on method's implementation
' (Nothing is being passed as the first argument)
'
' In Roslyn we disable this functionality which is a breaking change in a sense,
' but really should only affect a very few customers.
' TODO: revise and maybe report a special error message
End If
' NOTE: since we don't have the symbol of the anonymous type, we use
' "<anonymous type>" literal to be consistent with Dev10
ReportDiagnostic(diagnostics, node, ERRID.ERR_NameNotMemberOfAnonymousType2, name, StringConstants.AnonymousTypeName)
Return BadExpression(node, ErrorTypeSymbol.UnknownResultType)
End Function
Protected Overrides Function TryBindOmittedLeftForDictionaryAccess(node As MemberAccessExpressionSyntax, accessingBinder As Binder, diagnostics As BindingDiagnosticBag) As BoundExpression
' NOTE: since we don't have the symbol of the anonymous type, we use
' "<anonymous type>" literal to be consistent with Dev10
ReportDiagnostic(diagnostics, node, ERRID.ERR_NoDefaultNotExtend1, StringConstants.AnonymousTypeName)
Return BadExpression(node, ErrorTypeSymbol.UnknownResultType)
End Function
Protected Overrides Function TryBindOmittedLeftForConditionalAccess(node As ConditionalAccessExpressionSyntax, accessingBinder As Binder, diagnostics As BindingDiagnosticBag) As BoundExpression
Return Nothing
End Function
#End Region
End Class
End Class
End Namespace
|
AlekseyTs/roslyn
|
src/Compilers/VisualBasic/Portable/Binding/Binder_AnonymousTypes.vb
|
Visual Basic
|
mit
| 28,237
|
' 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.
'vbc /t:library /vbruntime- MultiModule.vb /addmodule:mod2.netmodule,mod3.netmodule
Public Class Class1
Sub Goo()
Dim x = {1,2}
Dim y = x.Count()
End Sub
End Class
|
CyrusNajmabadi/roslyn
|
src/Compilers/Test/Resources/Core/SymbolsTests/MultiModule/MultiModule.vb
|
Visual Basic
|
mit
| 369
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.VisualBasic.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' When compiling in metadata-only mode, <see cref="MethodCompiler"/> is not run. This is problematic because
''' <see cref="MethodCompiler"/> adds synthesized explicit implementations to the list of synthesized definitions.
''' In lieu of running <see cref="MethodCompiler"/>, this class performs a quick
''' traversal of the symbol table and performs processing of synthesized symbols if necessary.
''' </summary>
Friend Class SynthesizedMetadataCompiler
Inherits VisualBasicSymbolVisitor
Private ReadOnly _moduleBeingBuilt As PEModuleBuilder
Private ReadOnly _cancellationToken As CancellationToken
Private Sub New(moduleBeingBuilt As PEModuleBuilder, cancellationToken As CancellationToken)
Me._moduleBeingBuilt = moduleBeingBuilt
Me._cancellationToken = cancellationToken
End Sub
''' <summary>
''' Traverse the symbol table and properly add/process synthesized extra metadata if needed.
''' </summary>
Friend Shared Sub ProcessSynthesizedMembers(compilation As VisualBasicCompilation,
moduleBeingBuilt As PEModuleBuilder,
Optional cancellationToken As CancellationToken = Nothing)
Debug.Assert(moduleBeingBuilt IsNot Nothing)
Dim compiler = New SynthesizedMetadataCompiler(moduleBeingBuilt:=moduleBeingBuilt, cancellationToken:=cancellationToken)
compilation.SourceModule.GlobalNamespace.Accept(compiler)
End Sub
Public Overrides Sub VisitNamespace(symbol As NamespaceSymbol)
Me._cancellationToken.ThrowIfCancellationRequested()
For Each member In symbol.GetMembers()
member.Accept(Me)
Next
End Sub
Public Overrides Sub VisitNamedType(symbol As NamedTypeSymbol)
Me._cancellationToken.ThrowIfCancellationRequested()
For Each member In symbol.GetMembers()
Select Case member.Kind
Case SymbolKind.NamedType
member.Accept(Me)
End Select
Next
End Sub
#If DEBUG Then
Public Overrides Sub VisitProperty(symbol As PropertySymbol)
Throw ExceptionUtilities.Unreachable
End Sub
Public Overrides Sub VisitMethod(symbol As MethodSymbol)
Throw ExceptionUtilities.Unreachable
End Sub
#End If
End Class
End Namespace
|
AlekseyTs/roslyn
|
src/Compilers/VisualBasic/Portable/Compilation/SynthesizedMetadataCompiler.vb
|
Visual Basic
|
mit
| 2,945
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Partial Friend MustInherit Class SynthesizedAccessor(Of T As Symbol)
Inherits SynthesizedMethodBase
Protected ReadOnly m_propertyOrEvent As T
Private _lazyMetadataName As String
Protected Sub New(container As NamedTypeSymbol, propertyOrEvent As T)
MyBase.New(container)
m_propertyOrEvent = propertyOrEvent
End Sub
Public NotOverridable Overrides ReadOnly Property Name As String
Get
Return Binder.GetAccessorName(m_propertyOrEvent.Name, Me.MethodKind, Me.IsCompilationOutputWinMdObj())
End Get
End Property
Public Overrides ReadOnly Property MetadataName As String
Get
If _lazyMetadataName Is Nothing Then
Interlocked.CompareExchange(_lazyMetadataName, GenerateMetadataName(), Nothing)
End If
Return _lazyMetadataName
End Get
End Property
Protected Overridable Function GenerateMetadataName() As String
' VB compiler uses different rules for accessors that other members or the associated properties
' (probably a bug, but we have to maintain binary compatibility now). An accessor name is set to match
' its overridden method, regardless of what happens to its associated property.
Dim overriddenMethod = Me.OverriddenMethod
If overriddenMethod IsNot Nothing Then
Return overriddenMethod.MetadataName
Else
Return Me.Name
End If
End Function
Friend NotOverridable Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return True
End Get
End Property
Public NotOverridable Overrides ReadOnly Property AssociatedSymbol As Symbol
Get
Return m_propertyOrEvent
End Get
End Property
Public ReadOnly Property PropertyOrEvent As T
Get
Return m_propertyOrEvent
End Get
End Property
Public NotOverridable Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return m_propertyOrEvent.DeclaredAccessibility
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return m_propertyOrEvent.IsMustOverride
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return m_propertyOrEvent.IsNotOverridable
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsOverloads As Boolean
Get
Return m_propertyOrEvent.IsOverloads
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property ShadowsExplicitly As Boolean
Get
Return m_propertyOrEvent.ShadowsExplicitly
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsOverridable As Boolean
Get
Return m_propertyOrEvent.IsOverridable
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsOverrides As Boolean
Get
Return m_propertyOrEvent.IsOverrides
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsShared As Boolean
Get
Return m_propertyOrEvent.IsShared
End Get
End Property
Friend Overrides Function GetLexicalSortKey() As LexicalSortKey
Return m_propertyOrEvent.GetLexicalSortKey()
End Function
Public NotOverridable Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return m_propertyOrEvent.Locations
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property ImplicitlyDefinedBy(Optional membersInProgress As Dictionary(Of String, ArrayBuilder(Of Symbol)) = Nothing) As Symbol
Get
Return m_propertyOrEvent
End Get
End Property
End Class
End Namespace
|
aelij/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedAccessor.vb
|
Visual Basic
|
apache-2.0
| 4,833
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods
Public Class ExtendedSemanticInfoTests : Inherits SemanticModelTestBase
<Fact>
Public Sub Test_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
Dim x As New C1()
x.F1()'BIND:"F1"
End Sub
<Extension()>
Function F1(ByRef this As C1) As Integer
Return 0
End Function
End Module
Class C1
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Null(semanticInfo.Type)
Assert.Null(semanticInfo.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim method = DirectCast(semanticInfo.Symbol, MethodSymbol)
Assert.Equal("Function C1.F1() As System.Int32", method.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, method.Kind)
Assert.Equal(MethodKind.ReducedExtension, method.MethodKind)
Assert.Equal("C1", method.ReceiverType.ToTestDisplayString())
Assert.Equal("Function Module1.F1(ByRef this As C1) As System.Int32", method.ReducedFrom.ToTestDisplayString())
Assert.Equal(MethodKind.Ordinary, method.CallsiteReducedFromMethod.MethodKind)
Assert.Equal("Function Module1.F1(ByRef this As C1) As System.Int32", method.CallsiteReducedFromMethod.ToTestDisplayString())
Dim reducedMethod As MethodSymbol = method.ReducedFrom.ReduceExtensionMethod(method.ReceiverType)
Assert.Equal("Function C1.F1() As System.Int32", reducedMethod.ToTestDisplayString())
Assert.Equal(MethodKind.ReducedExtension, reducedMethod.MethodKind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(1, semanticInfo.MemberGroup.Length)
Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString())
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<Fact>
Public Sub Test_2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
Dim x As New C1()
x.F1()'BIND:"F1"
End Sub
<Extension()>
Function F1(this As C1) As Integer
Return 0
End Function
End Module
Class C1
Function F1(x As Integer) As Integer
Return 0
End Function
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Null(semanticInfo.Type)
Assert.Null(semanticInfo.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Function C1.F1() As System.Int32", semanticInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(2, semanticInfo.MemberGroup.Length)
Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString())
Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", sortedMethodGroup(1).ToTestDisplayString())
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<Fact>
Public Sub Test_3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
Dim x As New C1()
x.F1()'BIND:"x.F1()"
End Sub
<Extension()>
Function F1(this As C1) As Integer
Return 0
End Function
End Module
Class C1
Function F1(x As Integer) As Integer
Return 0
End Function
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb")
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Function C1.F1() As System.Int32", semanticInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
End Class
End Namespace
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class SemanticModelTests
<Fact>
Public Sub ExtensionMethodsLookupSymbols1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
Dim x As New C1()
x.F1()'BIND:"x"
End Sub
<Extension()>
Function F1(this As C1) As Integer
Return 0
End Function
End Module
Class C1
Function F1(x As Integer) As Integer
Return 0
End Function
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Dim c1 = compilation.GetTypeByMetadataName("C1")
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="F1", container:=c1, includeReducedExtensionMethods:=True)
Assert.Equal(2, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString())
Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", sortedMethodGroup(1).ToTestDisplayString())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="F1", container:=c1, includeReducedExtensionMethods:=False)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub ExtensionMethodsLookupSymbols2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
End Sub
<Extension()>
Function F1(this As C1) As Integer
Return 0
End Function
End Module
Class C1
Function F1(x As Integer) As Integer
Return 0
End Function
Shared Sub Main()
F1()'BIND:"F1"
End Sub
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="F1", includeReducedExtensionMethods:=True)
Assert.Equal(2, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString())
Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", sortedMethodGroup(1).ToTestDisplayString())
End Sub
<Fact>
Public Sub ExtensionMethodsLookupSymbols3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main()
Dim x As New C1()
x.Test1() 'BIND:"Test1"
End Sub
<Extension()>
Sub Test1(Of T1)(this As NS1.NS2.Module1.C1)
End Sub
Class C1
End Class
End Module
Module Module2
<Extension()>
Sub Test1(Of T1, T2)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test1(Of T1, T2, T3)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test1(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module6
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module8
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T1)(this As NS1.NS2.Module1.C1)", actual_lookupSymbols(0).ToTestDisplayString())
Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1")
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, includeReducedExtensionMethods:=True)
Assert.Equal(8, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1
Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString())
Next
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1)
Assert.Equal(0, actual_lookupSymbols.Count)
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub ExtensionMethodsLookupSymbols4()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main()
End Sub
<Extension()>
Sub Test1(Of T1)(this As NS1.NS2.Module1.C1)
End Sub
Class C1
Sub Main()
Test1() 'BIND:"Test1"
End Sub
End Class
End Module
Module Module2
<Extension()>
Sub Test1(Of T1, T2)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test1(Of T1, T2, T3)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test1(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module6
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module8
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True)
Assert.Equal(8, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1
Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString())
Next
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1")
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T1)(this As NS1.NS2.Module1.C1)", actual_lookupSymbols(0).ToTestDisplayString())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub ExtensionMethodsLookupSymbols5()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main()
Dim x As C1 = Nothing
x.Test1() 'BIND:"Test1"
End Sub
<Extension()>
Sub Test1(Of T1)(this As NS1.NS2.Module1.C1)
End Sub
Interface C1
End Interface
End Module
Module Module2
<Extension()>
Sub Test1(Of T1, T2)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test1(Of T1, T2, T3)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test1(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module6
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module8
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T1)(this As NS1.NS2.Module1.C1)", actual_lookupSymbols(0).ToTestDisplayString())
Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1")
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, includeReducedExtensionMethods:=True)
Assert.Equal(8, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1
Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString())
Next
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1)
Assert.Equal(0, actual_lookupSymbols.Count)
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub ExtensionMethodsLookupSymbols6()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main(Of T)(x as T)
x.Test1() 'BIND:"Test1"
End Sub
<Extension()>
Sub Test1(Of T, T1)(this As T)
End Sub
End Module
Module Module2
<Extension()>
Sub Test1(Of T, T1, T2)(this As T)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test1(Of T, T1, T2, T3)(this As T)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test1(Of T, T1, T2, T3, T4)(this As T)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test1(Of T, T1, T2, T3, T4, T5)(this As T)
End Sub
End Module
Module Module6
<Extension()>
Sub Test1(Of T, T1, T2, T3, T4, T5, T6)(this As T)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test1(Of T, T1, T2, T3, T4, T5, T6, T7)(this As T)
End Sub
End Module
Module Module8
<Extension()>
Sub Test1(Of T, T1, T2, T3, T4, T5, T6, T7, T8)(this As T)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test1(Of T, T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As T)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T, T1)(this As T)", actual_lookupSymbols(0).ToTestDisplayString())
Dim module1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1")
Dim main = DirectCast(module1.GetMember("Main"), MethodSymbol)
Dim t = main.TypeParameters(0)
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=t, includeReducedExtensionMethods:=True)
Assert.Equal(8, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Dim expected() As String = {"Sub T.Test1(Of T1)()",
"Sub T.Test1(Of T1, T2)()",
"Sub T.Test1(Of T1, T2, T3)()",
"Sub T.Test1(Of T1, T2, T3, T4)()",
"Sub T.Test1(Of T1, T2, T3, T4, T5)()",
"Sub T.Test1(Of T1, T2, T3, T4, T5, T6)()",
"Sub T.Test1(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub T.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1
Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString())
Next
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=t)
Assert.Equal(0, actual_lookupSymbols.Count)
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=t, arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub T.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub ExtensionMethodsLookupSymbols7()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main()
Dim x As New C1()
x.Test1() 'BIND:"Test1"
End Sub
<Extension()>
Sub Test1(Of T1)(this As NS1.NS2.Module1.C1)
End Sub
Class C1
End Class
End Module
Module Module2
<Extension()>
Sub Test2(Of T1, T2)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test3(Of T1, T2, T3)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test4(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test5(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module6
<Extension()>
Sub Test6(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test7(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module8
<Extension()>
Sub Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test9(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1")
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, includeReducedExtensionMethods:=True)
Assert.Equal(14, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Dim expected() As String = {"Function System.Object.Equals(obj As System.Object) As System.Boolean",
"Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean",
"Function System.Object.GetHashCode() As System.Int32",
"Function System.Object.GetType() As System.Type",
"Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean",
"Function System.Object.ToString() As System.String",
"Sub NS1.NS2.Module1.C1.Test1(Of T1)()",
"Sub NS1.NS2.Module1.C1.Test2(Of T1, T2)()",
"Sub NS1.NS2.Module1.C1.Test3(Of T1, T2, T3)()",
"Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()",
"Sub NS1.NS2.Module1.C1.Test5(Of T1, T2, T3, T4, T5)()",
"Sub NS1.NS2.Module1.C1.Test6(Of T1, T2, T3, T4, T5, T6)()",
"Sub NS1.NS2.Module1.C1.Test7(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub NS1.NS2.Module1.C1.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1
Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString())
Next
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1)
Assert.Equal(6, actual_lookupSymbols.Count)
sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
For i As Integer = 0 To sortedMethodGroup.Length - 1
Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString())
Next
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, name:="Test4", arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub ExtensionMethodsLookupSymbols8()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main()
End Sub
<Extension()>
Sub Test1(Of T1)(this As NS1.NS2.Module1.C1)
End Sub
Class C1
Sub Main()
Test1() 'BIND:"Test1"
End Sub
End Class
End Module
Module Module2
<Extension()>
Sub Test2(Of T1, T2)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test3(Of T1, T2, T3)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test4(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test5(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module6
<Extension()>
Sub Test6(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test7(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module8
<Extension()>
Sub Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test9(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", includeReducedExtensionMethods:=True)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Dim expected() As String = {"Function System.Object.Equals(obj As System.Object) As System.Boolean",
"Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean",
"Function System.Object.GetHashCode() As System.Int32",
"Function System.Object.GetType() As System.Type",
"Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean",
"Function System.Object.ToString() As System.String",
"Sub NS1.NS2.Module1.C1.Test1(Of T1)()",
"Sub NS1.NS2.Module1.C1.Test2(Of T1, T2)()",
"Sub NS1.NS2.Module1.C1.Test3(Of T1, T2, T3)()",
"Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()",
"Sub NS1.NS2.Module1.C1.Test5(Of T1, T2, T3, T4, T5)()",
"Sub NS1.NS2.Module1.C1.Test6(Of T1, T2, T3, T4, T5, T6)()",
"Sub NS1.NS2.Module1.C1.Test7(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub NS1.NS2.Module1.C1.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
Assert.Equal(expected.Length, Aggregate name In expected Join symbol In actual_lookupSymbols
On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb")
Assert.Equal(0, Aggregate symbol In actual_lookupSymbols Join name In expected.Skip(6)
On symbol.ToTestDisplayString() Equals name Into Count())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test4", arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub ExtensionMethodsLookupSymbols9()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main()
Dim x As C1 = Nothing
x.Test1() 'BIND:"Test1"
End Sub
<Extension()>
Sub Test1(Of T1)(this As NS1.NS2.Module1.C1)
End Sub
Interface C1
End Interface
End Module
Module Module2
<Extension()>
Sub Test2(Of T1, T2)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test3(Of T1, T2, T3)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test4(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test5(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module6
<Extension()>
Sub Test6(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test7(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module8
<Extension()>
Sub Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test9(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1")
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, includeReducedExtensionMethods:=True)
Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()",
"Sub NS1.NS2.Module1.C1.Test2(Of T1, T2)()",
"Sub NS1.NS2.Module1.C1.Test3(Of T1, T2, T3)()",
"Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()",
"Sub NS1.NS2.Module1.C1.Test5(Of T1, T2, T3, T4, T5)()",
"Sub NS1.NS2.Module1.C1.Test6(Of T1, T2, T3, T4, T5, T6)()",
"Sub NS1.NS2.Module1.C1.Test7(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub NS1.NS2.Module1.C1.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
Assert.Equal(expected.Length, Aggregate name In expected Join symbol In actual_lookupSymbols
On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1)
Assert.Equal(0, Aggregate name In expected Join symbol In actual_lookupSymbols
On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, name:="Test4", arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub ExtensionMethodsLookupSymbols10()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main(Of T)(x as T)
x.Test1() 'BIND:"Test1"
End Sub
<Extension()>
Sub Test1(Of T, T1)(this As T)
End Sub
End Module
Module Module2
<Extension()>
Sub Test2(Of T, T1, T2)(this As T)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test3(Of T, T1, T2, T3)(this As T)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test4(Of T, T1, T2, T3, T4)(this As T)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test5(Of T, T1, T2, T3, T4, T5)(this As T)
End Sub
End Module
Module Module6
<Extension()>
Sub Test6(Of T, T1, T2, T3, T4, T5, T6)(this As T)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test7(Of T, T1, T2, T3, T4, T5, T6, T7)(this As T)
End Sub
End Module
Module Module8
<Extension()>
Sub Test8(Of T, T1, T2, T3, T4, T5, T6, T7, T8)(this As T)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test9(Of T, T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As T)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim module1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1")
Dim main = DirectCast(module1.GetMember("Main"), MethodSymbol)
Dim t = main.TypeParameters(0)
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=t, includeReducedExtensionMethods:=True)
Dim expected() As String = {"Sub T.Test1(Of T1)()",
"Sub T.Test2(Of T1, T2)()",
"Sub T.Test3(Of T1, T2, T3)()",
"Sub T.Test4(Of T1, T2, T3, T4)()",
"Sub T.Test5(Of T1, T2, T3, T4, T5)()",
"Sub T.Test6(Of T1, T2, T3, T4, T5, T6)()",
"Sub T.Test7(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub T.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
Assert.Equal(expected.Length, Aggregate name In expected Join symbol In actual_lookupSymbols
On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=t, includeReducedExtensionMethods:=False)
Assert.Equal(0, Aggregate name In expected Join symbol In actual_lookupSymbols
On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=t, name:="Test4", arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub T.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub Bug8942_1()
Dim compilation = CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb">
Imports System
Imports System.Runtime.CompilerServices
Module M
<Extension()>
Sub Foo(x As Exception)
End Sub
End Module
Class E
Inherits Exception
Sub Bar()
Me.Foo() 'BIND:"Foo"
End Sub
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Null(semanticInfo.Type)
Assert.Null(semanticInfo.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Sub System.Exception.Foo()", semanticInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(1, semanticInfo.MemberGroup.Length)
Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Sub System.Exception.Foo()", sortedMethodGroup(0).ToTestDisplayString())
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<Fact>
Public Sub Bug8942_2()
Dim compilation = CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb">
Imports System
Imports System.Runtime.CompilerServices
Module M
<Extension()>
Sub Foo(x As Exception)
End Sub
End Module
Class E
Inherits Exception
Sub Bar()
Foo() 'BIND:"Foo"
End Sub
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Null(semanticInfo.Type)
Assert.Null(semanticInfo.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Sub System.Exception.Foo()", semanticInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(1, semanticInfo.MemberGroup.Length)
Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Sub System.Exception.Foo()", sortedMethodGroup(0).ToTestDisplayString())
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<WorkItem(544933, "DevDiv")>
<Fact>
Public Sub LookupSymbolsGenericExtensionMethodWithConstraints()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Class A
End Class
Class B
End Class
Module E
Sub M(_a As A, _b As B)
_a.F()
_b.F()
End Sub
<Extension()>
Sub F(Of T As A)(o As T)
End Sub
End Module
]]></file>
</compilation>, {SystemCoreRef})
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC30456: 'F' is not a member of 'B'.
_b.F()
~~~~
]]></errors>)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim position = FindNodeFromText(tree, "_a.F()").SpanStart
Dim method = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("E").GetMember(Of MethodSymbol)("M")
' No type.
Dim symbols = model.LookupSymbols(position, container:=Nothing, name:="F", includeReducedExtensionMethods:=True)
CheckSymbols(symbols, "Sub E.F(Of T)(o As T)")
' Type satisfying constraints.
symbols = model.LookupSymbols(position, container:=method.Parameters(0).Type, name:="F", includeReducedExtensionMethods:=True)
CheckSymbols(symbols, "Sub A.F()")
' Type not satisfying constraints.
symbols = model.LookupSymbols(position, container:=method.Parameters(1).Type, name:="F", includeReducedExtensionMethods:=True)
CheckSymbols(symbols)
End Sub
<Fact, WorkItem(963125)>
Public Sub Bug963125()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb">
Imports alias2 = System
Module Module1
Sub Main()
alias1.Console.WriteLine()
alias2.Console.WriteLine()
End Sub
End Module
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"alias1 = System"})))
compilation.AssertNoDiagnostics()
Dim tree = compilation.SyntaxTrees.Single()
Dim model = compilation.GetSemanticModel(tree)
Dim node1 = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "alias1").Single()
Dim alias1 = model.GetAliasInfo(node1)
Assert.Equal("alias1=System", alias1.ToTestDisplayString())
Assert.Equal(LocationKind.None, alias1.Locations.Single().Kind)
Dim node2 = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "alias2").Single()
Dim alias2 = model.GetAliasInfo(node2)
Assert.Equal("alias2=System", alias2.ToTestDisplayString())
Assert.Equal(LocationKind.SourceFile, alias2.Locations.Single().Kind)
End Sub
End Class
End Namespace
|
hanu412/roslyn
|
src/Compilers/VisualBasic/Test/Semantic/ExtensionMethods/SemanticModelTests.vb
|
Visual Basic
|
apache-2.0
| 51,437
|
Option Strict Off
Option Explicit On
Imports Microsoft.VisualBasic.PowerPacks
Friend Class frmOrderWizardFilter
Inherits System.Windows.Forms.Form
Public gDayEndStart As Integer
Public gDayEndEnd As String
Public gFilter As String
'Dim gNodeFilter As IXMLDOMNode
Public gFilterSQL As String
Dim MonthView As New List(Of MonthCalendar)
Private Sub loadLanguage()
'Label2 = No Code [When Calculating your ordering levels.......]
'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
'If rsLang.RecordCount Then Label2.Caption = rsLang("LanguageLayoutLnk_Description"): Label2.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
'Label1(0) = No Code [Day End Criteria]
'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
'If rsLang.RecordCount Then Label1(0).Caption = rsLang("LanguageLayoutLnk_Description"): Label1(0).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
'_lbl_5 = No Code [From Date]
'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
'If rsLang.RecordCount Then _lbl_5.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_5.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
'_lbl_3 = No Code [To Date]
'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
'If rsLang.RecordCount Then _lbl_3.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_3.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
'_lbl_1 = No Code [Calculated Day End Criteria]
'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
'If rsLang.RecordCount Then _lbl_1.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_1.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
'Label1(1) = No Code [Wizard Rules]
'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
'If rsLang.RecordCount Then Label1(1).Caption = rsLang("LanguageLayoutLnk_Description"): Label1(1).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
'_lbl_0 = No Code [Forecast my stock holding for]
'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
'If rsLang.RecordCount Then _lbl_0.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_0.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
'_lbl_2 = No Code ["Day Ends" and then guarantee no re-order]
'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
'If rsLang.RecordCount Then _lbl_2.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_2.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
'_lbl_4 = No Code [level will be below]
'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
'If rsLang.RecordCount Then _lbl_4.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_4.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
'chkDynamic = No Code [Automatically re-calculate start and end dates based on current "Day End" date]
'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
'If rsLang.RecordCount Then chkDynamic.Caption = rsLang("LanguageLayoutLnk_Description"): chkDynamic.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1006 'Filter|Checked
If rsLang.RecordCount Then _Label1_2.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : _Label1_2.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value
rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1006 'Filter|Checked
If rsLang.RecordCount Then cmdFilter.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : cmdFilter.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value
rsHelp.filter = "Help_Section=0 AND Help_Form='" & Me.Name & "'"
'UPGRADE_ISSUE: Form property frmOrderWizardFilter.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
If rsHelp.RecordCount Then Me.ToolTip1 = rsHelp.Fields("Help_ContextID").Value
End Sub
Private Sub save()
Dim lStart, lEnd As Short
Dim rs As ADODB.Recordset
If Me.chkDynamic.CheckState Then
rs = getRS("SELECT " & gDayEndEnd & " - MAX(DayEndID) AS id From DayEnd")
lStart = rs.Fields("id").Value
Else
lStart = CShort(gDayEndEnd)
End If
lEnd = CDbl(gDayEndEnd) - gDayEndStart + 1
cnnDB.Execute("UPDATE MinMax SET MinMax_DayEndIDStart = " & lStart & ", MinMax_DayEndIDBack = " & lEnd & ", MinMax_DaysForward = " & Me.txtDays.Text & ", MinMax_Minimum = " & Me.txtMinimum.Text & " Where (MinMaxID = 1)")
Me.Close()
End Sub
Public Sub setDayEndRange()
Dim lDate As Date
Dim lDateString As String
Dim lDateArray() As String
Dim rs As ADODB.Recordset
Dim lDateStart As Date
Dim lDateEnd As Date
On Error Resume Next
lDateStart = _MonthView1_0.SelectionStart
lDateEnd = _MonthView1_1.SelectionEnd
If _MonthView1_0.SelectionStart > _MonthView1_1.SelectionEnd Then
lDateStart = _MonthView1_1.SelectionStart
lDateEnd = _MonthView1_0.SelectionEnd
End If
rs = getRS("SELECT TOP 1 DayEndID, DayEnd_Date AS [date] From DayEnd WHERE (DayEnd_Date >= #" & lDateStart & "#) ORDER BY DayEnd_Date")
If rs.BOF Or rs.EOF Then
rs.Close()
rs = getRS("SELECT TOP 1 DayEndID, DayEnd_Date AS [date] From DayEnd ORDER BY DayEndID DESC")
gDayEndStart = rs.Fields("DayEndID").Value
Else
gDayEndStart = rs.Fields("DayEndID").Value
End If
rs.Close()
rs = getRS("SELECT TOP 1 DayEndID, DayEnd_Date AS [date] From DayEnd WHERE (DayEnd_Date <= #" & lDateEnd & "#) ORDER BY DayEnd_Date DESC")
If rs.BOF Or rs.EOF Then
rs.Close()
rs = getRS("SELECT TOP 1 DayEndID, DayEnd_Date AS [date] From DayEnd ORDER BY DayEndID DESC")
gDayEndEnd = rs.Fields("DayEndID").Value
Else
gDayEndEnd = rs.Fields("DayEndID").Value
End If
rs.Close()
rs = getRS("SELECT TOP 100 PERCENT COUNT(*) AS [count], MIN(DayEnd_Date) AS fromDate, MAX(DayEnd_Date) AS toDate From DayEnd WHERE (DayEndID >= " & gDayEndStart & " AND DayEndID <= " & gDayEndEnd & ")")
If rs.BOF Or rs.EOF Then
Else
lDateString = Format(rs.Fields("fromDate").Value, "dddd dd,mmm yyyy")
lblDayEnd.Text = "Day End date Range From "
lblDayEnd.Text = lblDayEnd.Text & lDateString
lDateString = Format(rs.Fields("toDate").Value, "dddd dd,mmm yyyy")
lblDayEnd.Text = lblDayEnd.Text & " to "
lblDayEnd.Text = lblDayEnd.Text & lDateString
lblDayEnd.Text = lblDayEnd.Text & " covering a dayend range of "
lblDayEnd.Text = lblDayEnd.Text & rs.Fields("count").Value & " days."
End If
End Sub
Private Sub cmdFilter_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdFilter.Click
frmFilter.loadFilter(gFilter)
frmFilter.buildCriteria(gFilter)
lblFilter.Text = frmFilter.gHeading
gFilterSQL = frmFilter.gCriteria
End Sub
Private Sub setup()
Dim lDate As Date
Dim rs As ADODB.Recordset
Dim lStart, lEnd As Integer
rs = getRS("SELECT * FROM MinMax WHERE (MinMaxID = 1)")
If rs.BOF Or rs.EOF Then
Else
lStart = rs.Fields("MinMax_DayEndIDStart").Value
lEnd = rs.Fields("MinMax_DayEndIDBack").Value
Me.txtMinimum.Text = rs.Fields("MinMax_Minimum").Value
Me.txtDays.Text = rs.Fields("MinMax_DaysForward").Value
rs.Close()
If lStart < 1 Then
Me.chkDynamic.CheckState = System.Windows.Forms.CheckState.Checked
rs = getRS("SELECT [Company].[Company_DayEndID]-(-1*[MinMax].[MinMax_DayEndIDStart]) AS id FROM Company, MinMax Where (MinMax.MinMaxID = 1)")
lStart = rs.Fields("id").Value - 1
Else
Me.chkDynamic.CheckState = System.Windows.Forms.CheckState.Unchecked
End If
rs = getRS("SELECT DayEnd_Date FROM DayEnd Where (DayEndID = " & lStart & ")")
If rs.RecordCount Then _MonthView1_1 = rs.Fields("DayEnd_Date").Value
rs = getRS("SELECT DayEnd_Date FROM DayEnd Where (DayEndID = " & lStart - lEnd + 1 & ")")
If rs.RecordCount Then
lDate = rs.Fields("DayEnd_Date").Value
_MonthView1_0 = rs.Fields("DayEnd_Date").Value
End If
End If
setDayEndRange()
End Sub
Private Sub frmOrderWizardFilter_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
If KeyAscii = 27 Then
KeyAscii = 0
save()
End If
eventArgs.KeyChar = Chr(KeyAscii)
If KeyAscii = 0 Then
eventArgs.Handled = True
End If
End Sub
Private Sub frmOrderWizardFilter_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
' Dim gDOMFilter As New DOMDocument
MonthView.AddRange(New MonthCalendar() {_MonthView1_0, _MonthView1_1})
Dim mc As New MonthCalendar
For Each mc In MonthView
AddHandler mc.Enter, AddressOf MonthView1_Enter
AddHandler mc.Leave, AddressOf MonthView1_Leave
AddHandler mc.DateChanged, AddressOf MonthView1_SelChange
Next
gFilter = "stockitem"
getNamespace()
loadLanguage()
setup()
End Sub
Private Sub MonthView1_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)
Dim mv As New MonthCalendar
mv = DirectCast(eventSender, MonthCalendar)
Dim Index As Integer = GetIndexer(mv, MonthView)
If Index Then
' MonthView1(1).MonthBackColor = RGB(255, 255, 255)
_MonthView1_1.BackColor = System.Drawing.ColorTranslator.FromOle(-2147483624)
Else
' MonthView1(0).MonthBackColor = RGB(255, 255, 255)
_MonthView1_0.BackColor = System.Drawing.ColorTranslator.FromOle(-2147483624)
End If
End Sub
Private Sub MonthView1_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)
Dim mv As New MonthCalendar
mv = DirectCast(eventSender, MonthCalendar)
Dim Index As Integer = GetIndexer(mv, MonthView)
' If Index Then
_MonthView1_1.BackColor = System.Drawing.ColorTranslator.FromOle(RGB(255, 255, 255))
' MonthView1(0).MonthBackColor = -2147483624
' Else
_MonthView1_0.BackColor = System.Drawing.ColorTranslator.FromOle(RGB(255, 255, 255))
' MonthView1(1).MonthBackColor = -2147483624
' End If
End Sub
Private Sub MonthView1_SelChange(ByVal eventSender As System.Object, ByVal eventArgs As DateRangeEventArgs)
'Dim Index As Short = MonthView1.GetIndex(eventSender)
setDayEndRange()
End Sub
Private Sub txtDays_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDays.Enter
MyGotFocusNumeric(txtDays)
End Sub
Private Sub txtDays_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtDays.KeyPress
Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
MyKeyPress(KeyAscii)
eventArgs.KeyChar = Chr(KeyAscii)
If KeyAscii = 0 Then
eventArgs.Handled = True
End If
End Sub
Private Sub txtDays_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtDays.Leave
MyLostFocus(txtDays, 0)
End Sub
Private Sub txtMinimum_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtMinimum.Enter
MyGotFocusNumeric(txtMinimum)
End Sub
Private Sub txtMinimum_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtMinimum.KeyPress
Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
MyKeyPress(KeyAscii)
eventArgs.KeyChar = Chr(KeyAscii)
If KeyAscii = 0 Then
eventArgs.Handled = True
End If
End Sub
Private Sub txtMinimum_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtMinimum.Leave
MyLostFocus(txtMinimum, 0)
End Sub
Private Sub getNamespace()
If gFilter = "" Then
Me.lblFilter.Text = ""
Else
frmFilter.buildCriteria(gFilter)
Me.lblFilter.Text = frmFilter.gHeading
End If
gFilterSQL = frmFilter.gCriteria
' doSearch
End Sub
End Class
|
nodoid/PointOfSale
|
VB/4PosBackOffice.NET/frmOrderWizardFilter.vb
|
Visual Basic
|
mit
| 12,410
|
Namespace Objects.Misc
Public Class ColorClass
Property MaxColors As Integer = 31
Property Colors As Color()
Public Sub New()
Me.Colors = New Color(MaxColors - 1) {}
For ii As Integer = 0 To MaxColors - 1
Select Case ii
Case 0
Me.Colors(ii) = Color.Aquamarine
Case 1
Me.Colors(ii) = Color.AntiqueWhite
Case 2
Me.Colors(ii) = Color.Chartreuse
Case 3
Me.Colors(ii) = Color.Crimson
Case 4
Me.Colors(ii) = Color.Gold
Case 5
Me.Colors(ii) = Color.GreenYellow
Case 6
Me.Colors(ii) = Color.Coral
Case 7
Me.Colors(ii) = Color.Ivory
Case 8
Me.Colors(ii) = Color.LightSeaGreen
Case 9
Me.Colors(ii) = Color.MintCream
Case 10
Me.Colors(ii) = Color.Turquoise
Case 11
Me.Colors(ii) = Color.WhiteSmoke
Case 12
Me.Colors(ii) = Color.SlateGray
Case 13
Me.Colors(ii) = Color.Salmon
Case 14
Me.Colors(ii) = Color.Sienna
Case 15
Me.Colors(ii) = Color.Violet
Case 16
Me.Colors(ii) = Color.Magenta
Case 17
Me.Colors(ii) = Color.LimeGreen
Case 18
Me.Colors(ii) = Color.PeachPuff
Case 19
Me.Colors(ii) = Color.MediumTurquoise
Case 20
Me.Colors(ii) = Color.Coral
Case 21
Me.Colors(ii) = Color.Cornsilk
Case 22
Me.Colors(ii) = Color.Purple
Case 23
Me.Colors(ii) = Color.MintCream
Case 24
Me.Colors(ii) = Color.MistyRose
Case 25
Me.Colors(ii) = Color.LightPink
Case 26
Me.Colors(ii) = Color.LightSteelBlue
Case 27
Me.Colors(ii) = Color.LightCyan
Case 28
Me.Colors(ii) = Color.LavenderBlush
Case 29
Me.Colors(ii) = Color.LightSkyBlue
Case 30
Me.Colors(ii) = Color.PaleGreen
Case 31
Me.Colors(ii) = Color.LightGray
End Select
Next
End Sub
End Class
End Namespace
|
wboxx1/85-EIS-PUMA
|
puma/src/Supporting Objects/Misc/ColorClass.vb
|
Visual Basic
|
mit
| 3,058
|
Imports System.ComponentModel
Imports System.Collections.ObjectModel
''' <summary>
'''
''' </summary>
''' <remarks>
''' Ein Spiel besteht aus den darin teilnehmenden Spielern, und den Ergebnissen die sie verbuchen konnten.
''' Jedes Ergebnis besteht aus 3 oder 5 Sätzen, und den Punkten die darin angehäuft wurden.
''' </remarks>
'''
<DebuggerDisplay("Runde = {RundenName}")>
Public Class SpielPartie
Inherits ObservableCollection(Of Satz)
Private ReadOnly Spieler As KeyValuePair(Of SpielerInfo, SpielerInfo)
Private ReadOnly _RundenName As String
Public ReadOnly Property RundenName As String
Get
Return _RundenName
End Get
End Property
Public Sub New(rundenName As String, ByVal spielerLinks As SpielerInfo, ByVal spielerRechts As SpielerInfo)
If spielerLinks Is Nothing Then Throw New ArgumentNullException
If spielerRechts Is Nothing Then Throw New ArgumentNullException
Spieler = New KeyValuePair(Of SpielerInfo, SpielerInfo)(spielerLinks, spielerRechts)
_RundenName = rundenName
AddHandler Me.CollectionChanged, Sub()
Me.OnPropertyChanged(New PropertyChangedEventArgs("MySelf"))
End Sub
End Sub
Public ReadOnly Property SpielerLinks As SpielerInfo
Get
Return Spieler.Key
End Get
End Property
Public ReadOnly Property SpielerRechts As SpielerInfo
Get
Return Spieler.Value
End Get
End Property
Public Property ZeitStempel As Date
Public ReadOnly Property MeinGegner(ByVal ich As SpielerInfo) As SpielerInfo
Get
If Spieler.Key = ich Then
Return Spieler.Value
Else
Return Spieler.Key
End If
End Get
End Property
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, SpielPartie)
If other Is Nothing Then Return False
If Me.SpielerLinks <> other.SpielerLinks Then Return False
If Me.SpielerRechts <> other.SpielerRechts Then Return False
If Me.RundenName <> other.RundenName Then Return False
Return True
End Function
Public Shared Operator <>(ByVal left As SpielPartie, ByVal right As SpielPartie) As Boolean
Return Not left = right
End Operator
Public Shared Operator =(ByVal left As SpielPartie, ByVal right As SpielPartie) As Boolean
Return left.Equals(right)
End Operator
Public ReadOnly Property MySelf As SpielPartie
Get
Return Me
End Get
End Property
Public Overrides Function GetHashCode() As Integer
Return SpielerLinks.GetHashCode Xor SpielerRechts.GetHashCode Xor RundenName.GetHashCode
End Function
Public Overrides Function ToString() As String
Return String.Format("{0} : {1}", SpielerLinks, SpielerRechts)
End Function
End Class
|
GoppeltM/PPC-Manager
|
Trunk/PPC Manager/PPC Manager/Model/SpielPartie.vb
|
Visual Basic
|
mit
| 3,007
|
Option Strict On
Option Explicit On
Friend Class frmNewSetup
Inherits System.Windows.Forms.Form
Public Overloads Function ShowDialog(ByVal name As String) As System.Windows.Forms.DialogResult
txtName.Text = name
Return MyBase.ShowDialog()
End Function
Private Sub cmdCancel_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdCancel.Click
Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.Close()
End Sub
Public ReadOnly Property GetName() As String
Get
Return txtName.Text.Trim
End Get
End Property
Private Sub cmdOK_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdOK.Click
Me.DialogResult = System.Windows.Forms.DialogResult.OK
Me.Hide()
End Sub
Private Sub txtName_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtName.KeyPress
Dim KeyAscii As Integer = Asc(eventArgs.KeyChar)
If KeyAscii = 34 Then KeyAscii = 0
eventArgs.KeyChar = Chr(KeyAscii)
If KeyAscii = 0 Then
eventArgs.Handled = True
End If
End Sub
End Class
|
JasonTitcomb/Basic_CNC_Viewer
|
CNCViewer/frmNewSetup.vb
|
Visual Basic
|
mit
| 1,254
|
NameSpace Models.DMSLOG
Partial Public Class DocLogNote
Inherits DMS.Base.Models.GenericEntity
#Region " Properties "
Public Overrides Property ID As String
Get
Return "{0}".FormatWith(DocLogNoteID)
End Get
Set(value as String)
DocLogNoteID=ToIntegerDB(value)
End Set
End Property
Private _DocID As Integer = -1 ' Column 1
Public Property DocID As Integer
Get
Return _DocID
End Get
Set(value as Integer)
SetProperty(_DocID,value,"DocID")
End Set
End Property
Private _DocLogNoteID As Integer = -1 ' Column 0
Public Property DocLogNoteID As Integer
Get
Return _DocLogNoteID
End Get
Set(value as Integer)
SetProperty(_DocLogNoteID,value,"DocLogNoteID",{"ID"})
End Set
End Property
Private _DocNumber As String = "" ' Column 5
Public Property DocNumber As String
Get
Return _DocNumber
End Get
Set(value as String)
SetProperty(_DocNumber,value,"DocNumber")
End Set
End Property
Private _ExtraNote As String = "" ' Column 11
Public Property ExtraNote As String
Get
Return _ExtraNote
End Get
Set(value as String)
SetProperty(_ExtraNote,value,"ExtraNote")
End Set
End Property
Private _LegacyStatus As String = "" ' Column 4
Public Property LegacyStatus As String
Get
Return _LegacyStatus
End Get
Set(value as String)
SetProperty(_LegacyStatus,value,"LegacyStatus")
End Set
End Property
Private _ModNote As String = "" ' Column 9
Public Property ModNote As String
Get
Return _ModNote
End Get
Set(value as String)
SetProperty(_ModNote,value,"ModNote")
End Set
End Property
Private _ModRef As String = "" ' Column 10
Public Property ModRef As String
Get
Return _ModRef
End Get
Set(value as String)
SetProperty(_ModRef,value,"ModRef")
End Set
End Property
Private _NoteDate As DateTime = Nothing ' Column 8
Public Property NoteDate As DateTime
Get
Return _NoteDate
End Get
Set(value as DateTime)
SetProperty(_NoteDate,value,"NoteDate")
End Set
End Property
Private _Revision As String = "" ' Column 6
Public Property Revision As String
Get
Return _Revision
End Get
Set(value as String)
SetProperty(_Revision,value,"Revision")
End Set
End Property
Private _Sheet As String = "" ' Column 7
Public Property Sheet As String
Get
Return _Sheet
End Get
Set(value as String)
SetProperty(_Sheet,value,"Sheet")
End Set
End Property
Private _StatusID As Integer = -1 ' Column 3
Public Property StatusID As Integer
Get
Return _StatusID
End Get
Set(value as Integer)
SetProperty(_StatusID,value,"StatusID")
End Set
End Property
Private _UserID As Integer = -1 ' Column 2
Public Property UserID As Integer
Get
Return _UserID
End Get
Set(value as Integer)
SetProperty(_UserID,value,"UserID")
End Set
End Property
#End Region
Public Async Function Delete(dbAccess as DMS.Base.Data.IDBAccess) As Task
Await Delete(dbAccess,Me)
End Function
Public Overrides Sub LoadFromEntity(genericEntity As DMS.Base.Models.GenericEntity)
If Me Is genericEntity Then
Return
End If
If Not (TypeOf (genericEntity) Is DocLogNote) Then
Return
End If
Dim Entity As DocLogNote = DirectCast(genericEntity, DocLogNote)
Me.DocLogNoteID = Entity.DocLogNoteID
Me.DocID = Entity.DocID
Me.UserID = Entity.UserID
Me.StatusID = Entity.StatusID
Me.LegacyStatus = Entity.LegacyStatus
Me.DocNumber = Entity.DocNumber
Me.Revision = Entity.Revision
Me.Sheet = Entity.Sheet
Me.NoteDate = Entity.NoteDate
Me.ModNote = Entity.ModNote
Me.ModRef = Entity.ModRef
Me.ExtraNote = Entity.ExtraNote
End Sub
Public Overrides Sub LoadFromReader(reader As IDataReader)
Me.DocLogNoteID = ToIntegerDB(reader(0))
Me.DocID = ToIntegerDB(reader(1))
Me.UserID = ToIntegerDB(reader(2))
Me.StatusID = ToIntegerDB(reader(3))
Me.LegacyStatus = ToStringDB(reader(4))
Me.DocNumber = ToStringDB(reader(5))
Me.Revision = ToStringDB(reader(6))
Me.Sheet = ToStringDB(reader(7))
Me.NoteDate = ToDateTimeDB(reader(8))
Me.ModNote = ToStringDB(reader(9))
Me.ModRef = ToStringDB(reader(10))
Me.ExtraNote = ToStringDB(reader(11))
End Sub
Public Overrides Sub PopulateDataRow(ByRef dataRow As System.Data.DataRow)
dataRow.Item(0) = Me.DocLogNoteID
dataRow.Item(1) = Me.DocID
dataRow.Item(2) = Me.UserID
dataRow.Item(3) = Me.StatusID
dataRow.Item(4) = Me.LegacyStatus
dataRow.Item(5) = Me.DocNumber
dataRow.Item(6) = Me.Revision
dataRow.Item(7) = Me.Sheet
dataRow.Item(8) = Me.NoteDate
dataRow.Item(9) = Me.ModNote
dataRow.Item(10) = Me.ModRef
dataRow.Item(11) = Me.ExtraNote
End Sub
Public Async Function Upsert(dbAccess As DMS.Base.Data.IDBAccess) As Task
Await Upsert(dbAccess, Me)
End Function
Public Overrides Function GetParameters() As IDictionary(Of String, Object)
Dim Results As New Dictionary(Of String, Object)
Results.Add("DocLogNoteID", Me.DocLogNoteID)
Results.Add("DocID", Me.DocID)
Results.Add("UserID", Me.UserID)
Results.Add("StatusID", Me.StatusID)
Results.Add("LegacyStatus", Me.LegacyStatus)
Results.Add("DocNumber", Me.DocNumber)
Results.Add("Revision", Me.Revision)
Results.Add("Sheet", Me.Sheet)
Results.Add("NoteDate", Me.NoteDate)
Results.Add("ModNote", Me.ModNote)
Results.Add("ModRef", Me.ModRef)
Results.Add("ExtraNote", Me.ExtraNote)
Return Results
End Function
#Region " Shared "
Private Shared _DBDetails As DMS.Base.Models.DBDetails = Nothing
Public Shared Async Function Delete(dbAccess As DMS.Base.Data.IDBAccess, entities As IEnumerable(Of DocLogNote)) As Task
Dim Tasks As New List(Of Task)
For Each Entity As DocLogNote In entities
Tasks.Add(Delete(dbAccess, Entity))
Next
Await Task.WhenAll(Tasks)
End Function
Public Shared Async Function Delete(dbAccess As DMS.Base.Data.IDBAccess, entity As DocLogNote) As Task
Await dbAccess.ExecuteNonQuery(GetDBDetails.Delete, entity.GetParameters())
End Function
Public Shared Async Function Upsert(dbAccess As DMS.Base.Data.IDBAccess, entities As IEnumerable(Of DocLogNote)) As Task
If entities.Count = 1 Then
Await Upsert(dbAccess, entities.FirstOrDefault())
Else
Dim DBDetails As DMS.Base.Models.DBDetails = GetDBDetails()
Using DataTable As DataTable = GetDataTable()
For Each Entity As DocLogNote In entities
Dim DataRow As DataRow = DataTable.NewRow
Entity.PopulateDataRow(DataRow)
DataTable.Rows.Add(DataRow)
Next
Await dbAccess.Merge(DBDetails.CreateTemp, DBDetails.DropTemp, DataTable, DBDetails.Merge, DBDetails.TableName)
End Using
End If
End Function
Public Shared Async Function Upsert(dbAccess As DMS.Base.Data.IDBAccess, entity As DocLogNote) As Task
Dim Parameters As IDictionary(Of String, Object) = entity.GetParameters()
If String.IsNullOrEmpty(entity.ID) OrElse entity.ID.Equals("-1") OrElse ToIntegerDB(Await dbAccess.ExecuteScalar(GetDBDetails.CountSingle, Parameters)) <= 0 Then
entity.DocLogNoteID = ToIntegerDB(Await dbAccess.ExecuteScalar(GetDBDetails.Insert, Parameters))
Else
Await dbAccess.ExecuteNonQuery(GetDBDetails.Update, Parameters)
End If
End Function
Public Shared Async Function GetAll(dbAccess As DMS.Base.Data.IDBAccess) As Threading.Tasks.Task(Of IEnumerable(Of DocLogNote))
Return Await dbAccess.ExecuteReader(Of DocLogNote)(GetDBDetails.SelectAll)
End Function
Public Shared Function GetDataTable() As DataTable
Dim DataTable As New DataTable
DataTable.Columns.Add("DocLogNoteID")
DataTable.Columns.Add("DocID")
DataTable.Columns.Add("UserID")
DataTable.Columns.Add("StatusID")
DataTable.Columns.Add("LegacyStatus")
DataTable.Columns.Add("DocNumber")
DataTable.Columns.Add("Revision")
DataTable.Columns.Add("Sheet")
DataTable.Columns.Add("NoteDate")
DataTable.Columns.Add("ModNote")
DataTable.Columns.Add("ModRef")
DataTable.Columns.Add("ExtraNote")
Return DataTable
End Function
Public Shared Function GetDBDetails() As DMS.Base.Models.DBDetails
If _DBDetails Is Nothing Then
_DBDetails = New DMS.Base.Models.DBDetails
_DBDetails.CountAll = "SELECT COUNT(*) FROM [DocLogNotes]"
_DBDetails.CountSingle = "SELECT COUNT(*) FROM [DocLogNotes] WHERE (([DocLogNoteID]=@DocLogNoteID))"
_DBDetails.CreateTemp = "CREATE TABLE #DocLogNotes ([DocLogNoteID] [int] NULL,[DocID] [int] NULL,[UserID] [int] NULL,[StatusID] [int] NULL,[LegacyStatus] [varchar](255) NULL,[DocNumber] [varchar](255) NULL,[Revision] [varchar](50) NULL,[Sheet] [varchar](50) NULL,[NoteDate] [datetime] NULL,[ModNote] [varchar](255) NULL,[ModRef] [varchar](255) NULL,[ExtraNote] [text] NULL)"
_DBDetails.Delete = "DELETE FROM [DocLogNotes] WHERE (([DocLogNoteID]=@DocLogNoteID))"
_DBDetails.DropTemp = "DROP TABLE #DocLogNotes"
_DBDetails.GetDataTable = New DMS.Base.Delegates.GetDataTable(AddressOf GetDataTable)
_DBDetails.Insert = "INSERT INTO [DocLogNotes] ([DocID],[UserID],[StatusID],[LegacyStatus],[DocNumber],[Revision],[Sheet],[NoteDate],[ModNote],[ModRef],[ExtraNote]) OUTPUT Inserted.[DocLogNoteID] VALUES (@DocID,@UserID,@StatusID,@LegacyStatus,@DocNumber,@Revision,@Sheet,@NoteDate,@ModNote,@ModRef,@ExtraNote)"
_DBDetails.Merge = "MERGE INTO [DocLogNotes] As [Target] USING #DocLogNotes As [Source] ON [Target].[DocLogNoteID]=[Source].[DocLogNoteID] WHEN MATCHED THEN UPDATE SET [Target].[DocID]=[Source].[DocID],[Target].[UserID]=[Source].[UserID],[Target].[StatusID]=[Source].[StatusID],[Target].[LegacyStatus]=[Source].[LegacyStatus],[Target].[DocNumber]=[Source].[DocNumber],[Target].[Revision]=[Source].[Revision],[Target].[Sheet]=[Source].[Sheet],[Target].[NoteDate]=[Source].[NoteDate],[Target].[ModNote]=[Source].[ModNote],[Target].[ModRef]=[Source].[ModRef],[Target].[ExtraNote]=[Source].[ExtraNote] WHEN NOT MATCHED THEN INSERT ([DocID],[UserID],[StatusID],[LegacyStatus],[DocNumber],[Revision],[Sheet],[NoteDate],[ModNote],[ModRef],[ExtraNote]) VALUES ([Source].[DocID],[Source].[UserID],[Source].[StatusID],[Source].[LegacyStatus],[Source].[DocNumber],[Source].[Revision],[Source].[Sheet],[Source].[NoteDate],[Source].[ModNote],[Source].[ModRef],[Source].[ExtraNote]);"
_DBDetails.ModelName = "DocLogNote"
_DBDetails.SelectAll = "SELECT [DocLogNoteID],[DocID],[UserID],[StatusID],[LegacyStatus],[DocNumber],[Revision],[Sheet],[NoteDate],[ModNote],[ModRef],[ExtraNote] FROM [DocLogNotes]"
_DBDetails.TableName = "DocLogNotes"
_DBDetails.Update = "UPDATE [DocLogNotes] SET [DocID]=@DocID,[UserID]=@UserID,[StatusID]=@StatusID,[LegacyStatus]=@LegacyStatus,[DocNumber]=@DocNumber,[Revision]=@Revision,[Sheet]=@Sheet,[NoteDate]=@NoteDate,[ModNote]=@ModNote,[ModRef]=@ModRef,[ExtraNote]=@ExtraNote WHERE (([DocLogNoteID]=@DocLogNoteID))"
End If
Return _DBDetails
End Function
#End Region
End Class
End Namespace
|
nublet/DMS
|
DMS.Base/Models/DMSLOG/Base/DocLogNote.vb
|
Visual Basic
|
mit
| 11,041
|
Imports System.Data
Imports System.Data.SqlClient
Partial Class moderators_membershemade
Inherits System.Web.UI.Page
Public cf As New comonfunctions
Private Sub PopulatePublishersGridView()
Dim connectionString As String = cf.friendshipdb
Dim accessConnection As SqlConnection = New SqlConnection(connectionString)
Dim sqlQuery As String = ""
sqlQuery = "select distinct profile.pid,profile.profiledate,email,profile.passw,fname,lname,bdate,purpose,gender,ethnic,religion,caste,profile.countryname,whoami, profile.state, profile.cityid,photoname,ipaddress from profile left join photo on profile.pid=photo.pid where " & makequery()
sqlQuery = sqlQuery & " order by Profiledate desc"
Dim accessCommand As New SqlCommand(sqlQuery, accessConnection)
Dim publishersDataAdapter As New SqlDataAdapter(accessCommand)
Dim publishersDataTable As New DataTable("profile")
publishersDataAdapter.Fill(publishersDataTable)
Dim dataTableRowCount As Integer = publishersDataTable.Rows.Count
If dataTableRowCount > 0 Then
gridViewPublishers.DataSource = publishersDataTable
gridViewPublishers.DataBind()
Else
label1.Text = "No Profiles Found"
End If
accessConnection.Close()
End Sub
Private Property GridViewSortDirection() As String
Get
Return IIf(ViewState("SortDirection") = Nothing, "ASC", ViewState("SortDirection"))
End Get
Set(ByVal value As String)
ViewState("SortDirection") = value
End Set
End Property
Private Property GridViewSortExpression() As String
Get
Return IIf(ViewState("SortExpression") = Nothing, String.Empty, ViewState("SortExpression"))
End Get
Set(ByVal value As String)
ViewState("SortExpression") = value
End Set
End Property
Private Function GetSortDirection() As String
Select Case GridViewSortDirection
Case "ASC"
GridViewSortDirection = "DESC"
Case "DESC"
GridViewSortDirection = "ASC"
End Select
Return GridViewSortDirection
End Function
Protected Sub gridViewPublishers_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
'gridViewPublishers.DataSource = SortDataTable(CType(gridViewPublishers.DataSource, DataTable), True)
gridViewPublishers.PageIndex = e.NewPageIndex
PopulatePublishersGridView()
'gridViewPublishers.DataBind()
End Sub
Protected Function SortDataTable(ByVal pdataTable As DataTable, ByVal isPageIndexChanging As Boolean) As DataView
If Not pdataTable Is Nothing Then
Dim pdataView As New DataView(pdataTable)
If GridViewSortExpression <> String.Empty Then
If isPageIndexChanging Then
pdataView.Sort = String.Format("{0} {1}", GridViewSortExpression, GridViewSortDirection)
Else
pdataView.Sort = String.Format("{0} {1}", GridViewSortExpression, GetSortDirection())
End If
End If
Return pdataView
Else
Return New DataView()
End If
End Function
Protected Sub gridViewPublishers_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
GridViewSortExpression = e.SortExpression
Dim pageIndex As Integer = gridViewPublishers.PageIndex
gridViewPublishers.DataSource = SortDataTable(CType(gridViewPublishers.DataSource, DataTable), False)
gridViewPublishers.DataBind()
gridViewPublishers.PageIndex = pageIndex
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
'If Page.IsPostBack = True Then
'Else
'End If
End Sub
Function makequery() As String
'Dim country, sqlcountry, state, sqlstate, city, sqlcity As String
makequery = " approved='Y' and profile.pid in (Select referd from topearners where mid=" & Request.QueryString("pid") & ") and pstatus='" & Request.QueryString("pstatus") & "'" 'ref1='" & Request.QueryString("pid") & "'
End Function
Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
'If checklogin() = False Then
' Response.Redirect("~/modlogin.aspx")
' Exit Sub
'End If
If Page.IsPostBack = False Then
PopulatePublishersGridView()
End If
End Sub
End Class
|
aminnagpure/matrimonydatingcommunity1.0
|
lovenmarry - EmptyFreeCode/moderators/membershemade.aspx.vb
|
Visual Basic
|
mit
| 4,743
|
'
' News Articles for DotNetNuke - http://www.dotnetnuke.com
' Copyright (c) 2002-2007
' by Ventrian ( sales@ventrian.com ) ( http://www.ventrian.com )
'
Imports System.IO
Imports System.Net
Imports System.Text.RegularExpressions
Namespace Ventrian.NewsArticles.Tracking
Public Class TrackBackProxy
#Region " Public Methods "
Public Function TrackBackPing(ByVal pageText As String, ByVal url As String, ByVal title As String, ByVal link As String, ByVal blogname As String, ByVal description As String) As Boolean
Dim objLogController As New DotNetNuke.Services.Log.EventLog.EventLogController
Dim objEventLog As New DotNetNuke.Services.Log.EventLog.EventLogController
' objEventLog.AddLog("Ping Exception", "Ping with a Return URL of ->" & link, DotNetNuke.Common.Globals.GetPortalSettings(), -1, DotNetNuke.Services.Log.EventLog.EventLogController.EventLogType.ADMIN_ALERT)
Dim trackBackItem As String = GetTrackBackText(pageText, url, link)
If Not trackBackItem Is Nothing Then
If Not trackBackItem.ToLower().StartsWith("http://") Then
trackBackItem = "http://" + trackBackItem
End If
Dim parameters As String = "title=" + HtmlEncode(title) + "&url=" + HtmlEncode(link) + "&blog_name=" + HtmlEncode(blogname) + "&excerpt=" + HtmlEncode(description)
SendPing(trackBackItem, parameters)
Else
' objEventLog.AddLog("Ping Exception", "Pinging ->" & link & " -> Trackback Text not found on this page!", DotNetNuke.Common.Globals.GetPortalSettings(), -1, DotNetNuke.Services.Log.EventLog.EventLogController.EventLogType.ADMIN_ALERT)
End If
Return True
End Function
#End Region
#Region " Private Methods "
Private Function GetTrackBackText(ByVal pageText As String, ByVal url As String, ByVal PostUrl As String) As String
If Not Regex.IsMatch(pageText, PostUrl, RegexOptions.IgnoreCase Or RegexOptions.Singleline) Then
Dim sPattern As String = "<rdf:\w+\s[^>]*?>(</rdf:rdf>)?"
Dim r As Regex = New Regex(sPattern, RegexOptions.IgnoreCase)
Dim m As Match
m = r.Match(pageText)
While (m.Success)
If m.Groups.ToString().Length > 0 Then
Dim text As String = m.Groups(0).ToString()
If text.IndexOf(url) > 0 Then
Dim tbPattern As String = "trackback:ping=\""([^\""]+)\"""
Dim reg As Regex = New Regex(tbPattern, RegexOptions.IgnoreCase)
Dim m2 As Match = reg.Match(text)
If m2.Success Then
Return m2.Result("$1")
End If
Return text
End If
End If
m = m.NextMatch
End While
End If
Return Nothing
End Function
Private Function HtmlEncode(ByVal text As String) As String
Return System.Web.HttpUtility.HtmlEncode(text)
End Function
Private Sub SendPing(ByVal trackBackItem As String, ByVal parameters As String)
Dim myWriter As StreamWriter = Nothing
Dim request As HttpWebRequest = CType(HttpWebRequest.Create(trackBackItem), HttpWebRequest)
If Not (request Is Nothing) Then
request.UserAgent = "My User Agent String"
request.Referer = "http://www.smcculloch.net/"
request.Timeout = 60000
End If
request.Method = "POST"
request.ContentLength = parameters.Length
request.ContentType = "application/x-www-form-urlencoded"
request.KeepAlive = False
' Try
myWriter = New StreamWriter(request.GetRequestStream())
myWriter.Write(parameters)
'Finally
myWriter.Close()
' End Try
End Sub
#End Region
End Class
End Namespace
|
ventrian/News-Articles
|
Components/Tracking/TrackBackProxy.vb
|
Visual Basic
|
mit
| 4,313
|
Option Strict On
Option Explicit On
Imports ananse
Public Class ClassParser
Inherits AstNodeParser
Public Overrides ReadOnly Property lookAhead As Token
Get
Return Token.CLASS_KEYWORD
End Get
End Property
Public Overrides Function parse() As AstNode
parser.getNextToken()
parser.match(Token.IDENTIFIER)
End Function
End Class
|
ananse/ananse
|
src/ast/parsers/ClassParser.vb
|
Visual Basic
|
mit
| 396
|
Imports System.Data
Partial Class rVendedores_Clientes
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.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1))
Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2))
Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2))
Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3))
Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3))
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim loComandoSeleccionar As New StringBuilder()
loComandoSeleccionar.AppendLine("SELECT Vendedores.Cod_Ven, " )
loComandoSeleccionar.AppendLine(" Vendedores.Nom_Ven, " )
loComandoSeleccionar.AppendLine(" Clientes.Telefonos, " )
loComandoSeleccionar.AppendLine(" Vendedores.Cod_Tip, " )
loComandoSeleccionar.AppendLine(" Clientes.Fax, " )
loComandoSeleccionar.AppendLine(" Clientes.Cod_Zon, " )
loComandoSeleccionar.AppendLine(" Clientes.Cod_Cli, " )
loComandoSeleccionar.AppendLine(" Clientes.Nom_Cli, " )
loComandoSeleccionar.AppendLine(" Zonas.Nom_Zon, " )
loComandoSeleccionar.AppendLine(" Tipos_Vendedores.Nom_Tip " )
loComandoSeleccionar.AppendLine("FROM Vendedores, " )
loComandoSeleccionar.AppendLine(" Tipos_Vendedores, " )
loComandoSeleccionar.AppendLine(" Zonas, " )
loComandoSeleccionar.AppendLine(" Clientes " )
loComandoSeleccionar.AppendLine("WHERE Vendedores.Cod_Tip = Tipos_Vendedores.Cod_Tip " )
loComandoSeleccionar.AppendLine(" AND Vendedores.Cod_Zon = Zonas.Cod_Zon " )
loComandoSeleccionar.AppendLine(" AND Vendedores.Cod_Ven = Clientes.Cod_Ven " )
loComandoSeleccionar.AppendLine(" AND Vendedores.Cod_Ven between " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Vendedores.status IN (" & lcParametro1Desde & ")")
loComandoSeleccionar.AppendLine(" AND Vendedores.Cod_Tip between " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Vendedores.Cod_Zon between " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine("ORDER BY " & lcOrdenamiento)
'loComandoSeleccionar.AppendLine(" ORDER BY Vendedores.Cod_Ven, Vendedores.Nom_Ven")
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes")
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rVendedores_Clientes", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrVendedores_Clientes.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 : 10/07/08 : Codigo inicial
'-------------------------------------------------------------------------------------------'
' MVP : 11/07/08 : Adición de loObjetoReporte para eliminar los archivos temp en Uranus
'-------------------------------------------------------------------------------------------'
' MVP: 04/08/08: Cambios para multi idioma, mensaje de error y clase padre.
'-------------------------------------------------------------------------------------------'
' GCR: 02/04/09: Estandarizacion de código y ajustes al diseño.
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
rVendedores_Clientes.aspx.vb
|
Visual Basic
|
mit
| 5,162
|
Public Interface IInterruptController
Function GetPendingInterrupt() As Byte
End Interface
|
morphx666/x8086NetEmu
|
x8086NetEmu/Helpers/Misc/IInterruptController.vb
|
Visual Basic
|
mit
| 98
|
'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.Resources
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
<Assembly: AssemblyTitle("ApplicativeAlgorithmsPage")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("ESRI Cartonet")>
<Assembly: AssemblyProduct("ApplicativeAlgorithmsPage")>
<Assembly: AssemblyCopyright("Copyright © ESRI Cartonet 2008")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(True)>
<Assembly: Guid("9310FCB0-F62C-480B-BAF3-C4A78CD92C64")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
<Assembly: NeutralResourcesLanguageAttribute("en-US")>
|
Esri/arcobjects-sdk-community-samples
|
Net/Schematics/SchematicLayoutAlgoSample/VBNet/ApplicativeAlgorithmsPage/My Project/AssemblyInfo.vb
|
Visual Basic
|
apache-2.0
| 1,194
|
' 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.Concurrent
Imports System.Collections.Immutable
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.Instrumentation
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend NotInheritable Class MethodCompiler
Inherits VisualBasicSymbolVisitor
Private ReadOnly _compilation As VisualBasicCompilation
Private ReadOnly _cancellationToken As CancellationToken
Private ReadOnly _generateDebugInfo As Boolean
Private ReadOnly _diagnostics As DiagnosticBag
Private ReadOnly _hasDeclarationErrors As Boolean
Private ReadOnly _namespaceScopeBuilder As NamespaceScopeBuilder
Private ReadOnly _moduleBeingBuiltOpt As PEModuleBuilder ' Nothing if compiling for diagnostics
Private ReadOnly _filterOpt As Predicate(Of Symbol) ' If not Nothing, limit analysis to specific symbols
Private ReadOnly _debugDocumentProvider As DebugDocumentProvider
' GetDiagnostics only needs to Bind. If we need to go further, _doEmitPhase needs to be set.
' It normally happens during actual compile, but also happens when getting emit diagnostics for
' testing purposes.
Private ReadOnly _doEmitPhase As Boolean
' MethodCompiler employs concurrency by following flattened fork/join pattern.
'
' For every item that we want to compile in parallel a new task is forked.
' compileTaskQueue is used to track and observe all the tasks.
' Once compileTaskQueue is empty, we know that there are no more tasks (and no more can be created)
' and that means we are done compiling. WaitForWorkers ensures this condition.
'
' Note that while tasks may fork more tasks (nested types, lambdas, whatever else that may introduce more types),
' we do not want any child/parent relationship between spawned tasks and their creators.
' Creator has no real dependencies on the completion of its children and should finish and release any resources
' as soon as it can regardless of the tasks it may have spawned.
'
' Stack is used so that the wait would observe the most recently added task and have
' more chances to do inlined execution.
Private compilerTasks As ConcurrentStack(Of Task)
' Tracks whether any method body has hasErrors set, and used to avoid
' emitting if there are errors without corresponding diagnostics.
' NOTE: once the flag is set to true, it should never go back to false!!!
Private _globalHasErrors As Boolean
Private ReadOnly Property GlobalHasErrors As Boolean
Get
Return _globalHasErrors
End Get
End Property
Private Sub SetGlobalErrorIfTrue(arg As Boolean)
' NOTE: this is not a volatile write
' for correctness we need only single threaded consistency.
' Within a single task - if we have got an error it may not be safe to continue with some lowerings.
' It is ok if other tasks will see the change after some delay or does not observe at all.
' Such races are unavoidable and will just result in performing some work that is safe to do
' but may no longer be needed.
' The final Join of compiling tasks cannot happen without interlocked operations and that
' will that the final state of the flag is synchronized after we are done compiling.
If arg Then
_globalHasErrors = True
End If
End Sub
' moduleBeingBuilt can be Nothing in order to just analyze methods for errors.
Private Sub New(compilation As VisualBasicCompilation,
moduleBeingBuiltOpt As PEModuleBuilder,
generateDebugInfo As Boolean,
doEmitPhase As Boolean,
hasDeclarationErrors As Boolean,
diagnostics As DiagnosticBag,
filter As Predicate(Of Symbol),
cancellationToken As CancellationToken)
Me._compilation = compilation
Me._moduleBeingBuiltOpt = moduleBeingBuiltOpt
Me._diagnostics = diagnostics
Me._hasDeclarationErrors = hasDeclarationErrors
Me._cancellationToken = cancellationToken
Me._doEmitPhase = doEmitPhase
Me._generateDebugInfo = generateDebugInfo
Me._filterOpt = filter
If generateDebugInfo Then
Me._debugDocumentProvider = Function(path As String, basePath As String) moduleBeingBuiltOpt.GetOrAddDebugDocument(path, basePath, AddressOf CreateDebugDocumentForFile)
End If
If compilation.Options.ConcurrentBuild Then
Me.compilerTasks = New ConcurrentStack(Of Task)()
End If
End Sub
Private Shared Function IsDefinedOrImplementedInSourceTree(symbol As Symbol, tree As SyntaxTree, span As TextSpan?) As Boolean
If symbol.IsDefinedInSourceTree(tree, span) Then
Return True
End If
Dim method = TryCast(symbol, SourceMemberMethodSymbol)
If method IsNot Nothing AndAlso
method.IsPartialDefinition Then
Dim implementationPart = method.PartialImplementationPart
If implementationPart IsNot Nothing Then
Return implementationPart.IsDefinedInSourceTree(tree, span)
End If
End If
If symbol.Kind = SymbolKind.Method AndAlso symbol.IsImplicitlyDeclared AndAlso
DirectCast(symbol, MethodSymbol).MethodKind = MethodKind.Constructor Then
' Include implicitly declared constructor if containing type is included
Return IsDefinedOrImplementedInSourceTree(symbol.ContainingType, tree, span)
End If
Return False
End Function
''' <summary>
''' Completes binding and performs analysis of bound trees for the purpose of obtaining diagnostics.
'''
''' NOTE: This method does not perform lowering/rewriting/emit.
''' Errors from those stages require complete compile,
''' but generally are not interesting during editing.
'''
''' NOTE: the bound tree produced by this method are not stored anywhere
''' and immediately lost after diagnostics of a particular tree is done.
'''
''' </summary>
Public Shared Sub GetCompileDiagnostics(compilation As VisualBasicCompilation,
root As NamespaceSymbol,
tree As SyntaxTree,
filterSpanWithinTree As TextSpan?,
hasDeclarationErrors As Boolean,
diagnostics As DiagnosticBag,
doEmitPhase As Boolean,
cancellationToken As CancellationToken)
Dim filter As Predicate(Of Symbol) = Nothing
If tree IsNot Nothing Then
filter = Function(sym) IsDefinedOrImplementedInSourceTree(sym, tree, filterSpanWithinTree)
End If
Dim compiler = New MethodCompiler(compilation,
moduleBeingBuiltOpt:=Nothing,
generateDebugInfo:=False,
doEmitPhase:=doEmitPhase,
hasDeclarationErrors:=hasDeclarationErrors,
diagnostics:=diagnostics,
filter:=filter,
cancellationToken:=cancellationToken)
root.Accept(compiler)
If tree Is Nothing Then
' include entry point diagnostics if we are compiling the entire compilation, not just a single tree:
Dim entryPointAndDiagnostics = compilation.GetEntryPointAndDiagnostics(cancellationToken)
If entryPointAndDiagnostics IsNot Nothing Then
diagnostics.AddRange(entryPointAndDiagnostics.Diagnostics)
End If
End If
compiler.WaitForWorkers()
End Sub
''' <summary>
''' Compiles given compilation into provided module.
'''
''' NOTE: it is ok for moduleBeingBuiltOpt to be Nothing.
''' In such case the only results of this method would be diagnostics for complete compile.
'''
''' NOTE: the bound/lowered trees produced by this method are not stored anywhere and
''' immediately lost after obtaining method bodies and diagnostics for a particular
''' tree.
''' </summary>
Friend Shared Sub CompileMethodBodies(compilation As VisualBasicCompilation,
moduleBeingBuiltOpt As PEModuleBuilder,
generateDebugInfo As Boolean,
hasDeclarationErrors As Boolean,
filter As Predicate(Of Symbol),
diagnostics As DiagnosticBag,
Optional cancellationToken As CancellationToken = Nothing)
Using Logger.LogBlock(FunctionId.VisualBasic_Compiler_CompileMethodBodies, message:=compilation.AssemblyName, cancellationToken:=cancellationToken)
If compilation.PreviousSubmission IsNot Nothing Then
' In case there is a previous submission, we should ensure
' it has already created anonymous type/delegates templates
' NOTE: if there are any errors, we will pick up what was created anyway
compilation.PreviousSubmission.EnsureAnonymousTypeTemplates(cancellationToken)
' TODO: revise to use a loop instead of a recursion
End If
#If DEBUG Then
compilation.EmbeddedSymbolManager.AssertMarkAllDeferredSymbolsAsReferencedIsCalled()
#End If
Dim compiler = New MethodCompiler(compilation,
moduleBeingBuiltOpt,
generateDebugInfo,
doEmitPhase:=True,
hasDeclarationErrors:=hasDeclarationErrors,
diagnostics:=diagnostics,
filter:=filter,
cancellationToken:=cancellationToken)
compilation.SourceModule.GlobalNamespace.Accept(compiler)
compiler.WaitForWorkers()
If moduleBeingBuiltOpt IsNot Nothing Then
Dim additionalTypes = moduleBeingBuiltOpt.GetAdditionalTopLevelTypes()
If Not additionalTypes.IsEmpty Then
compiler.CompileSynthesizedMethods(additionalTypes)
End If
compilation.AnonymousTypeManager.AssignTemplatesNamesAndCompile(compiler, moduleBeingBuiltOpt, diagnostics)
compiler.WaitForWorkers()
' Process symbols from embedded code if needed.
If compilation.EmbeddedSymbolManager.Embedded <> EmbeddedSymbolKind.None Then
compiler.ProcessEmbeddedMethods()
End If
Dim privateImplClass = moduleBeingBuiltOpt.PrivateImplClass
If privateImplClass IsNot Nothing Then
' all threads that were adding methods must be finished now, we can freeze the class:
privateImplClass.Freeze()
compiler.CompileSynthesizedMethods(privateImplClass)
End If
End If
Dim entryPoint = GetEntryPoint(compilation, moduleBeingBuiltOpt, diagnostics, cancellationToken)
If moduleBeingBuiltOpt IsNot Nothing Then
moduleBeingBuiltOpt.SetEntryPoint(entryPoint)
If compiler.GlobalHasErrors AndAlso Not hasDeclarationErrors AndAlso Not diagnostics.HasAnyErrors Then
' If there were errors but no diagnostics, explicitly add
' a "Failed to emit module" error to prevent emitting.
diagnostics.Add(ERRID.ERR_ModuleEmitFailure, NoLocation.Singleton, moduleBeingBuiltOpt.SourceModule.Name)
End If
End If
End Using
End Sub
Friend Shared Function GetEntryPoint(compilation As VisualBasicCompilation,
moduleBeingBuilt As PEModuleBuilder,
diagnostics As DiagnosticBag,
cancellationToken As CancellationToken) As MethodSymbol
Dim options As VisualBasicCompilationOptions = compilation.Options
If Not options.OutputKind.IsApplication() Then
Debug.Assert(compilation.GetEntryPointAndDiagnostics(Nothing) Is Nothing)
If compilation.IsSubmission Then
Dim submissionReturnType As TypeSymbol = compilation.GetSubmissionReturnType()
Return DefineScriptEntryPoint(compilation, moduleBeingBuilt, submissionReturnType, diagnostics)
End If
Return Nothing
End If
Debug.Assert(Not compilation.IsSubmission)
Debug.Assert(options.OutputKind.IsApplication())
Dim entryPointAndDiagnostics = compilation.GetEntryPointAndDiagnostics(cancellationToken)
Debug.Assert(entryPointAndDiagnostics IsNot Nothing)
Debug.Assert(Not entryPointAndDiagnostics.Diagnostics.IsDefault)
diagnostics.AddRange(entryPointAndDiagnostics.Diagnostics)
If compilation.ScriptClass IsNot Nothing Then
Debug.Assert(entryPointAndDiagnostics.MethodSymbol Is Nothing)
Return DefineScriptEntryPoint(compilation, moduleBeingBuilt, compilation.GetSpecialType(SpecialType.System_Void), diagnostics)
End If
Debug.Assert(entryPointAndDiagnostics.MethodSymbol IsNot Nothing OrElse entryPointAndDiagnostics.Diagnostics.HasAnyErrors() OrElse Not compilation.Options.Errors.IsDefaultOrEmpty)
Return entryPointAndDiagnostics.MethodSymbol
End Function
Friend Shared Function DefineScriptEntryPoint(compilation As VisualBasicCompilation, moduleBeingBuilt As PEModuleBuilder, returnType As TypeSymbol, diagnostics As DiagnosticBag) As MethodSymbol
Dim scriptEntryPoint = New SynthesizedEntryPointSymbol(compilation.ScriptClass, returnType)
If moduleBeingBuilt IsNot Nothing AndAlso Not diagnostics.HasAnyErrors Then
Dim compilationState = New TypeCompilationState(compilation, moduleBeingBuilt, initializeComponentOpt:=Nothing)
Dim body = scriptEntryPoint.CreateBody()
Dim emittedBody = GenerateMethodBody(moduleBeingBuilt,
scriptEntryPoint,
body,
stateMachineTypeOpt:=Nothing,
variableSlotAllocatorOpt:=Nothing,
debugDocumentProvider:=Nothing,
diagnostics:=diagnostics,
generateDebugInfo:=False)
moduleBeingBuilt.SetMethodBody(scriptEntryPoint, emittedBody)
moduleBeingBuilt.AddSynthesizedDefinition(compilation.ScriptClass, scriptEntryPoint)
End If
Return scriptEntryPoint
End Function
Private Sub WaitForWorkers()
Dim tasks As ConcurrentStack(Of Task) = Me.compilerTasks
If tasks Is Nothing Then
Return
End If
Dim curTask As Task = Nothing
While tasks.TryPop(curTask)
curTask.GetAwaiter().GetResult()
End While
End Sub
#Region "Embedded symbols processing"
Private Sub ProcessEmbeddedMethods()
Dim manager = _compilation.EmbeddedSymbolManager
Dim processedSymbols As New ConcurrentSet(Of Symbol)(ReferenceEqualityComparer.Instance)
Dim methodOrdinal = 0
Dim builder = ArrayBuilder(Of Symbol).GetInstance
Do
' We iterate all the symbols for embedded code that are CURRENTLY known
' to be referenced by user code or already emitted embedded code.
'
' If this the first full emit of the current compilation and there are no
' concurrent emits this collection will consist of embedded symbols referenced
' from attributes on compilation source symbols (by directly using embedded
' attributes OR referencing embedded types from attributes' arguments via
' 'GetType(EmbeddedTypeName)' expressions).
'
' The consecutive iterations may also see new embedded symbols referenced
' as we compile and emit embedded methods.
'
' If there are concurrent emits in place more referenced symbols may be returned
' by GetCurrentReferencedSymbolsSnapshot than in simple case described above,
' thus reducing the number of iterations of the outer Do loop.
'
' Note that GetCurrentReferencedSymbolsSnapshot actually makes a snapshot
' of the referenced symbols.
manager.GetCurrentReferencedSymbolsSnapshot(builder, processedSymbols)
If builder.Count = 0 Then
Exit Do
End If
For index = 0 To builder.Count - 1
Dim symbol As symbol = builder(index)
processedSymbols.Add(symbol)
#If DEBUG Then
' In DEBUG assert that the type does not have
' field initializers except those in const fields
If symbol.Kind = SymbolKind.NamedType Then
Dim embeddedType = DirectCast(symbol, EmbeddedSymbolManager.EmbeddedNamedTypeSymbol)
AssertAllInitializersAreConstants(embeddedType.StaticInitializers)
AssertAllInitializersAreConstants(embeddedType.InstanceInitializers)
End If
#End If
' Compile method
If symbol.Kind = SymbolKind.Method Then
Dim embeddedMethod = DirectCast(symbol, MethodSymbol)
EmbeddedSymbolManager.ValidateMethod(embeddedMethod)
VisitEmbeddedMethod(embeddedMethod)
End If
Next
builder.Clear()
Loop
builder.Free()
' Seal the referenced symbol collection
manager.SealCollection()
End Sub
Private Sub VisitEmbeddedMethod(method As MethodSymbol)
' Lazily created collection of synthetic methods which
' may be created during compilation of methods
Dim compilationState As TypeCompilationState = New TypeCompilationState(_compilation, _moduleBeingBuiltOpt, initializeComponentOpt:=Nothing)
' Containing type binder
' NOTE: we need to provide type binder for the constructor compilation,
' so we create it for each constructor, but it does not seem to be a
' problem since current embedded types have only one constructor per
' type; this might need to be revised later if this assumption changes
Dim sourceTypeBinder As Binder = If(method.MethodKind = MethodKind.Ordinary, Nothing,
BinderBuilder.CreateBinderForType(
DirectCast(method.ContainingModule, SourceModuleSymbol),
method.ContainingType.Locations(0).PossiblyEmbeddedOrMySourceTree(),
method.ContainingType))
' Since embedded method bodies don't produce synthesized methods (see the assertion below)
' there is no need to assign an ordinal to embedded methods.
Const methodOrdinal As Integer = -1
Dim withEventPropertyIdDispenser = 0
Dim delegateRelaxationIdDispenser = 0
Dim referencedConstructor As MethodSymbol = Nothing
CompileMethod(method,
methodOrdinal,
withEventPropertyIdDispenser,
delegateRelaxationIdDispenser,
filter:=Nothing,
compilationState:=compilationState,
processedInitializers:=Binder.ProcessedFieldOrPropertyInitializers.Empty,
containingTypeBinder:=sourceTypeBinder,
previousSubmissionFields:=Nothing,
referencedConstructor:=referencedConstructor)
' Do not expect WithEvents
Debug.Assert(withEventPropertyIdDispenser = 0)
' Do not expect delegate relaxation stubs
Debug.Assert(delegateRelaxationIdDispenser = 0)
' Do not expect constructor --> constructor calls for embedded types
Debug.Assert(referencedConstructor Is Nothing OrElse
Not referencedConstructor.ContainingType.Equals(method.ContainingType))
' Don't expect any synthetic methods created for embedded types
Debug.Assert(Not compilationState.HasSynthesizedMethods)
End Sub
<Conditional("DEBUG")>
Private Sub AssertAllInitializersAreConstants(initializers As ImmutableArray(Of ImmutableArray(Of FieldOrPropertyInitializer)))
If Not initializers.IsDefaultOrEmpty Then
For Each initializerGroup In initializers
If Not initializerGroup.IsEmpty Then
For Each initializer In initializerGroup
For Each fieldOrProperty In initializer.FieldsOrProperty
Debug.Assert(fieldOrProperty.Kind = SymbolKind.Field)
Debug.Assert(DirectCast(fieldOrProperty, FieldSymbol).IsConst)
Next
Next
End If
Next
End If
End Sub
#End Region
Private ReadOnly Property DoEmitPhase() As Boolean
Get
Return _doEmitPhase
End Get
End Property
Public Overrides Sub VisitNamespace(symbol As NamespaceSymbol)
_cancellationToken.ThrowIfCancellationRequested()
If Me._compilation.Options.ConcurrentBuild Then
Dim worker As Task = CompileNamespaceAsTask(symbol)
compilerTasks.Push(worker)
Else
CompileNamespace(symbol)
End If
End Sub
Private Function CompileNamespaceAsTask(symbol As NamespaceSymbol) As Task
Return Task.Run(
UICultureUtilities.WithCurrentUICulture(
Sub()
Try
CompileNamespace(symbol)
Catch e As Exception When FatalError.ReportUnlessCanceled(e)
Throw ExceptionUtilities.Unreachable
End Try
End Sub),
Me._cancellationToken)
End Function
Private Sub CompileNamespace(symbol As NamespaceSymbol)
If PassesFilter(_filterOpt, symbol) Then
For Each member In symbol.GetMembersUnordered()
member.Accept(Me)
Next
End If
End Sub
Public Overrides Sub VisitNamedType(symbol As NamedTypeSymbol)
_cancellationToken.ThrowIfCancellationRequested()
If PassesFilter(_filterOpt, symbol) Then
If Me._compilation.Options.ConcurrentBuild Then
Dim worker As Task = CompileNamedTypeAsTask(symbol, _filterOpt)
compilerTasks.Push(worker)
Else
CompileNamedType(symbol, _filterOpt)
End If
End If
End Sub
Private Function CompileNamedTypeAsTask(symbol As NamedTypeSymbol, filter As Predicate(Of Symbol)) As Task
Return Task.Run(
UICultureUtilities.WithCurrentUICulture(
Sub()
Try
CompileNamedType(symbol, filter)
Catch e As Exception When FatalError.ReportUnlessCanceled(e)
Throw ExceptionUtilities.Unreachable
End Try
End Sub),
Me._cancellationToken)
End Function
Private Sub CompileNamedType(symbol As NamedTypeSymbol, filter As Predicate(Of Symbol))
If symbol.IsEmbedded Then
' Don't process embedded types
Return
End If
' Find the constructor of a script class.
Dim scriptCtor As MethodSymbol = Nothing
Dim submissionCtorOrdinal = -1
If symbol.IsScriptClass Then
scriptCtor = symbol.InstanceConstructors(0)
Debug.Assert(scriptCtor IsNot Nothing)
End If
Dim processedStaticInitializers = Binder.ProcessedFieldOrPropertyInitializers.Empty
Dim processedInstanceInitializers = Binder.ProcessedFieldOrPropertyInitializers.Empty
Dim synthesizedSubmissionFields = If(symbol.IsSubmissionClass, New synthesizedSubmissionFields(_compilation, symbol), Nothing)
' if this is a type symbol from source we'll try to bind the field initializers as well
Dim sourceTypeSymbol = TryCast(symbol, SourceMemberContainerTypeSymbol)
Dim initializeComponent As MethodSymbol = Nothing
If sourceTypeSymbol IsNot Nothing AndAlso DoEmitPhase Then
initializeComponent = GetDesignerInitializeComponentMethod(sourceTypeSymbol)
End If
' Lazily created collection of synthetic methods which
' may be created during compilation of methods
Dim compilationState As TypeCompilationState = New TypeCompilationState(_compilation, _moduleBeingBuiltOpt, initializeComponent)
' Containing type binder
Dim sourceTypeBinder As Binder = Nothing
If sourceTypeSymbol IsNot Nothing Then
Debug.Assert(sourceTypeSymbol.Locations.Length > 0)
sourceTypeBinder = BinderBuilder.CreateBinderForType(
DirectCast(sourceTypeSymbol.ContainingModule, SourceModuleSymbol),
sourceTypeSymbol.Locations(0).PossiblyEmbeddedOrMySourceTree,
sourceTypeSymbol)
Binder.BindFieldAndPropertyInitializers(sourceTypeSymbol,
sourceTypeSymbol.StaticInitializers,
scriptCtor,
processedStaticInitializers,
_diagnostics)
Binder.BindFieldAndPropertyInitializers(sourceTypeSymbol,
sourceTypeSymbol.InstanceInitializers,
scriptCtor,
processedInstanceInitializers,
_diagnostics)
' TODO: any flow analysis for initializers?
' const fields of type date or decimal require a shared constructor. We decided that this constructor
' should not be part of the type's member list. If there is not already a shared constructor, we're
' creating one and call CompileMethod to rewrite the field initializers.
Dim sharedDefaultConstructor = sourceTypeSymbol.CreateSharedConstructorsForConstFieldsIfRequired(sourceTypeBinder, _diagnostics)
If sharedDefaultConstructor IsNot Nothing AndAlso PassesFilter(filter, sharedDefaultConstructor) Then
Dim sharedConstructorWithEventPropertyIdDispenser = 0
Dim sharedConstructorDelegateRelaxationIdDispenser = 0
CompileMethod(sharedDefaultConstructor,
-1,
sharedConstructorWithEventPropertyIdDispenser,
sharedConstructorDelegateRelaxationIdDispenser,
filter,
compilationState,
processedStaticInitializers,
sourceTypeBinder,
synthesizedSubmissionFields)
' Default shared constructor shall not have any Handles clause
Debug.Assert(sharedConstructorWithEventPropertyIdDispenser = 0)
' Default shared constructor shall not produce delegate relaxation stubs
Debug.Assert(sharedConstructorDelegateRelaxationIdDispenser = 0)
If _moduleBeingBuiltOpt IsNot Nothing Then
_moduleBeingBuiltOpt.AddSynthesizedDefinition(sourceTypeSymbol, sharedDefaultConstructor)
End If
End If
End If
' Constructor --> Constructor calls to be used in cycles detection
Dim constructorCallMap As Dictionary(Of MethodSymbol, MethodSymbol) = Nothing
Dim members = symbol.GetMembers()
' Unique ids assigned to synthesized overrides of WithEvents properties.
Dim withEventPropertyIdDispenser = 0
' Unique ids assigned to synthesized delegate relaxation stubs.
Dim delegateRelaxationIdDispenser = 0
For memberOrdinal = 0 To members.Length - 1
Dim member = members(memberOrdinal)
If Not PassesFilter(filter, member) Then
Continue For
End If
Select Case member.Kind
Case SymbolKind.NamedType
member.Accept(Me)
Case SymbolKind.Method
Dim method = DirectCast(member, MethodSymbol)
If method.IsSubmissionConstructor Then
Debug.Assert(submissionCtorOrdinal = -1)
submissionCtorOrdinal = memberOrdinal
Continue For
End If
If method.IsPartial() Then
Dim impl = method.PartialImplementationPart
If impl IsNot method Then
If CType(method, SourceMethodSymbol).SetDiagnostics(ImmutableArray(Of Diagnostic).Empty) Then
method.DeclaringCompilation.SymbolDeclaredEvent(method)
End If
If impl Is Nothing Then
Continue For
End If
method = impl
End If
End If
' pass correct processed initializers for the static or instance constructors,
' otherwise pass nothing
Dim processedInitializers = Binder.ProcessedFieldOrPropertyInitializers.Empty
If method.MethodKind = MethodKind.SharedConstructor Then
processedInitializers = processedStaticInitializers
ElseIf method.MethodKind = MethodKind.Constructor Then
processedInitializers = processedInstanceInitializers
End If
Dim referencedConstructor As MethodSymbol = Nothing
CompileMethod(method,
memberOrdinal,
withEventPropertyIdDispenser,
delegateRelaxationIdDispenser,
filter,
compilationState,
processedInitializers,
sourceTypeBinder,
synthesizedSubmissionFields,
referencedConstructor)
' If 'referencedConstructor' is returned by 'CompileMethod', the method just compiled
' was a constructor which references the returned symbol. We might want to store
' some of those constructors in 'constructorCallMap' to process later for cycle detection
If referencedConstructor IsNot Nothing Then
' If base class constructor is called, the constructor cannot be part of a cycle
If referencedConstructor.ContainingType.Equals(symbol) Then
If constructorCallMap Is Nothing Then
constructorCallMap = New Dictionary(Of MethodSymbol, MethodSymbol)
End If
constructorCallMap.Add(method, referencedConstructor)
End If
End If
' Create exact signature stubs for interface implementations.
If DoEmitPhase AndAlso _moduleBeingBuiltOpt IsNot Nothing Then
CreateExplicitInterfaceImplementationStubs(compilationState, method)
End If
End Select
Next
Debug.Assert(symbol.TypeKind <> TypeKind.Submission OrElse (scriptCtor IsNot Nothing AndAlso scriptCtor.IsSubmissionConstructor))
' Detect and report cycles in constructor calls
If constructorCallMap IsNot Nothing Then
DetectAndReportCyclesInConstructorCalls(constructorCallMap, _diagnostics)
End If
' Compile submission constructor last so that synthesized submission fields are collected from all script methods:
If scriptCtor IsNot Nothing AndAlso scriptCtor.IsSubmissionConstructor Then
CompileMethod(scriptCtor,
submissionCtorOrdinal,
withEventPropertyIdDispenser,
delegateRelaxationIdDispenser,
filter,
compilationState,
processedInstanceInitializers,
sourceTypeBinder,
synthesizedSubmissionFields)
If synthesizedSubmissionFields IsNot Nothing AndAlso _moduleBeingBuiltOpt IsNot Nothing Then
synthesizedSubmissionFields.AddToType(symbol, _moduleBeingBuiltOpt)
End If
End If
' Report warnings for constructors that do not call InitializeComponent
If initializeComponent IsNot Nothing Then
For Each member In symbol.GetMembers()
If member.IsShared OrElse Not member.IsFromCompilation(_compilation) OrElse member.Kind <> SymbolKind.Method Then
Continue For
End If
Dim sourceMethod = TryCast(member, SourceMemberMethodSymbol)
If sourceMethod IsNot Nothing AndAlso
sourceMethod.MethodKind = MethodKind.Constructor AndAlso
Not compilationState.CallsInitializeComponent(sourceMethod) Then
Dim location As location = sourceMethod.NonMergedLocation
Debug.Assert(location IsNot Nothing)
If location IsNot Nothing Then
Binder.ReportDiagnostic(_diagnostics, location, ERRID.WRN_ExpectedInitComponentCall2, sourceMethod, sourceTypeSymbol)
End If
End If
Next
End If
' Add synthetic methods created for this type in above calls to CompileMethod
If _moduleBeingBuiltOpt IsNot Nothing Then
CompileSynthesizedMethods(compilationState)
End If
compilationState.Free()
End Sub
Private Sub CreateExplicitInterfaceImplementationStubs(compilationState As TypeCompilationState, method As MethodSymbol)
' It is not common to have signature mismatch, let's avoid any extra work
' and allocations until we know that we have a mismatch.
Dim stubs As ArrayBuilder(Of SynthesizedInterfaceImplementationStubSymbol) = Nothing
For Each implemented In method.ExplicitInterfaceImplementations
If Not MethodSignatureComparer.CustomModifiersAndParametersAndReturnTypeSignatureComparer.Equals(method, implemented) Then
If stubs Is Nothing Then
stubs = ArrayBuilder(Of SynthesizedInterfaceImplementationStubSymbol).GetInstance()
End If
Dim matchingStub As SynthesizedInterfaceImplementationStubSymbol = Nothing
For Each candidate In stubs
If MethodSignatureComparer.CustomModifiersAndParametersAndReturnTypeSignatureComparer.Equals(candidate, implemented) Then
matchingStub = candidate
Exit For
End If
Next
If matchingStub Is Nothing Then
matchingStub = New SynthesizedInterfaceImplementationStubSymbol(method, implemented)
stubs.Add(matchingStub)
Dim f = New SyntheticBoundNodeFactory(matchingStub, matchingStub, method.Syntax, compilationState, New DiagnosticBag())
Dim methodToInvoke As MethodSymbol
If method.IsGenericMethod Then
methodToInvoke = method.Construct(matchingStub.TypeArguments)
Else
methodToInvoke = method
End If
Dim arguments = ArrayBuilder(Of BoundExpression).GetInstance(matchingStub.ParameterCount)
For Each param In matchingStub.Parameters
Dim parameterExpression = f.Parameter(param)
If Not param.IsByRef Then
parameterExpression = parameterExpression.MakeRValue()
End If
arguments.Add(parameterExpression)
Next
Dim invocation = f.Call(f.Me, methodToInvoke, arguments.ToImmutableAndFree())
Dim body As BoundBlock
If method.IsSub Then
body = f.Block(f.ExpressionStatement(invocation), f.Return())
Else
body = f.Block(f.Return(invocation))
End If
f.CloseMethod(body)
_moduleBeingBuiltOpt.AddSynthesizedDefinition(method.ContainingType, DirectCast(matchingStub, Microsoft.Cci.IMethodDefinition))
End If
matchingStub.AddImplementedMethod(implemented)
End If
Next
If stubs IsNot Nothing Then
For Each stub In stubs
stub.Seal()
Next
stubs.Free()
End If
End Sub
Private Shared Function GetDesignerInitializeComponentMethod(sourceTypeSymbol As SourceMemberContainerTypeSymbol) As MethodSymbol
If sourceTypeSymbol.TypeKind = TypeKind.Class AndAlso sourceTypeSymbol.GetAttributes().IndexOfAttribute(sourceTypeSymbol, AttributeDescription.DesignerGeneratedAttribute) > -1 Then
For Each member As Symbol In sourceTypeSymbol.GetMembers("InitializeComponent")
If member.Kind = SymbolKind.Method Then
Dim method = DirectCast(member, MethodSymbol)
If method.IsSub AndAlso Not method.IsShared AndAlso Not method.IsGenericMethod AndAlso method.ParameterCount = 0 Then
Return method
End If
End If
Next
End If
Return Nothing
End Function
Private Sub CompileSynthesizedMethods(privateImplClass As PrivateImplementationDetails)
Debug.Assert(_moduleBeingBuiltOpt IsNot Nothing)
For Each method As MethodSymbol In privateImplClass.GetMethods(Nothing)
Dim diagnosticsThisMethod = DiagnosticBag.GetInstance()
Dim boundBody = method.GetBoundMethodBody(diagnosticsThisMethod)
Dim emittedBody = GenerateMethodBody(_moduleBeingBuiltOpt,
method,
boundBody,
stateMachineTypeOpt:=Nothing,
variableSlotAllocatorOpt:=Nothing,
debugDocumentProvider:=Nothing,
diagnostics:=diagnosticsThisMethod,
generateDebugInfo:=False)
_diagnostics.AddRange(diagnosticsThisMethod)
diagnosticsThisMethod.Free()
' error while generating IL
If emittedBody Is Nothing Then
Exit For
End If
_moduleBeingBuiltOpt.SetMethodBody(method, emittedBody)
Next
End Sub
Private Sub CompileSynthesizedMethods(additionalTypes As ImmutableArray(Of NamedTypeSymbol))
Debug.Assert(_moduleBeingBuiltOpt IsNot Nothing)
Dim compilationState As New TypeCompilationState(_compilation, _moduleBeingBuiltOpt, initializeComponentOpt:=Nothing)
For Each additionalType In additionalTypes
Dim methodOrdinal As Integer = 0
For Each method In additionalType.GetMethodsToEmit()
Dim diagnosticsThisMethod = DiagnosticBag.GetInstance()
Dim boundBody = method.GetBoundMethodBody(diagnosticsThisMethod)
Dim emittedBody As MethodBody = Nothing
If Not diagnosticsThisMethod.HasAnyErrors Then
Dim variableSlotAllocatorOpt As VariableSlotAllocator = Nothing
Dim statemachineTypeOpt As StateMachineTypeSymbol = Nothing
Dim lambdaOrdinalDispenser = 0
Dim scopeOrdinalDispenser = 0
Dim delegateRelaxationIdDispenser = 0
Dim rewrittenBody = Rewriter.LowerBodyOrInitializer(
method,
methodOrdinal,
boundBody,
previousSubmissionFields:=Nothing,
compilationState:=compilationState,
diagnostics:=diagnosticsThisMethod,
lambdaOrdinalDispenser:=lambdaOrdinalDispenser,
scopeOrdinalDispenser:=scopeOrdinalDispenser,
delegateRelaxationIdDispenser:=delegateRelaxationIdDispenser,
stateMachineTypeOpt:=statemachineTypeOpt,
variableSlotAllocatorOpt:=variableSlotAllocatorOpt,
allowOmissionOfConditionalCalls:=_moduleBeingBuiltOpt.AllowOmissionOfConditionalCalls,
isBodySynthesized:=True)
If Not diagnosticsThisMethod.HasAnyErrors Then
emittedBody = GenerateMethodBody(_moduleBeingBuiltOpt,
method,
rewrittenBody,
statemachineTypeOpt,
variableSlotAllocatorOpt,
debugDocumentProvider:=Nothing,
diagnostics:=diagnosticsThisMethod,
generateDebugInfo:=False)
End If
End If
_diagnostics.AddRange(diagnosticsThisMethod)
diagnosticsThisMethod.Free()
' error while generating IL
If emittedBody Is Nothing Then
Exit For
End If
_moduleBeingBuiltOpt.SetMethodBody(method, emittedBody)
methodOrdinal += 1
Next
Next
If Not _diagnostics.HasAnyErrors() Then
CompileSynthesizedMethods(compilationState)
End If
compilationState.Free()
End Sub
Private Sub CompileSynthesizedMethods(compilationState As TypeCompilationState)
Debug.Assert(_moduleBeingBuiltOpt IsNot Nothing)
If Not compilationState.HasSynthesizedMethods Then
Return
End If
For Each methodWithBody In compilationState.SynthesizedMethods
If Not methodWithBody.Body.HasErrors Then
Dim method = methodWithBody.Method
Dim diagnosticsThisMethod As DiagnosticBag = DiagnosticBag.GetInstance()
Dim emittedBody = GenerateMethodBody(_moduleBeingBuiltOpt,
method,
methodWithBody.Body,
stateMachineTypeOpt:=Nothing,
variableSlotAllocatorOpt:=Nothing,
debugDocumentProvider:=_debugDocumentProvider,
diagnostics:=diagnosticsThisMethod,
generateDebugInfo:=_generateDebugInfo AndAlso method.GenerateDebugInfo)
_diagnostics.AddRange(diagnosticsThisMethod)
diagnosticsThisMethod.Free()
' error while generating IL
If emittedBody Is Nothing Then
Exit For
End If
_moduleBeingBuiltOpt.SetMethodBody(method, emittedBody)
End If
Next
End Sub
''' <summary>
''' Detects cycles in constructor invocations based on the 'constructor-calls-constructor'
''' map provided in 'constructorCallMap', reports errors if found.
'''
''' NOTE: 'constructorCallMap' is being mutated by this method
''' </summary>
Private Sub DetectAndReportCyclesInConstructorCalls(constructorCallMap As Dictionary(Of MethodSymbol, MethodSymbol), diagnostics As DiagnosticBag)
Debug.Assert(constructorCallMap.Count > 0)
Dim constructorsInPath As New Dictionary(Of MethodSymbol, Integer)
Dim constructorsPath = ArrayBuilder(Of MethodSymbol).GetInstance()
Dim currentMethod As MethodSymbol = constructorCallMap.Keys.First()
' Cycle constructor calls
Do
' Where this constructor points to?
Dim currentMethodPointTo As MethodSymbol = Nothing
If Not constructorCallMap.TryGetValue(currentMethod, currentMethodPointTo) Then
' We didn't find anything, which means we maybe already processed 'currentMethod'
' or it does not reference another constructor of this type, or there is somethig wrong with it;
' In any case we can restart iteration, none of the constructors in path are part of cycles
Else
' 'currentMethod' references another constructor; we may safely remove 'currentMethod'
' from 'constructorCallMap' because we won't need to process it again
constructorCallMap.Remove(currentMethod)
constructorsInPath.Add(currentMethod, constructorsPath.Count)
constructorsPath.Add(currentMethod)
Dim foundAt As Integer
If constructorsInPath.TryGetValue(currentMethodPointTo, foundAt) Then
' We found a cycle which starts at 'foundAt' and goes to the end of constructorsPath
constructorsPath.Add(currentMethodPointTo)
ReportConstructorCycles(foundAt, constructorsPath.Count - 1, constructorsPath, diagnostics)
' We can restart iteration, none of the constructors
' in path may be part of other cycles
Else
' No cycles so far, just move to the next constructor
currentMethod = currentMethodPointTo
Continue Do
End If
End If
' Restart iteration
constructorsInPath.Clear()
constructorsPath.Clear()
If constructorCallMap.Count = 0 Then
' Nothing left
constructorsPath.Free()
Exit Sub
End If
currentMethod = constructorCallMap.Keys.First()
Loop
Throw ExceptionUtilities.Unreachable
End Sub
''' <summary> All the constructors in the cycle will be reported </summary>
Private Sub ReportConstructorCycles(startsAt As Integer, endsAt As Integer,
path As ArrayBuilder(Of MethodSymbol),
diagnostics As DiagnosticBag)
' Cycle is: constructorsCycle(startsAt) -->
' constructorsCycle(startsAt + 1) -->
' ....
' constructorsCycle(endsAt) = constructorsCycle(startsAt)
'
' In case the constructor constructorsCycle(startsAt) calls itself, startsAt = endsAt + 1
Debug.Assert(startsAt <= endsAt)
Debug.Assert(path(startsAt).Equals(path(endsAt)))
' Generate cycle info
Dim diagnosticInfos = ArrayBuilder(Of DiagnosticInfo).GetInstance()
Dim referencingMethod As MethodSymbol = path(startsAt)
For i = startsAt + 1 To endsAt
Dim referencedMethod As MethodSymbol = path(i)
diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_SubNewCycle2, referencingMethod, referencedMethod))
referencingMethod = referencedMethod
Next
' Report Errors for all constructors in the cycle
For i = startsAt To endsAt - 1
referencingMethod = path(i)
' Report an error
diagnostics.Add(
New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_SubNewCycle1, referencingMethod,
New CompoundDiagnosticInfo(diagnosticInfos.ToArray())),
referencingMethod.Locations(0)))
' Rotate 'diagnosticInfos' for the next constructor
If diagnosticInfos.Count > 1 Then
Dim diagnostic = diagnosticInfos(0)
diagnosticInfos.RemoveAt(0)
diagnosticInfos.Add(diagnostic)
End If
Next
diagnosticInfos.Free()
End Sub
Friend Shared Function CanBindMethod(method As MethodSymbol) As Boolean
If method.IsExternalMethod OrElse method.IsMustOverride Then
Return False
End If
' Synthesized struct constructors are not emitted.
If method.IsDefaultValueTypeConstructor() Then
Return False
End If
If method.IsPartialWithoutImplementation Then
' Exclude partial methods without implementation
Return False
End If
If Not method.IsImplicitlyDeclared Then
' Only compile the method if the method has a body.
Dim sourceMethod = TryCast(method, SourceMethodSymbol)
If sourceMethod Is Nothing OrElse sourceMethod.BlockSyntax Is Nothing Then
Return False
End If
End If
Return True
End Function
''' <summary>
''' Compiles the method.
''' </summary>
''' <param name="referencedConstructor">
''' If the method being compiled is a constructor, CompileMethod returns in this parameter
''' the symbol of the constructor called from the one being compiled either explicitly or implicitly.
''' For structure constructors calling parameterless constructor returns the synthesized constructor symbol.
''' </param>
Private Sub CompileMethod(
method As MethodSymbol,
methodOrdinal As Integer,
ByRef withEventPropertyIdDispenser As Integer,
ByRef delegateRelaxationIdDispenser As Integer,
filter As Predicate(Of Symbol),
compilationState As TypeCompilationState,
processedInitializers As Binder.ProcessedFieldOrPropertyInitializers,
containingTypeBinder As Binder,
previousSubmissionFields As SynthesizedSubmissionFields,
Optional ByRef referencedConstructor As MethodSymbol = Nothing
)
'' TODO: add filtering as follows
'If filter IsNot Nothing AndAlso Not filter(method) Then
' Return
'End If
_cancellationToken.ThrowIfCancellationRequested()
Dim sourceMethod = TryCast(method, SourceMethodSymbol)
'get cached diagnostics if not building and we have 'em
If Not DoEmitPhase AndAlso (sourceMethod IsNot Nothing) Then
Dim cachedDiagnostics = sourceMethod.Diagnostics
If Not cachedDiagnostics.IsDefault Then
Me._diagnostics.AddRange(cachedDiagnostics)
Return
End If
End If
If Not CanBindMethod(method) Then
If sourceMethod IsNot Nothing AndAlso sourceMethod.SetDiagnostics(ImmutableArray(Of Diagnostic).Empty) Then
sourceMethod.DeclaringCompilation.SymbolDeclaredEvent(method)
End If
Return
End If
' In order to avoid generating code for methods with errors, we create a diagnostic bag just for this method.
Dim diagsForCurrentMethod As DiagnosticBag = DiagnosticBag.GetInstance()
Dim methodBinderOpt As Binder = Nothing
Dim injectConstructorCall As Boolean
Dim block = BindAndAnalyzeMethodBody(method, compilationState, diagsForCurrentMethod, containingTypeBinder, referencedConstructor, injectConstructorCall, methodBinderOpt)
If method.MethodKind = MethodKind.Constructor OrElse method.MethodKind = MethodKind.SharedConstructor Then
' If this is a constructor and we do have initializers they need to be flow-analyzed for
' warnings like 'Function '??' doesn't return a value on all code paths' or unreferenced variables.
' Because if there are any initializers they will eventually get to one or more constructors
' it does not matter which constructor is being used as a method symbol for their analysis,
' so we don't perform any analysis of which constructor symbol to pass to EnsureInitializersAnalyzed,
' but call this method for on all constructor symbols making sure instance/static initializers
' are analyzed on the first instance/static constructor processed
processedInitializers.EnsureInitializersAnalyzed(method, diagsForCurrentMethod)
End If
Dim hasErrors = _hasDeclarationErrors OrElse diagsForCurrentMethod.HasAnyErrors() OrElse processedInitializers.HasAnyErrors OrElse block.HasErrors
SetGlobalErrorIfTrue(hasErrors)
If sourceMethod IsNot Nothing AndAlso sourceMethod.SetDiagnostics(diagsForCurrentMethod.ToReadOnly()) Then
Dim compilation = compilationState.Compilation
If compilation.EventQueue IsNot Nothing Then
If block Is Nothing Then
compilation.SymbolDeclaredEvent(sourceMethod)
Else
'create a compilation event that caches the already-computed bound tree
Dim lazySemanticModel = New Lazy(Of SemanticModel)(
Function()
Dim syntax = block.Syntax
Dim semanticModel = CType(compilation.GetSemanticModel(syntax.SyntaxTree), SyntaxTreeSemanticModel)
Dim memberModel = CType(semanticModel.GetMemberSemanticModel(syntax), MethodBodySemanticModel)
If memberModel IsNot Nothing Then
memberModel.CacheBoundNodes(block, syntax)
End If
Return semanticModel
End Function)
compilation.EventQueue.Enqueue(New SymbolDeclaredCompilationEvent(compilation, method, lazySemanticModel))
End If
End If
End If
If Not DoEmitPhase AndAlso sourceMethod IsNot Nothing Then
_diagnostics.AddRange(sourceMethod.Diagnostics)
Return
End If
If DoEmitPhase AndAlso Not hasErrors Then
LowerAndEmitMethod(method,
methodOrdinal,
block,
If(methodBinderOpt, containingTypeBinder),
compilationState,
diagsForCurrentMethod,
processedInitializers,
previousSubmissionFields,
If(injectConstructorCall, referencedConstructor, Nothing),
delegateRelaxationIdDispenser)
' if method happen to handle events of a base WithEvents, ensure that we have an overriding WithEvents property
Dim handledEvents = method.HandledEvents
If Not handledEvents.IsEmpty Then
CreateSyntheticWithEventOverridesIfNeeded(handledEvents,
delegateRelaxationIdDispenser,
withEventPropertyIdDispenser,
compilationState,
containingTypeBinder,
diagsForCurrentMethod,
previousSubmissionFields)
End If
End If
' Add the generated diagnostics into the full diagnostic bag.
_diagnostics.AddRange(diagsForCurrentMethod)
diagsForCurrentMethod.Free()
End Sub
''' <summary>
''' If any of the "Handles" in the list have synthetic WithEvent override
''' as a container, then this method will (if not done already) inject
''' property/accessors symbol into the emit module and assign bodies to the accessors.
''' </summary>
Private Sub CreateSyntheticWithEventOverridesIfNeeded(handledEvents As ImmutableArray(Of HandledEvent),
ByRef delegateRelaxationIdDispenser As Integer,
ByRef withEventPropertyIdDispenser As Integer,
compilationState As TypeCompilationState,
containingTypeBinder As Binder,
diagnostics As DiagnosticBag,
previousSubmissionFields As SynthesizedSubmissionFields)
Debug.Assert(_moduleBeingBuiltOpt Is Nothing OrElse _moduleBeingBuiltOpt.AllowOmissionOfConditionalCalls)
For Each handledEvent In handledEvents
If handledEvent.HandlesKind <> HandledEventKind.WithEvents Then
Continue For
End If
Dim prop = TryCast(handledEvent.hookupMethod.AssociatedSymbol, SynthesizedOverridingWithEventsProperty)
If prop Is Nothing Then
Continue For
End If
Dim getter = prop.GetMethod
If compilationState.HasMethodWrapper(getter) Then
Continue For
End If
Dim setter = prop.SetMethod
Dim containingType = prop.ContainingType
Debug.Assert(containingType Is getter.ContainingType AndAlso containingType Is setter.ContainingType)
Dim getterBody = getter.GetBoundMethodBody(diagnostics, containingTypeBinder)
' no need to rewrite getter, they are pretty simple and
' are already in a lowered form.
compilationState.AddMethodWrapper(getter, getter, getterBody)
_moduleBeingBuiltOpt.AddSynthesizedDefinition(containingType, getter)
' setter needs to rewritten as it may require lambda conversions
Dim setterBody = setter.GetBoundMethodBody(diagnostics, containingTypeBinder)
Dim lambdaOrdinalDispenser = 0
Dim scopeOrdinalDispenser = 0
setterBody = Rewriter.LowerBodyOrInitializer(setter,
withEventPropertyIdDispenser,
setterBody,
previousSubmissionFields,
compilationState,
diagnostics,
lambdaOrdinalDispenser:=lambdaOrdinalDispenser,
scopeOrdinalDispenser:=scopeOrdinalDispenser,
delegateRelaxationIdDispenser:=delegateRelaxationIdDispenser,
stateMachineTypeOpt:=Nothing,
variableSlotAllocatorOpt:=Nothing,
allowOmissionOfConditionalCalls:=True,
isBodySynthesized:=True)
' There shall be no lambdas in the synthesized accessor but delegate relaxation conversions:
Debug.Assert(lambdaOrdinalDispenser = 0)
Debug.Assert(scopeOrdinalDispenser = 0)
compilationState.AddMethodWrapper(setter, setter, setterBody)
_moduleBeingBuiltOpt.AddSynthesizedDefinition(containingType, setter)
' add property too
_moduleBeingBuiltOpt.AddSynthesizedDefinition(containingType, prop)
withEventPropertyIdDispenser += 1
Next
End Sub
''' <summary>
''' Assuming the statement is a constructor call wrapped in bound expression
''' statement, get the method symbol being called
''' </summary>
Private Shared Function TryGetMethodCalledInBoundExpressionStatement(stmt As BoundExpressionStatement) As MethodSymbol
' No statement provided or has errors
If stmt Is Nothing OrElse stmt.HasErrors Then
Return Nothing
End If
' Statement is not a call
Dim expression As BoundExpression = stmt.Expression
If expression.Kind <> BoundKind.Call Then
Return Nothing
End If
Return DirectCast(expression, BoundCall).Method
End Function
Private Sub LowerAndEmitMethod(
method As MethodSymbol,
methodOrdinal As Integer,
block As BoundBlock,
binderOpt As Binder,
compilationState As TypeCompilationState,
diagsForCurrentMethod As DiagnosticBag,
processedInitializers As Binder.ProcessedFieldOrPropertyInitializers,
previousSubmissionFields As SynthesizedSubmissionFields,
constructorToInject As MethodSymbol,
ByRef delegateRelaxationIdDispenser As Integer
)
Dim constructorInitializerOpt = If(constructorToInject Is Nothing,
Nothing,
BindDefaultConstructorInitializer(method, constructorToInject, diagsForCurrentMethod, binderOpt))
If diagsForCurrentMethod.HasAnyErrors Then
Return
End If
If constructorInitializerOpt IsNot Nothing AndAlso constructorInitializerOpt.HasErrors Then
Return
End If
Dim body As BoundBlock
If method.MethodKind = MethodKind.Constructor OrElse method.MethodKind = MethodKind.SharedConstructor Then
' Turns field initializers into bound assignment statements and top-level script statements into bound statements in the beginning the body.
' For submission constructor, the body only includes bound initializers and a return statement. The rest is filled in later.
body = InitializerRewriter.BuildConstructorBody(
compilationState,
method,
If(method.IsSubmissionConstructor, Nothing, constructorInitializerOpt), processedInitializers, block)
Else
body = block
End If
Dim diagnostics As DiagnosticBag = diagsForCurrentMethod
If method.IsImplicitlyDeclared AndAlso
method.AssociatedSymbol IsNot Nothing AndAlso
method.AssociatedSymbol.IsMyGroupCollectionProperty Then
diagnostics = DiagnosticBag.GetInstance()
End If
Dim variableSlotAllocatorOpt As VariableSlotAllocator = Nothing
Dim stateMachineTypeOpt As StateMachineTypeSymbol = Nothing
Dim allowOmissionOfConditionalCalls = _moduleBeingBuiltOpt Is Nothing OrElse _moduleBeingBuiltOpt.AllowOmissionOfConditionalCalls
Dim lambdaOrdinalDispenser = 0
Dim scopeOrdinalDispenser = 0
body = Rewriter.LowerBodyOrInitializer(method,
methodOrdinal,
body,
previousSubmissionFields,
compilationState,
diagnostics,
lambdaOrdinalDispenser,
scopeOrdinalDispenser,
delegateRelaxationIdDispenser,
stateMachineTypeOpt,
variableSlotAllocatorOpt,
allowOmissionOfConditionalCalls,
isBodySynthesized:=False)
' The submission initializer has to be constructed after the body is rewritten (all previous submission references are visited):
Dim submissionInitialization As ImmutableArray(Of BoundStatement)
If method.IsSubmissionConstructor Then
submissionInitialization = SynthesizedSubmissionConstructorSymbol.MakeSubmissionInitialization(block.Syntax, method, previousSubmissionFields, _compilation, diagnostics)
Else
submissionInitialization = Nothing
End If
Dim hasErrors = body.HasErrors OrElse diagsForCurrentMethod.HasAnyErrors OrElse (diagnostics IsNot diagsForCurrentMethod AndAlso diagnostics.HasAnyErrors)
SetGlobalErrorIfTrue(hasErrors)
' Actual emitting is only done if we have a module in which to emit and no errors so far.
If _moduleBeingBuiltOpt Is Nothing OrElse hasErrors Then
If diagnostics IsNot diagsForCurrentMethod Then
DirectCast(method.AssociatedSymbol, SynthesizedMyGroupCollectionPropertySymbol).RelocateDiagnostics(diagnostics, diagsForCurrentMethod)
diagnostics.Free()
End If
Return
End If
' now we have everything we need to build complete submission
If method.IsSubmissionConstructor Then
Debug.Assert(previousSubmissionFields IsNot Nothing)
Dim boundStatements = ArrayBuilder(Of BoundStatement).GetInstance(1 + submissionInitialization.Length + 1)
boundStatements.Add(constructorInitializerOpt)
boundStatements.AddRange(submissionInitialization)
boundStatements.Add(body)
body = New BoundBlock(body.Syntax, Nothing, ImmutableArray(Of LocalSymbol).Empty, boundStatements.ToImmutableAndFree(), body.HasErrors).MakeCompilerGenerated()
End If
' NOTE: additional check for statement.HasErrors is needed to identify parse errors which didn't get into diagsForCurrentMethod
Dim methodBody As methodBody = GenerateMethodBody(_moduleBeingBuiltOpt,
method,
body,
stateMachineTypeOpt,
variableSlotAllocatorOpt,
_debugDocumentProvider,
diagnostics,
generateDebugInfo:=_generateDebugInfo AndAlso method.GenerateDebugInfo)
If diagnostics IsNot diagsForCurrentMethod Then
DirectCast(method.AssociatedSymbol, SynthesizedMyGroupCollectionPropertySymbol).RelocateDiagnostics(diagnostics, diagsForCurrentMethod)
diagnostics.Free()
End If
_moduleBeingBuiltOpt.SetMethodBody(If(method.PartialDefinitionPart, method), methodBody)
End Sub
Friend Shared Function GenerateMethodBody(moduleBuilder As PEModuleBuilder,
method As MethodSymbol,
block As BoundStatement,
stateMachineTypeOpt As StateMachineTypeSymbol,
variableSlotAllocatorOpt As VariableSlotAllocator,
debugDocumentProvider As DebugDocumentProvider,
diagnostics As DiagnosticBag,
generateDebugInfo As Boolean) As MethodBody
Dim compilation = moduleBuilder.Compilation
Dim localSlotManager = New localSlotManager(variableSlotAllocatorOpt)
Dim optimizations = compilation.Options.OptimizationLevel
If method.IsEmbedded Then
optimizations = OptimizationLevel.Release
End If
Dim builder As ILBuilder = New ILBuilder(moduleBuilder, localSlotManager, optimizations)
Try
Debug.Assert(Not diagnostics.HasAnyErrors)
Dim asyncDebugInfo As Cci.AsyncMethodBodyDebugInfo = Nothing
Dim codeGen = New codeGen.CodeGenerator(method, block, builder, moduleBuilder, diagnostics, optimizations, generateDebugInfo)
' We need to save additional debugging information for MoveNext of an async state machine.
Dim stateMachineMethod = TryCast(method, SynthesizedStateMachineMethod)
Dim isStateMachineMoveNextMethod As Boolean = stateMachineMethod IsNot Nothing AndAlso method.Name = WellKnownMemberNames.MoveNextMethodName
If isStateMachineMoveNextMethod AndAlso stateMachineMethod.StateMachineType.KickoffMethod.IsAsync Then
Dim asyncCatchHandlerOffset As Integer = -1
Dim asyncYieldPoints As ImmutableArray(Of Integer) = Nothing
Dim asyncResumePoints As ImmutableArray(Of Integer) = Nothing
codeGen.Generate(asyncCatchHandlerOffset, asyncYieldPoints, asyncResumePoints)
Dim kickoffMethod = stateMachineMethod.StateMachineType.KickoffMethod
' In VB async method may be partial. Debug info needs to be associated with the emitted definition,
' but the kickoff method is the method implementation (the part with body).
' The exception handler IL offset is used by the debugger to treat exceptions caught by the marked catch block as "user unhandled".
' This is important for async void because async void exceptions generally result in the process being terminated,
' but without anything useful on the call stack. Async Task methods on the other hand return exceptions as the result of the Task.
' So it is undesirable to consider these exceptions "user unhandled" since there may well be user code that is awaiting the task.
' This is a heuristic since it's possible that there is no user code awaiting the task.
asyncDebugInfo = New Cci.AsyncMethodBodyDebugInfo(
If(kickoffMethod.PartialDefinitionPart, kickoffMethod),
If(kickoffMethod.IsSub, asyncCatchHandlerOffset, -1),
asyncYieldPoints,
asyncResumePoints)
Else
codeGen.Generate()
End If
If diagnostics.HasAnyErrors() Then
Return Nothing
End If
' We will only save the IL builders when running tests.
If moduleBuilder.SaveTestData Then
moduleBuilder.SetMethodTestData(method, builder.GetSnapshot())
End If
Dim stateMachineHoistedLocalSlots As ImmutableArray(Of EncHoistedLocalInfo) = Nothing
Dim stateMachineAwaiterSlots As ImmutableArray(Of Cci.ITypeReference) = Nothing
If optimizations = OptimizationLevel.Debug AndAlso stateMachineTypeOpt IsNot Nothing Then
Debug.Assert(method.IsAsync OrElse method.IsIterator)
GetStateMachineSlotDebugInfo(moduleBuilder.GetSynthesizedFields(stateMachineTypeOpt), stateMachineHoistedLocalSlots, stateMachineAwaiterSlots)
End If
Dim namespaceScopes = If(generateDebugInfo, moduleBuilder.SourceModule.GetSourceFile(method.Syntax.SyntaxTree), Nothing)
' edgeInclusive must be true as that is what VB EE expects.
'<PdbUtil.cpp>
'HRESULT()
'PdbUtil::IsScopeInOffset(
' _In_ ISymUnmanagedScope* pScope,
' _In_ DWORD offset,
' _Out_ bool* inOffset)
'{
' VerifyInPtr(pScope);
' VerifyOutPtr(inOffset);
' HRESULT hr;
' ULONG32 start, end;
' IfFailGo( pScope->GetStartOffset(&start) );
' IfFailGo( pScope->GetEndOffset(&end) );
' *inOffset = (end >= offset) && (offset >= start); <==== HERE
'Error:
' return hr;
'}
Dim localScopes = builder.GetAllScopes()
Return New MethodBody(builder.RealizedIL,
builder.MaxStack,
If(method.PartialDefinitionPart, method),
0, ' TODO: implement Lambda EnC
builder.LocalSlotManager.LocalsInOrder(),
builder.RealizedSequencePoints,
debugDocumentProvider,
builder.RealizedExceptionHandlers,
localScopes,
hasDynamicLocalVariables:=False,
importScopeOpt:=namespaceScopes,
lambdaDebugInfo:=ImmutableArray(Of LambdaDebugInfo).Empty,
closureDebugInfo:=ImmutableArray(Of ClosureDebugInfo).Empty,
stateMachineTypeNameOpt:=stateMachineTypeOpt?.Name, ' TODO: remove or update AddedOrChangedMethodInfo
stateMachineHoistedLocalScopes:=Nothing,
stateMachineHoistedLocalSlots:=stateMachineHoistedLocalSlots,
stateMachineAwaiterSlots:=stateMachineAwaiterSlots,
asyncMethodDebugInfo:=asyncDebugInfo)
Finally
' Free resources used by the basic blocks in the builder.
builder.FreeBasicBlocks()
End Try
End Function
Private Shared Sub GetStateMachineSlotDebugInfo(fieldDefs As IEnumerable(Of Cci.IFieldDefinition),
ByRef hoistedVariableSlots As ImmutableArray(Of EncHoistedLocalInfo),
ByRef awaiterSlots As ImmutableArray(Of Cci.ITypeReference))
Dim hoistedVariables = ArrayBuilder(Of EncHoistedLocalInfo).GetInstance()
Dim awaiters = ArrayBuilder(Of Cci.ITypeReference).GetInstance()
For Each field As StateMachineFieldSymbol In fieldDefs
Dim index = field.SlotIndex
If field.SlotDebugInfo.SynthesizedKind = SynthesizedLocalKind.AwaiterField Then
Debug.Assert(index >= 0)
While index >= awaiters.Count
awaiters.Add(Nothing)
End While
awaiters(index) = TryCast(field.Type, Cci.ITypeReference)
ElseIf Not field.SlotDebugInfo.Id.IsNone Then
Debug.Assert(index >= 0 AndAlso field.SlotDebugInfo.SynthesizedKind.IsLongLived())
While index >= hoistedVariables.Count
' Empty slots may be present if variables were deleted during EnC.
hoistedVariables.Add(New EncHoistedLocalInfo())
End While
hoistedVariables(index) = New EncHoistedLocalInfo(field.SlotDebugInfo, TryCast(field.Type, Cci.ITypeReference))
End If
Next
hoistedVariableSlots = hoistedVariables.ToImmutableAndFree()
awaiterSlots = awaiters.ToImmutableAndFree()
End Sub
Friend Shared Function BindAndAnalyzeMethodBody(method As MethodSymbol,
compilationState As TypeCompilationState,
diagnostics As DiagnosticBag,
containingTypeBinder As Binder,
ByRef referencedConstructor As MethodSymbol,
ByRef injectDefaultConstructorCall As Boolean,
ByRef methodBodyBinder As Binder) As BoundBlock
referencedConstructor = Nothing
injectDefaultConstructorCall = False
methodBodyBinder = Nothing
Dim body = method.GetBoundMethodBody(diagnostics, methodBodyBinder)
Debug.Assert(body IsNot Nothing)
Analyzer.AnalyzeMethodBody(method, body, diagnostics)
DiagnosticsPass.IssueDiagnostics(body, diagnostics, method)
Debug.Assert(method.IsFromCompilation(compilationState.Compilation))
If Not method.IsShared AndAlso compilationState.InitializeComponentOpt IsNot Nothing AndAlso
Not method.IsImplicitlyDeclared Then
InitializeComponentCallTreeBuilder.CollectCallees(compilationState, method, body)
End If
' Instance constructor should return the referenced constructor in 'referencedConstructor'
If method.MethodKind = MethodKind.Constructor Then
' class constructors must inject call to the base
injectDefaultConstructorCall = Not method.ContainingType.IsValueType
' Try find explicitly called constructor, it should be the first statement in the block
If body IsNot Nothing AndAlso body.Statements.Length > 0 Then
Dim theFirstStatement As BoundStatement = body.Statements(0)
' Must be BoundExpressionStatement/BoundCall
If theFirstStatement.HasErrors Then
injectDefaultConstructorCall = False
ElseIf theFirstStatement.Kind = BoundKind.ExpressionStatement Then
Dim referencedMethod As MethodSymbol = TryGetMethodCalledInBoundExpressionStatement(DirectCast(theFirstStatement, BoundExpressionStatement))
If referencedMethod IsNot Nothing AndAlso referencedMethod.MethodKind = MethodKind.Constructor Then
referencedConstructor = referencedMethod
injectDefaultConstructorCall = False
End If
End If
End If
' If we didn't find explicitly referenced constructor, use implicitly generated call
If injectDefaultConstructorCall Then
' NOTE: We might generate an error in this call in case there is
' no parameterless constructor suitable for calling
referencedConstructor = FindConstructorToCallByDefault(method, diagnostics, If(methodBodyBinder, containingTypeBinder))
End If
End If
Return body
End Function
Private Class InitializeComponentCallTreeBuilder
Inherits BoundTreeWalker
Private m_CalledMethods As HashSet(Of MethodSymbol)
Private ReadOnly m_ContainingType As NamedTypeSymbol
Private Sub New(containingType As NamedTypeSymbol)
m_ContainingType = containingType
End Sub
Public Shared Sub CollectCallees(compilationState As TypeCompilationState, method As MethodSymbol, block As BoundBlock)
Dim visitor As New InitializeComponentCallTreeBuilder(method.ContainingType)
visitor.VisitBlock(block)
If visitor.m_CalledMethods IsNot Nothing Then
compilationState.AddToInitializeComponentCallTree(method, visitor.m_CalledMethods.ToArray().AsImmutableOrNull())
End If
End Sub
Public Overrides Function VisitCall(node As BoundCall) As BoundNode
If node.ReceiverOpt IsNot Nothing AndAlso
(node.ReceiverOpt.Kind = BoundKind.MeReference OrElse node.ReceiverOpt.Kind = BoundKind.MyClassReference) AndAlso
Not node.Method.IsShared AndAlso node.Method.OriginalDefinition.ContainingType Is m_ContainingType Then
If m_CalledMethods Is Nothing Then
m_CalledMethods = New HashSet(Of MethodSymbol)(ReferenceEqualityComparer.Instance)
End If
m_CalledMethods.Add(node.Method.OriginalDefinition)
End If
Return MyBase.VisitCall(node)
End Function
End Class
' This method may force completion of attributes to calculate if a symbol is Obsolete. Since this method is only called during
' lowering of default constructors, this should not cause any cycles.
Private Shared Function FindConstructorToCallByDefault(constructor As MethodSymbol, diagnostics As DiagnosticBag, Optional binderForAccessibilityCheckOpt As Binder = Nothing) As MethodSymbol
Debug.Assert(constructor IsNot Nothing)
Debug.Assert(constructor.MethodKind = MethodKind.Constructor)
Dim containingType As NamedTypeSymbol = constructor.ContainingType
Debug.Assert(Not containingType.IsValueType)
If containingType.IsSubmissionClass Then
' TODO (tomat): report errors if not available
Dim objectType = constructor.ContainingAssembly.GetSpecialType(SpecialType.System_Object)
Return objectType.InstanceConstructors.Single()
End If
' If the type is a structure, then invoke the default constructor on the current type.
' Otherwise, invoke the default constructor on the base type.
Dim defaultConstructorType As NamedTypeSymbol = containingType.BaseTypeNoUseSiteDiagnostics
If defaultConstructorType Is Nothing OrElse defaultConstructorType.IsErrorType Then
' possible if class System.Object in source doesn't have an explicit constructor
Return Nothing
End If
' If 'binderForAccessibilityCheckOpt' is not specified, containing type must be System.Object
If binderForAccessibilityCheckOpt Is Nothing Then
Debug.Assert(defaultConstructorType.IsObjectType)
End If
Dim candidate As MethodSymbol = Nothing
Dim atLeastOneAccessibleCandidateFound As Boolean = False
For Each m In defaultConstructorType.InstanceConstructors
' NOTE: Generic constructors are disallowed, but in case they
' show up because of bad metadata, ignore them.
If m.IsGenericMethod Then
Continue For
End If
If binderForAccessibilityCheckOpt IsNot Nothing Then
' Use binder to check accessibility
If Not binderForAccessibilityCheckOpt.IsAccessible(m, useSiteDiagnostics:=Nothing, accessThroughType:=containingType) Then
Continue For
End If
Else
' If there is no binder, just check if the method is public
If m.DeclaredAccessibility <> Accessibility.Public Then
Continue For
End If
' NOTE: if there is no binder, we will only be able to emit a call to parameterless
' constructor, but not for constructors with optional parameters and/or ParamArray
If m.ParameterCount <> 0 Then
atLeastOneAccessibleCandidateFound = True ' it is still accessible
Continue For
End If
End If
' The constructor is accessible
atLeastOneAccessibleCandidateFound = True
' Class constructors can be called with no parameters when the parameters are optional or paramarray. However, for structures
' there cannot be any parameters.
Dim canBeCalledWithNoParameters = If(containingType.IsReferenceType, m.CanBeCalledWithNoParameters(), m.ParameterCount = 0)
If canBeCalledWithNoParameters Then
If candidate Is Nothing Then
candidate = m
Else
' Too many candidates, use different errors for synthesized and regular constructors
If constructor.IsImplicitlyDeclared Then
' Synthesized constructor
diagnostics.Add(New VBDiagnostic(
ErrorFactory.ErrorInfo(ERRID.ERR_NoUniqueConstructorOnBase2, containingType, containingType.BaseTypeNoUseSiteDiagnostics),
containingType.Locations(0)))
Else
' Regular constructor
diagnostics.Add(New VBDiagnostic(
ErrorFactory.ErrorInfo(ERRID.ERR_RequiredNewCallTooMany2, defaultConstructorType, containingType),
constructor.Locations(0)))
End If
Return candidate
End If
End If
Next
' Generate an error
If candidate Is Nothing Then
If atLeastOneAccessibleCandidateFound Then
' Different errors for synthesized and regular constructors
If constructor.IsImplicitlyDeclared Then
' Synthesized constructor
diagnostics.Add(New VBDiagnostic(
ErrorFactory.ErrorInfo(ERRID.ERR_NoConstructorOnBase2, containingType, containingType.BaseTypeNoUseSiteDiagnostics),
containingType.Locations(0)))
Else
' Regular constructor
diagnostics.Add(New VBDiagnostic(
ErrorFactory.ErrorInfo(ERRID.ERR_RequiredNewCall2, defaultConstructorType, containingType),
constructor.Locations(0)))
End If
Else
' No accessible constructor
' NOTE: Dev10 generates this error in 'Inherits' clause of the type, but it is not available
' in *all* cases, so changing the error location to containingType's location
diagnostics.Add(New VBDiagnostic(
ErrorFactory.ErrorInfo(ERRID.ERR_NoAccessibleConstructorOnBase, containingType.BaseTypeNoUseSiteDiagnostics),
containingType.Locations(0)))
End If
End If
Debug.Assert(candidate <> constructor)
' If the candidate is Obsolete then report diagnostics.
If candidate IsNot Nothing Then
candidate.ForceCompleteObsoleteAttribute()
If candidate.ObsoleteState = ThreeState.True Then
Dim data = candidate.ObsoleteAttributeData
' If we have a synthesized constructor then give an error saying that there is no non-obsolete
' base constructor. If we have a user-defined constructor then ask the user to explcitly call a
' constructor so that they have a chance to call a non-obsolete base constructor.
If constructor.IsImplicitlyDeclared Then
' Synthesized constructor.
If String.IsNullOrEmpty(data.Message) Then
diagnostics.Add(If(data.IsError, ERRID.ERR_NoNonObsoleteConstructorOnBase3, ERRID.WRN_NoNonObsoleteConstructorOnBase3),
containingType.Locations(0),
containingType,
candidate,
containingType.BaseTypeNoUseSiteDiagnostics)
Else
diagnostics.Add(If(data.IsError, ERRID.ERR_NoNonObsoleteConstructorOnBase4, ERRID.WRN_NoNonObsoleteConstructorOnBase4),
containingType.Locations(0),
containingType,
candidate,
containingType.BaseTypeNoUseSiteDiagnostics,
data.Message)
End If
Else
' Regular constructor.
If String.IsNullOrEmpty(data.Message) Then
diagnostics.Add(If(data.IsError, ERRID.ERR_RequiredNonObsoleteNewCall3, ERRID.WRN_RequiredNonObsoleteNewCall3),
constructor.Locations(0),
candidate,
containingType.BaseTypeNoUseSiteDiagnostics,
containingType)
Else
diagnostics.Add(If(data.IsError, ERRID.ERR_RequiredNonObsoleteNewCall4, ERRID.WRN_RequiredNonObsoleteNewCall4),
constructor.Locations(0),
candidate,
containingType.BaseTypeNoUseSiteDiagnostics,
containingType,
data.Message)
End If
End If
End If
End If
Return candidate
End Function
Private Shared Function BindDefaultConstructorInitializer(constructor As MethodSymbol,
constructorToCall As MethodSymbol,
diagnostics As DiagnosticBag,
Optional binderOpt As Binder = Nothing) As BoundExpressionStatement
Dim voidType As NamedTypeSymbol = constructor.ContainingAssembly.GetSpecialType(SpecialType.System_Void)
' NOTE: we can ignore use site errors in this place because they should have already be reported
' either in real or synthesized constructor
Dim syntaxNode As VisualBasicSyntaxNode = constructor.Syntax
Dim thisRef As New BoundMeReference(syntaxNode, constructor.ContainingType)
thisRef.SetWasCompilerGenerated()
Dim baseInvocation As BoundExpression = Nothing
If constructorToCall.ParameterCount = 0 Then
' If this is parameterless constructor, we can build a call directly
baseInvocation = New BoundCall(syntaxNode, constructorToCall, Nothing, thisRef, ImmutableArray(Of BoundExpression).Empty, Nothing, voidType)
Else
' Otherwise we should bind invocation exprerssion
' Binder must be passed in 'binderOpt'
Debug.Assert(binderOpt IsNot Nothing)
' Build a method group
Dim group As New BoundMethodGroup(constructor.Syntax,
typeArgumentsOpt:=Nothing,
methods:=ImmutableArray.Create(Of MethodSymbol)(constructorToCall),
resultKind:=LookupResultKind.Good,
receiverOpt:=thisRef,
qualificationKind:=QualificationKind.QualifiedViaValue)
baseInvocation = binderOpt.BindInvocationExpression(constructor.Syntax,
Nothing,
TypeCharacter.None,
group,
ImmutableArray(Of BoundExpression).Empty,
Nothing,
diagnostics,
callerInfoOpt:=Nothing,
allowConstructorCall:=True)
End If
baseInvocation.SetWasCompilerGenerated()
Dim statement As New BoundExpressionStatement(syntaxNode, baseInvocation)
statement.SetWasCompilerGenerated()
Return statement
End Function
Friend Shared Function BindDefaultConstructorInitializer(constructor As MethodSymbol, diagnostics As DiagnosticBag) As BoundExpressionStatement
' NOTE: this method is only called from outside
' NOTE: Because we don't pass a binder into this method, we assume that (a) containing type of
' the constructor is a reference type inherited from System.Object (later is asserted
' in 'FindConstructorToCallByDefault'), and (b) System.Object must have Public parameterless
' constructor (asserted in 'BindDefaultConstructorInitializer')
' NOTE: We might generate an error in this call in case there is
' no parameterless constructor suitable for calling
Dim baseConstructor As MethodSymbol = FindConstructorToCallByDefault(constructor, diagnostics)
If baseConstructor Is Nothing Then
Return Nothing
End If
Return BindDefaultConstructorInitializer(constructor, baseConstructor, diagnostics)
End Function
Private Shared Function CreateDebugDocumentForFile(normalizedPath As String) As Cci.DebugSourceDocument
Return New Cci.DebugSourceDocument(normalizedPath, Cci.DebugSourceDocument.CorSymLanguageTypeBasic)
End Function
Private Shared Function PassesFilter(filterOpt As Predicate(Of Symbol), symbol As Symbol) As Boolean
Return filterOpt Is Nothing OrElse filterOpt(symbol)
End Function
End Class
End Namespace
|
mono/roslyn
|
src/Compilers/VisualBasic/Portable/Compilation/MethodCompiler.vb
|
Visual Basic
|
apache-2.0
| 102,315
|
'*******************************************************************************************'
' '
' 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.BarCode
Module Module1
Sub Main()
' Create new barcode
Dim barcode As New Barcode()
' Set symbology
barcode.Symbology = SymbologyType.DutchKix
' Set value
barcode.Value = "thisisateststring"
' Save barcode to image
barcode.SaveImage("result.png")
' Show image in default image viewer
Process.Start("result.png")
End Sub
End Module
|
bytescout/ByteScout-SDK-SourceCode
|
Premium Suite/VB.NET/Generate dutch kix barcode with barcode sdk/Module1.vb
|
Visual Basic
|
apache-2.0
| 1,410
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
'-----------------------------------------------------------------------------------------------------------
'Reads the tree from an XML file into a ParseTree object and sub-objects. Reports many kinds of errors
'during the reading process.
'-----------------------------------------------------------------------------------------------------------
Imports System.IO
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports System.Xml
Imports System.Xml.Schema
Imports <xmlns="http://schemas.microsoft.com/VisualStudio/Roslyn/Compiler">
Public Module ReadTree
Private s_currentFile As String
' Read an XML file and return the resulting ParseTree object.
Public Function TryReadTheTree(fileName As String, <Out> ByRef tree As ParseTree) As Boolean
tree = Nothing
Dim validationError As Boolean = False
Dim xDoc = GetXDocument(fileName, validationError)
If validationError Then
Return False
End If
tree = New ParseTree
Dim x = xDoc.<define-parse-tree>
tree.FileName = fileName
tree.NamespaceName = xDoc.<define-parse-tree>.@namespace
tree.VisitorName = xDoc.<define-parse-tree>.@visitor
tree.RewriteVisitorName = xDoc.<define-parse-tree>.@<rewrite-visitor>
tree.FactoryClassName = xDoc.<define-parse-tree>.@<factory-class>
tree.ContextualFactoryClassName = xDoc.<define-parse-tree>.@<contextual-factory-class>
Dim defs = xDoc.<define-parse-tree>.<definitions>
For Each struct In defs.<node-structure>
If tree.NodeStructures.ContainsKey(struct.@name) Then
tree.ReportError(struct, "node-structure with name ""{0}"" already defined", struct.@name)
Else
tree.NodeStructures.Add(struct.@name, New ParseNodeStructure(struct, tree))
End If
Next
For Each al In defs.<node-kind-alias>
If tree.Aliases.ContainsKey(al.@name) Then
tree.ReportError(al, "node-kind-alias with name ""{0}"" already defined", al.@name)
Else
tree.Aliases.Add(al.@name, New ParseNodeKindAlias(al, tree))
End If
Next
For Each en In defs.<enumeration>
If tree.Enumerations.ContainsKey(en.@name) Then
tree.ReportError(en, "enumeration with name ""{0}"" already defined", en.@name)
Else
tree.Enumerations.Add(en.@name, New ParseEnumeration(en, tree))
End If
Next
tree.FinishedReading()
Return True
End Function
' Open the input XML file as an XDocument, using the reading options that we want.
' We use a schema to validate the input.
Private Function GetXDocument(fileName As String, <Out> ByRef validationError As Boolean) As XDocument
s_currentFile = fileName
Dim hadError = False
Dim onValidationError =
Sub(sender As Object, e As ValidationEventArgs)
' A validation error occurred while reading the document. Tell the user.
Console.Error.WriteLine("{0}({1},{2}): Invalid input: {3}", s_currentFile, e.Exception.LineNumber, e.Exception.LinePosition, e.Exception.Message)
hadError = True
End Sub
Dim xDoc As XDocument
Using schemaReader = XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream("VBSyntaxModelSchema.xsd"))
Dim readerSettings As New XmlReaderSettings()
readerSettings.DtdProcessing = DtdProcessing.Prohibit
readerSettings.XmlResolver = Nothing
readerSettings.Schemas.Add(Nothing, schemaReader)
readerSettings.ValidationType = ValidationType.Schema
AddHandler readerSettings.ValidationEventHandler, onValidationError
Dim fileStream As New FileStream(fileName, FileMode.Open, FileAccess.Read)
Using reader = XmlReader.Create(fileStream, readerSettings)
xDoc = XDocument.Load(reader, LoadOptions.SetLineInfo Or LoadOptions.PreserveWhitespace)
End Using
End Using
validationError = hadError
Return xDoc
End Function
End Module
|
moozzyk/roslyn
|
src/Tools/Source/CompilerGeneratorTools/Source/VisualBasicSyntaxGenerator/XML/ReadTree.vb
|
Visual Basic
|
apache-2.0
| 4,405
|
' 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.Concurrent
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Collections.ObjectModel
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Allows asking semantic questions about any node in a SyntaxTree within a Compilation.
''' </summary>
Friend Class SyntaxTreeSemanticModel
Inherits VBSemanticModel
Private ReadOnly _compilation As VisualBasicCompilation
Private ReadOnly _sourceModule As SourceModuleSymbol
Private ReadOnly _syntaxTree As SyntaxTree
Private ReadOnly _binderFactory As BinderFactory
Private ReadOnly _ignoresAccessibility As Boolean
' maps from a higher-level binder to an appropriate SemanticModel for the construct (such as a method, or initializer).
Private ReadOnly _semanticModelCache As New ConcurrentDictionary(Of Tuple(Of Binder, Boolean), MemberSemanticModel)()
Friend Sub New(compilation As VisualBasicCompilation, sourceModule As SourceModuleSymbol, syntaxTree As SyntaxTree, Optional ignoreAccessibility As Boolean = False)
_compilation = compilation
_sourceModule = sourceModule
_syntaxTree = syntaxTree
_ignoresAccessibility = ignoreAccessibility
_binderFactory = New BinderFactory(sourceModule, syntaxTree)
End Sub
''' <summary>
''' The compilation associated with this binding.
''' </summary>
Public Overrides ReadOnly Property Compilation As VisualBasicCompilation
Get
Return _compilation
End Get
End Property
''' <summary>
''' The root node of the syntax tree that this binding is based on.
''' </summary>
Friend Overrides ReadOnly Property Root As VisualBasicSyntaxNode
Get
Return DirectCast(_syntaxTree.GetRoot(), VisualBasicSyntaxNode)
End Get
End Property
''' <summary>
''' The SyntaxTree that is bound
''' </summary>
Public Overrides ReadOnly Property SyntaxTree As SyntaxTree
Get
Return Me._syntaxTree
End Get
End Property
''' <summary>
''' Returns true if this Is a SemanticModel that ignores accessibility rules when answering semantic questions.
''' </summary>
Public NotOverridable Overrides ReadOnly Property IgnoresAccessibility As Boolean
Get
Return Me._ignoresAccessibility
End Get
End Property
''' <summary>
''' Get all the errors within the syntax tree associated with this object. Includes errors involving compiling
''' method bodies or initializers, in addition to the errors returned by GetDeclarationDiagnostics and parse errors.
''' </summary>
''' <param name="span">Optional span within the syntax tree for which to get diagnostics.
''' If no argument is specified, then diagnostics for the entire tree are returned.</param>
''' <param name="cancellationToken">A cancellation token that can be used to cancel the process of obtaining the
''' diagnostics.</param>
''' <remarks>
''' Because this method must semantically analyze all method bodies and initializers to check for diagnostics, it may
''' take a significant amount of time. Unlike GetDeclarationDiagnostics, diagnostics for method bodies and
''' initializers are not cached, the any semantic information used to obtain the diagnostics is discarded.
''' </remarks>
Public Overrides Function GetDiagnostics(Optional span As TextSpan? = Nothing, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic)
Return _compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Compile, _syntaxTree, span, includeEarlierStages:=True, cancellationToken:=cancellationToken)
End Function
''' <summary>
''' Get all of the syntax errors within the syntax tree associated with this
''' object. Does not get errors involving declarations or compiling method bodies or initializers.
''' </summary>
''' <param name="span">Optional span within the syntax tree for which to get diagnostics.
''' If no argument is specified, then diagnostics for the entire tree are returned.</param>
''' <param name="cancellationToken">A cancellation token that can be used to cancel the
''' process of obtaining the diagnostics.</param>
Public Overrides Function GetSyntaxDiagnostics(Optional span As TextSpan? = Nothing, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic)
Return _compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Parse, _syntaxTree, span, includeEarlierStages:=False, cancellationToken:=cancellationToken)
End Function
''' <summary>
''' Get all the syntax and declaration errors within the syntax tree associated with this object. Does not get
''' errors involving compiling method bodies or initializers.
''' </summary>
''' <param name="span">Optional span within the syntax tree for which to get diagnostics.
''' If no argument is specified, then diagnostics for the entire tree are returned.</param>
''' <param name="cancellationToken">A cancellation token that can be used to cancel the process of obtaining the
''' diagnostics.</param>
''' <remarks>The declaration errors for a syntax tree are cached. The first time this method is called, a ll
''' declarations are analyzed for diagnostics. Calling this a second time will return the cached diagnostics.
''' </remarks>
Public Overrides Function GetDeclarationDiagnostics(Optional span As TextSpan? = Nothing, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic)
Return _compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Declare, _syntaxTree, span, includeEarlierStages:=False, cancellationToken:=cancellationToken)
End Function
''' <summary>
''' Get all the syntax and declaration errors within the syntax tree associated with this object. Does not get
''' errors involving compiling method bodies or initializers.
''' </summary>
''' <param name="span">Optional span within the syntax tree for which to get diagnostics.
''' If no argument is specified, then diagnostics for the entire tree are returned.</param>
''' <param name="cancellationToken">A cancellation token that can be used to cancel the process of obtaining the
''' diagnostics.</param>
''' <remarks>The declaration errors for a syntax tree are cached. The first time this method is called, a ll
''' declarations are analyzed for diagnostics. Calling this a second time will return the cached diagnostics.
''' </remarks>
Public Overrides Function GetMethodBodyDiagnostics(Optional span As TextSpan? = Nothing, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic)
Return _compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Compile, _syntaxTree, span, includeEarlierStages:=False, cancellationToken:=cancellationToken)
End Function
' PERF: These shared variables avoid repeated allocation of Func(Of Binder, MemberSemanticModel) in GetMemberSemanticModel
Private Shared ReadOnly s_methodBodySemanticModelCreator As Func(Of Tuple(Of Binder, Boolean), MemberSemanticModel) = Function(key As Tuple(Of Binder, Boolean)) MethodBodySemanticModel.Create(DirectCast(key.Item1, MethodBodyBinder), key.Item2)
Private Shared ReadOnly s_initializerSemanticModelCreator As Func(Of Tuple(Of Binder, Boolean), MemberSemanticModel) = Function(key As Tuple(Of Binder, Boolean)) InitializerSemanticModel.Create(DirectCast(key.Item1, DeclarationInitializerBinder), key.Item2)
Private Shared ReadOnly s_attributeSemanticModelCreator As Func(Of Tuple(Of Binder, Boolean), MemberSemanticModel) = Function(key As Tuple(Of Binder, Boolean)) AttributeSemanticModel.Create(DirectCast(key.Item1, AttributeBinder), key.Item2)
Private Shared ReadOnly s_topLevelCodeSemanticModelCreator As Func(Of Tuple(Of Binder, Boolean), MemberSemanticModel) = Function(key As Tuple(Of Binder, Boolean)) New TopLevelCodeSemanticModel(DirectCast(key.Item1, TopLevelCodeBinder), key.Item2)
Public Function GetMemberSemanticModel(binder As Binder) As MemberSemanticModel
If TypeOf binder Is MethodBodyBinder Then
Return _semanticModelCache.GetOrAdd(Tuple.Create(binder, IgnoresAccessibility), s_methodBodySemanticModelCreator)
End If
If TypeOf binder Is DeclarationInitializerBinder Then
Return _semanticModelCache.GetOrAdd(Tuple.Create(binder, IgnoresAccessibility), s_initializerSemanticModelCreator)
End If
If TypeOf binder Is AttributeBinder Then
Return _semanticModelCache.GetOrAdd(Tuple.Create(binder, IgnoresAccessibility), s_attributeSemanticModelCreator)
End If
If TypeOf binder Is TopLevelCodeBinder Then
Return _semanticModelCache.GetOrAdd(Tuple.Create(binder, IgnoresAccessibility), s_topLevelCodeSemanticModelCreator)
End If
Return Nothing
End Function
Friend Function GetMemberSemanticModel(position As Integer) As MemberSemanticModel
Dim binder As binder = _binderFactory.GetBinderForPosition(FindInitialNodeFromPosition(position), position)
Dim model = GetMemberSemanticModel(binder) ' Depends on the runtime type, so don't wrap in a SemanticModelBinder.
Debug.Assert(model Is Nothing OrElse model.RootBinder.IsSemanticModelBinder)
Return model
End Function
Friend Function GetMemberSemanticModel(node As VisualBasicSyntaxNode) As MemberSemanticModel
Return GetMemberSemanticModel(node.SpanStart)
End Function
Friend Overrides Function GetEnclosingBinder(position As Integer) As Binder
' special case if node is from interior of a member declaration (method body, etc)
Dim model As MemberSemanticModel = GetMemberSemanticModel(position)
If model IsNot Nothing Then
' If the node is from the interior of a member declaration, then we need to go further
' to find more nested binders.
Return model.GetEnclosingBinder(position)
Else
Dim binder As binder = _binderFactory.GetBinderForPosition(FindInitialNodeFromPosition(position), position)
Return SemanticModelBinder.Mark(binder, IgnoresAccessibility)
End If
End Function
Friend Overrides Function GetInvokeSummaryForRaiseEvent(node As RaiseEventStatementSyntax) As BoundNodeSummary
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetInvokeSummaryForRaiseEvent(node)
Else
Return Nothing
End If
End Function
Friend Overrides Function GetCrefReferenceSymbolInfo(crefReference As CrefReferenceSyntax, options As VBSemanticModel.SymbolInfoOptions, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
ValidateSymbolInfoOptions(options)
Debug.Assert(IsInCrefOrNameAttributeInterior(crefReference))
Return GetSymbolInfoForCrefOrNameAttributeReference(crefReference, options)
End Function
Friend Overrides Function GetExpressionSymbolInfo(node As ExpressionSyntax, options As SymbolInfoOptions, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
ValidateSymbolInfoOptions(options)
node = SyntaxFactory.GetStandaloneExpression(DirectCast(node, ExpressionSyntax))
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
Dim result As SymbolInfo
If model IsNot Nothing Then
result = model.GetExpressionSymbolInfo(node, options, cancellationToken)
' If we didn't get anything and were in Type/Namespace only context, let's bind normally and see
' if any symbol comes out.
If result.IsEmpty AndAlso SyntaxFacts.IsInNamespaceOrTypeContext(node) Then
Dim tryAsExpression = TryBindNamespaceOrTypeAsExpression(node, options)
If Not tryAsExpression.IsEmpty Then
result = tryAsExpression
End If
End If
Else
' We don't have a bound tree to examine outside of a member semantic model. Instead, we just
' rebind the appropriate syntax as if we were binding it as part of symbol creation.
'
' if expression is not part of a member semantic model then
' a) it may be a reference to a type or namespace name
' b) it may be a reference to a interface member in an Implements clause
' c) it may be a reference to a field in an Handles clause
' d) it may be a reference to an event in an Handles clause
If SyntaxFacts.IsImplementedMember(node) Then
result = GetImplementedMemberSymbolInfo(DirectCast(node, QualifiedNameSyntax), options)
ElseIf SyntaxFacts.IsHandlesEvent(node) Then
result = GetHandlesEventSymbolInfo(DirectCast(node.Parent, HandlesClauseItemSyntax), options)
ElseIf SyntaxFacts.IsHandlesContainer(node) Then
Dim parent = node.Parent
If parent.Kind <> SyntaxKind.HandlesClauseItem Then
parent = parent.Parent
End If
result = GetHandlesContainerSymbolInfo(DirectCast(parent, HandlesClauseItemSyntax), options)
ElseIf SyntaxFacts.IsHandlesProperty(node) Then
result = GetHandlesPropertySymbolInfo(DirectCast(node.Parent.Parent, HandlesClauseItemSyntax), options)
ElseIf IsInCrefOrNameAttributeInterior(node) Then
result = GetSymbolInfoForCrefOrNameAttributeReference(node, options)
ElseIf SyntaxFacts.IsInNamespaceOrTypeContext(node) Then
' Bind the type or namespace name.
result = GetTypeOrNamespaceSymbolInfoNotInMember(DirectCast(node, TypeSyntax), options)
Else
result = SymbolInfo.None
End If
End If
Return result
End Function
Friend Overrides Function GetCollectionInitializerAddSymbolInfo(collectionInitializer As ObjectCreationExpressionSyntax, node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(collectionInitializer)
If model IsNot Nothing Then
Return model.GetCollectionInitializerAddSymbolInfo(collectionInitializer, node, cancellationToken)
End If
Return SymbolInfo.None
End Function
Private Function TryBindNamespaceOrTypeAsExpression(node As ExpressionSyntax, options As SymbolInfoOptions) As SymbolInfo
' Let's bind expression normally and use what comes back as candidate symbols.
Dim binder As Binder = GetEnclosingBinder(node.SpanStart)
If binder IsNot Nothing Then
Dim diagnostics As DiagnosticBag = DiagnosticBag.GetInstance()
Dim bound As BoundExpression = binder.BindExpression(node, diagnostics)
diagnostics.Free()
Dim newSymbolInfo = GetSymbolInfoForNode(options, New BoundNodeSummary(bound, bound, Nothing), binderOpt:=Nothing)
If Not newSymbolInfo.GetAllSymbols().IsDefaultOrEmpty Then
Return SymbolInfoFactory.Create(newSymbolInfo.GetAllSymbols(), LookupResultKind.NotATypeOrNamespace)
End If
End If
Return SymbolInfo.None
End Function
Friend Overrides Function GetExpressionTypeInfo(node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As VisualBasicTypeInfo
node = SyntaxFactory.GetStandaloneExpression(DirectCast(node, ExpressionSyntax))
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetExpressionTypeInfo(node, cancellationToken)
Else
' We don't have a bound tree to examine outside of a member semantic model. Instead, we just
' rebind the appropriate syntax as if we were binding it as part of symbol creation.
'
' if expression is not part of a member semantic model then
' a) it may be a reference to a type or namespace name
' b) it may be a reference to a interface member in an Implements clause
' c) it may be a reference to a field in an Handles clause
' d) it may be a reference to an event in an Handles clause
If SyntaxFacts.IsImplementedMember(node) Then
Return GetImplementedMemberTypeInfo(DirectCast(node, QualifiedNameSyntax))
ElseIf SyntaxFacts.IsHandlesEvent(node) Then
Return GetHandlesEventTypeInfo(DirectCast(node, IdentifierNameSyntax))
ElseIf SyntaxFacts.IsHandlesContainer(node) Then
Dim parent = node.Parent
If parent.Kind <> SyntaxKind.HandlesClauseItem Then
parent = parent.Parent
End If
Return GetHandlesContainerTypeInfo(DirectCast(parent, HandlesClauseItemSyntax))
ElseIf SyntaxFacts.IsHandlesProperty(node) Then
Return GetHandlesPropertyTypeInfo(DirectCast(node.Parent.Parent, HandlesClauseItemSyntax))
ElseIf IsInCrefOrNameAttributeInterior(node) Then
Dim typeSyntax = TryCast(node, TypeSyntax)
If typeSyntax IsNot Nothing Then
Return GetTypeInfoForCrefOrNameAttributeReference(typeSyntax)
End If
ElseIf SyntaxFacts.IsInNamespaceOrTypeContext(node) Then
' Bind the type or namespace name.
Return GetTypeOrNamespaceTypeInfoNotInMember(DirectCast(node, TypeSyntax))
End If
Return VisualBasicTypeInfo.None
End If
End Function
Friend Overrides Function GetExpressionMemberGroup(node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Symbol)
node = SyntaxFactory.GetStandaloneExpression(DirectCast(node, ExpressionSyntax))
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetExpressionMemberGroup(node, cancellationToken)
Else
Return ImmutableArray(Of Symbol).Empty
End If
End Function
Friend Overrides Function GetExpressionConstantValue(node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As ConstantValue
node = SyntaxFactory.GetStandaloneExpression(DirectCast(node, ExpressionSyntax))
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetExpressionConstantValue(node, cancellationToken)
Else
Return Nothing
End If
End Function
Friend Overrides Function GetAttributeSymbolInfo(attribute As AttributeSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(attribute)
If model IsNot Nothing Then
Return model.GetAttributeSymbolInfo(attribute, cancellationToken)
Else
Return SymbolInfo.None
End If
End Function
Friend Overrides Function GetQueryClauseSymbolInfo(node As QueryClauseSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetQueryClauseSymbolInfo(node, cancellationToken)
Else
Return SymbolInfo.None
End If
End Function
Friend Overrides Function GetLetClauseSymbolInfo(node As ExpressionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetLetClauseSymbolInfo(node, cancellationToken)
Else
Return SymbolInfo.None
End If
End Function
Friend Overrides Function GetOrderingSymbolInfo(node As OrderingSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetOrderingSymbolInfo(node, cancellationToken)
Else
Return SymbolInfo.None
End If
End Function
Friend Overrides Function GetAggregateClauseSymbolInfoWorker(node As AggregateClauseSyntax, Optional cancellationToken As CancellationToken = Nothing) As AggregateClauseSymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetAggregateClauseSymbolInfoWorker(node, cancellationToken)
Else
Return New AggregateClauseSymbolInfo(SymbolInfo.None, SymbolInfo.None)
End If
End Function
Friend Overrides Function GetCollectionRangeVariableSymbolInfoWorker(node As CollectionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As CollectionRangeVariableSymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetCollectionRangeVariableSymbolInfoWorker(node, cancellationToken)
Else
Return CollectionRangeVariableSymbolInfo.None
End If
End Function
Friend Overrides Function GetAttributeTypeInfo(attribute As AttributeSyntax, Optional cancellationToken As CancellationToken = Nothing) As VisualBasicTypeInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(attribute)
If model IsNot Nothing Then
Return model.GetAttributeTypeInfo(attribute, cancellationToken)
Else
Return VisualBasicTypeInfo.None
End If
End Function
Friend Overrides Function GetAttributeMemberGroup(attribute As AttributeSyntax, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Symbol)
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(attribute)
If model IsNot Nothing Then
Return model.GetAttributeMemberGroup(attribute, cancellationToken)
Else
Return ImmutableArray(Of Symbol).Empty
End If
End Function
Private Function GetTypeOrNamespaceSymbolNotInMember(expression As TypeSyntax) As Symbol
Dim diagnostics As DiagnosticBag = DiagnosticBag.GetInstance()
Try
' Set up the binding context.
Dim binder As Binder = GetEnclosingBinder(expression.SpanStart)
' Attempt to bind the type or namespace
Dim resultSymbol As Symbol
If SyntaxFacts.IsInTypeOnlyContext(expression) Then
resultSymbol = binder.BindTypeOrAliasSyntax(expression, diagnostics)
Else
resultSymbol = binder.BindNamespaceOrTypeOrAliasSyntax(expression, diagnostics)
End If
' Create the result.
Return resultSymbol
Finally
diagnostics.Free()
End Try
End Function
' Get the symbol info of reference from 'cref' or 'name' attribute value
Private Function GetSymbolInfoForCrefOrNameAttributeReference(node As VisualBasicSyntaxNode, options As SymbolInfoOptions) As SymbolInfo
Dim typeParameters As ImmutableArray(Of Symbol) = Nothing
Dim result As ImmutableArray(Of Symbol) = GetCrefOrNameAttributeReferenceSymbols(node, (options And SymbolInfoOptions.ResolveAliases) = 0, typeParameters)
If result.IsDefaultOrEmpty Then
If typeParameters.IsDefaultOrEmpty Then
Return SymbolInfo.None
Else
Return SymbolInfoFactory.Create(typeParameters, LookupResultKind.NotReferencable)
End If
End If
If result.Length = 1 Then
Dim retValue As SymbolInfo = GetSymbolInfoForSymbol(result(0), options)
If retValue.CandidateReason = CandidateReason.None Then
Return retValue
End If
result = ImmutableArray(Of Symbol).Empty
End If
Dim symbolsBuilder = ArrayBuilder(Of Symbol).GetInstance()
symbolsBuilder.AddRange(result)
Dim symbols As ImmutableArray(Of Symbol) = RemoveErrorTypesAndDuplicates(symbolsBuilder, options)
symbolsBuilder.Free()
If symbols.Length = 0 Then
Return SymbolInfoFactory.Create(symbols, LookupResultKind.Empty)
End If
Return SymbolInfoFactory.Create(symbols, If(symbols.Length = 1, LookupResultKind.Good, LookupResultKind.Ambiguous))
End Function
' Get the type info of reference from 'cref' or 'name' attribute value
Private Function GetTypeInfoForCrefOrNameAttributeReference(name As TypeSyntax) As VisualBasicTypeInfo
Dim typeParameters As ImmutableArray(Of Symbol) = Nothing
Dim result As ImmutableArray(Of Symbol) = GetCrefOrNameAttributeReferenceSymbols(name, preserveAlias:=False, typeParameters:=typeParameters)
If result.IsDefaultOrEmpty Then
result = typeParameters
If result.IsDefaultOrEmpty Then
Return VisualBasicTypeInfo.None
End If
End If
If result.Length > 1 Then
Return VisualBasicTypeInfo.None
End If
Dim resultSymbol As Symbol = result(0)
Select Case resultSymbol.Kind
Case SymbolKind.ArrayType,
SymbolKind.TypeParameter,
SymbolKind.NamedType
Return GetTypeInfoForSymbol(resultSymbol)
End Select
Return VisualBasicTypeInfo.None
End Function
''' <summary>
''' Get symbols referenced from 'cref' or 'name' attribute value.
''' </summary>
''' <param name="node">Node to bind.</param>
''' <param name="preserveAlias">True to leave <see cref="AliasSymbol"/>s, False to unwrap them.</param>
''' <param name="typeParameters">Out: symbols that would have been in the return value but improperly refer to type parameters.</param>
''' <returns>Referenced symbols, less type parameters.</returns>
Private Function GetCrefOrNameAttributeReferenceSymbols(node As VisualBasicSyntaxNode,
preserveAlias As Boolean,
<Out> ByRef typeParameters As ImmutableArray(Of Symbol)) As ImmutableArray(Of Symbol)
typeParameters = ImmutableArray(Of Symbol).Empty
' We only allow a certain list of node kinds to be processed here
If node.Kind = SyntaxKind.XmlString Then
Return Nothing
End If
Debug.Assert(node.Kind = SyntaxKind.IdentifierName OrElse
node.Kind = SyntaxKind.GenericName OrElse
node.Kind = SyntaxKind.PredefinedType OrElse
node.Kind = SyntaxKind.QualifiedName OrElse
node.Kind = SyntaxKind.GlobalName OrElse
node.Kind = SyntaxKind.QualifiedCrefOperatorReference OrElse
node.Kind = SyntaxKind.CrefOperatorReference OrElse
node.Kind = SyntaxKind.CrefReference)
' We need to find trivia's enclosing binder first
Dim parent As VisualBasicSyntaxNode = node.Parent
Debug.Assert(parent IsNot Nothing)
Dim attributeNode As BaseXmlAttributeSyntax = Nothing
Do
Debug.Assert(parent IsNot Nothing)
Select Case parent.Kind
Case SyntaxKind.XmlCrefAttribute,
SyntaxKind.XmlNameAttribute
attributeNode = DirectCast(parent, BaseXmlAttributeSyntax)
Case SyntaxKind.DocumentationCommentTrivia
Exit Do
End Select
parent = parent.Parent
Loop
Debug.Assert(parent IsNot Nothing)
If attributeNode Is Nothing Then
Return Nothing
End If
Dim isCrefAttribute As Boolean = attributeNode.Kind = SyntaxKind.XmlCrefAttribute
Debug.Assert(isCrefAttribute OrElse attributeNode.Kind = SyntaxKind.XmlNameAttribute)
Dim trivia As SyntaxTrivia = DirectCast(parent, DocumentationCommentTriviaSyntax).ParentTrivia
If trivia.Kind = SyntaxKind.None Then
Return Nothing
End If
Dim token As SyntaxToken = CType(trivia.Token, SyntaxToken)
If token.Kind = SyntaxKind.None Then
Return Nothing
End If
Dim docCommentBinder = Me._binderFactory.GetBinderForPosition(node, node.SpanStart)
docCommentBinder = SemanticModelBinder.Mark(docCommentBinder, IgnoresAccessibility)
If isCrefAttribute Then
Dim symbols As ImmutableArray(Of Symbol)
Dim isTopLevel As Boolean
If node.Kind = SyntaxKind.CrefReference Then
isTopLevel = True
symbols = docCommentBinder.BindInsideCrefAttributeValue(DirectCast(node, CrefReferenceSyntax), preserveAlias, Nothing, Nothing)
Else
isTopLevel = node.Parent IsNot Nothing AndAlso node.Parent.Kind = SyntaxKind.CrefReference
symbols = docCommentBinder.BindInsideCrefAttributeValue(DirectCast(node, TypeSyntax), preserveAlias, Nothing, Nothing)
End If
If isTopLevel Then
Dim symbolsBuilder As ArrayBuilder(Of Symbol) = Nothing
Dim typeParametersBuilder As ArrayBuilder(Of Symbol) = Nothing
For i = 0 To symbols.Length - 1
Dim symbol = symbols(i)
If symbol.Kind = SymbolKind.TypeParameter Then
If symbolsBuilder Is Nothing Then
symbolsBuilder = ArrayBuilder(Of Symbol).GetInstance(i)
typeParametersBuilder = ArrayBuilder(Of Symbol).GetInstance()
symbolsBuilder.AddRange(symbols, i)
End If
typeParametersBuilder.Add(DirectCast(symbol, TypeParameterSymbol))
ElseIf symbolsBuilder IsNot Nothing Then
symbolsBuilder.Add(symbol)
End If
Next
If symbolsBuilder IsNot Nothing Then
symbols = symbolsBuilder.ToImmutableAndFree()
typeParameters = typeParametersBuilder.ToImmutableAndFree()
End If
End If
Return symbols
Else
Return docCommentBinder.BindXmlNameAttributeValue(DirectCast(node, IdentifierNameSyntax), useSiteDiagnostics:=Nothing)
End If
End Function
' Get the symbol info of type or namespace syntax that is outside a member body
Private Function GetTypeOrNamespaceSymbolInfoNotInMember(expression As TypeSyntax, options As SymbolInfoOptions) As SymbolInfo
Dim resultSymbol As Symbol = GetTypeOrNamespaceSymbolNotInMember(expression)
' Deal with the case of a namespace group. We may need to bind more in order to see if the ambiguity can be resolved.
If resultSymbol.Kind = SymbolKind.Namespace AndAlso
expression.Parent IsNot Nothing AndAlso
expression.Parent.Kind = SyntaxKind.QualifiedName AndAlso
DirectCast(expression.Parent, QualifiedNameSyntax).Left Is expression Then
Dim ns = DirectCast(resultSymbol, NamespaceSymbol)
If ns.NamespaceKind = NamespaceKindNamespaceGroup Then
Dim parentInfo As SymbolInfo = GetTypeOrNamespaceSymbolInfoNotInMember(DirectCast(expression.Parent, QualifiedNameSyntax), Nothing)
If Not parentInfo.IsEmpty Then
Dim namespaces = New SmallDictionary(Of NamespaceSymbol, Boolean)()
If parentInfo.Symbol IsNot Nothing Then
If Not Binder.AddReceiverNamespaces(namespaces, DirectCast(parentInfo.Symbol, Symbol), Compilation) Then
namespaces = Nothing
End If
Else
For Each candidate In parentInfo.CandidateSymbols
If Not Binder.AddReceiverNamespaces(namespaces, DirectCast(candidate, Symbol), Compilation) Then
namespaces = Nothing
Exit For
End If
Next
End If
If namespaces IsNot Nothing AndAlso namespaces.Count < ns.ConstituentNamespaces.Length Then
resultSymbol = DirectCast(ns, MergedNamespaceSymbol).Shrink(namespaces.Keys)
End If
End If
End If
End If
' Create the result.
Dim result = GetSymbolInfoForSymbol(resultSymbol, options)
' If we didn't get anything and were in Type/Namespace only context, let's bind normally and see
' if any symbol comes out.
If result.IsEmpty Then
Dim tryAsExpression = TryBindNamespaceOrTypeAsExpression(expression, options)
If Not tryAsExpression.IsEmpty Then
result = tryAsExpression
End If
End If
Return result
End Function
' Get the symbol info of type or namespace syntax that is outside a member body
Private Function GetTypeOrNamespaceTypeInfoNotInMember(expression As TypeSyntax) As VisualBasicTypeInfo
Dim resultSymbol As Symbol = GetTypeOrNamespaceSymbolNotInMember(expression)
' Create the result.
Return GetTypeInfoForSymbol(resultSymbol)
End Function
Private Function GetImplementedMemberAndResultKind(symbolBuilder As ArrayBuilder(Of Symbol), memberName As QualifiedNameSyntax) As LookupResultKind
Debug.Assert(symbolBuilder.Count = 0)
Dim diagnostics As DiagnosticBag = DiagnosticBag.GetInstance()
Dim resultKind As LookupResultKind = LookupResultKind.Good
Try
' Set up the binding context.
Dim binder As Binder = GetEnclosingBinder(memberName.SpanStart)
' Figure out the symbol this implements clause is on, and bind the syntax for it.
Dim implementingMemberSyntax = TryCast(memberName.Parent.Parent, MethodBaseSyntax)
If implementingMemberSyntax IsNot Nothing Then
Dim implementingMember = GetDeclaredSymbol(implementingMemberSyntax)
If implementingMember IsNot Nothing Then
Select Case implementingMember.Kind
Case SymbolKind.Method
ImplementsHelper.FindExplicitlyImplementedMember(Of MethodSymbol)(
DirectCast(implementingMember, MethodSymbol),
DirectCast(implementingMember, MethodSymbol).ContainingType,
memberName,
binder,
diagnostics,
symbolBuilder,
resultKind)
Case SymbolKind.Property
ImplementsHelper.FindExplicitlyImplementedMember(Of PropertySymbol)(
DirectCast(implementingMember, PropertySymbol),
DirectCast(implementingMember, PropertySymbol).ContainingType,
memberName,
binder,
diagnostics,
symbolBuilder,
resultKind)
Case SymbolKind.Event
ImplementsHelper.FindExplicitlyImplementedMember(Of EventSymbol)(
DirectCast(implementingMember, EventSymbol),
DirectCast(implementingMember, EventSymbol).ContainingType,
memberName,
binder,
diagnostics,
symbolBuilder,
resultKind)
Case Else
Throw ExceptionUtilities.UnexpectedValue(implementingMember.Kind)
End Select
End If
End If
Return resultKind
Finally
diagnostics.Free()
End Try
End Function
Private Function GetHandledEventOrContainerSymbolsAndResultKind(eventSymbolBuilder As ArrayBuilder(Of Symbol),
containerSymbolBuilder As ArrayBuilder(Of Symbol),
propertySymbolBuilder As ArrayBuilder(Of Symbol),
handlesClause As HandlesClauseItemSyntax) As LookupResultKind
Dim resultKind As LookupResultKind = LookupResultKind.Good
' Set up the binding context.
Dim binder As Binder = GetEnclosingBinder(handlesClause.SpanStart)
' Figure out the symbol this handles clause is on, and bind the syntax for it.
Dim handlingMethodSyntax = TryCast(handlesClause.Parent.Parent, MethodStatementSyntax)
If handlingMethodSyntax IsNot Nothing Then
Dim implementingMember = GetDeclaredSymbol(handlingMethodSyntax)
If implementingMember IsNot Nothing Then
Dim methodSym = DirectCast(implementingMember, SourceMemberMethodSymbol)
Dim diagbag = DiagnosticBag.GetInstance()
methodSym.BindSingleHandlesClause(handlesClause,
binder,
diagbag,
eventSymbolBuilder,
containerSymbolBuilder,
propertySymbolBuilder,
resultKind)
diagbag.Free()
End If
End If
Return resultKind
End Function
' Get the symbol info of an implemented member in an implements clause.
Private Function GetImplementedMemberSymbolInfo(memberName As QualifiedNameSyntax, options As SymbolInfoOptions) As SymbolInfo
Dim implementedMemberBuilder As ArrayBuilder(Of Symbol) = ArrayBuilder(Of Symbol).GetInstance()
Dim resultKind As LookupResultKind = GetImplementedMemberAndResultKind(implementedMemberBuilder, memberName)
Dim symbols As ImmutableArray(Of Symbol) = RemoveErrorTypesAndDuplicates(implementedMemberBuilder, options)
implementedMemberBuilder.Free()
Return SymbolInfoFactory.Create(symbols, resultKind)
End Function
' Get the symbol info of a handled event in a handles clause.
Private Function GetHandlesEventSymbolInfo(handlesClause As HandlesClauseItemSyntax, options As SymbolInfoOptions) As SymbolInfo
Dim builder As ArrayBuilder(Of Symbol) = ArrayBuilder(Of Symbol).GetInstance()
Dim resultKind As LookupResultKind = GetHandledEventOrContainerSymbolsAndResultKind(eventSymbolBuilder:=builder,
containerSymbolBuilder:=Nothing,
propertySymbolBuilder:=Nothing,
handlesClause:=handlesClause)
Dim symbols As ImmutableArray(Of Symbol) = RemoveErrorTypesAndDuplicates(builder, options)
builder.Free()
Return SymbolInfoFactory.Create(symbols, resultKind)
End Function
' Get the symbol info of an identifier event container in a handles clause.
Private Function GetHandlesContainerSymbolInfo(handlesClause As HandlesClauseItemSyntax, options As SymbolInfoOptions) As SymbolInfo
Dim builder As ArrayBuilder(Of Symbol) = ArrayBuilder(Of Symbol).GetInstance()
Dim resultKind As LookupResultKind = GetHandledEventOrContainerSymbolsAndResultKind(eventSymbolBuilder:=Nothing,
containerSymbolBuilder:=builder,
propertySymbolBuilder:=Nothing,
handlesClause:=handlesClause)
Dim symbols As ImmutableArray(Of Symbol) = RemoveErrorTypesAndDuplicates(builder, options)
builder.Free()
Return SymbolInfoFactory.Create(symbols, resultKind)
End Function
' Get the symbol info of an withevents sourcing property in a handles clause.
Private Function GetHandlesPropertySymbolInfo(handlesClause As HandlesClauseItemSyntax, options As SymbolInfoOptions) As SymbolInfo
Dim builder As ArrayBuilder(Of Symbol) = ArrayBuilder(Of Symbol).GetInstance()
Dim resultKind As LookupResultKind = GetHandledEventOrContainerSymbolsAndResultKind(eventSymbolBuilder:=Nothing,
containerSymbolBuilder:=Nothing,
propertySymbolBuilder:=builder,
handlesClause:=handlesClause)
Dim symbols As ImmutableArray(Of Symbol) = RemoveErrorTypesAndDuplicates(builder, options)
builder.Free()
Return SymbolInfoFactory.Create(symbols, resultKind)
End Function
' Get the type info of a implemented member in a implements clause.
Private Function GetImplementedMemberTypeInfo(memberName As QualifiedNameSyntax) As VisualBasicTypeInfo
' Implemented members have no type.
Return VisualBasicTypeInfo.None
End Function
' Get the type info of a implemented member in a implements clause.
Private Function GetHandlesEventTypeInfo(memberName As IdentifierNameSyntax) As VisualBasicTypeInfo
' Handled events have no type.
Return VisualBasicTypeInfo.None
End Function
' Get the type info of a implemented member in a implements clause.
Private Function GetHandlesContainerTypeInfo(memberName As HandlesClauseItemSyntax) As VisualBasicTypeInfo
' Handled events have no type.
Return VisualBasicTypeInfo.None
End Function
' Get the type info of a implemented member in a implements clause.
Private Function GetHandlesPropertyTypeInfo(memberName As HandlesClauseItemSyntax) As VisualBasicTypeInfo
' Handled events have no type.
Return VisualBasicTypeInfo.None
End Function
''' <summary>
''' Checks all symbol locations against the syntax provided and return symbol if any of the locations is
''' inside the syntax span. Returns Nothing otherwise.
''' </summary>
Private Function CheckSymbolLocationsAgainstSyntax(symbol As NamedTypeSymbol, nodeToCheck As VisualBasicSyntaxNode) As NamedTypeSymbol
For Each location In symbol.Locations
If location.SourceTree Is Me.SyntaxTree AndAlso nodeToCheck.Span.Contains(location.SourceSpan.Start) Then
Return symbol
End If
Next
Return Nothing
End Function
''' <summary>
''' Given a delegate declaration, get the corresponding type symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a type.</param>
''' <returns>The type symbol that was declared.</returns>
Public Overloads Function GetDeclaredSymbol(declarationSyntax As DelegateStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As NamedTypeSymbol
If declarationSyntax Is Nothing Then Throw New ArgumentNullException(NameOf(declarationSyntax))
If Not IsInTree(declarationSyntax) Then Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
' Don't need to wrap in a SemanticModelBinder, since we're not binding.
Dim binder As Binder = _binderFactory.GetNamedTypeBinder(declarationSyntax)
If binder IsNot Nothing AndAlso TypeOf binder Is NamedTypeBinder Then
Return CheckSymbolLocationsAgainstSyntax(DirectCast(binder.ContainingType, NamedTypeSymbol), declarationSyntax)
Else
Return Nothing ' Can this happen? Maybe in some edge case error cases.
End If
End Function
''' <summary>
''' Given a type declaration, get the corresponding type symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a type.</param>
''' <returns>The type symbol that was declared.</returns>
Public Overloads Overrides Function GetDeclaredSymbol(declarationSyntax As TypeStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As INamedTypeSymbol
If declarationSyntax Is Nothing Then Throw New ArgumentNullException(NameOf(declarationSyntax))
If Not IsInTree(declarationSyntax) Then Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
' Don't need to wrap in a SemanticModelBinder, since we're not binding.
Dim binder As Binder = _binderFactory.GetNamedTypeBinder(declarationSyntax)
If binder IsNot Nothing AndAlso TypeOf binder Is NamedTypeBinder Then
Return CheckSymbolLocationsAgainstSyntax(DirectCast(binder.ContainingType, NamedTypeSymbol), declarationSyntax)
Else
Return Nothing ' Can this happen? Maybe in some edge case error cases.
End If
End Function
''' <summary>
''' Given a enum declaration, get the corresponding type symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares an enum.</param>
''' <returns>The type symbol that was declared.</returns>
Public Overloads Overrides Function GetDeclaredSymbol(declarationSyntax As EnumStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As INamedTypeSymbol
If declarationSyntax Is Nothing Then Throw New ArgumentNullException(NameOf(declarationSyntax))
If Not IsInTree(declarationSyntax) Then Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
' Don't need to wrap in a SemanticModelBinder, since we're not binding.
Dim binder As Binder = _binderFactory.GetNamedTypeBinder(declarationSyntax)
If binder IsNot Nothing AndAlso TypeOf binder Is NamedTypeBinder Then
Return CheckSymbolLocationsAgainstSyntax(DirectCast(binder.ContainingType, NamedTypeSymbol), declarationSyntax)
Else
Return Nothing ' Can this happen? Maybe in some edge case with errors
End If
End Function
''' <summary>
''' Given a namespace declaration, get the corresponding type symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a namespace.</param>
''' <returns>The namespace symbol that was declared.</returns>
Public Overloads Overrides Function GetDeclaredSymbol(declarationSyntax As NamespaceStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As INamespaceSymbol
If declarationSyntax Is Nothing Then Throw New ArgumentNullException(NameOf(declarationSyntax))
If Not IsInTree(declarationSyntax) Then Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
Dim parentBlock = TryCast(declarationSyntax.Parent, NamespaceBlockSyntax)
If parentBlock IsNot Nothing Then
' Don't need to wrap in a SemanticModelBinder, since we're not binding.
Dim binder As Binder = _binderFactory.GetNamespaceBinder(parentBlock)
If binder IsNot Nothing AndAlso TypeOf binder Is NamespaceBinder Then
Return DirectCast(binder.ContainingNamespaceOrType, NamespaceSymbol)
End If
End If
Return Nothing ' Edge case with errors
End Function
''' <summary>
''' Given a method, property, or event declaration, get the corresponding symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a method, property, or event.</param>
''' <returns>The method, property, or event symbol that was declared.</returns>
Friend Overloads Overrides Function GetDeclaredSymbol(declarationSyntax As MethodBaseSyntax, Optional cancellationToken As CancellationToken = Nothing) As ISymbol
If declarationSyntax Is Nothing Then Throw New ArgumentNullException(NameOf(declarationSyntax))
If Not IsInTree(declarationSyntax) Then
Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
End If
' Delegate declarations are a subclass of MethodBaseSyntax syntax-wise, but they are
' more like a type declaration, so we need to special case here.
If declarationSyntax.Kind = SyntaxKind.DelegateFunctionStatement OrElse
declarationSyntax.Kind = SyntaxKind.DelegateSubStatement Then
Return GetDeclaredSymbol(DirectCast(declarationSyntax, DelegateStatementSyntax), cancellationToken)
End If
Dim statementSyntax = TryCast(declarationSyntax.Parent, StatementSyntax)
If statementSyntax IsNot Nothing Then
' get parent type block
Dim parentTypeBlock As TypeBlockSyntax = Nothing
Select Case statementSyntax.Kind
Case SyntaxKind.ClassBlock, SyntaxKind.EnumBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock
parentTypeBlock = TryCast(statementSyntax, TypeBlockSyntax)
Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock, SyntaxKind.PropertyBlock, SyntaxKind.EventBlock
parentTypeBlock = TryCast(statementSyntax.Parent, TypeBlockSyntax)
' EDMAURER maybe this is a top-level decl in which case the parent is a CompilationUnitSyntax
If parentTypeBlock Is Nothing AndAlso statementSyntax.Parent IsNot Nothing Then
Dim namespaceToLookInForImplicitType As INamespaceSymbol = Nothing
Select Case statementSyntax.Parent.Kind
Case SyntaxKind.CompilationUnit
namespaceToLookInForImplicitType = Me._sourceModule.RootNamespace
Case SyntaxKind.NamespaceBlock
namespaceToLookInForImplicitType = GetDeclaredSymbol(DirectCast(statementSyntax.Parent, NamespaceBlockSyntax))
End Select
If namespaceToLookInForImplicitType IsNot Nothing Then
Dim implicitType = DirectCast(namespaceToLookInForImplicitType.GetMembers(TypeSymbol.ImplicitTypeName).SingleOrDefault(), NamedTypeSymbol)
If implicitType IsNot Nothing Then
Return SourceMethodSymbol.FindSymbolFromSyntax(declarationSyntax, _syntaxTree, implicitType)
End If
End If
End If
Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock
' redirect to upper property or event symbol
If statementSyntax.Parent IsNot Nothing Then
parentTypeBlock = TryCast(statementSyntax.Parent.Parent, TypeBlockSyntax)
End If
Case SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock
' redirect to upper event symbol
If statementSyntax.Parent IsNot Nothing Then
parentTypeBlock = TryCast(statementSyntax.Parent.Parent, TypeBlockSyntax)
End If
Case Else
' broken code scenarios end up here
' to end up here, a methodbasesyntax's parent must be a statement and not be one of the above.
' The parser does e.g. not generate an enclosing block for accessors statements,
' but for Operators, conversions and constructors.
' The case where an invalid accessor is contained in e.g. an interface is handled further down in "FindSymbolFromSyntax".
' TODO: consider always creating a (missing) block around the statements in the parser
' We are asserting what we know so far. If this assert fails, this is not a bug, we either need to remove this assert or relax the assert.
Debug.Assert(statementSyntax.Kind = SyntaxKind.NamespaceBlock AndAlso
(TypeOf (declarationSyntax) Is AccessorStatementSyntax OrElse
TypeOf (declarationSyntax) Is EventStatementSyntax OrElse
TypeOf (declarationSyntax) Is MethodStatementSyntax OrElse
TypeOf (declarationSyntax) Is PropertyStatementSyntax))
Return Nothing
End Select
If parentTypeBlock IsNot Nothing Then
Dim containingType = DirectCast(GetDeclaredSymbol(parentTypeBlock.BlockStatement, cancellationToken), NamedTypeSymbol)
If containingType IsNot Nothing Then
Return SourceMethodSymbol.FindSymbolFromSyntax(declarationSyntax, _syntaxTree, containingType)
End If
End If
End If
Return Nothing
End Function
''' <summary>
''' Given a parameter declaration, get the corresponding parameter symbol.
''' </summary>
''' <param name="parameter">The syntax node that declares a parameter.</param>
''' <returns>The parameter symbol that was declared.</returns>
Public Overloads Overrides Function GetDeclaredSymbol(parameter As ParameterSyntax, Optional cancellationToken As CancellationToken = Nothing) As IParameterSymbol
If parameter Is Nothing Then
Throw New ArgumentNullException(NameOf(parameter))
End If
Dim paramList As ParameterListSyntax = TryCast(parameter.Parent, ParameterListSyntax)
If paramList IsNot Nothing Then
Dim declarationSyntax As MethodBaseSyntax = TryCast(paramList.Parent, MethodBaseSyntax)
If declarationSyntax IsNot Nothing Then
Dim symbol = GetDeclaredSymbol(declarationSyntax, cancellationToken)
If symbol IsNot Nothing Then
Select Case symbol.Kind
Case SymbolKind.Method
Return GetParameterSymbol(DirectCast(symbol, MethodSymbol).Parameters, parameter)
Case SymbolKind.Event
Return GetParameterSymbol(DirectCast(symbol, EventSymbol).DelegateParameters, parameter)
Case SymbolKind.Property
Return GetParameterSymbol(DirectCast(symbol, PropertySymbol).Parameters, parameter)
Case SymbolKind.NamedType
' check for being delegate
Dim typeSymbol = DirectCast(symbol, NamedTypeSymbol)
Debug.Assert(typeSymbol.TypeKind = TypeKind.Delegate)
If typeSymbol.DelegateInvokeMethod IsNot Nothing Then
Return GetParameterSymbol(typeSymbol.DelegateInvokeMethod.Parameters, parameter)
End If
End Select
ElseIf TypeOf declarationSyntax Is LambdaHeaderSyntax Then
' This could be a lambda parameter.
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(declarationSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(parameter, cancellationToken)
End If
End If
End If
End If
Return Nothing
End Function
''' <summary>
''' Given a type parameter declaration, get the corresponding type parameter symbol.
''' </summary>
''' <param name="typeParameter">The syntax node that declares a type parameter.</param>
''' <returns>The type parameter symbol that was declared.</returns>
Public Overloads Overrides Function GetDeclaredSymbol(typeParameter As TypeParameterSyntax, Optional cancellationToken As CancellationToken = Nothing) As ITypeParameterSymbol
If typeParameter Is Nothing Then
Throw New ArgumentNullException(NameOf(typeParameter))
End If
If Not IsInTree(typeParameter) Then
Throw New ArgumentException(VBResources.TypeParameterNotWithinTree)
End If
Dim symbol As ISymbol = Nothing
Dim typeParamList = TryCast(typeParameter.Parent, TypeParameterListSyntax)
If typeParamList IsNot Nothing AndAlso typeParamList.Parent IsNot Nothing Then
If TypeOf typeParamList.Parent Is MethodStatementSyntax Then
symbol = GetDeclaredSymbol(DirectCast(typeParamList.Parent, MethodStatementSyntax), cancellationToken)
ElseIf TypeOf typeParamList.Parent Is TypeStatementSyntax Then
symbol = GetDeclaredSymbol(DirectCast(typeParamList.Parent, TypeStatementSyntax), cancellationToken)
ElseIf TypeOf typeParamList.Parent Is DelegateStatementSyntax Then
symbol = GetDeclaredSymbol(DirectCast(typeParamList.Parent, DelegateStatementSyntax), cancellationToken)
End If
If symbol IsNot Nothing Then
Dim typeSymbol = TryCast(symbol, NamedTypeSymbol)
If typeSymbol IsNot Nothing Then
Return Me.GetTypeParameterSymbol(typeSymbol.TypeParameters, typeParameter)
End If
Dim methodSymbol = TryCast(symbol, MethodSymbol)
If methodSymbol IsNot Nothing Then
Return Me.GetTypeParameterSymbol(methodSymbol.TypeParameters, typeParameter)
End If
End If
End If
Return Nothing
End Function
' Get a type parameter symbol from a ROA of TypeParametersSymbols and the syntax for one.
Private Function GetTypeParameterSymbol(parameters As ImmutableArray(Of TypeParameterSymbol), parameter As TypeParameterSyntax) As TypeParameterSymbol
For Each symbol In parameters
For Each location In symbol.Locations
If location.IsInSource AndAlso location.SourceTree Is _syntaxTree AndAlso parameter.Span.Contains(location.SourceSpan) Then
Return symbol
End If
Next
Next
Return Nothing
End Function
Public Overrides Function GetDeclaredSymbol(declarationSyntax As EnumMemberDeclarationSyntax, Optional cancellationToken As CancellationToken = Nothing) As IFieldSymbol
If declarationSyntax Is Nothing Then
Throw New ArgumentNullException(NameOf(declarationSyntax))
End If
If Not IsInTree(declarationSyntax) Then
Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
End If
Dim enumBlock As EnumBlockSyntax = DirectCast(declarationSyntax.Parent, EnumBlockSyntax)
If enumBlock IsNot Nothing Then
Dim containingType = DirectCast(GetDeclaredSymbol(enumBlock.EnumStatement, cancellationToken), NamedTypeSymbol)
If containingType IsNot Nothing Then
Return DirectCast(SourceFieldSymbol.FindFieldOrWithEventsSymbolFromSyntax(declarationSyntax.Identifier, _syntaxTree, containingType), FieldSymbol)
End If
End If
Return Nothing
End Function
''' <summary>
''' Given a variable declaration, get the corresponding symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a variable.</param>
''' <returns>The symbol that was declared.</returns>
Public Overrides Function GetDeclaredSymbol(declarationSyntax As ModifiedIdentifierSyntax, Optional cancellationToken As CancellationToken = Nothing) As ISymbol
If declarationSyntax Is Nothing Then
Throw New ArgumentNullException(NameOf(declarationSyntax))
End If
If Not IsInTree(declarationSyntax) Then
Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
End If
Dim declarationParent = declarationSyntax.Parent
' Possibility 1: Field syntax, could be a Field or WithEvent property
Dim fieldSyntax As FieldDeclarationSyntax = Nothing
If declarationParent IsNot Nothing Then
fieldSyntax = TryCast(declarationParent.Parent, FieldDeclarationSyntax)
End If
Dim parentTypeBlock As TypeBlockSyntax = Nothing
If fieldSyntax IsNot Nothing Then
parentTypeBlock = TryCast(fieldSyntax.Parent, TypeBlockSyntax)
Else : End If
If parentTypeBlock IsNot Nothing Then
Dim containingType = DirectCast(GetDeclaredSymbol(parentTypeBlock.BlockStatement, cancellationToken), NamedTypeSymbol)
If containingType IsNot Nothing Then
Return SourceFieldSymbol.FindFieldOrWithEventsSymbolFromSyntax(declarationSyntax.Identifier, _syntaxTree, containingType)
End If
End If
' Possibility 2: Parameter
Dim parameterSyntax As ParameterSyntax = TryCast(declarationParent, ParameterSyntax)
If parameterSyntax IsNot Nothing Then
Return GetDeclaredSymbol(parameterSyntax, cancellationToken)
End If
' Possibility 3: Local variable
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(declarationSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(declarationSyntax, cancellationToken)
End If
Return MyBase.GetDeclaredSymbol(declarationSyntax, cancellationToken)
End Function
''' <summary>
''' Given an FieldInitializerSyntax, get the corresponding symbol of anonymous type creation.
''' </summary>
''' <param name="fieldInitializerSyntax">The anonymous object creation field initializer syntax.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overrides Function GetDeclaredSymbol(fieldInitializerSyntax As FieldInitializerSyntax, Optional cancellationToken As System.Threading.CancellationToken = Nothing) As IPropertySymbol
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(fieldInitializerSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(fieldInitializerSyntax, cancellationToken)
End If
Return MyBase.GetDeclaredSymbol(fieldInitializerSyntax, cancellationToken)
End Function
''' <summary>
''' Given an AnonymousObjectCreationExpressionSyntax, get the corresponding symbol of anonymous type.
''' </summary>
''' <param name="anonymousObjectCreationExpressionSyntax">The anonymous object creation syntax.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overrides Function GetDeclaredSymbol(anonymousObjectCreationExpressionSyntax As AnonymousObjectCreationExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As INamedTypeSymbol
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(anonymousObjectCreationExpressionSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(anonymousObjectCreationExpressionSyntax, cancellationToken)
End If
Return MyBase.GetDeclaredSymbol(anonymousObjectCreationExpressionSyntax, cancellationToken)
End Function
''' <summary>
''' Given an ExpressionRangeVariableSyntax, get the corresponding symbol.
''' </summary>
''' <param name="rangeVariableSyntax">The range variable syntax that declares a variable.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overrides Function GetDeclaredSymbol(rangeVariableSyntax As ExpressionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As IRangeVariableSymbol
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(rangeVariableSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(rangeVariableSyntax, cancellationToken)
End If
Return MyBase.GetDeclaredSymbol(rangeVariableSyntax, cancellationToken)
End Function
''' <summary>
''' Given an CollectionRangeVariableSyntax, get the corresponding symbol.
''' </summary>
''' <param name="rangeVariableSyntax">The range variable syntax that declares a variable.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overrides Function GetDeclaredSymbol(rangeVariableSyntax As CollectionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As IRangeVariableSymbol
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(rangeVariableSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(rangeVariableSyntax, cancellationToken)
End If
Return MyBase.GetDeclaredSymbol(rangeVariableSyntax, cancellationToken)
End Function
''' <summary>
''' Given an AggregationRangeVariableSyntax, get the corresponding symbol.
''' </summary>
''' <param name="rangeVariableSyntax">The range variable syntax that declares a variable.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overrides Function GetDeclaredSymbol(rangeVariableSyntax As AggregationRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As IRangeVariableSymbol
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(rangeVariableSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(rangeVariableSyntax, cancellationToken)
End If
Return MyBase.GetDeclaredSymbol(rangeVariableSyntax, cancellationToken)
End Function
''' <summary>
''' Given an import clause get the corresponding symbol for the import alias that was introduced.
''' </summary>
''' <param name="declarationSyntax">The import statement syntax node.</param>
''' <returns>The alias symbol that was declared or Nothing if no alias symbol was declared.</returns>
Public Overloads Overrides Function GetDeclaredSymbol(declarationSyntax As SimpleImportsClauseSyntax, Optional cancellationToken As CancellationToken = Nothing) As IAliasSymbol
If declarationSyntax Is Nothing Then
Throw New ArgumentNullException(NameOf(declarationSyntax))
End If
If Not IsInTree(declarationSyntax) Then
Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
End If
If declarationSyntax.Alias Is Nothing Then
Return Nothing
End If
Dim aliasName As String = declarationSyntax.Alias.Identifier.ValueText
If Not String.IsNullOrEmpty(aliasName) Then
Dim sourceFile = Me._sourceModule.GetSourceFile(Me.SyntaxTree)
Dim aliasImports As Dictionary(Of String, AliasAndImportsClausePosition) = sourceFile.AliasImports
Dim symbol As AliasAndImportsClausePosition = Nothing
If aliasImports IsNot Nothing AndAlso aliasImports.TryGetValue(aliasName, symbol) Then
' make sure the symbol is declared inside declarationSyntax node
For Each location In symbol.Alias.Locations
If location.IsInSource AndAlso location.SourceTree Is _syntaxTree AndAlso declarationSyntax.Span.Contains(location.SourceSpan) Then
Return symbol.Alias
End If
Next
' If the alias name was in the map but the location didn't match, then the syntax declares a duplicate alias.
' We'll return a new AliasSymbol to improve the API experience.
Dim binder As Binder = GetEnclosingBinder(declarationSyntax.SpanStart)
Dim discardedDiagnostics = DiagnosticBag.GetInstance()
Dim targetSymbol As NamespaceOrTypeSymbol = binder.BindNamespaceOrTypeSyntax(declarationSyntax.Name, discardedDiagnostics)
discardedDiagnostics.Free()
If targetSymbol IsNot Nothing Then
Return New AliasSymbol(binder.Compilation, binder.ContainingNamespaceOrType, aliasName, targetSymbol, declarationSyntax.GetLocation())
End If
End If
End If
Return Nothing
End Function
''' <summary>
''' Given a field declaration syntax, get the corresponding symbols.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares one or more fields.</param>
''' <returns>The field symbols that were declared.</returns>
Friend Overrides Function GetDeclaredSymbols(declarationSyntax As FieldDeclarationSyntax, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of ISymbol)
If declarationSyntax Is Nothing Then
Throw New ArgumentNullException(NameOf(declarationSyntax))
End If
If Not IsInTree(declarationSyntax) Then
Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
End If
Dim builder = New ArrayBuilder(Of ISymbol)
For Each declarator In declarationSyntax.Declarators
For Each identifier In declarator.Names
Dim field = TryCast(Me.GetDeclaredSymbol(identifier, cancellationToken), IFieldSymbol)
If field IsNot Nothing Then
builder.Add(field)
End If
Next
Next
Return builder.ToImmutableAndFree()
End Function
''' <summary>
''' Determines what type of conversion, if any, would be used if a given expression was converted to a given
''' type.
''' </summary>
''' <param name="expression">An expression which much occur within the syntax tree associated with this
''' object.</param>
''' <param name="destination">The type to attempt conversion to.</param>
''' <returns>Returns a Conversion object that summarizes whether the conversion was possible, and if so, what
''' kind of conversion it was. If no conversion was possible, a Conversion object with a false "Exists "
''' property is returned.</returns>
''' <remarks>To determine the conversion between two types (instead of an expression and a type), use
''' Compilation.ClassifyConversion.</remarks>
Public Overrides Function ClassifyConversion(expression As ExpressionSyntax, destination As ITypeSymbol) As Conversion
CheckSyntaxNode(expression)
If destination Is Nothing Then
Throw New ArgumentNullException(NameOf(destination))
End If
Dim vbdestination = destination.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(destination))
' TODO(cyrusn): Check arguments. This is a public entrypoint, so we must do appropriate
' checks here. However, no other methods in this type do any checking currently. SO i'm
' going to hold off on this until we do a full sweep of the API.
Dim binding = Me.GetMemberSemanticModel(expression)
If binding Is Nothing Then
Return New Conversion(Nothing) 'NoConversion
End If
Return binding.ClassifyConversion(expression, vbdestination)
End Function
Public Overrides ReadOnly Property IsSpeculativeSemanticModel As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property OriginalPositionForSpeculation As Integer
Get
Return 0
End Get
End Property
Public Overrides ReadOnly Property ParentModel As SemanticModel
Get
Return Nothing
End Get
End Property
Friend Overrides Function TryGetSpeculativeSemanticModelForMethodBodyCore(parentModel As SyntaxTreeSemanticModel, position As Integer, method As MethodBlockBaseSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
Dim memberModel = Me.GetMemberSemanticModel(position)
If memberModel IsNot Nothing Then
Return memberModel.TryGetSpeculativeSemanticModelForMethodBodyCore(parentModel, position, method, speculativeModel)
End If
speculativeModel = Nothing
Return False
End Function
Friend Overrides Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, type As TypeSyntax, bindingOption As SpeculativeBindingOption, <Out> ByRef speculativeModel As SemanticModel) As Boolean
Dim memberModel = Me.GetMemberSemanticModel(position)
If memberModel IsNot Nothing Then
Return memberModel.TryGetSpeculativeSemanticModelCore(parentModel, position, type, bindingOption, speculativeModel)
End If
Dim binder As Binder = Me.GetSpeculativeBinderForExpression(position, type, bindingOption)
If binder IsNot Nothing Then
speculativeModel = SpeculativeSyntaxTreeSemanticModel.Create(Me, type, binder, position, bindingOption)
Return True
End If
speculativeModel = Nothing
Return False
End Function
Friend Overrides Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, rangeArgument As RangeArgumentSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
Dim memberModel = Me.GetMemberSemanticModel(position)
If memberModel IsNot Nothing Then
Return memberModel.TryGetSpeculativeSemanticModelCore(parentModel, position, rangeArgument, speculativeModel)
End If
speculativeModel = Nothing
Return False
End Function
Friend Overrides Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, statement As ExecutableStatementSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
Dim memberModel = Me.GetMemberSemanticModel(position)
If memberModel IsNot Nothing Then
Return memberModel.TryGetSpeculativeSemanticModelCore(parentModel, position, statement, speculativeModel)
End If
speculativeModel = Nothing
Return False
End Function
Friend Overrides Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, initializer As EqualsValueSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
Dim memberModel = Me.GetMemberSemanticModel(position)
If memberModel IsNot Nothing Then
Return memberModel.TryGetSpeculativeSemanticModelCore(parentModel, position, initializer, speculativeModel)
End If
speculativeModel = Nothing
Return False
End Function
''' <summary>
''' Analyze control-flow within a part of a method body.
''' </summary>
''' <param name="firstStatement">The first statement to be included in the analysis.</param>
''' <param name="lastStatement">The last statement to be included in the analysis.</param>
''' <returns>An object that can be used to obtain the result of the control flow analysis.</returns>
''' <exception cref="ArgumentException">The two statements are not contained within the same statement list.</exception>
Public Overrides Function AnalyzeControlFlow(firstStatement As StatementSyntax, lastStatement As StatementSyntax) As ControlFlowAnalysis
Dim context As RegionAnalysisContext = If(ValidateRegionDefiningStatementsRange(firstStatement, lastStatement),
CreateRegionAnalysisContext(firstStatement, lastStatement),
CreateFailedRegionAnalysisContext())
Dim result = New VisualBasicControlFlowAnalysis(context)
' we assume the analysis should only fail if the original context is invalid
Debug.Assert(result.Succeeded OrElse context.Failed)
Return result
End Function
''' <summary>
''' The first statement to be included in the analysis.
''' </summary>
''' <param name="firstStatement">The first statement to be included in the analysis.</param>
''' <param name="lastStatement">The last statement to be included in the analysis.</param>
''' <returns>An object that can be used to obtain the result of the data flow analysis.</returns>
''' <exception cref="ArgumentException">The two statements are not contained within the same statement list.</exception>
Public Overrides Function AnalyzeDataFlow(firstStatement As StatementSyntax, lastStatement As StatementSyntax) As DataFlowAnalysis
Dim context As RegionAnalysisContext = If(ValidateRegionDefiningStatementsRange(firstStatement, lastStatement),
CreateRegionAnalysisContext(firstStatement, lastStatement),
CreateFailedRegionAnalysisContext())
Dim result = New VisualBasicDataFlowAnalysis(context)
' we assume the analysis should only fail if the original context is invalid
Debug.Assert(result.Succeeded OrElse result.InvalidRegionDetectedInternal OrElse context.Failed)
Return result
End Function
''' <summary>
''' Analyze data-flow within an expression.
''' </summary>
''' <param name="expression">The expression within the associated SyntaxTree to analyze.</param>
''' <returns>An object that can be used to obtain the result of the data flow analysis.</returns>
Public Overrides Function AnalyzeDataFlow(expression As ExpressionSyntax) As DataFlowAnalysis
Dim context As RegionAnalysisContext = If(ValidateRegionDefiningExpression(expression),
CreateRegionAnalysisContext(expression),
CreateFailedRegionAnalysisContext())
Dim result = New VisualBasicDataFlowAnalysis(context)
' Assert that we either correctly precalculated succeeded
' flag or we know for sure why we failed to precalculate it
CheckSucceededFlagInAnalyzeDataFlow(expression, result, context)
Return result
End Function
<Conditional("DEBUG")>
Private Sub CheckSucceededFlagInAnalyzeDataFlow(expression As ExpressionSyntax, result As VisualBasicDataFlowAnalysis, context As RegionAnalysisContext)
If result.Succeeded OrElse result.InvalidRegionDetectedInternal OrElse context.Failed Then
Return
End If
' Some cases of unsucceeded result that cannot be precalculated properly are handled below
' CASE 1: If the region flow analysis is performed on the left part of member access like
' on 'a' part of 'a.b.c()' expression AND 'a.b' is a type, we don't create a bound node
' to be linked with syntax node 'a'. In this case FirstInRegion/LastInRegion nodes are
' calculated by trying to bind 'a' itself, and in most cases it binds into Namespace
' or Type expression. This case is handles in RegionAnalysisContext..ctor.
'
' But in Color/Color case it binds into other symbol kinds and we suppress
' assertion for this case here
Dim expressionParent As VisualBasicSyntaxNode = expression.Parent
If expression.Kind = SyntaxKind.IdentifierName AndAlso
expressionParent IsNot Nothing AndAlso expressionParent.Kind = SyntaxKind.SimpleMemberAccessExpression AndAlso
DirectCast(expressionParent, MemberAccessExpressionSyntax).Expression Is expression Then
' Color/Color confusion may only be possible if expression is an IdentifierName
' and is nested in member access. This is too wide definition, but it's
' difficult to improve this without doing semantic analysis
Return
End If
' CASE 2: If the region flow analysis is performed on the arguments of field declaration of array
' data type having explicit initializer, like 'Public AnArray(2) = {0, 1}';
' VB semantics generates an error about specifying both bounds and initializer and ignores them
If expression.Kind = SyntaxKind.NumericLiteralExpression AndAlso
expressionParent IsNot Nothing AndAlso (expressionParent.Kind = SyntaxKind.SimpleArgument AndAlso Not DirectCast(expressionParent, SimpleArgumentSyntax).IsNamed) Then
' VariableDeclarator
' | |
' ModifiedIdentifier EqualsValue
' |
' ArgumentList
' |...|...|
' SimpleArgument
' |
' NumericalLiteral
Dim argList As VisualBasicSyntaxNode = expressionParent.Parent
If argList IsNot Nothing AndAlso argList.Kind = SyntaxKind.ArgumentList Then
Dim modIdentifier As VisualBasicSyntaxNode = argList.Parent
If modIdentifier IsNot Nothing AndAlso modIdentifier.Kind = SyntaxKind.ModifiedIdentifier Then
Dim varDeclarator As VisualBasicSyntaxNode = modIdentifier.Parent
If varDeclarator IsNot Nothing AndAlso varDeclarator.Kind = SyntaxKind.VariableDeclarator AndAlso
DirectCast(varDeclarator, VariableDeclaratorSyntax).Initializer IsNot Nothing Then
Return
End If
End If
End If
End If
Throw ExceptionUtilities.Unreachable
End Sub
''' <summary>
''' Checks if the node is inside the attribute arguments
''' </summary>
Private Shared Function IsNodeInsideAttributeArguments(node As VisualBasicSyntaxNode) As Boolean
While node IsNot Nothing
If node.Kind = SyntaxKind.Attribute Then
Return True
End If
node = node.Parent
End While
Return False
End Function
''' <summary>
''' Check Expression for being in right context, for example 'For ... Next [x]'
''' is not correct context
''' </summary>
Private Shared Function IsExpressionInValidContext(expression As ExpressionSyntax) As Boolean
Dim currentNode As VisualBasicSyntaxNode = expression
Do
Dim parent As VisualBasicSyntaxNode = currentNode.Parent
If parent Is Nothing Then Return True
Dim expressionParent = TryCast(parent, ExpressionSyntax)
If expressionParent Is Nothing Then
Select Case parent.Kind
Case SyntaxKind.NextStatement
Return False
Case SyntaxKind.EqualsValue
' One cannot perform flow analysis on an expression from Enum member declaration
parent = parent.Parent
If parent Is Nothing Then
Return True
End If
Select Case parent.Kind
Case SyntaxKind.EnumMemberDeclaration,
SyntaxKind.Parameter
Return False
Case SyntaxKind.VariableDeclarator
Dim localDeclSyntax = TryCast(parent.Parent, LocalDeclarationStatementSyntax)
If localDeclSyntax IsNot Nothing Then
For Each modifier In localDeclSyntax.Modifiers
Select Case modifier.Kind
Case SyntaxKind.ConstKeyword
Return False
End Select
Next
End If
Return True
Case Else
Return True
End Select
Case SyntaxKind.RaiseEventStatement
Return False
Case SyntaxKind.NamedFieldInitializer
If DirectCast(parent, NamedFieldInitializerSyntax).Name Is currentNode Then
Return False
End If
' else proceed to the upper-level node
Case SyntaxKind.NameColonEquals
Return False
Case SyntaxKind.RangeArgument
If DirectCast(parent, RangeArgumentSyntax).LowerBound Is currentNode Then
Return False
End If
' proceed to the upper-level node
Case SyntaxKind.ArgumentList,
SyntaxKind.SimpleArgument,
SyntaxKind.ObjectMemberInitializer
' proceed to the upper-level node
Case SyntaxKind.GoToStatement
Return False
Case SyntaxKind.XmlDeclarationOption
Return False
Case Else
Return True
End Select
Else
Select Case parent.Kind
Case SyntaxKind.XmlElementEndTag
Return False
End Select
End If
' up one level
currentNode = parent
Loop
End Function
Private Sub AssertNodeInTree(node As VisualBasicSyntaxNode, argName As String)
If node Is Nothing Then
Throw New ArgumentNullException(argName)
End If
If Not IsInTree(node) Then
Throw New ArgumentException(argName & VBResources.NotWithinTree)
End If
End Sub
Private Function ValidateRegionDefiningExpression(expression As ExpressionSyntax) As Boolean
AssertNodeInTree(expression, NameOf(expression))
If expression.Kind = SyntaxKind.PredefinedType OrElse SyntaxFacts.IsInNamespaceOrTypeContext(expression) Then
Return False
End If
If SyntaxFactory.GetStandaloneExpression(expression) IsNot expression Then
Return False
End If
' Check for pseudo-expressions
Select Case expression.Kind
Case SyntaxKind.CollectionInitializer
Dim parent As VisualBasicSyntaxNode = expression.Parent
If parent IsNot Nothing Then
Select Case parent.Kind
Case SyntaxKind.ObjectCollectionInitializer
If DirectCast(parent, ObjectCollectionInitializerSyntax).Initializer Is expression Then
Return False
End If
Case SyntaxKind.ArrayCreationExpression
If DirectCast(parent, ArrayCreationExpressionSyntax).Initializer Is expression Then
Return False
End If
Case SyntaxKind.CollectionInitializer
' Nested collection initializer is not an expression from the language point of view.
' However, third level collection initializer under ObjectCollectionInitializer should
' be treated as a stand alone expression.
Dim possibleSecondLevelInitializer As VisualBasicSyntaxNode = parent
parent = parent.Parent
If parent IsNot Nothing AndAlso parent.Kind = SyntaxKind.CollectionInitializer Then
Dim possibleFirstLevelInitializer As VisualBasicSyntaxNode = parent
parent = parent.Parent
If parent IsNot Nothing AndAlso parent.Kind = SyntaxKind.ObjectCollectionInitializer AndAlso
DirectCast(parent, ObjectCollectionInitializerSyntax).Initializer Is possibleFirstLevelInitializer Then
Exit Select
End If
End If
Return False
End Select
End If
Case SyntaxKind.NumericLabel,
SyntaxKind.IdentifierLabel,
SyntaxKind.NextLabel
Return False
End Select
If Not IsExpressionInValidContext(expression) OrElse IsNodeInsideAttributeArguments(expression) Then
Return False
End If
Return True
End Function
Private Function ValidateRegionDefiningStatementsRange(firstStatement As StatementSyntax, lastStatement As StatementSyntax) As Boolean
AssertNodeInTree(firstStatement, NameOf(firstStatement))
AssertNodeInTree(lastStatement, NameOf(lastStatement))
If firstStatement.Parent Is Nothing OrElse firstStatement.Parent IsNot lastStatement.Parent Then
Throw New ArgumentException("statements not within the same statement list")
End If
If firstStatement.SpanStart > lastStatement.SpanStart Then
Throw New ArgumentException("first statement does not precede last statement")
End If
If Not TypeOf firstStatement Is ExecutableStatementSyntax OrElse Not TypeOf lastStatement Is ExecutableStatementSyntax Then
Return False
End If
' Test for |For ... Next x, y|
If IsNotUppermostForBlock(firstStatement) Then
Return False
End If
If firstStatement IsNot lastStatement AndAlso IsNotUppermostForBlock(lastStatement) Then
Return False
End If
If IsNodeInsideAttributeArguments(firstStatement) OrElse (firstStatement IsNot lastStatement AndAlso IsNodeInsideAttributeArguments(lastStatement)) Then
Return False
End If
Return True
End Function
''' <summary>
''' Check ForBlockSyntax for being the uppermost For block. By uppermost
''' For block we mean that if Next clause contains several control variables,
''' the uppermost block is the one which includes all the For blocks ending with
''' the same Next clause
''' </summary>
Private Function IsNotUppermostForBlock(forBlockOrStatement As VisualBasicSyntaxNode) As Boolean
Debug.Assert(forBlockOrStatement.Kind <> SyntaxKind.ForStatement)
Debug.Assert(forBlockOrStatement.Kind <> SyntaxKind.ForEachStatement)
Dim forBlock = TryCast(forBlockOrStatement, ForOrForEachBlockSyntax)
If forBlock Is Nothing Then
Return False
End If
Dim endNode As NextStatementSyntax = forBlock.NextStatement
If endNode IsNot Nothing Then
' The only case where the statement is valid is this case is
' that the Next clause contains one single control variable (or none)
Return endNode.ControlVariables.Count > 1
End If
' go down the For statements chain until the last and ensure it has as many
' variables as there were nested For statements
Dim nesting As Integer = 1
Do
If forBlock.Statements.Count = 0 Then
Return True
End If
Dim lastStatement = TryCast(forBlock.Statements.Last(), ForOrForEachBlockSyntax)
If lastStatement Is Nothing Then
Return True
End If
nesting += 1
endNode = lastStatement.NextStatement
If endNode IsNot Nothing Then
Return endNode.ControlVariables.Count <> nesting
End If
' Else - next level
forBlock = lastStatement
Loop
End Function
''' <summary>
''' Gets the semantic information of a for each statement.
''' </summary>
''' <param name="node">The for each syntax node.</param>
Friend Overrides Function GetForEachStatementInfoWorker(node As ForEachBlockSyntax) As ForEachStatementInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetForEachStatementInfoWorker(node)
Else
Return Nothing
End If
End Function
Friend Overrides Function GetAwaitExpressionInfoWorker(awaitExpression As AwaitExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As AwaitExpressionInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(awaitExpression)
If model IsNot Nothing Then
Return model.GetAwaitExpressionInfoWorker(awaitExpression, cancellationToken)
Else
Return Nothing
End If
End Function
#Region "Region Analysis Context Creation"
''' <summary> Used to create a region analysis context
''' with failed flag set to be used in 'failed' scenarios </summary>
Private Function CreateFailedRegionAnalysisContext() As RegionAnalysisContext
Return New RegionAnalysisContext(Me.Compilation)
End Function
Private Function CreateRegionAnalysisContext(expression As ExpressionSyntax) As RegionAnalysisContext
Dim region As TextSpan = expression.Span
Dim memberModel As MemberSemanticModel = GetMemberSemanticModel(expression)
If memberModel Is Nothing Then
' Recover from error cases
Dim node As BoundBadStatement = New BoundBadStatement(expression, ImmutableArray(Of BoundNode).Empty)
Return New RegionAnalysisContext(Compilation, Nothing, node, node, node, region)
End If
Dim boundNode As BoundNode = memberModel.GetBoundRoot()
Dim boundExpression As BoundNode = memberModel.GetUpperBoundNode(expression)
Return New RegionAnalysisContext(Compilation, memberModel.MemberSymbol, boundNode, boundExpression, boundExpression, region)
End Function
Private Function CreateRegionAnalysisContext(firstStatement As StatementSyntax, lastStatement As StatementSyntax) As RegionAnalysisContext
Dim region As TextSpan = TextSpan.FromBounds(firstStatement.SpanStart, lastStatement.Span.End)
Dim memberModel As MemberSemanticModel = GetMemberSemanticModel(firstStatement)
If memberModel Is Nothing Then
' Recover from error cases
Dim node As BoundBadStatement = New BoundBadStatement(firstStatement, ImmutableArray(Of BoundNode).Empty)
Return New RegionAnalysisContext(Compilation, Nothing, node, node, node, region)
End If
Dim boundNode As BoundNode = memberModel.GetBoundRoot()
Dim firstBoundNode As BoundNode = memberModel.GetUpperBoundNode(firstStatement)
Dim lastBoundNode As BoundNode = memberModel.GetUpperBoundNode(lastStatement)
Return New RegionAnalysisContext(Compilation, memberModel.MemberSymbol, boundNode, firstBoundNode, lastBoundNode, region)
End Function
#End Region
End Class
End Namespace
|
MihaMarkic/roslyn-prank
|
src/Compilers/VisualBasic/Portable/Compilation/SyntaxTreeSemanticModel.vb
|
Visual Basic
|
apache-2.0
| 103,891
|
Imports System
Imports Aspose.Cells
Imports Aspose.Cells.Drawing
Namespace Articles
Public Class GlowEffectOfShape
Public Shared Sub Run()
' ExStart:GlowEffectOfShape
' The path to the documents directory.
Dim dataDir As String = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
' Load your source excel file
Dim wb As New Workbook(dataDir & Convert.ToString("sample.xlsx"))
' Access first worksheet
Dim ws As Worksheet = wb.Worksheets(0)
' Access first shape
Dim sh As Shape = ws.Shapes(0)
' Set the glow effect of the shape, Set its Size and Transparency properties
Dim ge As GlowEffect = sh.Glow
ge.Size = 30
ge.Transparency = 0.4
' Save the workbook in xlsx format
wb.Save(dataDir & Convert.ToString("output_out.xlsx"))
' ExEnd:GlowEffectOfShape
End Sub
End Class
End Namespace
|
maria-shahid-aspose/Aspose.Cells-for-.NET
|
Examples/VisualBasic/Articles/GlowEffectOfShape.vb
|
Visual Basic
|
mit
| 1,043
|
Imports SistFoncreagro.BussinessEntities
Public Interface ICuentaEnlaceBL
Function GetCUENTAENLACEByCtaOperacion(ByVal CtaOperacion As Int32, ByVal Destino As String, ByVal Tipo As String) As IList(Of CuentaEnlace)
Function GetAllFromCUENTAENLACE() As List(Of CuentaEnlace)
Function GetCUENTAENLACEByParameter(ByVal Texto As String, ByVal Tipo As String) As List(Of CuentaEnlace)
Function GetCUENTAENLACEByCtaOperacionAndCtaPagar(ByVal CtaOperacion As Int32, ByVal Destino As String, ByVal CtaPagar As Int32, ByVal Tipo As String) As CuentaEnlace
Function GetCUENTAENLACEByCtaPagar(ByVal CtaPagar As Int32, ByVal Tipo As String) As CuentaEnlace
Function GetCtaCobrarByCtaPagarAndDestino(ByVal CtaPagar As Int32, ByVal Destino As String, ByVal Tipo As String) As Int32
Function GetCUENTAENLACEByIdCtaEnlace(ByVal IdCtaEnlace As Int32) As CuentaEnlace
Function SaveCUENTAENLACE(ByVal _CuentaEnlace As CuentaEnlace) As Int32
Sub UpdateEstadoCUENTAENLACE(ByVal IdCtaEnlace As Int32)
Function GetCtaPagarByCtaCobrarAndDestino(ByVal CtaCobrar As Int32, ByVal Destino As String, ByVal Tipo As String) As Int32
Function GetCUENTAENLACEByCtaOperacionAndCtaCobrar(ByVal CtaOperacion As Int32, ByVal Destino As String, ByVal CtaCobrar As Int32, ByVal Tipo As String) As CuentaEnlace
Function GetOrigenCtaEnlace(ByVal CtaPagar As Int32, ByVal Destino As String) As String
Function GetOrigenCtaEnlace1(ByVal CtaCobrar As Int32, ByVal Destino As String) As String
Function GetCtaOperacionByCtaCobrarAndDestino(ByVal CtaCobrar As Int32, ByVal Destino As String, ByVal Tipo As String) As String
Function GetCtaOperacionByCtaPagarAndDestino(ByVal CtaPagar As Int32, ByVal Destino As String, ByVal Tipo As String) As String
Function VerifyExisteCUENTAENLACE(ByVal Origen As String, ByVal Destino As String, ByVal CtaOperacion As Int32, ByVal CtaPagar As Int32, ByVal CtaCobrar As Int32, ByVal Tipo As String) As Int32
End Interface
|
crackper/SistFoncreagro
|
SistFoncreagro.BussinesLogic/ICuentaEnlaceBL.vb
|
Visual Basic
|
mit
| 1,982
|
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("Cef Sample")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("VBJay Solutions")>
<Assembly: AssemblyProduct("Cef Sample")>
<Assembly: AssemblyCopyright("Copyright © VBJay Solutions 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("7b870e62-1a05-4af9-81e7-78560d63f694")>
' 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")>
|
VBDev2Dev/CefSharpSample
|
Cef Sample/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,155
|
'Imports Microsoft.Office.Interop.Excel
Imports Microsoft.VisualBasic
Imports MySql.Data.MySqlClient
Public Class formMonthlyBill
Dim con1 As New connection 'Mysql Connection 1 used thorugh the Form
Dim con2 As New connection 'Mysql Connection 2 used thorugh the Form
Dim comm1, comm2 As New MySqlCommand ' Mysql Commands used in the Form
'All the Excel Stuff
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object = ""
Dim filename As Object
Dim total As Integer 'For No. Of Students To Be Billed, Used in Progress Bar
Dim row As Integer = 0 'For Current Row
'Calculates No. Of Students To Be Billed, Used in Progress Bar
Private Sub cal_total()
Try
con1.connect()
Dim query6 As String = "Select count(distinct s_id) from student_takes"
Dim comm4 As New MySqlCommand(query6, con1.conn)
Dim dr6 As MySqlDataReader = comm4.ExecuteReader
dr6.Read()
total = dr6.Item(0) + 2
Catch ex As Exception
MsgBox("Error Occured! Please Try Again")
MsgBox(ex.Message.ToString)
End Try
End Sub
'Generates the Monthly Bill Excel File
Private Sub generate_all() 'Handles BackgroundWorker1.DoWork 'Handles Gen_Excel.Click
Try
filename = "D:" + "\Mess_Monthly_Bill_" + MonthName(MonthCalendar1.SelectionRange.Start.Month.ToString) + "_" + MonthCalendar1.SelectionRange.Start.Year.ToString + ".xlsx"
'Me.Text = filename
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add
oSheet = oBook.worksheets.add
oSheet.range("A1").Value = "Id No."
oSheet.RANGE("B1").VALUE = "Name"
oSheet.RANGE("C1").VALUE = "Room No."
oSheet.RANGE("D1").VALUE = "Bhawan"
oSheet.RANGE("E1").VALUE = "No of days"
oSheet.RANGE("F1").VALUE = "Basic per day"
oSheet.RANGE("G1").VALUE = "Monthly Items Total"
oSheet.RANGE("H1").VALUE = "Extras Total"
oSheet.RANGE("I1").VALUE = "Rebate Days"
oSheet.RANGE("J1").VALUE = "Rebate Total"
oSheet.RANGE("K1").VALUE = "Special Meal"
oSheet.RANGE("L1").VALUE = "ANC Bill"
oSheet.RANGE("M1").VALUE = "Total Payable"
'Dim row As Integer
Dim iter As Int16
iter = 1
con1.disconnect()
con1.connect()
con2.disconnect()
con2.connect()
comm1.Connection = con1.conn
comm2.Connection = con2.conn
comm1.CommandText = "SELECT * FROM STUDENT ORDER BY BHAWAN,ROOM "
Dim dr1, dr2, dr3 As MySqlDataReader
Dim tm, tmr, item0_amt, item1_amt, item2_amt, item3_amt, item4_amt, item5_amt, rebate_days As Integer
Dim mthly, xtra, nv As Double
Dim rebate_amount, mess_daily_amount, item0, item1, item2, item3, item4, item5 As Double
'Dim anc_bill As Double
row = 2
dr1 = comm1.ExecuteReader
'MsgBox("'" + MonthCalendar1.SelectionRange.Start.Year.ToString + "-" + MonthCalendar1.SelectionRange.Start.Month.ToString + "-00'")
comm2.CommandText = "SELECT * from MONTHLY_MASTER where MONTH_YEAR = '" + MonthCalendar1.SelectionRange.Start.Year.ToString + "-" + MonthCalendar1.SelectionRange.Start.Month.ToString("00") + "-00'"
dr2 = comm2.ExecuteReader()
If dr2.Read() Then
rebate_amount = dr2.Item(2)
mess_daily_amount = dr2.Item(1)
item0 = dr2.Item(3)
item1 = dr2.Item(4)
item2 = dr2.Item(5)
item3 = dr2.Item(6)
item4 = dr2.Item(7)
item5 = dr2.Item(8)
dr2.Close()
Else
rebate_amount = 0
mess_daily_amount = 0
item0 = 0
item1 = 0
item2 = 0
item3 = 0
item4 = 0
item5 = 0
dr2.Close()
End If
While (dr1.Read())
'MsgBox(dr1.Item(0).ToString())
'comm2.CommandText = "SELECT greatest(price, 0) FROM temp_monthly WHERE s_id ='" + dr1.Item(0).ToString + "'"
'mthly = comm2.ExecuteScalar()
comm2.CommandText = "SELECT * from MONTHLY_DETAILS where s_id = '" + dr1.Item(0).ToString + "' and MONTH_YEAR = '" + MonthCalendar1.SelectionRange.Start.Year.ToString + "-" + MonthCalendar1.SelectionRange.Start.Month.ToString("00") + "-00'"
dr3 = comm2.ExecuteReader
If dr3.Read() Then
rebate_days = dr3.Item(2)
item0_amt = dr3.Item(3)
item1_amt = dr3.Item(4)
item2_amt = dr3.Item(5)
item3_amt = dr3.Item(6)
item4_amt = dr3.Item(7)
item5_amt = dr3.Item(8)
Else
item0_amt = 0
rebate_days = 0
item1_amt = 0
item2_amt = 0
item3_amt = 0
item4_amt = 0
item5_amt = 0
End If
mthly = item0_amt * item0 + item1_amt * item1 + item2_amt * item2 + item3_amt * item3 + item4_amt * item4 + item5_amt * item5
dr3.Close()
comm2.CommandText = "SELECT coalesce(SUM(qty*(rate*(1+(tax/100)))), 0) AS tot FROM student_takes WHERE s_id ='" + dr1.Item(0).ToString + "' AND (date_format(DOR,'%m')='" + MonthCalendar1.SelectionRange.Start.Month.ToString + "' OR date_format(DOR,'%m')='0" + MonthCalendar1.SelectionRange.Start.Month.ToString + "') AND date_format(DOR,'%Y')= '" + MonthCalendar1.SelectionRange.Start.Year.ToString + "'"
xtra = comm2.ExecuteScalar()
'comm2.CommandText = "SELECT NVL(Sum(NV_PRICE.PRICE*STUDENT_TAKES.QTY),0) FROM STUDENT_TAKES, NV_PRICE WHERE STUDENT_TAKES.ITEM_ID=999 AND STUDENT_TAKES.S_ID='" + dr1.Item(0).ToString + "' AND TO_CHAR(NV_PRICE.DOR) = TO_CHAR(STUDENT_TAKES.DOR) AND (TO_CHAR(STUDENT_TAKES.DOR,'MM')='0" + MonthCalendar1.SelectionRange.Start.Month.ToString + "' OR TO_CHAR(STUDENT_TAKES.DOR,'MM')='" + MonthCalendar1.SelectionRange.Start.Month.ToString + "') AND TO_CHAR(STUDENT_TAKES.DOR,'YYYY')='" + MonthCalendar1.SelectionRange.Start.Year.ToString + "'"
'nv = OracleCommand2.ExecuteScalar()
'OracleCommand2.CommandText = "SELECT NVL(ANC_BILL,0) FROM MONTHLY_SPCL WHERE S_ID='" + dr1.Item(0).ToString + "' AND MONTH='" + MonthCalendar1.SelectionRange.Start.Month.ToString + "'"
'anc_bill = OracleCommand2.ExecuteScalar()
xtra = xtra + nv
tmr = 0
tm = 0
If dr1.Item("NAME") = "CASH" Then
mthly = 0
rebate_days = 0
End If
oSheet.RANGE("A" + row.ToString).Value = dr1.Item("IDNO").ToString
oSheet.RANGE("B" + row.ToString).VALUE = dr1.Item("NAME").ToString
oSheet.RANGE("C" + row.ToString).VALUE = dr1.Item("ROOM").ToString
oSheet.RANGE("D" + row.ToString).VALUE = dr1.Item("BHAWAN").ToString
oSheet.RANGE("E" + row.ToString).VALUE = System.DateTime.DaysInMonth(MonthCalendar1.SelectionRange.Start.Year, MonthCalendar1.SelectionRange.Start.Month)
oSheet.RANGE("F" + row.ToString).VALUE = mess_daily_amount
oSheet.RANGE("G" + row.ToString).VALUE = mthly.ToString
oSheet.RANGE("H" + row.ToString).VALUE = xtra.ToString
oSheet.RANGE("I" + row.ToString).VALUE = rebate_days
If dr1.Item("NAME") = "CASH" Then
oSheet.RANGE("E" + row.ToString).VALUE = 0
End If
If (Rebate.Text <> "" Or rebate_amount > 0) Then
If rebate_amount > 0 Then
oSheet.RANGE("J" + row.ToString).VALUE = "=(I" + row.ToString + "*" + rebate_amount.ToString + ")"
Else
oSheet.RANGE("J" + row.ToString).VALUE = "=(I" + row.ToString + "*" + Rebate.Text.ToString + ")"
End If
Else
oSheet.RANGE("J" + row.ToString).VALUE = "=(I" + row.ToString + "*0)"
End If
oSheet.RANGE("K" + row.ToString).VALUE = "0"
'oSheet.RANGE("L" + row.ToString).VALUE = anc_bill.ToString()
oSheet.RANGE("M" + row.ToString).VALUE = "=(E" + row.ToString + " * F" + row.ToString + ")+G" + row.ToString + "+H" + row.ToString + "-J" + row.ToString + "+K" + row.ToString
row += 1
System.Threading.Thread.Sleep(1000)
BackgroundWorker1.ReportProgress(CInt((row / 5) * 100))
End While
oSheet.RANGE("G" + row.ToString).VALUE = "=SUM(G2:G" + (row - 1).ToString + ")"
oSheet.RANGE("H" + row.ToString).VALUE = "=SUM(H2:H" + (row - 1).ToString + ")"
oSheet.RANGE("J" + row.ToString).VALUE = "=SUM(J2:J" + (row - 1).ToString + ")"
oSheet.RANGE("K" + row.ToString).VALUE = "=SUM(K2:K" + (row - 1).ToString + ")"
oSheet.RANGE("L" + row.ToString).VALUE = "=SUM(L2:L" + (row - 1).ToString + ")"
oSheet.RANGE("M" + row.ToString).VALUE = "=SUM(M2:M" + (row - 1).ToString + ")"
oSheet.RANGE("G" + row.ToString).INTERIOR.COLORINDEX = 46
oSheet.RANGE("G" + row.ToString).FONT.SIZE = 20
oSheet.RANGE("H" + row.ToString).INTERIOR.COLORINDEX = 43
oSheet.RANGE("H" + row.ToString).FONT.SIZE = 20
oSheet.RANGE("J" + row.ToString).INTERIOR.COLORINDEX = 46
oSheet.RANGE("J" + row.ToString).FONT.SIZE = 20
oSheet.RANGE("K" + row.ToString).INTERIOR.COLORINDEX = 43
oSheet.RANGE("K" + row.ToString).FONT.SIZE = 20
oSheet.RANGE("L" + row.ToString).INTERIOR.COLORINDEX = 46
oSheet.RANGE("L" + row.ToString).FONT.SIZE = 20
oSheet.RANGE("M" + row.ToString).INTERIOR.COLORINDEX = 43
oSheet.RANGE("M" + row.ToString).FONT.SIZE = 20
dr1.Close()
con1.disconnect()
con2.disconnect()
oSheet.Columns("A:Z").autofit()
oBook.SaveAs(filename)
oExcel.Quit()
'MsgBox("Monthly Bill SAVED at : " + filename.ToString)
'Me.Close()
Catch ex As Exception
MsgBox("Error Occured! PLease Try again!")
MsgBox(ex.Message.ToString)
End Try
End Sub
'Handles Keypresses on the Form
Private Sub formMonthlyBill_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
If e.KeyCode = Keys.Escape Then
Me.Close()
ElseIf e.KeyCode = Keys.F5 Then
Controls.Clear()
InitializeComponent()
Rebate.Focus()
End If
End Sub
'On Form load
Private Sub formMonthlyBill_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Rebate.Focus()
Me.KeyPreview = True
End Sub
'Handles Enter Pressed on Rebate Tb
Private Sub Rebate_KeyDown(sender As Object, e As KeyEventArgs) Handles Rebate.KeyDown
If e.KeyCode = Keys.Enter Then
If Rebate.Text <> "" Then
Gen_Excel.Focus()
Else
MsgBox("No Value For Rebate Entered!! Value 0(ZERO) Assumed!!")
Gen_Excel.Focus()
End If
End If
End Sub
Private Sub My_BgWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
generate_all()
BackgroundWorker1.ReportProgress(CInt((row / total) * 100))
End Sub
Private Sub My_BgWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MsgBox("Monthly Bill SAVED at : " + filename.ToString)
Me.Close()
End Sub
Private Sub My_BgWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
' Update the progress bar
If e.ProgressPercentage >= 0 And e.ProgressPercentage <= 100 Then
Me.ProgressBar1.Value = e.ProgressPercentage
End If
End Sub
Private Sub Gen_Excel_Click(sender As Object, e As EventArgs) Handles Gen_Excel.Click
ProgressBar1.Visible = True
cal_total()
Try
BackgroundWorker1.RunWorkerAsync()
Catch ex As Exception
BackgroundWorker1.Dispose()
MsgBox("Error OCcured in Background Worker!")
MsgBox(ex.Message.ToString)
End Try
End Sub
End Class
|
SSMS-Pilani/Mess-Management-System
|
Mess Management System/formMonthlyBill.vb
|
Visual Basic
|
mit
| 13,066
|
Imports System
Imports System.Net
Imports Independentsoft.Exchange
Namespace Sample
Class Module1
Shared Sub Main(ByVal args As String())
Dim credential As New NetworkCredential("username", "password")
Dim service As New Service("https://myserver/ews/Exchange.asmx", credential)
Try
Dim restriction As New IsEqualTo(MessagePropertyPath.Subject, "Test")
Dim inboxResponse As FindItemResponse = service.FindItem(StandardFolder.Inbox, restriction)
For i As Integer = 0 To inboxResponse.Items.Count - 1
Dim currentMessageId As ItemId = inboxResponse.Items(i).ItemId
Dim replyItem As New ReplyItem(currentMessageId)
replyItem.NewBody = New Body("This is reply message body text.")
Dim response As ItemInfoResponse = service.Reply(replyItem)
Next
Catch ex As ServiceRequestException
Console.WriteLine("Error: " + ex.Message)
Console.WriteLine("Error: " + ex.XmlMessage)
Console.Read()
Catch ex As WebException
Console.WriteLine("Error: " + ex.Message)
Console.Read()
End Try
End Sub
End Class
End Namespace
|
age-killer/Electronic-invoice-document-processing
|
MailSort_CSHARP/packages/Independentsoft.Exchange.3.0.400/Tutorial/VBReplyTo/Module1.vb
|
Visual Basic
|
mit
| 1,331
|
Public Class BeffsCalculator
Dim value1 As String = ""
Dim value2 As String = ""
Dim value3 As Double = 0.0
Private Sub Button19_Click(sender As Object, e As EventArgs) Handles Button19.Click
value1 = ""
value2 = ""
value3 = 0.0
Button1.Text = 0.0
End Sub
Private Sub Button18_Click(sender As Object, e As EventArgs) Handles Button18.Click
Me.Close()
End Sub
Private Sub Button16_Click(sender As Object, e As EventArgs) Handles Button16.Click
If value1 > "" And value2 = "+" Then
Button1.Text = Val(value1) + Val(Button1.Text)
value3 = Button1.Text
ElseIf value2 > "" And value2 = "-" Then
Button1.Text = Val(value1) - Val(Button1.Text)
value3 = Button1.Text
ElseIf value2 > "" And value2 = "*" Then
Button1.Text = Val(value1) * Val(Button1.Text)
value3 = Button1.Text
ElseIf value2 > "" And value2 = "/" Then
Button1.Text = Val(value1) / Val(Button1.Text)
value3 = Button1.Text
ElseIf value2 > "" And value2 = "^" Then
Button1.Text = Val(value1) ^ Val(Button1.Text)
value3 = Button1.Text
End If
End Sub
Private Sub Button17_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button17.Click, Button13.Click, Button9.Click, Button5.Click, Button20.Click
value2 = sender.text
value1 = Button1.Text
End Sub
Private Sub Button14_Click(sender As Object, e As EventArgs) Handles Button14.Click
If Button1.Text = value1 Then
Button1.Text = "0."
ElseIf Button1.Text = "0." Then
Button1.Text = "0."
ElseIf Button1.Text = "0" Then
Button1.Text = "0."
ElseIf Button1.Text = value1 Then
Button1.Text = "0."
Else : Button1.Text = Button1.Text & "0"
End If
End Sub
Private Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.Click
If Button1.Text = "0." Then
Button1.Text = "."
ElseIf Button1.Text = value3 Then
Button1.Text = "."
ElseIf Button1.Text = value1 Then
Button1.Text = "."
Else
If Button1.Text.Contains(".") Then
Else
Button1.Text = Button1.Text & "."
End If
End If
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button8.Click, Button7.Click, Button6.Click, Button4.Click, Button3.Click, Button2.Click, Button12.Click, Button11.Click, Button10.Click
If Button1.Text = value1 Then
Button1.Text = sender.text
ElseIf Button1.Text = "0." Then
Button1.Text = sender.text
ElseIf Button1.Text = value3 Then
Button1.Text = sender.text
Else
Button1.Text = Button1.Text & sender.text
End If
End Sub
Private Sub BeffsCalculator_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
My.Settings.calculations = Button1.Text
End Sub
Private Sub BeffsCalculator_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Button1.Text = My.Settings.Calculations
End Sub
Private Sub Button1_KeyDown(sender As Object, e As KeyEventArgs)
If (e.KeyCode = Keys.C) Then
My.Computer.Clipboard.Clear()
My.Computer.Clipboard.SetText(Button1.Text)
End If
End Sub
Private Sub Button21_Click(sender As Object, e As EventArgs) Handles Button21.Click
Button1.Focus()
SendKeys.Send("{BACKSPACE}")
End Sub
Private Sub Button23_Click(sender As Object, e As EventArgs) Handles Button23.Click
Me.Close()
End Sub
Private Sub Button22_Click(sender As Object, e As EventArgs) Handles Button22.Click
Me.WindowState = FormWindowState.Minimized
End Sub
Private Sub Button24_Click(sender As Object, e As EventArgs) Handles Button24.Click
SquareRootCalculator.Show()
End Sub
Private IsFormBeingDragged As Boolean = False
Private MouseDownX As Integer
Private MouseDownY As Integer
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseDown
If e.Button = MouseButtons.Left Then
IsFormBeingDragged = True
MouseDownX = e.X
MouseDownY = e.Y
End If
End Sub
Private Sub Form1_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseUp
If e.Button = MouseButtons.Left Then
IsFormBeingDragged = False
End If
End Sub
Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseMove
If IsFormBeingDragged Then
Dim temp As Point = New Point()
temp.X = Me.Location.X + (e.X - MouseDownX)
temp.Y = Me.Location.Y + (e.Y - MouseDownY)
Me.Location = temp
temp = Nothing
End If
End Sub
Private Sub Button25_Click(sender As Object, e As EventArgs) Handles Button25.Click
RoundNumbers.Show()
End Sub
Private Sub Button26_Click(sender As Object, e As EventArgs) Handles Button26.Click
My.Computer.Clipboard.Clear()
My.Computer.Clipboard.SetText(Button1.Text)
End Sub
End Class
|
jdc20181/BeffsBrowser
|
Source/Utilities/BeffsCalculator.vb
|
Visual Basic
|
mit
| 5,452
|
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("WillStrohl.OpenGraph Module")>
<Assembly: AssemblyDescription("This module allows you to quickly and easily add the open graph protocol to your DotNetNuke site.")>
<Assembly: AssemblyCompany("Will Strohl")>
<Assembly: AssemblyProduct("http://www.willstrohl.com")>
<Assembly: AssemblyCopyright("Copyright 2011-2013 Will Strohl")>
<Assembly: AssemblyTrademark("")>
<Assembly: CLSCompliant(True)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("39E40A3E-FF34-4DEC-86A3-CEA07CFC4D56")>
' 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("01.02.00")>
<Assembly: ComVisibleAttribute(False)>
<Assembly: AssemblyFileVersionAttribute("01.02.00")>
|
nvisionative/dnnextensions
|
Modules/WillStrohl.OpenGraph/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,301
|
Imports System.IO
Imports System.Text
Imports System.Globalization
''' <summary>
''' Classes responsible for JSON decoding.
''' </summary>
Public Class JsonDecoder
Private Shared ReadOnly SpaceCharCode As Integer = AscW(" ")
Private Shared ReadOnly TabCharCode As Integer = AscW(vbTab)
Private Shared ReadOnly LineFeedCharCode As Integer = AscW(vbLf)
Private Shared ReadOnly CarriageReturnCharCode As Integer = AscW(vbCr)
Private Shared ReadOnly MaxWhiteSpaceCharCode As Integer = Math.Max(Math.Max(SpaceCharCode, TabCharCode), Math.Max(LineFeedCharCode, CarriageReturnCharCode))
Private _options As JsonDecoderOptions = Nothing
Private _reader As TextReader = Nothing
Private _position As Integer = 1
Private _line As Integer = 1
Private _column As Integer = 1
Private _bufferedCharValid As Boolean = False
Private _bufferedChar As Char = Nothing
''' <summary>
''' Creates new decoder with given options.
''' </summary>
''' <param name="options">Options of the decoder.</param>
Public Sub New(Optional options As JsonDecoderOptions = Nothing)
If options Is Nothing Then
options = JsonDecoderOptions.Default
End If
Me._options = options
End Sub
''' <summary>
''' Deserializes JSON encoded string into object representation.
''' </summary>
''' <param name="reader">Reader of the json string.</param>
''' <returns>Decoded JSON value.</returns>
''' <exception cref="JsonFormatException">When json string is invalid.</exception>
''' <exception cref="IOException">An I/O error occurs.</exception>
''' <exception cref="ObjectDisposedException">The reader is closed.</exception>
Public Function Decode(reader As TextReader) As JsonValue
Try
Me._reader = reader
' is reader input empty?
Dim isEos = False
Me.PeekChar(isEos)
If isEos Then
Return Nothing
End If
Return Me.ReadValue()
Finally
Me._reader = Nothing
Me._position = 1
Me._line = 1
Me._column = 1
End Try
End Function
Private Function ReadValue() As JsonValue
Dim result As JsonValue = Nothing
Dim peek = Me.PeekToken()
Select Case peek
Case Token.ObjectBegin
Return Me.ReadObject()
Case Token.ArrayBegin
Return Me.ReadArray()
Case Token.Null
Return Me.ReadNull()
Case Token.False
Return Me.ReadFalse()
Case Token.True
Return Me.ReadTrue()
Case Token.String
Return Me.ReadString()
Case Token.Number
Return Me.ReadNumber()
Case Else
Dim peekChar = Me.PeekChar()
Throw CreateFormatException("Unexpected token " & peek.ToString() & " (char `" & peekChar & "`, int " & AscW(peekChar) & ").")
End Select
End Function
Private Function ReadNull() As JsonValue
Dim chars(3) As Char
chars(0) = Me.ReadChar()
chars(1) = Me.ReadChar()
chars(2) = Me.ReadChar()
chars(3) = Me.ReadChar()
' we don't need to test first char - its token
If chars(1) = "u"c AndAlso chars(2) = "l"c AndAlso chars(3) = "l"c Then
' null
Return Nothing
Else
' something else
Throw CreateFormatException("Unexpected data. Chars `null` expected but `" & New String(chars) & "` found.")
End If
End Function
Private Function ReadFalse() As JsonBool
Dim chars(4) As Char
chars(0) = Me.ReadChar()
chars(1) = Me.ReadChar()
chars(2) = Me.ReadChar()
chars(3) = Me.ReadChar()
chars(4) = Me.ReadChar()
' we don't need to test first char - its token
If chars(1) = "a"c AndAlso chars(2) = "l"c AndAlso chars(3) = "s"c AndAlso chars(4) = "e"c Then
' false
Return JsonBool.False
Else
' something else
Throw CreateFormatException("Unexpected data. Chars `false` expected but `" & New String(chars) & "` found.")
End If
End Function
Private Function ReadTrue() As JsonBool
Dim chars(3) As Char
chars(0) = Me.ReadChar()
chars(1) = Me.ReadChar()
chars(2) = Me.ReadChar()
chars(3) = Me.ReadChar()
' we don't need to test first char - its token
If chars(1) = "r"c AndAlso chars(2) = "u"c AndAlso chars(3) = "e"c Then
' null
Return JsonBool.True
Else
' something else
Throw CreateFormatException("Unexpected data. Chars `true` expected but `" & New String(chars) & "` found.")
End If
End Function
Private Function ReadString() As JsonString
' consume starting "
Me.ReadChar()
Dim value = Me.ReadStringValue()
' consume ending "
Me.ReadChar()
Return New JsonString(value)
End Function
Private Function ReadNumber() As JsonNumber
Dim digits = New StringBuilder()
Dim peek As Char = Nothing
Dim isEndOfStream = False
Do
digits.Append(Me.ReadChar())
peek = Me.PeekChar(isEndOfStream)
Loop While Not isEndOfStream AndAlso ((peek >= "0"c AndAlso peek <= "9"c) OrElse peek = "." OrElse peek = "+"c OrElse peek = "-"c OrElse peek = "e"c OrElse peek = "E"c)
Dim decimalValue = Decimal.Parse(digits.ToString(), NumberStyles.AllowExponent Or NumberStyles.AllowDecimalPoint Or NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture)
Return New JsonNumber(decimalValue)
End Function
Private Function ReadObject() As JsonObject
' consume {
Me.ReadChar()
Dim result = New JsonObject()
Do
' key
Dim peek = Me.PeekToken()
If peek = Token.ObjectEnd Then
Exit Do
ElseIf peek = Token.Comma Then
' consume , (memeber separator)
Me.ReadChar()
Continue Do
ElseIf Not peek = Token.String Then
Throw CreateFormatException("Double quotes were expected.")
End If
' consume "
Me.ReadChar()
Dim key = Me.ReadStringValue()
' consume "
Me.ReadChar()
' colon
peek = Me.PeekToken
If Not peek = Token.Colon Then
Throw CreateFormatException("Colon was expected.")
End If
' consume colon
Me.ReadChar()
' value
Dim value = Me.ReadValue()
' set member
result(key) = value
Loop
' consume }
Me.ReadChar()
Return result
End Function
Private Function ReadArray() As JsonArray
' consume [
Me.ReadChar()
Dim result = New JsonArray()
Do
Dim peek = Me.PeekToken()
If peek = Token.ArrayEnd Then
Exit Do
ElseIf peek = Token.Comma Then
' consume ,
Me.ReadChar()
End If
' value
Dim value = Me.ReadValue()
result.Add(value)
Loop
' consume ]
Me.ReadChar()
Return result
End Function
''' <summary>
''' Reads string from reader.
''' </summary>
''' <returns>String until next unescaped double quotes.</returns>
Private Function ReadStringValue() As String
Dim builder = New StringBuilder()
Do
Dim peek As Char = Me.PeekChar()
If peek = """"c Then
Exit Do
ElseIf peek = "\"c Then
' escape seq
Me.ReadChar()
Select Case Me.ReadChar()
Case """"c
builder.Append("""")
Case "\"c
builder.Append("\")
Case "/"c
builder.Append("/")
Case "b"c
builder.Append(vbBack)
Case "f"c
builder.Append(vbFormFeed)
Case "n"c
builder.Append(vbLf)
Case "r"c
builder.Append(vbCr)
Case "t"c
builder.Append(vbTab)
Case "u"c
' unicode escape seq
Dim chars(3) As Char
chars(0) = Me.ReadChar()
chars(1) = Me.ReadChar()
chars(2) = Me.ReadChar()
chars(3) = Me.ReadChar()
builder.Append(Me.ParseUnicode(chars))
End Select
Else
builder.Append(Me.ReadChar())
End If
Loop
Return builder.ToString()
End Function
Private Function ParseUnicode(chars As Char()) As Char
Dim p1 = ParseSingleChar(chars(0), &H1000)
Dim p2 = ParseSingleChar(chars(1), &H100)
Dim p3 = ParseSingleChar(chars(2), &H10)
Dim p4 = ParseSingleChar(chars(3), 1)
Return ChrW(p1 + p2 + p3 + p4)
End Function
Private Function ParseSingleChar(ch As Char, multipliyer As Integer) As Integer
Dim p1 As Integer = 0
If ch >= "0"c AndAlso ch <= "9"c Then
p1 = CInt(AscW(ch) - AscW("0"c)) * multipliyer
ElseIf ch >= "A"c AndAlso ch <= "F"c Then
p1 = CInt(AscW(ch) - AscW("A"c) + 10) * multipliyer
ElseIf ch >= "a"c AndAlso ch <= "f"c Then
p1 = CInt(AscW(ch) - AscW("a"c) + 10) * multipliyer
End If
Return p1
End Function
#Region "Helpers"
Private Function IsWhiteSpace(charCode As Integer) As Boolean
If charCode > MaxWhiteSpaceCharCode Then
Return False
ElseIf charCode = SpaceCharCode OrElse charCode = TabCharCode OrElse charCode = LineFeedCharCode OrElse charCode = CarriageReturnCharCode Then
Return True
Else
Return False
End If
End Function
Private Function PeekToken() As Token
Dim peek As Char = Me.PeekChar()
Do While Me.IsWhiteSpace(AscW(peek))
Me._bufferedCharValid = False ' this will cause to read next char
peek = Me.PeekChar()
Loop
Select Case peek
Case "{"c
Return Token.ObjectBegin
Case "}"c
Return Token.ObjectEnd
Case "["c
Return Token.ArrayBegin
Case "]"c
Return Token.ArrayEnd
Case ","c
Return Token.Comma
Case ":"c
Return Token.Colon
Case """"c
Return Token.String
Case "0"c, "1"c, "2"c, "3"c, "4"c, "5"c, "6"c, "7"c, "8"c, "9"c, "+"c, "-"c, "."c
Return Token.Number
Case "f"c
Return Token.False
Case "t"c
Return Token.True
Case "n"c
Return Token.Null
End Select
Return Token.Invalid
End Function
Private Function PeekChar() As Char
If Not Me._bufferedCharValid Then
Me._bufferedChar = Me.ReadChar()
Me._bufferedCharValid = True
End If
Return Me._bufferedChar
End Function
Private Function PeekChar(ByRef isEndOfStream As Boolean) As Char
isEndOfStream = False
If Not Me._bufferedCharValid Then
Me._bufferedChar = Me.ReadChar(isEndOfStream)
If isEndOfStream Then
Return Nothing
End If
Me._bufferedCharValid = True
End If
Return Me._bufferedChar
End Function
Private Function ReadChar() As Char
Dim isEndOfStream = False
Dim result = Me.ReadChar(isEndOfStream)
If isEndOfStream Then
Throw CreateFormatException("Unexpected end of input.")
Else
Return result
End If
End Function
Private Function ReadChar(ByRef isEndOfStream As Boolean) As Char
isEndOfStream = False
If Me._bufferedCharValid Then
' take char from buffered
Me._bufferedCharValid = False
Return Me._bufferedChar
End If
Dim charCode = Me._reader.Read()
If charCode < 0 Then
isEndOfStream = True
Return Nothing
ElseIf charCode = LineFeedCharCode Then
Me._line += 1
Me._column = 0
ElseIf charCode = CarriageReturnCharCode Then
Me._column -= 1
End If
Me._position += 1
Me._column += 1
Return ChrW(charCode)
End Function
Private Function CreateFormatException(message As String) As JsonFormatException
Return New JsonFormatException(message, Me._line, Me._column - 1, Me._position - 1)
End Function
#End Region
End Class
|
mancze/jsonie
|
Jsonie/Source/JsonDecoder.vb
|
Visual Basic
|
mit
| 10,689
|
' ///////////////////////////////////////////////////////////////////////
' Copyright 2001-2015 Aspose Pty Ltd. All Rights Reserved.
'
' This file is part of Aspose.Email. The source code in this file
' is only intended as a supplement to the documentation, and is provided
' "as is", without warranty of any kind, either expressed or implied.
' ///////////////////////////////////////////////////////////////////////
Imports System.IO
Imports Aspose.Email.Mail
Imports Aspose.Email.Outlook
Imports Aspose.Email.Pop3
Imports Aspose.Email
Imports Aspose.Email.Mime
Imports Aspose.Email.Imap
Imports System.Configuration
Imports System.Data
Imports Aspose.Email.Mail.Bounce
Imports Aspose.Email.Exchange
Public Class RenamingFolders
Public Shared Sub Run()
' The path to the documents directory.
Dim dataDir As String = RunExamples.GetDataDir_IMAP()
Dim dstEmail As String = dataDir & Convert.ToString("1234.eml")
'Create an instance of the ImapClient class
Dim client As New ImapClient()
'Specify host, username and password for your client
client.Host = "imap.gmail.com"
' Set username
client.Username = "your.username@gmail.com"
' Set password
client.Password = "your.password"
' Set the port to 993. This is the SSL port of IMAP server
client.Port = 993
' Enable SSL
client.SecurityOptions = SecurityOptions.Auto
Try
' Rename a folder
client.RenameFolder("Aspose", "Client")
'Disconnect to the remote IMAP server
client.Disconnect()
Catch ex As Exception
System.Console.Write(Environment.NewLine + ex.ToString())
End Try
Console.WriteLine(Environment.NewLine + "Renamed folders on IMAP server.")
End Sub
End Class
|
ZeeshanShafqat/Aspose_Email_NET
|
Examples/VisualBasic/IMAP/RenamingFolders.vb
|
Visual Basic
|
mit
| 1,851
|
'------------------------------------------------------------------------------
' <generado automáticamente>
' Este código fue generado por una herramienta.
'
' Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
' se vuelve a generar el código.
' </generado automáticamente>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Partial Public Class ReporteExistencias
'''<summary>
'''Control ReportViewer1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents ReportViewer1 As Global.Telerik.ReportViewer.WebForms.ReportViewer
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.WebSite/Monitoreo/Formularios/ReporteExistencias.aspx.designer.vb
|
Visual Basic
|
mit
| 855
|
Imports Athena.Core
Imports System.Linq
Imports System.Net
Imports System.IO
Imports System.Xml
Imports System.Web
Imports System.Web.HttpUtility
Namespace Web
Partial Public Class HtmlParser
#Region " Private Constants "
Private Const HTML_ATTRIBUTE_EVENT As String = "athena-event"
Private Const HTML_ATTRIBUTE_INSTANCE As String = "athena-instance"
Private Const HTML_ATTRIBUTE_COMPLETE As String = "athena-complete"
#End Region
#Region " Public Events "
Public Event Parsed_Athena_Tracked_Url()
#End Region
#Region " Public Methods "
Public Function Transform_Html( _
ByVal db As System.Data.IDbConnection, _
ByVal _exercise As Exercise, _
ByVal _instance As Instance, _
ByVal _completion As [Event], _
ByVal _data As Dictionary(Of String, String), _
ByVal _html As String, _
Optional ByVal enable_Tracking As Boolean = True, _
Optional ByVal tracking_Url As String = Nothing _
) As String
If Not _data Is Nothing AndAlso _data.Count > 0 Then
For Each key As String In _data.Keys
_html = _html.Replace("{" & key & "}", _data(key))
Next
End If
If Not _instance Is Nothing Then _
_html = _html.Replace("{" & HTML_ATTRIBUTE_INSTANCE & "}", _instance.Code)
If Not _completion Is Nothing Then _
_html = _html.Replace("{" & HTML_ATTRIBUTE_COMPLETE & "}", _completion.Code)
If enable_Tracking Then
Dim current_Position As Int32 = 0
Dim attr_Location As Int32 = _html.ToLower().IndexOf(HTML_ATTRIBUTE_EVENT & "=", current_Position)
While attr_Location >= 0
' -- Get the Relevant HTML Tag --
Dim tag_Start As Int32 = _html.LastIndexOf("<", attr_Location)
Dim tag_End As Int32 = _html.IndexOf(">", attr_Location) + 1 ' TODO: Is this robust enough?
Dim html_Tag As String = _html.Substring(tag_Start, tag_End - tag_Start)
' -------------------------------
' -- Get the Athena Attribute Value --
Dim attr_Length As Int32 = HTML_ATTRIBUTE_EVENT.length + 1
Dim attr_Value_Location As Integer = (attr_Location - tag_Start) + HTML_ATTRIBUTE_EVENT.length + 1
Dim attr_Value_Deliminator As String = " "
Do Until Not attr_Value_Deliminator = " "
attr_Value_Deliminator = html_Tag.Substring(attr_Value_Location, 1)
attr_Value_Location += 1
attr_Length += 1
Loop
Dim attr_End As Int32 = html_Tag.IndexOf(attr_Value_Deliminator, attr_Value_Location)
Dim attr_Value As String = html_Tag.Substring(attr_Value_Location, attr_End - attr_Value_Location)
attr_Length += attr_Value.Length
attr_Length += 1
Dim attr_Start As Int32 = attr_Location - tag_Start
html_Tag = html_Tag.Remove(attr_Start, attr_Length)
' ------------------------------------
' -- Get the Event for this Attribute --
Dim existing_Event As [Event] = [Event].Get_Event(db, _exercise, attr_Value)
' --------------------------------------
' -- Get the URL for this Attribute --
Dim url_Delimiter As String = " "
Dim url_Start As Integer = 0
If html_Tag.ToLower().IndexOf("src=") > 0 Then
url_Start = html_Tag.ToLower().IndexOf("src=") + "src=".Length
ElseIf html_Tag.ToLower().IndexOf("href=") > 0 Then
url_Start = html_Tag.ToLower().IndexOf("href=") + "href=".Length
ElseIf html_Tag.ToLower().IndexOf("onclick=") > 0 AndAlso html_Tag.ToLower().IndexOf("$.get(") > 0 Then
url_Start = html_Tag.ToLower().IndexOf("$.get(") + "$.get(".Length
End If
Dim url_Deliminator As String = " "
Do Until Not url_Deliminator = " "
url_Deliminator = html_Tag.Substring(url_Start, 1)
url_Start += 1
Loop
Dim url_End As Int32 = html_Tag.IndexOf(url_Deliminator, url_Start)
Dim url_Value As String = html_Tag.Substring(url_Start, url_End - url_Start)
Dim url_NewValue As String = String.Format(tracking_Url.Replace("&", "&"), _instance.Code, existing_Event.Code, UrlEncode(url_Value))
html_Tag = html_Tag.Replace(url_Value, url_NewValue)
' ------------------------------------
' -- Clean Up HTML --
_html = _html.Remove(tag_Start, tag_End - tag_Start) ' Removes entire HTML Tag
_html = _html.Insert(tag_Start, html_Tag)
' -------------------
current_Position = tag_Start + html_Tag.Length
attr_Location = _html.ToLower().IndexOf(HTML_ATTRIBUTE_EVENT & "=", current_Position)
End While
End If
Return _html
End Function
#End Region
End Class
End Namespace
|
thiscouldbejd/Athena
|
Athena/_Web/Partials/HtmlParser.vb
|
Visual Basic
|
mit
| 4,575
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEndConstruct
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.GenerateEndConstruct), [Shared]>
<ExtensionOrder(After:=PredefinedCodeFixProviderNames.FixIncorrectExitContinue)>
Friend Class GenerateEndConstructCodeFixProvider
Inherits CodeFixProvider
Friend Const BC30025 As String = "BC30025" ' error BC30025: Property missing 'End Property'.
Friend Const BC30026 As String = "BC30026" ' error BC30026: 'End Sub' expected.
Friend Const BC30027 As String = "BC30027" ' error BC30027: 'End Function' expected.
Friend Const BC30081 As String = "BC30081" ' error BC30081: 'If' must end with a matching 'End If'
Friend Const BC30082 As String = "BC30082" ' error BC30082: 'While' must end with a matching 'End While'.
Friend Const BC30083 As String = "BC30083" ' error BC30083: 'Do' must end with a matching 'Loop'.
Friend Const BC30084 As String = "BC30084" ' error BC30084: 'For' must end with a matching 'Next'.
Friend Const BC30085 As String = "BC30085" ' error BC30085: 'With' must end with a matching 'End With'.
Friend Const BC30185 As String = "BC30185" ' error BC30185: 'Enum' must end with a matching 'End Enum'.
Friend Const BC30253 As String = "BC30253" ' error BC30253: 'Interface' must end with a matching 'End Interface'.
Friend Const BC30384 As String = "BC30384" ' error BC30384: 'Try' must end with a matching 'End Try'.
Friend Const BC30481 As String = "BC30481" ' error BC30481: 'Class' statement must end with a matching 'End Class'.
Friend Const BC30624 As String = "BC30624" ' error BC30624: 'Structure' statement must end with a matching 'End Structure'.
Friend Const BC30625 As String = "BC30625" ' error BC30625: 'Module' statement must end with a matching 'End Module'.
Friend Const BC30626 As String = "BC30626" ' error BC30626: 'Namespace' statement must end with a matching 'End Namespace'.
Friend Const BC30631 As String = "BC30631" ' error BC30631: 'Get' statement must end with a matching 'End Get'.
Friend Const BC30633 As String = "BC30633" ' error BC30633: 'Set' statement must end with a matching 'End Set'.
Friend Const BC30675 As String = "BC30675" ' error BC30675: 'SyncLock' statement must end with a matching 'End SyncLock'.
Friend Const BC31114 As String = "BC31114" ' error BC31114: 'Custom Event' must end with a matching 'End Event'.
Friend Const BC31115 As String = "BC31115" ' error BC31115: 'AddHandler' declaration must end with a matching 'End AddHandler'.
Friend Const BC31116 As String = "BC31116" ' error BC31116: 'RemoveHandler' declaration must end with a matching 'End RemoveHandler'.
Friend Const BC31117 As String = "BC31117" ' error BC31117: 'RaiseEvent' declaration must end with a matching 'End RaiseEvent'.
Friend Const BC36008 As String = "BC36008" ' error BC36008: 'Using' must end with a matching 'End Using'.
Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String)
Get
Return ImmutableArray.Create(BC30025, BC30026, BC30027, BC30081, BC30082, BC30083, BC30084, BC30085, BC30185, BC30253, BC30384, BC30481, BC30624, BC30625,
BC30626, BC30631, BC30633, BC30675, BC31114, BC31115, BC31116, BC31117, BC36008)
End Get
End Property
Public NotOverridable Overrides Async Function RegisterCodeFixesAsync(context As CodeFixContext) As Task
Dim root = Await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(False)
Dim token = root.FindToken(context.Span.Start)
If Not token.Span.IntersectsWith(context.Span) Then
Return
End If
Dim beginStatement = token.GetAncestors(Of SyntaxNode) _
.FirstOrDefault(Function(c) c.Span.IntersectsWith(context.Span) AndAlso IsCandidate(c))
If beginStatement Is Nothing OrElse beginStatement.Parent Is Nothing Then
Return
End If
Dim endStatement = GetEndStatement(beginStatement.Parent)
If endStatement Is Nothing OrElse Not endStatement.IsMissing Then
Return
End If
If endStatement.Parent.Kind = SyntaxKind.PropertyBlock Then
context.RegisterCodeFix(
New MyCodeAction(
VBFeaturesResources.Insert_the_missing_End_Property_statement,
Function(c) GeneratePropertyEndConstructAsync(context.Document, DirectCast(endStatement.Parent, PropertyBlockSyntax), c)),
context.Diagnostics)
Return
End If
If endStatement.Kind = SyntaxKind.EndGetStatement OrElse endStatement.Kind = SyntaxKind.EndSetStatement Then
If endStatement?.Parent?.Parent.Kind = SyntaxKind.PropertyBlock Then
context.RegisterCodeFix(
New MyCodeAction(
VBFeaturesResources.Insert_the_missing_End_Property_statement,
Function(c) GeneratePropertyEndConstructAsync(context.Document, DirectCast(endStatement.Parent.Parent, PropertyBlockSyntax), c)),
context.Diagnostics)
Return
End If
End If
context.RegisterCodeFix(
New MyCodeAction(
GetDescription(endStatement),
Function(c) GenerateEndConstructAsync(context.Document, endStatement, c)),
context.Diagnostics)
End Function
Private Shared Function IsCandidate(node As SyntaxNode) As Boolean
If node Is Nothing Then
Return False
End If
Dim begin = GetBeginStatement(node.Parent)
If begin Is Nothing Then
Return False
End If
Return begin.Span.Contains(node.Span)
End Function
Private Shared Function GetBeginStatement(node As SyntaxNode) As SyntaxNode
Return node.TypeSwitch((Function(n As MultiLineIfBlockSyntax) n.IfStatement),
(Function(n As UsingBlockSyntax) n.UsingStatement),
(Function(n As StructureBlockSyntax) n.BlockStatement),
(Function(n As ModuleBlockSyntax) n.BlockStatement),
(Function(n As NamespaceBlockSyntax) n.NamespaceStatement),
(Function(n As ClassBlockSyntax) n.BlockStatement),
(Function(n As InterfaceBlockSyntax) n.BlockStatement),
(Function(n As EnumBlockSyntax) n.EnumStatement),
(Function(n As WhileBlockSyntax) n.WhileStatement),
(Function(n As WithBlockSyntax) n.WithStatement),
(Function(n As SyncLockBlockSyntax) n.SyncLockStatement),
(Function(n As DoLoopBlockSyntax) n.DoStatement),
(Function(n As ForOrForEachBlockSyntax) n.ForOrForEachStatement),
(Function(n As TryBlockSyntax) DirectCast(n, SyntaxNode)),
(Function(n As MethodBlockBaseSyntax) n.BlockStatement),
(Function(n As PropertyBlockSyntax) n.PropertyStatement))
End Function
Private Shared Function GetEndStatement(node As SyntaxNode) As SyntaxNode
Return node.TypeSwitch((Function(n As MultiLineIfBlockSyntax) DirectCast(n.EndIfStatement, SyntaxNode)),
(Function(n As UsingBlockSyntax) n.EndUsingStatement),
(Function(n As StructureBlockSyntax) n.EndBlockStatement),
(Function(n As ModuleBlockSyntax) n.EndBlockStatement),
(Function(n As NamespaceBlockSyntax) n.EndNamespaceStatement),
(Function(n As ClassBlockSyntax) n.EndBlockStatement),
(Function(n As InterfaceBlockSyntax) n.EndBlockStatement),
(Function(n As EnumBlockSyntax) n.EndEnumStatement),
(Function(n As WhileBlockSyntax) n.EndWhileStatement),
(Function(n As WithBlockSyntax) n.EndWithStatement),
(Function(n As SyncLockBlockSyntax) n.EndSyncLockStatement),
(Function(n As DoLoopBlockSyntax) n.LoopStatement),
(Function(n As ForOrForEachBlockSyntax) n.NextStatement),
(Function(n As TryBlockSyntax) n.EndTryStatement),
(Function(n As MethodBlockBaseSyntax) n.EndBlockStatement),
(Function(n As PropertyBlockSyntax) n.EndPropertyStatement))
End Function
Private Async Function GeneratePropertyEndConstructAsync(document As Document, node As PropertyBlockSyntax, cancellationToken As CancellationToken) As Task(Of Document)
' Make sure the PropertyBlock has End Property
Dim updatedProperty = node
If node.EndPropertyStatement.IsMissing Then
updatedProperty = node.WithEndPropertyStatement(SyntaxFactory.EndPropertyStatement())
End If
' Make sure any existing setters or getters have their End
Dim getter = updatedProperty.Accessors.FirstOrDefault(Function(a) a.Kind = SyntaxKind.GetAccessorBlock)
If getter IsNot Nothing AndAlso getter.EndBlockStatement.IsMissing Then
updatedProperty = updatedProperty.ReplaceNode(getter, getter.WithEndBlockStatement(SyntaxFactory.EndGetStatement()))
End If
Dim setter = updatedProperty.Accessors.FirstOrDefault(Function(a) a.Kind = SyntaxKind.SetAccessorBlock)
If setter IsNot Nothing AndAlso setter.EndBlockStatement.IsMissing Then
updatedProperty = updatedProperty.ReplaceNode(setter, setter.WithEndBlockStatement(SyntaxFactory.EndSetStatement()))
End If
Dim gen = document.GetLanguageService(Of SyntaxGenerator)()
If getter Is Nothing AndAlso Not updatedProperty.PropertyStatement.Modifiers.Any(SyntaxKind.WriteOnlyKeyword) Then
updatedProperty = DirectCast(gen.WithGetAccessorStatements(updatedProperty, Array.Empty(Of SyntaxNode)()), PropertyBlockSyntax)
End If
If setter Is Nothing AndAlso Not updatedProperty.PropertyStatement.Modifiers.Any(SyntaxKind.ReadOnlyKeyword) Then
updatedProperty = DirectCast(gen.WithSetAccessorStatements(updatedProperty, Array.Empty(Of SyntaxNode)()), PropertyBlockSyntax)
End If
Dim updatedDocument = Await document.ReplaceNodeAsync(node, updatedProperty.WithAdditionalAnnotations(Formatter.Annotation), cancellationToken).ConfigureAwait(False)
Return updatedDocument
End Function
Public Function GetDescription(node As SyntaxNode) As String
Dim endBlockSyntax = TryCast(node, EndBlockStatementSyntax)
If endBlockSyntax IsNot Nothing Then
Return String.Format(VBFeaturesResources.Insert_the_missing_0, "End " + SyntaxFacts.GetText(endBlockSyntax.BlockKeyword.Kind))
End If
Dim loopStatement = TryCast(node, LoopStatementSyntax)
If loopStatement IsNot Nothing Then
Return String.Format(VBFeaturesResources.Insert_the_missing_0, SyntaxFacts.GetText(SyntaxKind.LoopKeyword))
End If
Return String.Format(VBFeaturesResources.Insert_the_missing_0, SyntaxFacts.GetText(SyntaxKind.NextKeyword))
End Function
Private Async Function GenerateEndConstructAsync(document As Document, endStatement As SyntaxNode, cancellationToken As CancellationToken) As Task(Of Document)
If endStatement.Kind = SyntaxKind.EndEnumStatement Then
' InvInsideEndsEnum
Dim nextNode = endStatement.Parent.GetLastToken().GetNextToken().Parent
If nextNode IsNot Nothing Then
Dim diagnostics = nextNode.GetDiagnostics()
If diagnostics.SingleOrDefault(Function(d) d.Id = "BC30619") IsNot Nothing Then
Dim updatedParent = DirectCast(endStatement.Parent, EnumBlockSyntax).WithEndEnumStatement(SyntaxFactory.EndEnumStatement())
Dim updatedDocument = Await document.ReplaceNodeAsync(endStatement.Parent, updatedParent.WithAdditionalAnnotations(Formatter.Annotation), cancellationToken).ConfigureAwait(False)
Return updatedDocument
End If
End If
End If
Return Await InsertEndConstructAsync(document, endStatement, cancellationToken).ConfigureAwait(False)
End Function
Private Async Function InsertEndConstructAsync(document As Document, endStatement As SyntaxNode, cancellationToken As CancellationToken) As Task(Of Document)
Dim text = Await document.GetTextAsync(cancellationToken).ConfigureAwait(False)
Dim stringToAppend As String = Nothing
Dim endBlock = TryCast(endStatement, EndBlockStatementSyntax)
If endBlock IsNot Nothing Then
stringToAppend = vbCrLf + "End " + SyntaxFacts.GetText(endBlock.BlockKeyword.Kind) + vbCrLf
End If
Dim nextStatement = TryCast(endStatement, NextStatementSyntax)
If nextStatement IsNot Nothing Then
stringToAppend = vbCrLf & SyntaxFacts.GetText(nextStatement.NextKeyword.Kind) & vbCrLf
End If
Dim loopStatement = TryCast(endStatement, LoopStatementSyntax)
If loopStatement IsNot Nothing Then
stringToAppend = vbCrLf & SyntaxFacts.GetText(loopStatement.LoopKeyword.Kind) & vbCrLf
End If
Dim insertionPoint = GetBeginStatement(endStatement.Parent).FullSpan.End
Dim updatedText = text.WithChanges(New TextChange(TextSpan.FromBounds(insertionPoint, insertionPoint), stringToAppend))
Dim updatedDocument = document.WithText(updatedText)
Dim tree = Await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
updatedDocument = Await updatedDocument.ReplaceNodeAsync(tree, tree.WithAdditionalAnnotations(Formatter.Annotation), cancellationToken).ConfigureAwait(False)
Return updatedDocument
End Function
Private Class MyCodeAction
Inherits CodeAction.DocumentChangeAction
Public Sub New(title As String, createChangedDocument As Func(Of CancellationToken, Task(Of Document)))
MyBase.New(title, createChangedDocument)
End Sub
End Class
End Class
End Namespace
|
Pvlerick/roslyn
|
src/Features/VisualBasic/Portable/CodeFixes/GenerateEndConstruct/GenerateEndConstructCodeFixProvider.vb
|
Visual Basic
|
apache-2.0
| 15,740
|
' 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.Completion
Imports Microsoft.CodeAnalysis.Editor.CommandHandlers
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands
Imports Microsoft.VisualStudio.Utilities
Imports Roslyn.Utilities
Imports VSCommanding = Microsoft.VisualStudio.Commanding
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
Partial Friend Class LegacyTestState
Inherits TestStateBase
Friend ReadOnly CompletionCommandHandler As CompletionCommandHandler
Friend ReadOnly Property CurrentCompletionPresenterSession As TestCompletionPresenterSession
Get
Return SessionTestState.CurrentCompletionPresenterSession
End Get
End Property
' Do not call directly. Use TestStateFactory
Friend Sub New(workspaceElement As XElement,
extraCompletionProviders As CompletionProvider(),
excludedTypes As List(Of Type),
extraExportedTypes As List(Of Type),
includeFormatCommandHandler As Boolean,
workspaceKind As String)
MyBase.New(workspaceElement, extraCompletionProviders, excludedTypes, extraExportedTypes, includeFormatCommandHandler, workspaceKind)
Me.CompletionCommandHandler = GetExportedValue(Of CompletionCommandHandler)()
Dim featureServiceFactory = GetExportedValue(Of IFeatureServiceFactory)()
featureServiceFactory.GlobalFeatureService.Disable(PredefinedEditorFeatureNames.AsyncCompletion, EmptyFeatureController.Instance)
End Sub
#Region "Editor Related Operations"
Public Overrides Sub SendEscape()
Dim handler = DirectCast(CompletionCommandHandler, VSCommanding.IChainedCommandHandler(Of EscapeKeyCommandArgs))
MyBase.SendEscape(Sub(a, n, c) handler.ExecuteCommand(a, Sub() SignatureHelpAfterCompletionCommandHandler.ExecuteCommand(a, n, c), c), Sub() Return)
End Sub
Public Overrides Sub SendDownKey()
Dim handler = DirectCast(CompletionCommandHandler, VSCommanding.IChainedCommandHandler(Of DownKeyCommandArgs))
MyBase.SendDownKey(Sub(a, n, c) handler.ExecuteCommand(a, Sub() SignatureHelpAfterCompletionCommandHandler.ExecuteCommand(a, n, c), c), Sub()
EditorOperations.MoveLineDown(extendSelection:=False)
End Sub)
End Sub
Public Overrides Sub SendUpKey()
Dim handler = DirectCast(CompletionCommandHandler, VSCommanding.IChainedCommandHandler(Of UpKeyCommandArgs))
MyBase.SendUpKey(Sub(a, n, c) handler.ExecuteCommand(a, Sub() SignatureHelpAfterCompletionCommandHandler.ExecuteCommand(a, n, c), c), Sub()
EditorOperations.MoveLineUp(extendSelection:=False)
End Sub)
End Sub
Public Overrides Sub SendPageUp()
Dim handler = DirectCast(CompletionCommandHandler, VSCommanding.IChainedCommandHandler(Of PageUpKeyCommandArgs))
MyBase.SendPageUp(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overrides Sub SendCut()
Dim handler = DirectCast(CompletionCommandHandler, VSCommanding.IChainedCommandHandler(Of CutCommandArgs))
MyBase.SendCut(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overrides Sub SendPaste()
Dim handler = DirectCast(CompletionCommandHandler, VSCommanding.IChainedCommandHandler(Of PasteCommandArgs))
MyBase.SendPaste(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overrides Sub SendInvokeCompletionList()
Dim handler = DirectCast(CompletionCommandHandler, VSCommanding.IChainedCommandHandler(Of InvokeCompletionListCommandArgs))
MyBase.SendInvokeCompletionList(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overrides Sub SendInsertSnippetCommand()
Dim handler = DirectCast(CompletionCommandHandler, VSCommanding.IChainedCommandHandler(Of InsertSnippetCommandArgs))
MyBase.SendInsertSnippetCommand(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overrides Sub SendSurroundWithCommand()
Dim handler = DirectCast(CompletionCommandHandler, VSCommanding.IChainedCommandHandler(Of SurroundWithCommandArgs))
MyBase.SendSurroundWithCommand(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overrides Sub SendSave()
Dim handler = DirectCast(CompletionCommandHandler, VSCommanding.IChainedCommandHandler(Of SaveCommandArgs))
MyBase.SendSave(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overrides Sub SendSelectAll()
Dim handler = DirectCast(CompletionCommandHandler, VSCommanding.IChainedCommandHandler(Of SelectAllCommandArgs))
MyBase.SendSelectAll(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overrides Sub ToggleSuggestionMode()
Dim handler = DirectCast(CompletionCommandHandler, VSCommanding.IChainedCommandHandler(Of ToggleCompletionModeCommandArgs))
MyBase.ToggleSuggestionMode(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Protected Overrides Function GetHandler(Of T As VSCommanding.ICommandHandler)() As T
Return DirectCast(DirectCast(CompletionCommandHandler, VSCommanding.ICommandHandler), T)
End Function
#End Region
#Region "Completion Operations"
Public Overrides Function GetSelectedItem() As CompletionItem
Return CurrentCompletionPresenterSession.SelectedItem
End Function
Public Overrides Sub CalculateItemsIfSessionExists()
Throw ExceptionUtilities.Unreachable
End Sub
Public Overrides Function GetCompletionItems() As IList(Of CompletionItem)
Return CurrentCompletionPresenterSession.CompletionItems
End Function
Public Overrides Sub RaiseFiltersChanged(args As CompletionItemFilterStateChangedEventArgs)
CurrentCompletionPresenterSession.RaiseFiltersChanged(args)
End Sub
Public Overrides Function GetCompletionItemFilters() As ImmutableArray(Of CompletionItemFilter)
Return CurrentCompletionPresenterSession.CompletionItemFilters
End Function
Public Overrides Function HasSuggestedItem() As Boolean
' SuggestionModeItem is always not null but is displayed only when SuggestionMode = True
Return CurrentCompletionPresenterSession.SuggestionMode
End Function
Public Overrides Function IsSoftSelected() As Boolean
Return CurrentCompletionPresenterSession.IsSoftSelected
End Function
Public Overrides Sub SendCommitUniqueCompletionListItem()
Dim handler = DirectCast(CompletionCommandHandler, VSCommanding.IChainedCommandHandler(Of CommitUniqueCompletionListItemCommandArgs))
MyBase.SendCommitUniqueCompletionListItem(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return)
End Sub
Public Overrides Sub SendSelectCompletionItem(displayText As String)
Dim item = CurrentCompletionPresenterSession.CompletionItems.FirstOrDefault(Function(i) i.DisplayText = displayText)
Assert.NotNull(item)
CurrentCompletionPresenterSession.SetSelectedItem(item)
End Sub
Public Overrides Sub SendSelectCompletionItemThroughPresenterSession(item As CompletionItem)
CurrentCompletionPresenterSession.SetSelectedItem(item)
End Sub
Public Overrides Async Function AssertNoCompletionSession() As Task
Await WaitForAsynchronousOperationsAsync()
Assert.Null(Me.CurrentCompletionPresenterSession)
End Function
Public Overrides Sub AssertNoCompletionSessionWithNoBlock()
Assert.Null(Me.CurrentCompletionPresenterSession)
End Sub
Public Overrides Async Function AssertCompletionSessionAfterTypingHash() As Task
' The legacy completion implementation was not updated to treat # as an IntelliSense trigger
Await AssertNoCompletionSession()
End Function
Public Overrides Async Function AssertCompletionSession(Optional projectionsView As ITextView = Nothing) As Task
' projectionsView is not used in this implementation
Await WaitForAsynchronousOperationsAsync()
Assert.NotNull(Me.CurrentCompletionPresenterSession)
End Function
Public Overrides Sub AssertItemsInOrder(expectedOrder As String())
AssertNoAsynchronousOperationsRunning()
Dim items = CurrentCompletionPresenterSession.CompletionItems
Assert.Equal(expectedOrder.Count, items.Count)
For i = 0 To expectedOrder.Count - 1
Assert.Equal(expectedOrder(i), items(i).DisplayText)
Next
End Sub
Public Overrides Async Function AssertSelectedCompletionItem(
Optional displayText As String = Nothing,
Optional displayTextSuffix As String = Nothing,
Optional description As String = Nothing,
Optional isSoftSelected As Boolean? = Nothing,
Optional isHardSelected As Boolean? = Nothing,
Optional shouldFormatOnCommit As Boolean? = Nothing,
Optional inlineDescription As String = Nothing,
Optional projectionsView As ITextView = Nothing) As Task
' projectionsView is not used in this implementation.
Await WaitForAsynchronousOperationsAsync()
If isSoftSelected.HasValue Then
Assert.True(isSoftSelected.Value = Me.CurrentCompletionPresenterSession.IsSoftSelected, "Current completion is not soft-selected.")
End If
If isHardSelected.HasValue Then
Assert.True(isHardSelected.Value = Not Me.CurrentCompletionPresenterSession.IsSoftSelected, "Current completion is not hard-selected.")
End If
If displayText IsNot Nothing Then
Assert.Equal(displayText, Me.CurrentCompletionPresenterSession.SelectedItem.DisplayText)
End If
If displayTextSuffix IsNot Nothing Then
Assert.Equal(displayTextSuffix, Me.CurrentCompletionPresenterSession.SelectedItem.DisplayTextSuffix)
End If
If inlineDescription IsNot Nothing Then
Assert.Equal(inlineDescription, Me.CurrentCompletionPresenterSession.SelectedItem.InlineDescription)
End If
If shouldFormatOnCommit.HasValue Then
Assert.Equal(shouldFormatOnCommit.Value, Me.CurrentCompletionPresenterSession.SelectedItem.Rules.FormatOnCommit)
End If
If description IsNot Nothing Then
Dim document = Me.Workspace.CurrentSolution.Projects.First().Documents.First()
Dim service = CompletionService.GetService(document)
Dim itemDescription = Await service.GetDescriptionAsync(
document, Me.CurrentCompletionPresenterSession.SelectedItem)
Assert.Equal(description, itemDescription.Text)
End If
End Function
Public Overrides Function AssertSessionIsNothingOrNoCompletionItemLike(text As String) As Task
If Not CurrentCompletionPresenterSession Is Nothing Then
AssertCompletionItemsDoNotContainAny({text})
End If
Return Task.CompletedTask
End Function
Public Overrides Async Function WaitForUIRenderedAsync() As Task
Await WaitForAsynchronousOperationsAsync()
End Function
#End Region
End Class
End Namespace
|
nguerrera/roslyn
|
src/EditorFeatures/TestUtilities2/Intellisense/LegacyTestState.vb
|
Visual Basic
|
apache-2.0
| 12,944
|
' 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.Concurrent
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.RuntimeMembers
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' A source module binder provides the context associated with a source module.
''' </summary>
Friend Class SourceModuleBinder
Inherits Binder
Private ReadOnly _sourceModule As SourceModuleSymbol
Public Sub New(containingBinder As Binder, sourceModule As SourceModuleSymbol)
MyBase.New(containingBinder, sourceModule, sourceModule.ContainingSourceAssembly.DeclaringCompilation)
_sourceModule = sourceModule
End Sub
Public Overrides Function CheckAccessibility(sym As Symbol,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo),
Optional accessThroughType As TypeSymbol = Nothing,
Optional basesBeingResolved As BasesBeingResolved = Nothing) As AccessCheckResult
Return If(IgnoresAccessibility,
AccessCheckResult.Accessible,
AccessCheck.CheckSymbolAccessibility(sym, _sourceModule.ContainingSourceAssembly, useSiteDiagnostics, basesBeingResolved)) ' accessThroughType doesn't matter at assembly level.
End Function
Public Overrides ReadOnly Property OptionStrict As OptionStrict
Get
Return _sourceModule.Options.OptionStrict
End Get
End Property
Public Overrides ReadOnly Property OptionInfer As Boolean
Get
Return _sourceModule.Options.OptionInfer
End Get
End Property
Public Overrides ReadOnly Property OptionExplicit As Boolean
Get
Return _sourceModule.Options.OptionExplicit
End Get
End Property
Public Overrides ReadOnly Property OptionCompareText As Boolean
Get
Return _sourceModule.Options.OptionCompareText
End Get
End Property
Public Overrides ReadOnly Property CheckOverflow As Boolean
Get
Return _sourceModule.Options.CheckOverflow
End Get
End Property
Public Overrides ReadOnly Property QuickAttributeChecker As QuickAttributeChecker
Get
Return _sourceModule.QuickAttributeChecker
End Get
End Property
End Class
End Namespace
|
aelij/roslyn
|
src/Compilers/VisualBasic/Portable/Binding/SourceModuleBinder.vb
|
Visual Basic
|
apache-2.0
| 3,053
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.FindSymbols
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.Rename
Imports Microsoft.CodeAnalysis.Rename.ConflictEngine
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Rename
Friend Class VisualBasicRenameRewriterLanguageService
Implements IRenameRewriterLanguageService
Private ReadOnly _languageServiceProvider As HostLanguageServices
Public Sub New(provider As HostLanguageServices)
_languageServiceProvider = provider
End Sub
#Region "Annotate"
Public Function AnnotateAndRename(parameters As RenameRewriterParameters) As SyntaxNode Implements IRenameRewriterLanguageService.AnnotateAndRename
Dim renameRewriter = New RenameRewriter(parameters)
Return renameRewriter.Visit(parameters.SyntaxRoot)
End Function
Private Class RenameRewriter
Inherits VisualBasicSyntaxRewriter
Private ReadOnly _documentId As DocumentId
Private ReadOnly _renameRenamableSymbolDeclaration As RenameAnnotation
Private ReadOnly _solution As Solution
Private ReadOnly _replacementText As String
Private ReadOnly _originalText As String
Private ReadOnly _possibleNameConflicts As ICollection(Of String)
Private ReadOnly _renameLocations As Dictionary(Of TextSpan, RenameLocation)
Private ReadOnly _conflictLocations As IEnumerable(Of TextSpan)
Private ReadOnly _semanticModel As SemanticModel
Private ReadOnly _cancellationToken As CancellationToken
Private ReadOnly _renamedSymbol As ISymbol
Private ReadOnly _aliasSymbol As IAliasSymbol
Private ReadOnly _renamableDeclarationLocation As Location
Private ReadOnly _renameSpansTracker As RenamedSpansTracker
Private ReadOnly _isVerbatim As Boolean
Private ReadOnly _replacementTextValid As Boolean
Private ReadOnly _isRenamingInStrings As Boolean
Private ReadOnly _isRenamingInComments As Boolean
Private ReadOnly _stringAndCommentTextSpans As ISet(Of TextSpan)
Private ReadOnly _simplificationService As ISimplificationService
Private ReadOnly _annotatedIdentifierTokens As New HashSet(Of SyntaxToken)
Private ReadOnly _invocationExpressionsNeedingConflictChecks As New HashSet(Of InvocationExpressionSyntax)
Private ReadOnly _syntaxFactsService As ISyntaxFactsService
Private ReadOnly _semanticFactsService As ISemanticFactsService
Private ReadOnly _renameAnnotations As AnnotationTable(Of RenameAnnotation)
Private ReadOnly Property AnnotateForComplexification As Boolean
Get
Return Me._skipRenameForComplexification > 0 AndAlso Not Me._isProcessingComplexifiedSpans
End Get
End Property
Private _skipRenameForComplexification As Integer = 0
Private _isProcessingComplexifiedSpans As Boolean
Private _modifiedSubSpans As List(Of ValueTuple(Of TextSpan, TextSpan)) = Nothing
Private _speculativeModel As SemanticModel
Private _isProcessingStructuredTrivia As Integer
Private ReadOnly _complexifiedSpans As HashSet(Of TextSpan) = New HashSet(Of TextSpan)
Private Sub AddModifiedSpan(oldSpan As TextSpan, newSpan As TextSpan)
newSpan = New TextSpan(oldSpan.Start, newSpan.Length)
If Not Me._isProcessingComplexifiedSpans Then
_renameSpansTracker.AddModifiedSpan(_documentId, oldSpan, newSpan)
Else
Me._modifiedSubSpans.Add(ValueTuple.Create(oldSpan, newSpan))
End If
End Sub
Public Sub New(parameters As RenameRewriterParameters)
MyBase.New(visitIntoStructuredTrivia:=True)
Me._documentId = parameters.Document.Id
Me._renameRenamableSymbolDeclaration = parameters.RenamedSymbolDeclarationAnnotation
Me._solution = parameters.OriginalSolution
Me._replacementText = parameters.ReplacementText
Me._originalText = parameters.OriginalText
Me._possibleNameConflicts = parameters.PossibleNameConflicts
Me._renameLocations = parameters.RenameLocations
Me._conflictLocations = parameters.ConflictLocationSpans
Me._cancellationToken = parameters.CancellationToken
Me._semanticModel = DirectCast(parameters.SemanticModel, SemanticModel)
Me._renamedSymbol = parameters.RenameSymbol
Me._replacementTextValid = parameters.ReplacementTextValid
Me._renameSpansTracker = parameters.RenameSpansTracker
Me._isRenamingInStrings = parameters.OptionSet.GetOption(RenameOptions.RenameInStrings)
Me._isRenamingInComments = parameters.OptionSet.GetOption(RenameOptions.RenameInComments)
Me._stringAndCommentTextSpans = parameters.StringAndCommentTextSpans
Me._aliasSymbol = TryCast(Me._renamedSymbol, IAliasSymbol)
Me._renamableDeclarationLocation = Me._renamedSymbol.Locations.Where(Function(loc) loc.IsInSource AndAlso loc.SourceTree Is _semanticModel.SyntaxTree).FirstOrDefault()
Me._simplificationService = parameters.Document.Project.LanguageServices.GetService(Of ISimplificationService)()
Me._syntaxFactsService = parameters.Document.Project.LanguageServices.GetService(Of ISyntaxFactsService)()
Me._semanticFactsService = parameters.Document.Project.LanguageServices.GetService(Of ISemanticFactsService)()
Me._isVerbatim = Me._syntaxFactsService.IsVerbatimIdentifier(_replacementText)
Me._renameAnnotations = parameters.RenameAnnotations
End Sub
Public Overrides Function Visit(node As SyntaxNode) As SyntaxNode
If node Is Nothing Then
Return node
End If
Dim isInConflictLambdaBody = False
Dim lambdas = node.GetAncestorsOrThis(Of MultiLineLambdaExpressionSyntax)()
If lambdas.Count() <> 0 Then
For Each lambda In lambdas
If Me._conflictLocations.Any(Function(cf)
Return cf.Contains(lambda.Span)
End Function) Then
isInConflictLambdaBody = True
Exit For
End If
Next
End If
Dim shouldComplexifyNode = Me.ShouldComplexifyNode(node, isInConflictLambdaBody)
Dim result As SyntaxNode
If shouldComplexifyNode Then
Me._skipRenameForComplexification += 1
result = MyBase.Visit(node)
Me._skipRenameForComplexification -= 1
result = Complexify(node, result)
Else
result = MyBase.Visit(node)
End If
Return result
End Function
Private Function ShouldComplexifyNode(node As SyntaxNode, isInConflictLambdaBody As Boolean) As Boolean
Return Not isInConflictLambdaBody AndAlso
_skipRenameForComplexification = 0 AndAlso
Not _isProcessingComplexifiedSpans AndAlso
_conflictLocations.Contains(node.Span) AndAlso
(TypeOf node Is ExpressionSyntax OrElse
TypeOf node Is StatementSyntax OrElse
TypeOf node Is AttributeSyntax OrElse
TypeOf node Is SimpleArgumentSyntax OrElse
TypeOf node Is CrefReferenceSyntax OrElse
TypeOf node Is TypeConstraintSyntax)
End Function
Private Function Complexify(originalNode As SyntaxNode, newNode As SyntaxNode) As SyntaxNode
If Me._complexifiedSpans.Contains(originalNode.Span) Then
Return newNode
Else
Me._complexifiedSpans.Add(originalNode.Span)
End If
Me._isProcessingComplexifiedSpans = True
Me._modifiedSubSpans = New List(Of ValueTuple(Of TextSpan, TextSpan))()
Dim annotation = New SyntaxAnnotation()
newNode = newNode.WithAdditionalAnnotations(annotation)
Dim speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode)
newNode = speculativeTree.GetAnnotatedNodes(Of SyntaxNode)(annotation).First()
Me._speculativeModel = GetSemanticModelForNode(newNode, Me._semanticModel)
Debug.Assert(_speculativeModel IsNot Nothing, "expanding a syntax node which cannot be speculated?")
Dim oldSpan = originalNode.Span
Dim expandParameter = originalNode.GetAncestorsOrThis(Of LambdaExpressionSyntax).Count() = 0
Dim expandedNewNode = DirectCast(_simplificationService.Expand(newNode,
_speculativeModel,
annotationForReplacedAliasIdentifier:=Nothing,
expandInsideNode:=AddressOf IsExpandWithinMultiLineLambda,
expandParameter:=expandParameter,
cancellationToken:=_cancellationToken), SyntaxNode)
Dim annotationForSpeculativeNode = New SyntaxAnnotation()
expandedNewNode = expandedNewNode.WithAdditionalAnnotations(annotationForSpeculativeNode)
speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, expandedNewNode)
Dim probableRenameNode = speculativeTree.GetAnnotatedNodes(Of SyntaxNode)(annotation).First()
Dim speculativeNewNode = speculativeTree.GetAnnotatedNodes(Of SyntaxNode)(annotationForSpeculativeNode).First()
Me._speculativeModel = GetSemanticModelForNode(speculativeNewNode, Me._semanticModel)
Debug.Assert(_speculativeModel IsNot Nothing, "expanding a syntax node which cannot be speculated?")
Dim renamedNode = MyBase.Visit(probableRenameNode)
If Not ReferenceEquals(renamedNode, probableRenameNode) Then
renamedNode = renamedNode.WithoutAnnotations(annotation)
probableRenameNode = expandedNewNode.GetAnnotatedNodes(Of SyntaxNode)(annotation).First()
expandedNewNode = expandedNewNode.ReplaceNode(probableRenameNode, renamedNode)
End If
Dim newSpan = expandedNewNode.Span
probableRenameNode = probableRenameNode.WithoutAnnotations(annotation)
expandedNewNode = Me._renameAnnotations.WithAdditionalAnnotations(expandedNewNode, New RenameNodeSimplificationAnnotation() With {.OriginalTextSpan = oldSpan})
Me._renameSpansTracker.AddComplexifiedSpan(Me._documentId, oldSpan, New TextSpan(oldSpan.Start, newSpan.Length), Me._modifiedSubSpans)
Me._modifiedSubSpans = Nothing
Me._isProcessingComplexifiedSpans = False
Me._speculativeModel = Nothing
Return expandedNewNode
End Function
Private Function IsExpandWithinMultiLineLambda(node As SyntaxNode) As Boolean
If node Is Nothing Then
Return False
End If
If Me._conflictLocations.Contains(node.Span) Then
Return True
End If
If node.IsParentKind(SyntaxKind.MultiLineSubLambdaExpression) OrElse
node.IsParentKind(SyntaxKind.MultiLineFunctionLambdaExpression) Then
Dim parent = DirectCast(node.Parent, MultiLineLambdaExpressionSyntax)
If ReferenceEquals(parent.SubOrFunctionHeader, node) Then
Return True
Else
Return False
End If
End If
Return True
End Function
Private Function IsPossibleNameConflict(possibleNameConflicts As ICollection(Of String), candidate As String) As Boolean
For Each possibleNameConflict In possibleNameConflicts
If CaseInsensitiveComparison.Equals(possibleNameConflict, candidate) Then
Return True
End If
Next
Return False
End Function
Private Function UpdateAliasAnnotation(newToken As SyntaxToken) As SyntaxToken
If Me._aliasSymbol IsNot Nothing AndAlso Not Me.AnnotateForComplexification AndAlso newToken.HasAnnotations(AliasAnnotation.Kind) Then
newToken = RenameUtilities.UpdateAliasAnnotation(newToken, Me._aliasSymbol, Me._replacementText)
End If
Return newToken
End Function
Private Async Function RenameAndAnnotateAsync(token As SyntaxToken, newToken As SyntaxToken, isRenameLocation As Boolean, isOldText As Boolean) As Task(Of SyntaxToken)
If Me._isProcessingComplexifiedSpans Then
If isRenameLocation Then
Dim annotation = Me._renameAnnotations.GetAnnotations(Of RenameActionAnnotation)(token).FirstOrDefault()
If annotation IsNot Nothing Then
newToken = RenameToken(token, newToken, annotation.Prefix, annotation.Suffix)
AddModifiedSpan(annotation.OriginalSpan, New TextSpan(token.Span.Start, newToken.Span.Length))
Else
newToken = RenameToken(token, newToken, prefix:=Nothing, suffix:=Nothing)
End If
End If
Return newToken
End If
Dim symbols = RenameUtilities.GetSymbolsTouchingPosition(token.Span.Start, Me._semanticModel, Me._solution.Workspace, Me._cancellationToken)
' this is the compiler generated backing field of a non custom event. We need to store a "Event" suffix to properly rename it later on.
Dim prefix = If(isRenameLocation AndAlso Me._renameLocations(token.Span).IsRenamableAccessor, newToken.ValueText.Substring(0, newToken.ValueText.IndexOf("_"c) + 1), String.Empty)
Dim suffix As String = Nothing
If symbols.Count() = 1 Then
Dim symbol = symbols.Single()
If symbol.IsConstructor() Then
symbol = symbol.ContainingSymbol
End If
If symbol.Kind = SymbolKind.Field AndAlso symbol.IsImplicitlyDeclared Then
Dim fieldSymbol = DirectCast(symbol, IFieldSymbol)
If fieldSymbol.Type.IsDelegateType AndAlso
fieldSymbol.Type.IsImplicitlyDeclared AndAlso
DirectCast(fieldSymbol.Type, INamedTypeSymbol).AssociatedSymbol IsNot Nothing Then
suffix = "Event"
End If
If fieldSymbol.AssociatedSymbol IsNot Nothing AndAlso
fieldSymbol.AssociatedSymbol.IsKind(SymbolKind.Property) AndAlso
fieldSymbol.Name = "_" + fieldSymbol.AssociatedSymbol.Name Then
prefix = "_"
End If
ElseIf symbol.IsConstructor AndAlso
symbol.ContainingType.IsImplicitlyDeclared AndAlso
symbol.ContainingType.IsDelegateType AndAlso
symbol.ContainingType.AssociatedSymbol IsNot Nothing Then
suffix = "EventHandler"
ElseIf TypeOf symbol Is INamedTypeSymbol Then
Dim namedTypeSymbol = DirectCast(symbol, INamedTypeSymbol)
If namedTypeSymbol.IsImplicitlyDeclared AndAlso
namedTypeSymbol.IsDelegateType() AndAlso
namedTypeSymbol.AssociatedSymbol IsNot Nothing Then
suffix = "EventHandler"
End If
End If
If Not isRenameLocation AndAlso TypeOf (symbol) Is INamespaceSymbol AndAlso token.GetPreviousToken().Kind = SyntaxKind.NamespaceKeyword Then
Return newToken
End If
End If
If isRenameLocation AndAlso Not Me.AnnotateForComplexification Then
Dim oldSpan = token.Span
newToken = RenameToken(token, newToken, prefix:=prefix, suffix:=suffix)
AddModifiedSpan(oldSpan, newToken.Span)
End If
Dim renameDeclarationLocations As RenameDeclarationLocationReference() =
Await ConflictResolver.CreateDeclarationLocationAnnotationsAsync(_solution, symbols, _cancellationToken).ConfigureAwait(False)
Dim isNamespaceDeclarationReference = False
If isRenameLocation AndAlso token.GetPreviousToken().Kind = SyntaxKind.NamespaceKeyword Then
isNamespaceDeclarationReference = True
End If
Dim isMemberGroupReference = _semanticFactsService.IsNameOfContext(_semanticModel, token.Span.Start, _cancellationToken)
Dim renameAnnotation = New RenameActionAnnotation(
token.Span,
isRenameLocation,
prefix,
suffix,
isOldText,
renameDeclarationLocations,
isNamespaceDeclarationReference,
isInvocationExpression:=False,
isMemberGroupReference:=isMemberGroupReference)
_annotatedIdentifierTokens.Add(token)
newToken = Me._renameAnnotations.WithAdditionalAnnotations(newToken, renameAnnotation, New RenameTokenSimplificationAnnotation() With {.OriginalTextSpan = token.Span})
If Me._renameRenamableSymbolDeclaration IsNot Nothing AndAlso _renamableDeclarationLocation = token.GetLocation() Then
newToken = Me._renameAnnotations.WithAdditionalAnnotations(newToken, Me._renameRenamableSymbolDeclaration)
End If
Return newToken
End Function
Private Function IsInRenameLocation(token As SyntaxToken) As Boolean
If Not Me._isProcessingComplexifiedSpans Then
Return Me._renameLocations.ContainsKey(token.Span)
Else
If token.HasAnnotations(AliasAnnotation.Kind) Then
Return False
End If
If Me._renameAnnotations.HasAnnotations(Of RenameActionAnnotation)(token) Then
Return Me._renameAnnotations.GetAnnotations(Of RenameActionAnnotation)(token).First().IsRenameLocation
End If
If TypeOf token.Parent Is SimpleNameSyntax AndAlso token.Kind <> SyntaxKind.GlobalKeyword AndAlso token.Parent.Parent.IsKind(SyntaxKind.QualifiedName, SyntaxKind.QualifiedCrefOperatorReference) Then
Dim symbol = Me._speculativeModel.GetSymbolInfo(token.Parent, Me._cancellationToken).Symbol
If symbol IsNot Nothing AndAlso Me._renamedSymbol.Kind <> SymbolKind.Local AndAlso Me._renamedSymbol.Kind <> SymbolKind.RangeVariable AndAlso
(symbol Is Me._renamedSymbol OrElse SymbolKey.GetComparer(ignoreCase:=True, ignoreAssemblyKeys:=False).Equals(symbol.GetSymbolKey(), Me._renamedSymbol.GetSymbolKey())) Then
Return True
End If
End If
Return False
End If
End Function
Public Overrides Function VisitToken(oldToken As SyntaxToken) As SyntaxToken
If oldToken = Nothing Then
Return oldToken
End If
Dim newToken = oldToken
Dim shouldCheckTrivia = Me._stringAndCommentTextSpans.Contains(oldToken.Span)
If shouldCheckTrivia Then
Me._isProcessingStructuredTrivia += 1
newToken = MyBase.VisitToken(newToken)
Me._isProcessingStructuredTrivia -= 1
Else
newToken = MyBase.VisitToken(newToken)
End If
newToken = UpdateAliasAnnotation(newToken)
' Rename matches in strings and comments
newToken = RenameWithinToken(oldToken, newToken)
' We don't want to annotate XmlName with RenameActionAnnotation
If newToken.Kind = SyntaxKind.XmlNameToken Then
Return newToken
End If
Dim isRenameLocation = IsInRenameLocation(oldToken)
Dim isOldText = CaseInsensitiveComparison.Equals(oldToken.ValueText, _originalText)
Dim tokenNeedsConflictCheck = isRenameLocation OrElse
isOldText OrElse
CaseInsensitiveComparison.Equals(oldToken.ValueText, _replacementText) OrElse
IsPossibleNameConflict(_possibleNameConflicts, oldToken.ValueText)
If tokenNeedsConflictCheck Then
newToken = RenameAndAnnotateAsync(oldToken, newToken, isRenameLocation, isOldText).WaitAndGetResult_CanCallOnBackground(_cancellationToken)
If Not Me._isProcessingComplexifiedSpans Then
_invocationExpressionsNeedingConflictChecks.AddRange(oldToken.GetAncestors(Of InvocationExpressionSyntax)())
End If
End If
Return newToken
End Function
Private Function GetAnnotationForInvocationExpression(invocationExpression As InvocationExpressionSyntax) As RenameActionAnnotation
Dim identifierToken As SyntaxToken = Nothing
Dim expressionOfInvocation = invocationExpression.Expression
While expressionOfInvocation IsNot Nothing
Select Case expressionOfInvocation.Kind
Case SyntaxKind.IdentifierName, SyntaxKind.GenericName
identifierToken = DirectCast(expressionOfInvocation, SimpleNameSyntax).Identifier
Exit While
Case SyntaxKind.SimpleMemberAccessExpression
identifierToken = DirectCast(expressionOfInvocation, MemberAccessExpressionSyntax).Name.Identifier
Exit While
Case SyntaxKind.QualifiedName
identifierToken = DirectCast(expressionOfInvocation, QualifiedNameSyntax).Right.Identifier
Exit While
Case SyntaxKind.ParenthesizedExpression
expressionOfInvocation = DirectCast(expressionOfInvocation, ParenthesizedExpressionSyntax).Expression
Case SyntaxKind.MeExpression
Exit While
Case Else
' This isn't actually an invocation, so there's no member name to check.
Return Nothing
End Select
End While
If identifierToken <> Nothing AndAlso Not Me._annotatedIdentifierTokens.Contains(identifierToken) Then
Dim symbolInfo = Me._semanticModel.GetSymbolInfo(invocationExpression, Me._cancellationToken)
Dim symbols As IEnumerable(Of ISymbol) = Nothing
If symbolInfo.Symbol Is Nothing Then
Return Nothing
Else
symbols = SpecializedCollections.SingletonEnumerable(symbolInfo.Symbol)
End If
Dim renameDeclarationLocations As RenameDeclarationLocationReference() =
ConflictResolver.CreateDeclarationLocationAnnotationsAsync(_solution, symbols, _cancellationToken).WaitAndGetResult_CanCallOnBackground(_cancellationToken)
Dim renameAnnotation = New RenameActionAnnotation(
identifierToken.Span,
isRenameLocation:=False,
prefix:=Nothing,
suffix:=Nothing,
renameDeclarationLocations:=renameDeclarationLocations,
isOriginalTextLocation:=False,
isNamespaceDeclarationReference:=False,
isInvocationExpression:=True,
isMemberGroupReference:=False)
Return renameAnnotation
End If
Return Nothing
End Function
Public Overrides Function VisitInvocationExpression(node As InvocationExpressionSyntax) As SyntaxNode
Dim result = MyBase.VisitInvocationExpression(node)
If _invocationExpressionsNeedingConflictChecks.Contains(node) Then
Dim renameAnnotation = GetAnnotationForInvocationExpression(node)
If renameAnnotation IsNot Nothing Then
result = Me._renameAnnotations.WithAdditionalAnnotations(result, renameAnnotation)
End If
End If
Return result
End Function
Private Function RenameToken(oldToken As SyntaxToken, newToken As SyntaxToken, prefix As String, suffix As String) As SyntaxToken
Dim parent = oldToken.Parent
Dim currentNewIdentifier = Me._replacementText
Dim oldIdentifier = newToken.ValueText
Dim isAttributeName = SyntaxFacts.IsAttributeName(parent)
If isAttributeName Then
Debug.Assert(Me._renamedSymbol.IsAttribute() OrElse Me._aliasSymbol.Target.IsAttribute())
If oldIdentifier <> Me._renamedSymbol.Name Then
Dim withoutSuffix = String.Empty
If currentNewIdentifier.TryReduceAttributeSuffix(withoutSuffix) Then
currentNewIdentifier = withoutSuffix
End If
End If
Else
If Not String.IsNullOrEmpty(prefix) Then
currentNewIdentifier = prefix + currentNewIdentifier
End If
If Not String.IsNullOrEmpty(suffix) Then
currentNewIdentifier = currentNewIdentifier + suffix
End If
End If
' determine the canonical identifier name (unescaped, no type char, ...)
Dim valueText = currentNewIdentifier
Dim name = SyntaxFactory.ParseName(currentNewIdentifier)
If name.ContainsDiagnostics Then
name = SyntaxFactory.IdentifierName(currentNewIdentifier)
End If
If name.IsKind(SyntaxKind.GlobalName) Then
valueText = currentNewIdentifier
ElseIf name.IsKind(SyntaxKind.IdentifierName) Then
valueText = DirectCast(name, IdentifierNameSyntax).Identifier.ValueText
End If
If Me._isVerbatim Then
newToken = newToken.CopyAnnotationsTo(SyntaxFactory.BracketedIdentifier(newToken.LeadingTrivia, valueText, newToken.TrailingTrivia))
Else
newToken = newToken.CopyAnnotationsTo(SyntaxFactory.Identifier(
newToken.LeadingTrivia,
If(oldToken.GetTypeCharacter() = TypeCharacter.None, currentNewIdentifier, currentNewIdentifier + oldToken.ToString().Last()),
False,
valueText,
oldToken.GetTypeCharacter(),
newToken.TrailingTrivia))
If Me._replacementTextValid AndAlso
oldToken.GetTypeCharacter() <> TypeCharacter.None AndAlso
(SyntaxFacts.GetKeywordKind(valueText) = SyntaxKind.REMKeyword OrElse Me._syntaxFactsService.IsVerbatimIdentifier(newToken)) Then
newToken = Me._renameAnnotations.WithAdditionalAnnotations(newToken, RenameInvalidIdentifierAnnotation.Instance)
End If
End If
If Me._replacementTextValid Then
If newToken.IsBracketed Then
' a reference location should always be tried to be unescaped, whether it was escaped before rename
' or the replacement itself is escaped.
newToken = newToken.WithAdditionalAnnotations(Simplifier.Annotation)
Else
Dim semanticModel = GetSemanticModelForNode(parent, If(Me._speculativeModel, Me._semanticModel))
newToken = Simplification.VisualBasicSimplificationService.TryEscapeIdentifierToken(newToken, semanticModel, oldToken)
End If
End If
Return newToken
End Function
Private Function RenameInStringLiteral(oldToken As SyntaxToken, newToken As SyntaxToken, createNewStringLiteral As Func(Of SyntaxTriviaList, String, String, SyntaxTriviaList, SyntaxToken)) As SyntaxToken
Dim originalString = newToken.ToString()
Dim replacedString As String = RenameLocations.ReferenceProcessing.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText)
If replacedString <> originalString Then
Dim oldSpan = oldToken.Span
newToken = createNewStringLiteral(newToken.LeadingTrivia, replacedString, replacedString, newToken.TrailingTrivia)
AddModifiedSpan(oldSpan, newToken.Span)
Return newToken.CopyAnnotationsTo(Me._renameAnnotations.WithAdditionalAnnotations(newToken, New RenameTokenSimplificationAnnotation() With {.OriginalTextSpan = oldSpan}))
End If
Return newToken
End Function
Private Function RenameInCommentTrivia(trivia As SyntaxTrivia) As SyntaxTrivia
Dim originalString = trivia.ToString()
Dim replacedString As String = RenameLocations.ReferenceProcessing.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText)
If replacedString <> originalString Then
Dim oldSpan = trivia.Span
Dim newTrivia = SyntaxFactory.CommentTrivia(replacedString)
AddModifiedSpan(oldSpan, newTrivia.Span)
Return trivia.CopyAnnotationsTo(Me._renameAnnotations.WithAdditionalAnnotations(newTrivia, New RenameTokenSimplificationAnnotation() With {.OriginalTextSpan = oldSpan}))
End If
Return trivia
End Function
Private Function RenameInTrivia(token As SyntaxToken, leadingOrTrailingTriviaList As IEnumerable(Of SyntaxTrivia)) As SyntaxToken
Return token.ReplaceTrivia(leadingOrTrailingTriviaList, Function(oldTrivia, newTrivia)
If newTrivia.Kind = SyntaxKind.CommentTrivia Then
Return RenameInCommentTrivia(newTrivia)
End If
Return newTrivia
End Function)
End Function
Private Function RenameWithinToken(oldToken As SyntaxToken, newToken As SyntaxToken) As SyntaxToken
If Me._isProcessingComplexifiedSpans OrElse
(Me._isProcessingStructuredTrivia = 0 AndAlso Not Me._stringAndCommentTextSpans.Contains(oldToken.Span)) Then
Return newToken
End If
If Me._isRenamingInStrings Then
If newToken.Kind = SyntaxKind.StringLiteralToken Then
newToken = RenameInStringLiteral(oldToken, newToken, AddressOf SyntaxFactory.StringLiteralToken)
ElseIf newToken.Kind = SyntaxKind.InterpolatedStringTextToken Then
newToken = RenameInStringLiteral(oldToken, newToken, AddressOf SyntaxFactory.InterpolatedStringTextToken)
End If
End If
If Me._isRenamingInComments Then
If newToken.Kind = SyntaxKind.XmlTextLiteralToken Then
newToken = RenameInStringLiteral(oldToken, newToken, AddressOf SyntaxFactory.XmlTextLiteralToken)
ElseIf newToken.Kind = SyntaxKind.XmlNameToken AndAlso CaseInsensitiveComparison.Equals(oldToken.ValueText, _originalText) Then
Dim newIdentifierToken = SyntaxFactory.XmlNameToken(newToken.LeadingTrivia, _replacementText, SyntaxFacts.GetKeywordKind(_replacementText), newToken.TrailingTrivia)
newToken = newToken.CopyAnnotationsTo(Me._renameAnnotations.WithAdditionalAnnotations(newIdentifierToken, New RenameTokenSimplificationAnnotation() With {.OriginalTextSpan = oldToken.Span}))
AddModifiedSpan(oldToken.Span, newToken.Span)
End If
If newToken.HasLeadingTrivia Then
Dim updatedToken = RenameInTrivia(oldToken, oldToken.LeadingTrivia)
If updatedToken <> oldToken Then
newToken = newToken.WithLeadingTrivia(updatedToken.LeadingTrivia)
End If
End If
If newToken.HasTrailingTrivia Then
Dim updatedToken = RenameInTrivia(oldToken, oldToken.TrailingTrivia)
If updatedToken <> oldToken Then
newToken = newToken.WithTrailingTrivia(updatedToken.TrailingTrivia)
End If
End If
End If
Return newToken
End Function
End Class
#End Region
#Region "Declaration Conflicts"
Public Function LocalVariableConflict(
token As SyntaxToken,
newReferencedSymbols As IEnumerable(Of ISymbol)
) As Boolean Implements IRenameRewriterLanguageService.LocalVariableConflict
' This scenario is not present in VB and only in C#
Return False
End Function
Public Function ComputeDeclarationConflictsAsync(
replacementText As String,
renamedSymbol As ISymbol,
renameSymbol As ISymbol,
referencedSymbols As IEnumerable(Of ISymbol),
baseSolution As Solution,
newSolution As Solution,
reverseMappedLocations As IDictionary(Of Location, Location),
cancellationToken As CancellationToken
) As Task(Of IEnumerable(Of Location)) Implements IRenameRewriterLanguageService.ComputeDeclarationConflictsAsync
Dim conflicts As New List(Of Location)
If renamedSymbol.Kind = SymbolKind.Parameter OrElse
renamedSymbol.Kind = SymbolKind.Local OrElse
renamedSymbol.Kind = SymbolKind.RangeVariable Then
Dim token = renamedSymbol.Locations.Single().FindToken(cancellationToken)
' Find the method block or field declaration that we're in. Note the LastOrDefault
' so we find the uppermost one, since VariableDeclarators live in methods too.
Dim methodBase = token.Parent.AncestorsAndSelf.Where(Function(s) TypeOf s Is MethodBlockBaseSyntax OrElse TypeOf s Is VariableDeclaratorSyntax) _
.LastOrDefault()
Dim visitor As New LocalConflictVisitor(token, newSolution, cancellationToken)
visitor.Visit(methodBase)
conflicts.AddRange(visitor.ConflictingTokens.Select(Function(t) t.GetLocation()) _
.Select(Function(loc) reverseMappedLocations(loc)))
' in VB parameters of properties are not allowed to be the same as the containing property
If renamedSymbol.Kind = SymbolKind.Parameter AndAlso
renamedSymbol.ContainingSymbol.Kind = SymbolKind.Property AndAlso
CaseInsensitiveComparison.Equals(renamedSymbol.ContainingSymbol.Name, renamedSymbol.Name) Then
Dim propertySymbol = renamedSymbol.ContainingSymbol
While propertySymbol IsNot Nothing
conflicts.AddRange(renamedSymbol.ContainingSymbol.Locations _
.Select(Function(loc) reverseMappedLocations(loc)))
propertySymbol = propertySymbol.OverriddenMember
End While
End If
ElseIf renamedSymbol.Kind = SymbolKind.Label Then
Dim token = renamedSymbol.Locations.Single().FindToken(cancellationToken)
Dim containingMethod = token.Parent.FirstAncestorOrSelf(Of SyntaxNode)(
Function(s) TypeOf s Is MethodBlockBaseSyntax OrElse
TypeOf s Is LambdaExpressionSyntax)
Dim visitor As New LabelConflictVisitor(token)
visitor.Visit(containingMethod)
conflicts.AddRange(visitor.ConflictingTokens.Select(Function(t) t.GetLocation()) _
.Select(Function(loc) reverseMappedLocations(loc)))
ElseIf renamedSymbol.Kind = SymbolKind.Method Then
conflicts.AddRange(
DeclarationConflictHelpers.GetMembersWithConflictingSignatures(DirectCast(renamedSymbol, IMethodSymbol), trimOptionalParameters:=True) _
.Select(Function(loc) reverseMappedLocations(loc)))
ElseIf renamedSymbol.Kind = SymbolKind.Property Then
ConflictResolver.AddConflictingParametersOfProperties(referencedSymbols.Concat(renameSymbol).Where(Function(sym) sym.Kind = SymbolKind.Property),
renamedSymbol.Name,
conflicts)
ElseIf renamedSymbol.Kind = SymbolKind.TypeParameter Then
For Each location In renamedSymbol.Locations
Dim token = location.FindToken(cancellationToken)
Dim currentTypeParameter = token.Parent
For Each typeParameter In DirectCast(currentTypeParameter.Parent, TypeParameterListSyntax).Parameters
If typeParameter IsNot currentTypeParameter AndAlso CaseInsensitiveComparison.Equals(token.ValueText, typeParameter.Identifier.ValueText) Then
conflicts.Add(reverseMappedLocations(typeParameter.Identifier.GetLocation()))
End If
Next
Next
End If
' if the renamed symbol is a type member, it's name should not conflict with a type parameter
If renamedSymbol.ContainingType IsNot Nothing AndAlso renamedSymbol.ContainingType.GetMembers(renamedSymbol.Name).Contains(renamedSymbol) Then
Dim conflictingLocations = renamedSymbol.ContainingType.TypeParameters _
.Where(Function(t) CaseInsensitiveComparison.Equals(t.Name, renamedSymbol.Name)) _
.SelectMany(Function(t) t.Locations)
For Each location In conflictingLocations
Dim typeParameterToken = location.FindToken(cancellationToken)
conflicts.Add(reverseMappedLocations(typeParameterToken.GetLocation()))
Next
End If
Return Task.FromResult(Of IEnumerable(Of Location))(conflicts)
End Function
Public Async Function ComputeImplicitReferenceConflictsAsync(renameSymbol As ISymbol, renamedSymbol As ISymbol, implicitReferenceLocations As IEnumerable(Of ReferenceLocation), cancellationToken As CancellationToken) As Task(Of IEnumerable(Of Location)) Implements IRenameRewriterLanguageService.ComputeImplicitReferenceConflictsAsync
' Handle renaming of symbols used for foreach
Dim implicitReferencesMightConflict = renameSymbol.Kind = SymbolKind.Property AndAlso
CaseInsensitiveComparison.Equals(renameSymbol.Name, "Current")
implicitReferencesMightConflict = implicitReferencesMightConflict OrElse
(renameSymbol.Kind = SymbolKind.Method AndAlso
(CaseInsensitiveComparison.Equals(renameSymbol.Name, "MoveNext") OrElse
CaseInsensitiveComparison.Equals(renameSymbol.Name, "GetEnumerator")))
' TODO: handle Dispose for using statement and Add methods for collection initializers.
If implicitReferencesMightConflict Then
If Not CaseInsensitiveComparison.Equals(renamedSymbol.Name, renameSymbol.Name) Then
For Each implicitReferenceLocation In implicitReferenceLocations
Dim token = Await implicitReferenceLocation.Location.SourceTree.GetTouchingTokenAsync(
implicitReferenceLocation.Location.SourceSpan.Start, cancellationToken, findInsideTrivia:=False).ConfigureAwait(False)
If token.Kind = SyntaxKind.ForKeyword AndAlso token.Parent.IsKind(SyntaxKind.ForEachStatement) Then
Return SpecializedCollections.SingletonEnumerable(DirectCast(token.Parent, ForEachStatementSyntax).Expression.GetLocation())
End If
Next
End If
End If
Return SpecializedCollections.EmptyEnumerable(Of Location)()
End Function
#End Region
''' <summary>
''' Gets the top most enclosing statement as target to call MakeExplicit on.
''' It's either the enclosing statement, or if this statement is inside of a lambda expression, the enclosing
''' statement of this lambda.
''' </summary>
''' <param name="token">The token to get the complexification target for.</param>
Public Function GetExpansionTargetForLocation(token As SyntaxToken) As SyntaxNode Implements IRenameRewriterLanguageService.GetExpansionTargetForLocation
Return GetExpansionTarget(token)
End Function
Private Shared Function GetExpansionTarget(token As SyntaxToken) As SyntaxNode
' get the directly enclosing statement
Dim enclosingStatement = token.FirstAncestorOrSelf(Function(n) TypeOf (n) Is ExecutableStatementSyntax)
' for nodes in a using, for or for each statement, we do not need the enclosing _executable_ statement, which is the whole block.
' it's enough to expand the using, for or foreach statement.
Dim possibleSpecialStatement = token.FirstAncestorOrSelf(Function(n) n.Kind = SyntaxKind.ForStatement OrElse
n.Kind = SyntaxKind.ForEachStatement OrElse
n.Kind = SyntaxKind.UsingStatement OrElse
n.Kind = SyntaxKind.CatchBlock)
If possibleSpecialStatement IsNot Nothing Then
If enclosingStatement Is possibleSpecialStatement.Parent Then
enclosingStatement = If(possibleSpecialStatement.Kind = SyntaxKind.CatchBlock,
DirectCast(possibleSpecialStatement, CatchBlockSyntax).CatchStatement,
possibleSpecialStatement)
End If
End If
' see if there's an enclosing lambda expression
Dim possibleLambdaExpression As SyntaxNode = Nothing
If enclosingStatement Is Nothing Then
possibleLambdaExpression = token.FirstAncestorOrSelf(Function(n) TypeOf (n) Is LambdaExpressionSyntax)
End If
Dim enclosingCref = token.FirstAncestorOrSelf(Function(n) TypeOf (n) Is CrefReferenceSyntax)
If enclosingCref IsNot Nothing Then
Return enclosingCref
End If
' there seems to be no statement above this one. Let's see if we can at least get an SimpleNameSyntax
Return If(enclosingStatement, If(possibleLambdaExpression, token.FirstAncestorOrSelf(Function(n) TypeOf (n) Is SimpleNameSyntax)))
End Function
#Region "Helper Methods"
Public Function IsIdentifierValid(replacementText As String, syntaxFactsService As ISyntaxFactsService) As Boolean Implements IRenameRewriterLanguageService.IsIdentifierValid
replacementText = SyntaxFacts.MakeHalfWidthIdentifier(replacementText)
Dim possibleIdentifier As String
If syntaxFactsService.IsTypeCharacter(replacementText.Last()) Then
' We don't allow to use identifiers with type characters
Return False
Else
If replacementText.StartsWith("[", StringComparison.Ordinal) AndAlso replacementText.EndsWith("]", StringComparison.Ordinal) Then
possibleIdentifier = replacementText
Else
possibleIdentifier = "[" & replacementText & "]"
End If
End If
' Make sure we got an identifier.
If Not syntaxFactsService.IsValidIdentifier(possibleIdentifier) Then
' We still don't have an identifier, so let's fail
Return False
End If
' This is a valid Identifier
Return True
End Function
Public Function ComputePossibleImplicitUsageConflicts(
renamedSymbol As ISymbol,
semanticModel As SemanticModel,
originalDeclarationLocation As Location,
newDeclarationLocationStartingPosition As Integer,
cancellationToken As CancellationToken) As IEnumerable(Of Location) Implements IRenameRewriterLanguageService.ComputePossibleImplicitUsageConflicts
' TODO: support other implicitly used methods like dispose
If CaseInsensitiveComparison.Equals(renamedSymbol.Name, "MoveNext") OrElse
CaseInsensitiveComparison.Equals(renamedSymbol.Name, "GetEnumerator") OrElse
CaseInsensitiveComparison.Equals(renamedSymbol.Name, "Current") Then
If TypeOf renamedSymbol Is IMethodSymbol Then
If DirectCast(renamedSymbol, IMethodSymbol).IsOverloads AndAlso
(renamedSymbol.GetAllTypeArguments().Length <> 0 OrElse
DirectCast(renamedSymbol, IMethodSymbol).Parameters.Length <> 0) Then
Return SpecializedCollections.EmptyEnumerable(Of Location)()
End If
End If
If TypeOf renamedSymbol Is IPropertySymbol Then
If DirectCast(renamedSymbol, IPropertySymbol).IsOverloads Then
Return SpecializedCollections.EmptyEnumerable(Of Location)()
End If
End If
' TODO: Partial methods currently only show the location where the rename happens As a conflict.
' Consider showing both locations as a conflict.
Dim baseType = renamedSymbol.ContainingType?.GetBaseTypes().FirstOrDefault()
If baseType IsNot Nothing Then
Dim implicitSymbols = semanticModel.LookupSymbols(
newDeclarationLocationStartingPosition,
baseType,
renamedSymbol.Name) _
.Where(Function(sym) Not sym.Equals(renamedSymbol))
For Each symbol In implicitSymbols
If symbol.GetAllTypeArguments().Length <> 0 Then
Continue For
End If
If symbol.Kind = SymbolKind.Method Then
Dim method = DirectCast(symbol, IMethodSymbol)
If CaseInsensitiveComparison.Equals(symbol.Name, "MoveNext") Then
If Not method.ReturnsVoid AndAlso Not method.Parameters.Any() AndAlso method.ReturnType.SpecialType = SpecialType.System_Boolean Then
Return SpecializedCollections.SingletonEnumerable(originalDeclarationLocation)
End If
ElseIf CaseInsensitiveComparison.Equals(symbol.Name, "GetEnumerator") Then
' we are a bit pessimistic here.
' To be sure we would need to check if the returned type Is having a MoveNext And Current as required by foreach
If Not method.ReturnsVoid AndAlso
Not method.Parameters.Any() Then
Return SpecializedCollections.SingletonEnumerable(originalDeclarationLocation)
End If
End If
ElseIf CaseInsensitiveComparison.Equals(symbol.Name, "Current") Then
Dim [property] = DirectCast(symbol, IPropertySymbol)
If Not [property].Parameters.Any() AndAlso Not [property].IsWriteOnly Then
Return SpecializedCollections.SingletonEnumerable(originalDeclarationLocation)
End If
End If
Next
End If
End If
Return SpecializedCollections.EmptyEnumerable(Of Location)()
End Function
Public Sub TryAddPossibleNameConflicts(symbol As ISymbol, replacementText As String, possibleNameConflicts As ICollection(Of String)) Implements IRenameRewriterLanguageService.TryAddPossibleNameConflicts
Dim halfWidthReplacementText = SyntaxFacts.MakeHalfWidthIdentifier(replacementText)
Const AttributeSuffix As String = "Attribute"
Const AttributeSuffixLength As Integer = 9
Debug.Assert(AttributeSuffixLength = AttributeSuffix.Length, "Assert (AttributeSuffixLength = AttributeSuffix.Length) failed.")
If replacementText.Length > AttributeSuffixLength AndAlso CaseInsensitiveComparison.Equals(halfWidthReplacementText.Substring(halfWidthReplacementText.Length - AttributeSuffixLength), AttributeSuffix) Then
Dim conflict = replacementText.Substring(0, replacementText.Length - AttributeSuffixLength)
If Not possibleNameConflicts.Contains(conflict) Then
possibleNameConflicts.Add(conflict)
End If
End If
If symbol.Kind = SymbolKind.Property Then
For Each conflict In {"_" + replacementText, "get_" + replacementText, "set_" + replacementText}
If Not possibleNameConflicts.Contains(conflict) Then
possibleNameConflicts.Add(conflict)
End If
Next
End If
' consider both versions of the identifier (escaped and unescaped)
Dim valueText = replacementText
Dim kind = SyntaxFacts.GetKeywordKind(replacementText)
If kind <> SyntaxKind.None Then
valueText = SyntaxFacts.GetText(kind)
Else
Dim name = SyntaxFactory.ParseName(replacementText)
If name.Kind = SyntaxKind.IdentifierName Then
valueText = DirectCast(name, IdentifierNameSyntax).Identifier.ValueText
End If
End If
If Not CaseInsensitiveComparison.Equals(valueText, replacementText) Then
possibleNameConflicts.Add(valueText)
End If
End Sub
''' <summary>
''' Gets the semantic model for the given node.
''' If the node belongs to the syntax tree of the original semantic model, then returns originalSemanticModel.
''' Otherwise, returns a speculative model.
''' The assumption for the later case is that span start position of the given node in it's syntax tree is same as
''' the span start of the original node in the original syntax tree.
''' </summary>
''' <param name="node"></param>
''' <param name="originalSemanticModel"></param>
Public Shared Function GetSemanticModelForNode(node As SyntaxNode, originalSemanticModel As SemanticModel) As SemanticModel
If node.SyntaxTree Is originalSemanticModel.SyntaxTree Then
' This is possible if the previous rename phase didn't rewrite any nodes in this tree.
Return originalSemanticModel
End If
Dim syntax = node
Dim nodeToSpeculate = syntax.GetAncestorsOrThis(Of SyntaxNode).Where(Function(n) SpeculationAnalyzer.CanSpeculateOnNode(n)).LastOrDefault
If nodeToSpeculate Is Nothing Then
If syntax.IsKind(SyntaxKind.CrefReference) Then
nodeToSpeculate = DirectCast(syntax, CrefReferenceSyntax).Name
ElseIf syntax.IsKind(SyntaxKind.TypeConstraint) Then
nodeToSpeculate = DirectCast(syntax, TypeConstraintSyntax).Type
Else
Return Nothing
End If
End If
Dim isInNamespaceOrTypeContext = SyntaxFacts.IsInNamespaceOrTypeContext(TryCast(syntax, ExpressionSyntax))
Dim position = nodeToSpeculate.SpanStart
Return SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(nodeToSpeculate, DirectCast(originalSemanticModel, SemanticModel), position, isInNamespaceOrTypeContext)
End Function
#End Region
End Class
End Namespace
|
jhendrixMSFT/roslyn
|
src/Workspaces/VisualBasic/Portable/Rename/VisualBasicRenameRewriterLanguageService.vb
|
Visual Basic
|
apache-2.0
| 56,797
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.IntroduceVariable
Friend Partial Class VisualBasicIntroduceVariableService
Protected Overrides Function IntroduceQueryLocalAsync(document As SemanticDocument,
expression As ExpressionSyntax,
allOccurrences As Boolean,
cancellationToken As CancellationToken) As Task(Of Document)
Dim newLocalNameToken = CType(GenerateUniqueLocalName(document, expression, isConstant:=False, cancellationToken:=cancellationToken), SyntaxToken)
Dim newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken)
Dim letClause = SyntaxFactory.LetClause(
SyntaxFactory.ExpressionRangeVariable(
SyntaxFactory.VariableNameEquals(
SyntaxFactory.ModifiedIdentifier(newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()))),
expression)).WithAdditionalAnnotations(Formatter.Annotation)
Dim oldOutermostQuery = expression.GetAncestorsOrThis(Of QueryExpressionSyntax)().LastOrDefault()
Dim matches = FindMatches(document, expression, document, oldOutermostQuery, allOccurrences, cancellationToken)
Dim innermostClauses = New HashSet(Of QueryClauseSyntax)(
matches.Select(Function(expr) expr.GetAncestor(Of QueryClauseSyntax)()))
If innermostClauses.Count = 1 Then
' If there was only one match, or all the matches came from the same
' statement, then we want to place the declaration right above that
' statement. Note: we special case this because the statement we are going
' to go above might not be in a block and we may have to generate it
Return Task.FromResult(IntroduceQueryLocalForSingleOccurrence(
document, expression, newLocalName, letClause, allOccurrences, cancellationToken))
End If
Dim oldInnerMostCommonQuery = matches.FindInnermostCommonNode(Of QueryExpressionSyntax)()
Dim newInnerMostQuery = Rewrite(document, expression, newLocalName, document, oldInnerMostCommonQuery, allOccurrences, cancellationToken)
Dim allAffectedClauses = New HashSet(Of QueryClauseSyntax)(
matches.SelectMany(Function(expr) expr.GetAncestorsOrThis(Of QueryClauseSyntax)()))
Dim oldClauses = oldInnerMostCommonQuery.Clauses
Dim newClauses = newInnerMostQuery.Clauses
Dim firstClauseAffectedInQuery = oldClauses.First(AddressOf allAffectedClauses.Contains)
Dim firstClauseAffectedIndex = oldClauses.IndexOf(firstClauseAffectedInQuery)
Dim finalClauses = newClauses.Take(firstClauseAffectedIndex).
Concat(letClause).
Concat(newClauses.Skip(firstClauseAffectedIndex)).ToList()
Dim finalQuery = newInnerMostQuery.WithClauses(SyntaxFactory.List(finalClauses))
Dim newRoot = document.Root.ReplaceNode(oldInnerMostCommonQuery, finalQuery)
Return Task.FromResult(document.Document.WithSyntaxRoot(newRoot))
End Function
Private Function IntroduceQueryLocalForSingleOccurrence(
document As SemanticDocument,
expression As ExpressionSyntax,
newLocalName As NameSyntax,
letClause As LetClauseSyntax,
allOccurrences As Boolean,
cancellationToken As CancellationToken) As Document
Dim oldClause = expression.GetAncestor(Of QueryClauseSyntax)()
Dim newClause = Rewrite(document, expression, newLocalName, document, oldClause, allOccurrences, cancellationToken)
Dim oldQuery = DirectCast(oldClause.Parent, QueryExpressionSyntax)
Dim newQuery = GetNewQuery(oldQuery, oldClause, newClause, letClause)
Dim newRoot = document.Root.ReplaceNode(oldQuery, newQuery)
Return document.Document.WithSyntaxRoot(newRoot)
End Function
Private Function GetNewQuery(
oldQuery As QueryExpressionSyntax,
oldClause As QueryClauseSyntax,
newClause As QueryClauseSyntax,
letClause As LetClauseSyntax) As QueryExpressionSyntax
Dim oldClauses = oldQuery.Clauses
Dim oldClauseIndex = oldClauses.IndexOf(oldClause)
Dim newClauses = oldClauses.Take(oldClauseIndex).
Concat(letClause).
Concat(newClause).
Concat(oldClauses.Skip(oldClauseIndex + 1)).ToList()
Return oldQuery.WithClauses(SyntaxFactory.List(newClauses))
End Function
End Class
End Namespace
|
BugraC/roslyn
|
src/Features/VisualBasic/IntroduceVariable/VisualBasicIntroduceVariableService_IntroduceQueryLocal.vb
|
Visual Basic
|
apache-2.0
| 5,338
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Namespace Microsoft.CodeAnalysis.VisualBasic.DocumentationCommentFormatting
Friend Class DocumentationCommentUtilities
Private Shared ReadOnly s_newLineStrings As String() = {vbCrLf, vbCr, vbLf}
Public Shared Function ExtractXMLFragment(docComment As String) As String
Dim splitLines = docComment.Split(s_newLineStrings, StringSplitOptions.None)
For i = 0 To splitLines.Length - 1
If splitLines(i).StartsWith("'''", StringComparison.Ordinal) Then
splitLines(i) = splitLines(i).Substring(3)
End If
Next
Return splitLines.Join(vbCrLf)
End Function
End Class
End Namespace
|
KevinRansom/roslyn
|
src/Features/VisualBasic/Portable/DocumentationCommentFormatting/DocumentationCommentUtilities.vb
|
Visual Basic
|
apache-2.0
| 866
|
'------------------------------------------------------------------------------
' <generado automáticamente>
' Este código fue generado por una herramienta.
'
' Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
' se vuelve a generar el código.
' </generado automáticamente>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Partial Public Class FrmRequerimientoEditarAprobar
'''<summary>
'''Control RadCodeBlock1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents RadCodeBlock1 As Global.Telerik.Web.UI.RadCodeBlock
'''<summary>
'''Control lbHistorico.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lbHistorico As Global.System.Web.UI.WebControls.LinkButton
'''<summary>
'''Control lbAdjunto.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lbAdjunto As Global.System.Web.UI.WebControls.LinkButton
'''<summary>
'''Control lbAprobarRequerimiento.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lbAprobarRequerimiento As Global.System.Web.UI.WebControls.LinkButton
'''<summary>
'''Control lbRechazarRequerimiento.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lbRechazarRequerimiento As Global.System.Web.UI.WebControls.LinkButton
'''<summary>
'''Control lbRechazarRequerimiento_ModalPopupExtender.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lbRechazarRequerimiento_ModalPopupExtender As Global.AjaxControlToolkit.ModalPopupExtender
'''<summary>
'''Control lbAnularReq.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lbAnularReq As Global.System.Web.UI.WebControls.LinkButton
'''<summary>
'''Control lbAnularReqModalPopupExtender.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lbAnularReqModalPopupExtender As Global.AjaxControlToolkit.ModalPopupExtender
'''<summary>
'''Control PanelEncabezado.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents PanelEncabezado As Global.System.Web.UI.WebControls.Panel
'''<summary>
'''Control lblRequeridoPor.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lblRequeridoPor As Global.System.Web.UI.WebControls.Label
'''<summary>
'''Control lblNroRequerimiento.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lblNroRequerimiento As Global.System.Web.UI.WebControls.Label
'''<summary>
'''Control lblTipoRequerimiento.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lblTipoRequerimiento As Global.System.Web.UI.WebControls.Label
'''<summary>
'''Control lblEstadoRequerimiento.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lblEstadoRequerimiento As Global.System.Web.UI.WebControls.Label
'''<summary>
'''Control lblFechaRequerimiento.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lblFechaRequerimiento As Global.System.Web.UI.WebControls.Label
'''<summary>
'''Control lblPeridoInicio.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lblPeridoInicio As Global.System.Web.UI.WebControls.Label
'''<summary>
'''Control lblOrigen.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lblOrigen As Global.System.Web.UI.WebControls.Label
'''<summary>
'''Control lblDestino.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lblDestino As Global.System.Web.UI.WebControls.Label
'''<summary>
'''Control lblMoneda.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lblMoneda As Global.System.Web.UI.WebControls.Label
'''<summary>
'''Control lblAreaProyecto.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lblAreaProyecto As Global.System.Web.UI.WebControls.Label
'''<summary>
'''Control lblSustento.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lblSustento As Global.System.Web.UI.WebControls.Label
'''<summary>
'''Control txtTipoCatalogoRequerimiento.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents txtTipoCatalogoRequerimiento As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''Control txtObservacion.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents txtObservacion As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''Control txtCentroCostoHabilitado.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents txtCentroCostoHabilitado As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''Control GridView1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents GridView1 As Global.System.Web.UI.WebControls.GridView
'''<summary>
'''Control txtIdProyecto.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents txtIdProyecto As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''Control gvDetalleRequerimiento.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents gvDetalleRequerimiento As Global.System.Web.UI.WebControls.GridView
'''<summary>
'''Control panelRechazar.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents panelRechazar As Global.System.Web.UI.WebControls.Panel
'''<summary>
'''Control UpdatePanel1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents UpdatePanel1 As Global.System.Web.UI.UpdatePanel
'''<summary>
'''Control lbCerrar.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lbCerrar As Global.System.Web.UI.WebControls.LinkButton
'''<summary>
'''Control RequiredFieldValidator1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents RequiredFieldValidator1 As Global.System.Web.UI.WebControls.RequiredFieldValidator
'''<summary>
'''Control txtMotivo.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents txtMotivo As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''Control lbAceptarRechazo.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lbAceptarRechazo As Global.System.Web.UI.WebControls.LinkButton
'''<summary>
'''Control panelAnular.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents panelAnular As Global.System.Web.UI.WebControls.Panel
'''<summary>
'''Control UpdatePanel2.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents UpdatePanel2 As Global.System.Web.UI.UpdatePanel
'''<summary>
'''Control lbCerrar2.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lbCerrar2 As Global.System.Web.UI.WebControls.LinkButton
'''<summary>
'''Control RequiredFieldValidator2.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents RequiredFieldValidator2 As Global.System.Web.UI.WebControls.RequiredFieldValidator
'''<summary>
'''Control txtMotivoAnula.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents txtMotivoAnula As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''Control lbAnularRequerimientoR.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lbAnularRequerimientoR As Global.System.Web.UI.WebControls.LinkButton
'''<summary>
'''Control odsCentroCostoDetalle.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents odsCentroCostoDetalle As Global.System.Web.UI.WebControls.ObjectDataSource
'''<summary>
'''Control odsDetalleRequerimiento.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents odsDetalleRequerimiento As Global.System.Web.UI.WebControls.ObjectDataSource
'''<summary>
'''Control odsListaEstadoRequerimiento.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents odsListaEstadoRequerimiento As Global.System.Web.UI.WebControls.ObjectDataSource
'''<summary>
'''Control RadWindowManager1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents RadWindowManager1 As Global.Telerik.Web.UI.RadWindowManager
'''<summary>
'''Control CentroCosto.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents CentroCosto As Global.Telerik.Web.UI.RadWindow
'''<summary>
'''Control Historico.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents Historico As Global.Telerik.Web.UI.RadWindow
'''<summary>
'''Control VentanaAdjunto.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents VentanaAdjunto As Global.Telerik.Web.UI.RadWindow
'''<summary>
'''Control RadAjaxLoadingPanel1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents RadAjaxLoadingPanel1 As Global.Telerik.Web.UI.RadAjaxLoadingPanel
'''<summary>
'''Control RadAjaxManager1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents RadAjaxManager1 As Global.Telerik.Web.UI.RadAjaxManager
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.WebSite/Logistica/FrmRequerimientoEditarAprobar.aspx.designer.vb
|
Visual Basic
|
mit
| 16,939
|
#Region "License"
' The MIT License (MIT)
'
' Copyright (c) 2017 Richard L King (TradeWright Software Systems)
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
#End Region
Imports ChartSkil27
Imports TradeWright.Trading.Utils.Charts
Imports TWUtilities40
Module Globals
'
#Region "Interfaces"
#End Region
#Region "Events"
#End Region
#Region "Constants"
Public Const MinDouble As Double = -(2 - 2 ^ -52) * 2 ^ 1023
Public Const MaxDouble As Double = (2 - 2 ^ -52) * 2 ^ 1023
Public Const LB_SETHORZEXTENT As Integer = &H194
Public Const TaskTypeStartStudy As Integer = 1
Public Const TaskTypeReplayBars As Integer = 2
Public Const TaskTypeAddValueListener As Integer = 3
Public Const ErroredFieldColor As Integer = &HD0CAFA
Public Const PositiveChangeBackColor As Integer = &HB7E43
Public Const NegativeChangebackColor As Integer = &H4444EB
Public Const PositiveProfitColor As Integer = &HB7E43
Public Const NegativeProfitColor As Integer = &H4444EB
Public Const IncreasedValueColor As Integer = &HB7E43
Public Const DecreasedValueColor As Integer = &H4444EB
Public Const BarModeBar As String = "Bars"
Public Const BarModeCandle As String = "Candles"
Public Const BarModeSolidCandle As String = "Solid candles"
Public Const BarModeLine As String = "Line"
Public Const BarStyleNarrow As String = "Narrow"
Public Const BarStyleMedium As String = "Medium"
Public Const BarStyleWide As String = "Wide"
Public Const BarWidthNarrow As Single = 0.3
Public Const BarWidthMedium As Single = 0.6
Public Const BarWidthWide As Single = 0.9
Public Const HistogramStyleNarrow As String = "Narrow"
Public Const HistogramStyleMedium As String = "Medium"
Public Const HistogramStyleWide As String = "Wide"
Public Const HistogramWidthNarrow As Single = 0.3
Public Const HistogramWidthMedium As Single = 0.6
Public Const HistogramWidthWide As Single = 0.9
Public Const LineDisplayModePlain As String = "Plain"
Public Const LineDisplayModeArrowEnd As String = "End arrow"
Public Const LineDisplayModeArrowStart As String = "Start arrow"
Public Const LineDisplayModeArrowBoth As String = "Both arrows"
Public Const LineStyleSolid As String = "Solid"
Public Const LineStyleDash As String = "Dash"
Public Const LineStyleDot As String = "Dot"
Public Const LineStyleDashDot As String = "Dash dot"
Public Const LineStyleDashDotDot As String = "Dash dot dot"
Public Const LineStyleInsideSolid As String = "Inside solid"
Public Const LineStyleInvisible As String = "Invisible"
Public Const PointDisplayModeLine As String = "Line"
Public Const PointDisplayModePoint As String = "Point"
Public Const PointDisplayModeSteppedLine As String = "Stepped line"
Public Const PointDisplayModeHistogram As String = "Histogram"
Public Const PointStyleRound As String = "Round"
Public Const PointStyleSquare As String = "Square"
Public Const TextDisplayModePlain As String = "Plain"
Public Const TextDisplayModeWIthBackground As String = "With background"
Public Const TextDisplayModeWithBox As String = "With box"
Public Const TextDisplayModeWithFilledBox As String = "With filled box"
Public Const CustomStyle As String = "(Custom)"
Public Const CustomDisplayMode As String = "(Custom)"
#End Region
#Region "Enums"
#End Region
#Region "Types"
#End Region
#Region "Member variables"
Friend ChartSkil As New ChartSkil27.ChartSkil
Friend TWUtilities As New TWUtilities40.TWUtilities
Friend StudyUtils As New StudyUtils27.StudyUtils
'Private mDefaultStudyConfigurations As Collection
#End Region
#Region "Constructors"
#End Region
#Region "XXXX Interface Members"
#End Region
#Region "XXXX Event Handlers"
#End Region
#Region "Properties"
#End Region
#Region "Methods"
'Public Function chooseAColor(initialColor As Color, allowNull As Boolean, location As System.Drawing.Point) As Color
' Dim simpleColorPicker As New fSimpleColorPicker
' simpleColorPicker.Top = location.X
' simpleColorPicker.Left = location.Y
' simpleColorPicker.initialColor = initialColor
' If allowNull Then simpleColorPicker.NoColorButton.Enabled = True
' simpleColorPicker.ShowDialog()
' chooseAColor = simpleColorPicker.selectedColor
' simpleColorPicker.Close()
'End Function
'Public Function gGetBottomCentre(ctrl As Control) As System.Drawing.Point
' Return New System.Drawing.Point(ctrl.TopLevelControl.Location.X + ctrl.Location.X + ctrl.Size.Width / 2, ctrl.TopLevelControl.Location.Y + ctrl.Location.Y - ctrl.Size.Height / 2)
'End Function
Public Function gLineStyleToString(value As LineStyles) As String
Select Case value
Case LineStyles.LineSolid
gLineStyleToString = LineStyleSolid
Case LineStyles.LineDash
gLineStyleToString = LineStyleDash
Case LineStyles.LineDot
gLineStyleToString = LineStyleDot
Case LineStyles.LineDashDot
gLineStyleToString = LineStyleDashDot
Case LineStyles.LineDashDotDot
gLineStyleToString = LineStyleDashDotDot
Case LineStyles.LineInvisible
gLineStyleToString = LineStyleInvisible
Case LineStyles.LineInsideSolid
gLineStyleToString = LineStyleInsideSolid
Case Else
gLineStyleToString = LineStyleSolid
End Select
End Function
Public ReadOnly Property gLogger() As Logger
Get
Static lLogger As Logger
If lLogger Is Nothing Then lLogger = TWUtilities.GetLogger("log")
Return lLogger
End Get
End Property
Public Function gPointStyleToString(value As PointStyles) As String
Select Case value
Case PointStyles.PointRound
gPointStyleToString = PointStyleRound
Case PointStyles.PointSquare
gPointStyleToString = PointStyleSquare
Case Else
gPointStyleToString = PointStyleRound
End Select
End Function
Public Sub notImplemented()
MsgBox("This facility has not yet been implemented", , "Sorry")
End Sub
#End Region
#Region "Helper Functions"
#End Region
End Module
|
tradewright/tradebuild-platform.net
|
src/StudiesUI/Globals.vb
|
Visual Basic
|
mit
| 7,430
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Example08
Inherits System.Windows.Forms.UserControl
'UserControl überschreibt den Löschvorgang, um die Komponentenliste zu bereinigen.
<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
'Wird vom Windows Form-Designer benötigt.
Private components As System.ComponentModel.IContainer
'Hinweis: Die folgende Prozedur ist für den Windows Form-Designer erforderlich.
'Das Bearbeiten ist mit dem Windows Form-Designer möglich.
'Das Bearbeiten mit dem Code-Editor ist nicht möglich.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Example08))
Me.labelEventLogHeader = New System.Windows.Forms.Label()
Me.textBoxEvents = New System.Windows.Forms.TextBox()
Me.textBoxDescription = New System.Windows.Forms.TextBox()
Me.buttonStartExample = New System.Windows.Forms.Button()
Me.SuspendLayout()
'
'labelEventLogHeader
'
Me.labelEventLogHeader.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.labelEventLogHeader.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me.labelEventLogHeader.Location = New System.Drawing.Point(27, 134)
Me.labelEventLogHeader.Name = "labelEventLogHeader"
Me.labelEventLogHeader.Size = New System.Drawing.Size(682, 22)
Me.labelEventLogHeader.TabIndex = 21
Me.labelEventLogHeader.Text = "EventLog"
'
'textBoxEvents
'
Me.textBoxEvents.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.textBoxEvents.BackColor = System.Drawing.SystemColors.InactiveBorder
Me.textBoxEvents.Location = New System.Drawing.Point(27, 159)
Me.textBoxEvents.Multiline = True
Me.textBoxEvents.Name = "textBoxEvents"
Me.textBoxEvents.ScrollBars = System.Windows.Forms.ScrollBars.Vertical
Me.textBoxEvents.Size = New System.Drawing.Size(682, 121)
Me.textBoxEvents.TabIndex = 20
'
'textBoxDescription
'
Me.textBoxDescription.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.textBoxDescription.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me.textBoxDescription.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.textBoxDescription.Location = New System.Drawing.Point(27, 72)
Me.textBoxDescription.Multiline = True
Me.textBoxDescription.Name = "textBoxDescription"
Me.textBoxDescription.Size = New System.Drawing.Size(683, 49)
Me.textBoxDescription.TabIndex = 19
Me.textBoxDescription.Text = "This example contains code to catch events in excel." & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "example 9 shows you how to " &
"catch click events from excel gui." & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10)
'
'buttonStartExample
'
Me.buttonStartExample.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.buttonStartExample.FlatStyle = System.Windows.Forms.FlatStyle.Flat
Me.buttonStartExample.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.buttonStartExample.Image = CType(resources.GetObject("buttonStartExample.Image"), System.Drawing.Image)
Me.buttonStartExample.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft
Me.buttonStartExample.Location = New System.Drawing.Point(28, 25)
Me.buttonStartExample.Name = "buttonStartExample"
Me.buttonStartExample.Size = New System.Drawing.Size(683, 28)
Me.buttonStartExample.TabIndex = 18
Me.buttonStartExample.Text = "Start example"
Me.buttonStartExample.UseVisualStyleBackColor = True
'
'Example08
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.BackColor = System.Drawing.Color.FromArgb(CType(CType(201, Byte), Integer), CType(CType(227, Byte), Integer), CType(CType(243, Byte), Integer))
Me.Controls.Add(Me.labelEventLogHeader)
Me.Controls.Add(Me.textBoxEvents)
Me.Controls.Add(Me.textBoxDescription)
Me.Controls.Add(Me.buttonStartExample)
Me.Name = "Example08"
Me.Size = New System.Drawing.Size(739, 304)
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Private WithEvents labelEventLogHeader As System.Windows.Forms.Label
Private WithEvents textBoxEvents As System.Windows.Forms.TextBox
Private WithEvents textBoxDescription As System.Windows.Forms.TextBox
Private WithEvents buttonStartExample As System.Windows.Forms.Button
End Class
|
NetOfficeFw/NetOffice
|
Examples/Excel/VB/Standard Examples/ExcelExamples/Examples/Example08.Designer.vb
|
Visual Basic
|
mit
| 6,012
|
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("Loops_Homework")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("Loops_Homework")>
<Assembly: AssemblyCopyright("Copyright © 2015")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("e4e460ec-491a-4585-890d-b2f6e2ab4c89")>
' 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")>
|
dushka-dragoeva/Telerik
|
Homeworks/Web and UI Technologies/JavaScriptFundament/Loops-Homework/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,145
|
Imports Rhino.Geometry
Public Class AddNoise
Inherits OwlComponentBase
Sub New()
MyBase.New("Add Noise", "Noise", "Add Noise to a TensorSet", SubCategoryTensorSet)
End Sub
Public Overrides ReadOnly Property ComponentGuid As Guid
Get
Return New Guid("{42BC89B6-9FB9-4CAF-B112-78DABADEACD0}")
End Get
End Property
Protected Overrides ReadOnly Property Icon As Bitmap
Get
Return My.Resources.icon_38
End Get
End Property
Public Overrides ReadOnly Property Exposure As GH_Exposure
Get
Return GH_Exposure.primary
End Get
End Property
Protected Overrides Sub RegisterInputParams(pManager As GH_InputParamManager)
pManager.AddParameter(New Param_OwlTensorSet)
pManager.AddNumberParameter("Amplitude", "A", "Noise amplitude", GH_ParamAccess.item, 0.1)
pManager.AddIntegerParameter("Seed", "S", "Noise seed", GH_ParamAccess.item, 123)
pManager.AddIntervalParameter("Constrain", "C", "Constrain the TensorSet to this interval", GH_ParamAccess.item, New Interval(0, 1))
End Sub
Protected Overrides Sub RegisterOutputParams(pManager As GH_OutputParamManager)
pManager.AddParameter(New Param_OwlTensorSet)
End Sub
Protected Overrides Sub SolveInstance(DA As IGH_DataAccess)
Dim ts As New TensorSet
Dim pro As New Interval()
Dim amp As Double
Dim sed As Integer
If Not DA.GetData(0, ts) Then Return
If Not DA.GetData(1, amp) Then Return
If Not DA.GetData(2, sed) Then Return
If Not DA.GetData(3, pro) Then Return
ts.AddNoise(amp, sed)
ts.TrimCeiling(pro.Max)
ts.TrimFloor(pro.Min)
DA.SetData(0, ts)
End Sub
End Class
|
mateuszzwierzycki/Owl
|
Owl.GH/Components/Owl/TensorSet/AddNoise.vb
|
Visual Basic
|
mit
| 1,805
|
'------------------------------------------------------------------------------
' <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
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.Transporter_AEHF.Main
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateSplashScreen()
Me.SplashScreen = Global.Transporter_AEHF.SplashScreen1
End Sub
End Class
End Namespace
|
wboxx1/85-EIS-PUMA
|
puma/My Project/Application.Designer.vb
|
Visual Basic
|
mit
| 1,699
|
Option Infer On
Imports System
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim documents As SolidEdgeFramework.Documents = Nothing
Dim partDocument As SolidEdgePart.PartDocument = Nothing
Dim refPlanes As SolidEdgePart.RefPlanes = Nothing
Dim profileSets As SolidEdgePart.ProfileSets = Nothing
Dim profileSet As SolidEdgePart.ProfileSet = Nothing
Dim profiles As SolidEdgePart.Profiles = Nothing
Dim profile As SolidEdgePart.Profile = Nothing
Dim relations2d As SolidEdgeFrameworkSupport.Relations2d = Nothing
Dim relation2d As SolidEdgeFrameworkSupport.Relation2d = Nothing
Dim arcs2d As SolidEdgeFrameworkSupport.Arcs2d = Nothing
Dim arc2d1 As SolidEdgeFrameworkSupport.Arc2d = Nothing
Dim arc2d2 As SolidEdgeFrameworkSupport.Arc2d = Nothing
Dim lines2d As SolidEdgeFrameworkSupport.Lines2d = Nothing
Dim line2d As SolidEdgeFrameworkSupport.Line2d = Nothing
Try
' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register()
' Attempt to connect to a running instance of Solid Edge.
application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application)
documents = application.Documents
partDocument = CType(documents.Add("SolidEdge.PartDocument"), SolidEdgePart.PartDocument)
refPlanes = partDocument.RefPlanes
profileSets = partDocument.ProfileSets
profileSet = profileSets.Add()
profiles = profileSet.Profiles
profile = profiles.Add(refPlanes.Item(1))
relations2d = CType(profile.Relations2d, SolidEdgeFrameworkSupport.Relations2d)
arcs2d = profile.Arcs2d
lines2d = profile.Lines2d
arc2d1 = arcs2d.AddByStartAlongEnd(0.02, 0, 0, 0.05, -0.07, -0.04)
arc2d2 = arcs2d.AddByStartAlongEnd(0.05, 0.01, 0.07, 0.05, 0.01, -0.04)
line2d = lines2d.AddBy2Points(0, 0, 0.1, 0)
relation2d = relations2d.AddSymmetric(line2d, arc2d1, arc2d2)
Catch ex As System.Exception
Console.WriteLine(ex)
Finally
OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgeFrameworkSupport.Relations2d.AddSymmetric.vb
|
Visual Basic
|
mit
| 2,721
|
Partial Class JumpToImplementation
Inherits DevExpress.CodeRush.PlugInCore.StandardPlugIn
<System.Diagnostics.DebuggerNonUserCode()> _
Public Sub New()
MyBase.New()
'This call is required by the Component Designer.
InitializeComponent()
End Sub
'Component overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Component Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Component Designer
'It can be modified using the Component Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(JumpToImplementation))
Me.actJumpToImplementation = New DevExpress.CodeRush.Core.Action(Me.components)
CType(Me.actJumpToImplementation, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me, System.ComponentModel.ISupportInitialize).BeginInit()
'
'actJumpToImplementation
'
Me.actJumpToImplementation.ActionName = "JumpToImplementation"
Me.actJumpToImplementation.ButtonText = "Jump To Implementation"
Me.actJumpToImplementation.CommonMenu = DevExpress.CodeRush.Menus.VsCommonBar.None
Me.actJumpToImplementation.Description = "Jumps to the implementation of the underlying Interface"
Me.actJumpToImplementation.Image = CType(resources.GetObject("actJumpToImplementation.Image"), System.Drawing.Bitmap)
Me.actJumpToImplementation.ImageBackColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(254, Byte), Integer), CType(CType(0, Byte), Integer))
CType(Me.actJumpToImplementation, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me, System.ComponentModel.ISupportInitialize).EndInit()
End Sub
Friend WithEvents actJumpToImplementation As DevExpress.CodeRush.Core.Action
End Class
|
RoryBecker/CR_JumpToImplementation
|
CR_JumpToImplementation/JumpToImplementation.Designer.vb
|
Visual Basic
|
mit
| 2,424
|
'
' Will Strohl (will.strohl@gmail.com)
' http://www.willstrohl.com
'
'Copyright (c) 2009-2014, Will Strohl
'All rights reserved.
'
'Redistribution and use in source and binary forms, with or without modification, are
'permitted provided that the following conditions are met:
'
'Redistributions of source code must retain the above copyright notice, this list of
'conditions and the following disclaimer.
'
'Redistributions in binary form must reproduce the above copyright notice, this list
'of conditions and the following disclaimer in the documentation and/or other
'materials provided with the distribution.
'
'Neither the name of Will Strohl nor the names of its contributors may be
'used to endorse or promote products derived from this software without specific prior
'written permission.
'
'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
'EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
'OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
'SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
'INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
'TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
'BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
'CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
'ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
'DAMAGE.
'
Imports Newtonsoft.Json
Imports System.Text.RegularExpressions
Imports System.Web
Imports WillStrohl.API.oEmbed.Constants
Imports WillStrohl.API.oEmbed.Providers
Namespace WillStrohl.API.oEmbed
''' <summary>
''' Wrapper - this is the main class to use for any provider that is not provided in this API.
''' </summary>
''' <remarks></remarks>
Public NotInheritable Class Wrapper
Inherits Providers.ProviderBase
#Region " Private Members "
Private Const URL_FORMAT As String = "?url={0}&format={1}"
Private Const FORMAT_PATTERN As String = "\{format\}"
#End Region
Public Function GetContent(ByVal Request As RequestInfo) As String
Dim ctlProvider As New ProviderFormat
If ctlProvider.IsUrlSupported(Request.URL) Then
Dim strProvider As String = ctlProvider.ProviderToUse(Request.URL)
Console.WriteLine(String.Concat("PROVIDER: ", strProvider))
Select Case (strProvider)
Case PROVIDER_CLEARSPRINGWIDGETS
Dim ctlClearspring As New ClearspringWidgets
Return ctlClearspring.GetRichContent(Request.URL)
Case PROVIDER_EMBEDLY
Dim ctlEmbedly As New Embedly
Return ctlEmbedly.GetRichContent(Request.URL)
Case PROVIDER_FLICKR
Dim ctlFlickr As New Flickr
Return ctlFlickr.GetPhoto(Request.URL, Request.MaxWidth, Request.MaxHeight)
Case PROVIDER_HULU
Dim ctlHulu As New Hulu
Return ctlHulu.GetVideo(Request.URL)
Case PROVIDER_MYOPERA
Dim ctlMyOpera As New MyOpera
Return ctlMyOpera.GetRichContent(Request.URL)
Case PROVIDER_OOHEMBED
Dim ctlOohEmbed As New oohEmbed
Return ctlOohEmbed.GetRichContent(Request.URL)
Case PROVIDER_POLLEVERYWHERE
Dim ctlPollEverywhere As New PollEverywhere
Return ctlPollEverywhere.GetRichContent(Request.URL)
Case PROVIDER_QIK
Dim ctlQik As New Qik
Return ctlQik.GetVideo(Request.URL)
Case PROVIDER_REVISION3
Dim ctlRevision3 As New Revision3
Return ctlRevision3.GetVideo(Request.URL)
Case PROVIDER_VIDDLER
Dim ctlViddler As New Viddler
Return ctlViddler.GetVideo(Request.URL, Request.MaxWidth, Request.MaxHeight)
Case PROVIDER_VIMEO
Dim ctlVimeo As New Vimeo
Return ctlVimeo.GetVideo(Request.URL)
Case PROVIDER_YOUTUBE
Dim ctlYouTube As New YouTube
Return ctlYouTube.GetVideo(Request.URL)
Case Else
Throw New ArgumentOutOfRangeException("URL", "The specified URL is not supported by any existing OEmbed provider")
End Select
Else
Throw New ArgumentOutOfRangeException("URL", "The specified URL is not supported by any existing OEmbed provider")
End If
End Function
''' <summary>
''' GetPhotoContent - this method makes a call to a photo oEmbed provider, and returns the image URL that you request
''' </summary>
''' <param name="EndPoint">String - the endpoint as specified by the oEmbed provider</param>
''' <param name="Request">RequestInfo - the request object required to pass information into the EndPoint URL</param>
''' <returns>String - the image URL to embed into your content</returns>
''' <remarks></remarks>
Public Overloads Function GetPhotoContent(ByVal EndPoint As String, ByVal Request As RequestInfo) As String
Return GetPhotoContent(EndPoint, Request, Nothing)
End Function
''' <summary>
''' GetPhotoContent - this method makes a call to a photo oEmbed provider, and returns the image URL that you request
''' </summary>
''' <param name="EndPoint">String - the endpoint as specified by the oEmbed provider</param>
''' <param name="Request">RequestInfo - the request object required to pass information into the EndPoint URL</param>
''' <param name="Args">String() - optional arguments that can be appended to the end of the oEmbed GET request URL</param>
''' <returns>String - the image URL to embed into your content</returns>
''' <remarks></remarks>
Public Overloads Function GetPhotoContent(ByVal EndPoint As String, ByVal Request As RequestInfo, ByVal ParamArray Args() As String) As String
If String.IsNullOrEmpty(EndPoint) Then
Throw New ArgumentNullException("EndPoint")
End If
If Request Is Nothing Then
Throw New ArgumentNullException("Request")
Else
If String.IsNullOrEmpty(Request.URL) Then
Throw New ArgumentNullException("Request.URL")
End If
If Not Request.MaxHeight > NULL_INTEGER Then
Throw New ArgumentNullException("Request.MaxHeight")
End If
If Not Request.MaxWidth > NULL_INTEGER Then
Throw New ArgumentNullException("Request.MaxWidth")
End If
End If
Dim strUrl As String = GetParsedURL(EndPoint, Request, Args)
' make the request
Dim ctlRequest As New RequestController
'Dim strResponse As String = ctlRequest.GetRemoteWebContent(strUrl, UseSSL(strUrl))
Dim strResponse As String = ctlRequest.GetOEmbedContent(strUrl)
' parse the response
Dim objPhoto As New PhotoInfo
objPhoto = CType(JsonConvert.DeserializeObject(strResponse, objPhoto.GetType), PhotoInfo)
' return the content
Return objPhoto.Url
End Function
''' <summary>
''' GetVideoContent - this method makes a call to a video oEmbed provider, and returns the video markup that you request
''' </summary>
''' <param name="EndPoint">String - the endpoint as specified by the oEmbed provider</param>
''' <param name="Request">RequestInfo - the request object required to pass information into the EndPoint URL</param>
''' <returns>String - the video markup to embed into your content</returns>
''' <remarks></remarks>
Public Overloads Function GetVideoContent(ByVal EndPoint As String, ByVal Request As RequestInfo) As String
Return GetVideoContent(EndPoint, Request, Nothing)
End Function
''' <summary>
''' GetVideoContent - this method makes a call to a video oEmbed provider, and returns the video markup that you request
''' </summary>
''' <param name="EndPoint">String - the endpoint as specified by the oEmbed provider</param>
''' <param name="Request">RequestInfo - the request object required to pass information into the EndPoint URL</param>
''' <param name="Args">String() - optional arguments that can be appended to the end of the oEmbed GET request URL</param>
''' <returns>String - the video markup to embed into your content</returns>
''' <remarks></remarks>
Public Overloads Function GetVideoContent(ByVal EndPoint As String, ByVal Request As RequestInfo, ByVal ParamArray Args() As String) As String
If String.IsNullOrEmpty(EndPoint) Then
Throw New ArgumentNullException("EndPoint")
End If
If Request Is Nothing Then
Throw New ArgumentNullException("Request")
Else
If String.IsNullOrEmpty(Request.URL) Then
Throw New ArgumentNullException("Request.URL")
End If
If Not Request.MaxHeight > NULL_INTEGER Then
Throw New ArgumentNullException("Request.MaxHeight")
End If
If Not Request.MaxWidth > NULL_INTEGER Then
Throw New ArgumentNullException("Request.MaxWidth")
End If
End If
Dim strUrl As String = GetParsedURL(EndPoint, Request, Args)
' make the request
Dim ctlRequest As New RequestController
Dim strResponse As String = ctlRequest.GetOEmbedContent(strUrl)
' parse the response
Dim objVideo As New VideoInfo
objVideo = CType(JsonConvert.DeserializeObject(strResponse, objVideo.GetType), VideoInfo)
' return the content
Return objVideo.Html
End Function
''' <summary>
''' GetRichContent - this method makes a call to a rich content oEmbed provider, and returns the rich content markup that you request
''' </summary>
''' <param name="EndPoint">String - the endpoint as specified by the oEmbed provider</param>
''' <param name="Request">RequestInfo - the request object required to pass information into the EndPoint URL</param>
''' <returns>String - the rich content markup to embed into your content</returns>
''' <remarks></remarks>
Public Overloads Function GetRichContent(ByVal EndPoint As String, ByVal Request As RequestInfo) As String
Return GetRichContent(EndPoint, Request, Nothing)
End Function
''' <summary>
''' GetRichContent - this method makes a call to a rich content oEmbed provider, and returns the rich content markup that you request
''' </summary>
''' <param name="EndPoint">String - the endpoint as specified by the oEmbed provider</param>
''' <param name="Request">RequestInfo - the request object required to pass information into the EndPoint URL</param>
''' <param name="Args">String() - optional arguments that can be appended to the end of the oEmbed GET request URL</param>
''' <returns>String - the rich content markup to embed into your content</returns>
''' <remarks></remarks>
Public Overloads Function GetRichContent(ByVal EndPoint As String, ByVal Request As RequestInfo, ByVal ParamArray Args() As String) As String
If String.IsNullOrEmpty(EndPoint) Then
Throw New ArgumentNullException("EndPoint")
End If
If Request Is Nothing Then
Throw New ArgumentNullException("Request")
Else
If String.IsNullOrEmpty(Request.URL) Then
Throw New ArgumentNullException("Request.URL")
End If
End If
Dim strUrl As String = GetParsedURL(EndPoint, Request, Args)
' make the request
Dim ctlRequest As New RequestController
Dim strResponse As String = ctlRequest.GetOEmbedContent(strUrl)
' parse the response
Dim objRich As New RichInfo
objRich = CType(JsonConvert.DeserializeObject(strResponse, objRich.GetType), RichInfo)
' return the content
Return objRich.Html
End Function
#Region " Private Helper Methods "
''' <summary>
''' GetParsedURL - this method parses the URL and makes the necessary updates to the URL to make it oEmbed compatible.
''' </summary>
''' <param name="EndPoint">String - the endpoint as specified by the oEmbed provider</param>
''' <param name="Request">RequestInfo - the request object required to pass information into the EndPoint URL</param>
''' <param name="Args">String() - optional arguments that can be appended to the end of the oEmbed GET request URL</param>
''' <returns></returns>
''' <remarks>
''' If you use the Args() argument, you need to specify it in the following format:
''' Args = {"&arg1=value1&arg2=value2&arg3=value3"}
''' </remarks>
Private Function GetParsedURL(ByVal EndPoint As String, ByVal Request As RequestInfo, ByVal ParamArray Args() As String) As String
Dim strUrl As String = NULL_STRING
' check to see if the url has the format as part of the url itself
If Regex.IsMatch(EndPoint, FORMAT_PATTERN) Then
strUrl = Regex.Replace(EndPoint, FORMAT_PATTERN, Request.Format, RegexOptions.IgnoreCase)
If strUrl.Contains("?") Then
strUrl = String.Concat(strUrl, String.Concat("&url=", HttpUtility.UrlEncode(Request.URL)))
Else
strUrl = String.Concat(strUrl, String.Concat("?url=", HttpUtility.UrlEncode(Request.URL)))
End If
Else
' append the format and target url
strUrl = String.Concat(EndPoint, String.Format(URL_FORMAT, HttpUtility.UrlEncode(Request.URL), Request.Format))
End If
' iterate through the optional arguments and add them
If Not Args Is Nothing AndAlso Args.Length > 0 Then
For Each strObj As String In Args
strUrl = String.Concat(strUrl, strObj)
Next
End If
Return strUrl
End Function
#End Region
End Class
End Namespace
|
hismightiness/dnnextensions
|
Library/oEmbed/WillStrohl.oEmbed/Wrapper.vb
|
Visual Basic
|
mit
| 15,213
|
' 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 Microsoft.CodeAnalysis.VisualBasic.Symbols.TypeSymbolExtensions
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Summarizes whether a conversion is allowed, and if so, which kind of conversion (and in some cases, the
''' associated symbol).
''' </summary>
Public Structure Conversion
Implements IEquatable(Of Conversion)
Private ReadOnly _convKind As ConversionKind
Private ReadOnly _method As MethodSymbol
Friend Sub New(conv As KeyValuePair(Of ConversionKind, MethodSymbol))
_convKind = conv.Key
_method = conv.Value
End Sub
Friend ReadOnly Property Kind As ConversionKind
Get
Return _convKind
End Get
End Property
''' <summary>
''' Returns True if the conversion exists, either as a widening or narrowing conversion.
''' </summary>
''' <remarks>
''' If this returns True, exactly one of <see cref="IsNarrowing"/> or <see cref="IsWidening"/> will return True.
''' If this returns False, neither <see cref="IsNarrowing"/> or <see cref="IsWidening"/> will return True.
''' </remarks>
Public ReadOnly Property Exists As Boolean
Get
Return Not Conversions.NoConversion(_convKind)
End Get
End Property
''' <summary>
''' Returns True if this conversion a narrowing conversion, and not a widening conversion.
''' </summary>
Public ReadOnly Property IsNarrowing As Boolean
Get
Return Conversions.IsNarrowingConversion(_convKind)
End Get
End Property
''' <summary>
''' Returns True if this conversion is a widening conversion, and not a narrowing conversion.
''' </summary>
Public ReadOnly Property IsWidening As Boolean
Get
Return Conversions.IsWideningConversion(_convKind)
End Get
End Property
''' <summary>
''' Returns True if this conversion is an identity conversion.
''' </summary>
''' <remarks>
''' Note that identity conversion are also considered widening conversions.
''' </remarks>
Public ReadOnly Property IsIdentity As Boolean
Get
Return Conversions.IsIdentityConversion(_convKind)
End Get
End Property
''' <summary>
''' Returns True if this conversion is a default conversion (a conversion from the "Nothing" literal).
''' </summary>
''' <remarks>Note that default conversions are considered widening conversions.</remarks>
Public ReadOnly Property IsDefault As Boolean
Get
Return (_convKind And ConversionKind.WideningNothingLiteral) = ConversionKind.WideningNothingLiteral
End Get
End Property
''' <summary>
''' Returns True if this conversion is a widening numeric conversion or a narrowing numeric conversion, as defined in
''' section 8.3.
''' </summary>
Public ReadOnly Property IsNumeric As Boolean
Get
Return (_convKind And ConversionKind.Numeric) <> 0
End Get
End Property
''' <summary>
''' Returns True if this conversion is a narrowing boolean conversion, as defined in section 8.2.
''' </summary>
Public ReadOnly Property IsBoolean As Boolean
Get
Return (_convKind And ConversionKind.Boolean) <> 0
End Get
End Property
''' <summary>
''' Returns True if this conversion is a widening reference conversion or narrowing reference conversion, as defined in
''' section 8.4.
''' </summary>
Public ReadOnly Property IsReference As Boolean
Get
Return (_convKind And ConversionKind.Reference) <> 0
End Get
End Property
''' <summary>
''' Returns True if this conversion is a widening anonymous delegate conversion as defined in section 8.8, or a
''' narrowing anonymous delegate conversion as defined in section 8.9.
''' </summary>
Public ReadOnly Property IsAnonymousDelegate As Boolean
Get
Return (_convKind And ConversionKind.AnonymousDelegate) <> 0
End Get
End Property
''' <summary>
''' Returns True if this is a lambda conversion.
''' </summary>
Public ReadOnly Property IsLambda As Boolean
Get
Return (_convKind And ConversionKind.Lambda) <> 0
End Get
End Property
''' <summary>
''' Returns True if this conversion is a widening array conversion or a narrowing array conversion, as defined in
''' section 8.5.
''' </summary>
Public ReadOnly Property IsArray As Boolean
Get
Return (_convKind And ConversionKind.Array) <> 0
End Get
End Property
''' <summary>
''' Returns True if this conversion a widening value type conversion or a narrowing value type conversion as defined in
''' section 8.6.
''' </summary>
Public ReadOnly Property IsValueType As Boolean
Get
Return (_convKind And ConversionKind.Value) <> 0
End Get
End Property
''' <summary>
''' Returns True if this conversion a widening nullable value type conversion or a narrowing nullable value type
''' conversion as defined in section 8.6.1.
''' </summary>
Public ReadOnly Property IsNullableValueType As Boolean
Get
Return (_convKind And ConversionKind.Nullable) <> 0
End Get
End Property
''' <summary>
''' Returns True if this conversion a widening string conversion or a narrowing string conversion as defined in section
''' 8.7.
''' </summary>
Public ReadOnly Property IsString As Boolean
Get
Return (_convKind And ConversionKind.String) <> 0
End Get
End Property
''' <summary>
''' Returns True if this conversion a widening type parameter or a narrowing type parameter conversion, as defined in
''' section 8.10.
''' </summary>
Public ReadOnly Property IsTypeParameter As Boolean
Get
Return (_convKind And ConversionKind.TypeParameter) <> 0
End Get
End Property
''' <summary>
''' Returns True if this conversion a widening user defined or a narrowing user defined conversion, as defined in
''' section 8.11.
''' </summary>
''' <remarks>
''' If this returns True, the involved conversion method can be obtained with the <see cref="Method"/>
''' property.
''' </remarks>
Public ReadOnly Property IsUserDefined As Boolean
Get
Return (_convKind And ConversionKind.UserDefined) <> 0
End Get
End Property
Friend ReadOnly Property Method As MethodSymbol
Get
Return _method
End Get
End Property
''' <summary>
''' Returns the method that defines the user defined conversion, if any. Otherwise returns Nothing.
''' </summary>
Public ReadOnly Property MethodSymbol As IMethodSymbol
Get
Return _method
End Get
End Property
''' <summary>
''' Returns True if two <see cref="Conversion"/> values are equal.
''' </summary>
''' <param name="left">The left value.</param>
''' <param name="right">The right value.</param>
Public Shared Operator =(left As Conversion, right As Conversion) As Boolean
Return left.Equals(right)
End Operator
''' <summary>
''' Returns True if two <see cref="Conversion"/> values are not equal.
''' </summary>
''' <param name="left">The left value.</param>
''' <param name="right">The right value.</param>
Public Shared Operator <>(left As Conversion, right As Conversion) As Boolean
Return Not (left = right)
End Operator
''' <summary>
''' Determines whether the specified object is equal to the current object.
''' </summary>
''' <param name="obj">
''' The object to compare with the current object.
''' </param>
Public Overloads Overrides Function Equals(obj As Object) As Boolean
Return TypeOf obj Is Conversion AndAlso
Me = DirectCast(obj, Conversion)
End Function
''' <summary>
''' Determines whether the specified object is equal to the current object.
''' </summary>
''' <param name="other">
''' The object to compare with the current object.
''' </param>
Public Overloads Function Equals(other As Conversion) As Boolean Implements IEquatable(Of Conversion).Equals
Return Me._convKind = other._convKind AndAlso Me.Method = other.Method
End Function
''' <summary>
''' Returns a hash code for the current object.
''' </summary>
Public Overrides Function GetHashCode() As Integer
Return Hash.Combine(Method, CInt(_convKind))
End Function
''' <summary>
''' Returns a string that represents the current object.
''' </summary>
Public Overrides Function ToString() As String
Return _convKind.ToString()
End Function
End Structure
<Flags()>
Friend Enum ConversionKind
' If there is a conversion, either [Widening] or [Narrowing] bit must be set, but not both.
' All VB conversions are either Widening or Narrowing.
'
' To indicate the fact that no conversion exists:
' 1) Neither [Widening] nor [Narrowing] are set.
' 2) Additional flags may be set in order to provide specific reason.
'
' Bits from the following values are never set at the same time :
' Identity, Numeric, Nullable, Reference, Array, TypeParameter, Value, [String], WideningNothingLiteral, InterpolatedString
FailedDueToNumericOverflow = 1 << 31 ' Failure flag
FailedDueToIntegerOverflow = FailedDueToNumericOverflow Or (1 << 30) ' Failure flag
FailedDueToNumericOverflowMask = FailedDueToNumericOverflow Or FailedDueToIntegerOverflow
FailedDueToQueryLambdaBodyMismatch = 1 << 29 ' Failure flag to indicate that conversion failed because body of a query lambda couldn't be converted to the target delegate return type.
FailedDueToArrayLiteralElementConversion = 1 << 28 ' Failed because array literal element could not be converted to the target element type.
' If there is a conversion, one and only one of the following two bits must be set.
' All VB conversions are either Widening or Narrowing.
[Widening] = 1 << 0
[Narrowing] = 1 << 1
''' <summary>
''' Because flags can be combined, use the method IsIdentityConversion when testing for ConversionKind.Identity
''' </summary>
''' <remarks></remarks>
Identity = [Widening] Or 1 << 2 ' According to VB spec, identity conversion is Widening
Numeric = 1 << 3
WideningNumeric = [Widening] Or Numeric
NarrowingNumeric = [Narrowing] Or Numeric
Nullable = 1 << 4
WideningNullable = [Widening] Or Nullable
NarrowingNullable = [Narrowing] Or Nullable
Reference = 1 << 5
WideningReference = [Widening] Or Reference
NarrowingReference = [Narrowing] Or Reference
Array = 1 << 6
WideningArray = [Widening] Or Array
NarrowingArray = [Narrowing] Or Array
TypeParameter = 1 << 7
WideningTypeParameter = [Widening] Or TypeParameter
NarrowingTypeParameter = [Narrowing] Or TypeParameter
Value = 1 << 8
WideningValue = [Widening] Or Value
NarrowingValue = [Narrowing] Or Value
[String] = 1 << 9
WideningString = [Widening] Or [String]
NarrowingString = [Narrowing] Or [String]
[Boolean] = 1 << 10
' Note: there are no widening boolean conversions.
NarrowingBoolean = [Narrowing] Or [Boolean]
WideningNothingLiteral = [Widening] Or (1 << 11)
' Compiler might be interested in knowing if constant numeric conversion involves narrowing
' for constant's original type. When user-defined conversions are involved, this flag can be
' combined with widening conversions other than WideningNumericConstant.
'
' If this flag is combined with Narrowing, there should be no other reasons to treat
' conversion as narrowing. In some scenarios overload resolution is likely to dismiss
' narrowing in presence of this flag. Also, it appears that with Option Strict On, Dev10
' compiler does not report errors for narrowing conversions from an integral constant
' expression to an integral type (assuming integer overflow checks are disabled) or from a
' floating constant to a floating type.
InvolvesNarrowingFromNumericConstant = 1 << 12
' This flag is set when conversion involves conversion enum <-> underlying type,
' or conversion between two enums, etc
InvolvesEnumTypeConversions = 1 << 13
' Lambda conversion
Lambda = 1 << 14
' Delegate relaxation levels for Lambda and Delegate conversions
DelegateRelaxationLevelNone = 0 ' Identity / Whidbey
DelegateRelaxationLevelWidening = 1 << 15
DelegateRelaxationLevelWideningDropReturnOrArgs = 2 << 15
DelegateRelaxationLevelWideningToNonLambda = 3 << 15
DelegateRelaxationLevelNarrowing = 4 << 15 ' OrcasStrictOff
DelegateRelaxationLevelInvalid = 5 << 15 ' Keep invalid the biggest number
DelegateRelaxationLevelMask = 7 << 15 ' Three bits used!
'Can be combined with Narrowing
VarianceConversionAmbiguity = 1 << 18
' This bit can be combined with NoConversion to indicate that, even though there is no conversion
' from the language point of view, there is a slight chance that conversion might succeed at run-time
' under the right circumstances. It is used to detect possibly ambiguous variance conversions to an
' interface, so it is set only for scenarios that are relevant to variance conversions to an
' interface.
MightSucceedAtRuntime = 1 << 19
AnonymousDelegate = 1 << 20
NeedAStub = 1 << 21
ConvertedToExpressionTree = 1 << 22 ' Combined with Lambda, indicates a conversion of lambda to Expression(Of T).
UserDefined = 1 << 23
' Some variance delegate conversions are treated as special narrowing (Dev10 #820752).
' This flag is combined with Narrowing to indicate the fact.
NarrowingDueToContraVarianceInDelegate = 1 << 24
' Interpolated string conversions
InterpolatedString = [Widening] Or (1 << 25)
' Tuple conversions
Tuple = (1 << 26)
WideningTuple = [Widening] Or Tuple
NarrowingTuple = [Narrowing] Or Tuple
' Bits 28 - 31 are reserved for failure flags.
End Enum
<Flags()>
Friend Enum MethodConversionKind
Identity = &H0
OneArgumentIsVbOrBoxWidening = &H1
OneArgumentIsClrWidening = &H2
OneArgumentIsNarrowing = &H4
' TODO: It looks like Dev10 MethodConversionKinds for return are badly named because
' they appear to give classification in the direction opposite to the data
' flow. This is very confusing. However, I am not going to rename them just yet.
' Will do this when all parts are ported and working together, otherwise it will
' be very hard to port the rest of the feature.
ReturnIsWidening = &H8
ReturnIsClrNarrowing = &H10
ReturnIsIsVbOrBoxNarrowing = &H20
ReturnValueIsDropped = &H40
AllArgumentsIgnored = &H80
ExcessOptionalArgumentsOnTarget = &H100
Error_ByRefByValMismatch = &H200
Error_Unspecified = &H400
Error_IllegalToIgnoreAllArguments = &H800
Error_RestrictedType = &H1000
Error_SubToFunction = &H2000
Error_ReturnTypeMismatch = &H4000
Error_OverloadResolution = &H8000
AllErrorReasons = Error_ByRefByValMismatch Or
Error_Unspecified Or
Error_IllegalToIgnoreAllArguments Or
Error_RestrictedType Or
Error_SubToFunction Or
Error_ReturnTypeMismatch Or
Error_OverloadResolution
End Enum
''' <summary>
''' The purpose of this class is to answer questions about convertibility of one type to another.
''' It also answers questions about conversions from an expression to a type.
'''
''' The code is organized such that each method attempts to implement exactly one section of the
''' specification.
''' </summary>
''' <remarks></remarks>
Friend NotInheritable Class Conversions
Public Shared ReadOnly Identity As New KeyValuePair(Of ConversionKind, MethodSymbol)(ConversionKind.Identity, Nothing)
Private Sub New()
Throw ExceptionUtilities.Unreachable
End Sub
Friend Class ConversionEasyOut
' There are situations in which we know that there is no unusual conversion going on (such as a conversion involving constants,
' enumerated types, and so on.) In those situations we can classify conversions via a simple table lookup:
' PERF: Use Integer instead of ConversionKind so the compiler can use array literal initialization.
' The most natural type choice, Enum arrays, are not blittable due to a CLR limitation.
Private Shared ReadOnly s_convkind As Integer(,)
Shared Sub New()
Const NOC As Integer = Nothing 'ConversionKind.NoConversion
Const IDN As Integer = ConversionKind.Identity
Const NUM As Integer = ConversionKind.WideningNumeric
Const NNM As Integer = ConversionKind.NarrowingNumeric
Const IRF As Integer = ConversionKind.WideningReference
Const NRF As Integer = ConversionKind.NarrowingReference
Const WIV As Integer = ConversionKind.WideningValue
Const NAV As Integer = ConversionKind.NarrowingValue
Const NST As Integer = ConversionKind.NarrowingString
Const WST As Integer = ConversionKind.WideningString
Const NBO As Integer = ConversionKind.NarrowingBoolean
' TO TYPE
' Obj Str Bool Char SByt Shrt Int Long Byte UShr UInt ULng Sngl Dbl Dec Date
s_convkind = New Integer(,) { ' FROM TYPE
{IDN, NRF, NAV, NAV, NAV, NAV, NAV, NAV, NAV, NAV, NAV, NAV, NAV, NAV, NAV, NAV}, ' Obj
{IRF, IDN, NST, NST, NST, NST, NST, NST, NST, NST, NST, NST, NST, NST, NST, NST}, ' Str
{WIV, NST, IDN, NOC, NBO, NBO, NBO, NBO, NBO, NBO, NBO, NBO, NBO, NBO, NBO, NOC}, ' Bool
{WIV, WST, NOC, IDN, NOC, NOC, NOC, NOC, NOC, NOC, NOC, NOC, NOC, NOC, NOC, NOC}, ' Char
{WIV, NST, NBO, NOC, IDN, NUM, NUM, NUM, NNM, NNM, NNM, NNM, NUM, NUM, NUM, NOC}, ' SByt
{WIV, NST, NBO, NOC, NNM, IDN, NUM, NUM, NNM, NNM, NNM, NNM, NUM, NUM, NUM, NOC}, ' Shrt
{WIV, NST, NBO, NOC, NNM, NNM, IDN, NUM, NNM, NNM, NNM, NNM, NUM, NUM, NUM, NOC}, ' Int
{WIV, NST, NBO, NOC, NNM, NNM, NNM, IDN, NNM, NNM, NNM, NNM, NUM, NUM, NUM, NOC}, ' Long
{WIV, NST, NBO, NOC, NNM, NUM, NUM, NUM, IDN, NUM, NUM, NUM, NUM, NUM, NUM, NOC}, ' Byte
{WIV, NST, NBO, NOC, NNM, NNM, NUM, NUM, NNM, IDN, NUM, NUM, NUM, NUM, NUM, NOC}, ' UShr
{WIV, NST, NBO, NOC, NNM, NNM, NNM, NUM, NNM, NNM, IDN, NUM, NUM, NUM, NUM, NOC}, ' UInt
{WIV, NST, NBO, NOC, NNM, NNM, NNM, NNM, NNM, NNM, NNM, IDN, NUM, NUM, NUM, NOC}, ' ULng
{WIV, NST, NBO, NOC, NNM, NNM, NNM, NNM, NNM, NNM, NNM, NNM, IDN, NUM, NNM, NOC}, ' Sngl
{WIV, NST, NBO, NOC, NNM, NNM, NNM, NNM, NNM, NNM, NNM, NNM, NNM, IDN, NNM, NOC}, ' Dbl
{WIV, NST, NBO, NOC, NNM, NNM, NNM, NNM, NNM, NNM, NNM, NNM, NUM, NUM, IDN, NOC}, ' Dec
{WIV, NST, NOC, NOC, NOC, NOC, NOC, NOC, NOC, NOC, NOC, NOC, NOC, NOC, NOC, IDN} ' Date
}
' Obj Str Bool Char SByt Shrt Int Long Byte UShr UInt ULng Sngl Dbl Dec Date
End Sub
Public Shared Function ClassifyPredefinedConversion(source As TypeSymbol, target As TypeSymbol) As ConversionKind?
If source Is Nothing OrElse target Is Nothing Then
Return Nothing
End If
' First, dig through Nullable
Dim sourceNullableUnderlying = source.GetNullableUnderlyingTypeOrSelf()
Dim sourceIsNullable As Boolean = (sourceNullableUnderlying IsNot source)
Dim targetNullableUnderlying = target.GetNullableUnderlyingTypeOrSelf()
Dim targetIsNullable As Boolean = (targetNullableUnderlying IsNot target)
' Now dig through Enum
Dim sourceEnumUnderlying = sourceNullableUnderlying.GetEnumUnderlyingTypeOrSelf()
Dim sourceIsEnum As Boolean = (sourceEnumUnderlying IsNot sourceNullableUnderlying)
Dim targetEnumUnderlying = targetNullableUnderlying.GetEnumUnderlyingTypeOrSelf()
Dim targetIsEnum As Boolean = (targetEnumUnderlying IsNot targetNullableUnderlying)
' Filter out unexpected underlying types for Nullable and enum types
If (sourceIsEnum OrElse sourceIsNullable) AndAlso
(sourceEnumUnderlying.IsStringType() OrElse sourceEnumUnderlying.IsObjectType()) Then
Return Nothing
End If
If (targetIsEnum OrElse targetIsNullable) AndAlso
(targetEnumUnderlying.IsStringType() OrElse targetEnumUnderlying.IsObjectType()) Then
Return Nothing
End If
' Classify conversion between underlying types.
Dim sourceIndex As Integer? = TypeToIndex(sourceEnumUnderlying)
If sourceIndex Is Nothing Then
Return Nothing
End If
Dim targetIndex As Integer? = TypeToIndex(targetEnumUnderlying)
If targetIndex Is Nothing Then
Return Nothing
End If
' Table lookup for underlying type doesn't give correct classification
' for Nullable <=> Object conversion. Need to check them explicitly.
If sourceIsNullable Then
If target.IsObjectType() Then
Return ConversionKind.WideningValue
End If
ElseIf targetIsNullable Then
If source.IsObjectType() Then
Return ConversionKind.NarrowingValue
End If
End If
Dim conv As ConversionKind = CType(s_convkind(sourceIndex.Value, targetIndex.Value), ConversionKind)
If Conversions.NoConversion(conv) Then
Return conv
End If
' Adjust classification for enum conversions first, but don't adjust conversions enum <=> Object.
If ((sourceIsEnum AndAlso Not target.IsObjectType()) OrElse
(targetIsEnum AndAlso Not source.IsObjectType())) Then
'§8.8 Widening Conversions
'• From an enumerated type to its underlying numeric type, or to a numeric type
' that its underlying numeric type has a widening conversion to.
'§8.9 Narrowing Conversions
'• From a numeric type to an enumerated type.
'• From an enumerated type to a numeric type its underlying numeric type has a narrowing conversion to.
'• From an enumerated type to another enumerated type.
'!!! Spec doesn't mention this, but VB also supports conversions between enums and non-numeric intrinsic types.
Dim sourceEnum = sourceNullableUnderlying
Dim targetEnum = targetNullableUnderlying
If sourceIsEnum Then
If targetIsEnum Then
If Not (Conversions.IsIdentityConversion(conv) AndAlso sourceEnum.IsSameTypeIgnoringCustomModifiers(targetEnum)) Then
'• From an enumerated type to another enumerated type.
conv = ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions
End If
ElseIf Conversions.IsWideningConversion(conv) Then
'• From an enumerated type to its underlying numeric type, or to a type
' that its underlying numeric type has a widening conversion to.
conv = conv Or ConversionKind.InvolvesEnumTypeConversions
If (conv And ConversionKind.Identity) <> 0 Then
conv = (conv And Not ConversionKind.Identity) Or ConversionKind.Widening Or ConversionKind.Numeric
End If
Else
Debug.Assert(Conversions.IsNarrowingConversion(conv))
'• From an enumerated type to a numeric type its underlying numeric type has a narrowing conversion to.
conv = conv Or ConversionKind.InvolvesEnumTypeConversions
End If
Else
Debug.Assert(targetIsEnum)
'• From a type convertible to underlying type to an enumerated type.
conv = (conv And Not ConversionKind.Widening) Or ConversionKind.Narrowing Or ConversionKind.InvolvesEnumTypeConversions
If (conv And ConversionKind.Identity) <> 0 Then
conv = (conv And Not ConversionKind.Identity) Or ConversionKind.Numeric
End If
End If
Debug.Assert(Conversions.IsIdentityConversion(conv) OrElse (conv And ConversionKind.InvolvesEnumTypeConversions) <> 0)
End If
' Now adjust classification for Nullable conversions.
If sourceIsNullable OrElse targetIsNullable Then
Debug.Assert(Not source.IsObjectType() AndAlso Not target.IsObjectType())
'§8.8 Widening Conversions
'• From a type T to the type T?.
'• From a type T? to a type S?, where there is a widening conversion from the type T to the type S.
'• From a type T to a type S?, where there is a widening conversion from the type T to the type S.
'• From a type T? to an interface type that the type T implements.
'§8.9 Narrowing Conversions
'• From a type T? to a type T.
'• From a type T? to a type S?, where there is a narrowing conversion from the type T to the type S.
'• From a type T to a type S?, where there is a narrowing conversion from the type T to the type S.
'• From a type S? to a type T, where there is a conversion from the type S to the type T.
Dim sourceNullable = source
Dim targetNullable = target
If sourceIsNullable Then
If targetIsNullable Then
If Conversions.IsNarrowingConversion(conv) Then
'• From a type T? to a type S?, where there is a narrowing conversion from the type T to the type S.
conv = ConversionKind.NarrowingNullable
ElseIf Not Conversions.IsIdentityConversion(conv) Then
Debug.Assert(Conversions.IsWideningConversion(conv))
'• From a type T? to a type S?, where there is a widening conversion from the type T to the type S.
conv = ConversionKind.WideningNullable
Else
Debug.Assert(Conversions.IsIdentityConversion(conv) AndAlso sourceNullable.IsSameTypeIgnoringCustomModifiers(targetNullable))
End If
Else
'• From a type T? to a type T.
'• From a type S? to a type T, where there is a conversion from the type S to the type T.
conv = ConversionKind.NarrowingNullable
End If
Else
Debug.Assert(targetIsNullable)
If Conversions.IsWideningConversion(conv) Then
'• From a type T to the type T?.
'• From a type T to a type S?, where there is a widening conversion from the type T to the type S.
conv = ConversionKind.WideningNullable
Else
Debug.Assert(Conversions.IsNarrowingConversion(conv))
'• From a type T to a type S?, where there is a narrowing conversion from the type T to the type S.
conv = ConversionKind.NarrowingNullable
End If
End If
End If
Return conv
End Function
End Class
Private Shared Function FastClassifyPredefinedConversion(source As TypeSymbol, target As TypeSymbol) As ConversionKind?
Return ConversionEasyOut.ClassifyPredefinedConversion(source, target)
End Function
''' <summary>
''' Attempts to fold conversion of a constant expression.
'''
''' Returns Nothing if conversion cannot be folded.
'''
''' If conversion failed due to non-integer overflow, ConstantValue.Bad is returned. Consumer
''' is responsible for reporting appropriate diagnostics.
'''
''' If integer overflow occurs, integerOverflow is set to True and ConstantValue for overflowed result is returned.
''' Consumer is responsible for reporting appropriate diagnostics and potentially discarding the result.
''' </summary>
Public Shared Function TryFoldConstantConversion(
source As BoundExpression,
destination As TypeSymbol,
ByRef integerOverflow As Boolean
) As ConstantValue
Debug.Assert(source IsNot Nothing)
Debug.Assert(destination IsNot Nothing)
Debug.Assert(destination.Kind <> SymbolKind.ErrorType)
integerOverflow = False
Dim sourceValue As ConstantValue = source.ConstantValueOpt
If sourceValue Is Nothing OrElse sourceValue.IsBad Then
' Not a constant
Return Nothing
End If
If Not destination.AllowsCompileTimeConversions() Then
Return Nothing
End If
If source.IsNothingLiteral() Then
' A Nothing literal turns into the default value of the target type.
If destination.IsStringType() Then
Return source.ConstantValueOpt
End If
Dim dstDiscriminator As ConstantValueTypeDiscriminator = destination.GetConstantValueTypeDiscriminator()
Debug.Assert((dstDiscriminator <> ConstantValueTypeDiscriminator.Bad) AndAlso (dstDiscriminator <> ConstantValueTypeDiscriminator.Nothing))
Return ConstantValue.Default(dstDiscriminator)
End If
Dim sourceExpressionType = source.Type
If Not sourceExpressionType.AllowsCompileTimeConversions() Then
Return Nothing
End If
Debug.Assert(sourceExpressionType IsNot Nothing)
Debug.Assert(sourceExpressionType.IsValidForConstantValue(sourceValue))
Dim sourceType = sourceExpressionType.GetEnumUnderlyingTypeOrSelf()
Dim targetType = destination.GetEnumUnderlyingTypeOrSelf()
' Shortcut for identity conversions
If sourceType Is targetType Then
Return sourceValue
End If
' Convert the value of the constant to the result type.
If IsStringType(sourceType) Then
If IsCharType(targetType) Then
Dim str As String = If(sourceValue.IsNothing, Nothing, sourceValue.StringValue)
Dim [char] As Char
If str Is Nothing OrElse str.Length = 0 Then
[char] = ChrW(0)
Else
[char] = str(0)
End If
Return ConstantValue.Create([char])
End If
ElseIf IsCharType(sourceType) Then
If IsStringType(targetType) Then
Return ConstantValue.Create(New String(sourceValue.CharValue, 1))
End If
Else
Dim result = TryFoldConstantNumericOrBooleanConversion(
sourceValue,
sourceType,
targetType,
integerOverflow)
Debug.Assert(result Is Nothing OrElse Not result.IsBad OrElse integerOverflow = False)
Return result
End If
Return Nothing
End Function
''' <summary>
''' Attempts to fold conversion of a constant expression.
'''
''' Returns Nothing if conversion cannot be folded, i.e. unexpected source and destination types.
''' Returns Bad value (Discriminator = ConstantValueTypeDiscriminator.Bad) if conversion failed due to non-integer overflow.
'''
''' If integer overflow occurs, integerOverflow is set to True and the overflowed result is returned.
''' </summary>
Private Shared Function TryFoldConstantNumericOrBooleanConversion(
ByRef sourceValue As ConstantValue,
sourceType As TypeSymbol,
targetType As TypeSymbol,
ByRef integerOverflow As Boolean
) As ConstantValue
integerOverflow = False
If IsIntegralType(sourceType) OrElse IsBooleanType(sourceType) Then
If IsNumericType(targetType) OrElse IsBooleanType(targetType) Then
Dim value As Int64 = GetConstantValueAsInt64(sourceValue)
' // Converting True to an arithmetic value produces -1.
If IsBooleanType(sourceType) AndAlso value <> 0 Then
Const BASIC_TRUE As Integer = (-1)
If IsUnsignedIntegralType(targetType) Then
Dim ignoreOverflow As Boolean = False
value = NarrowIntegralResult(BASIC_TRUE, sourceType, targetType, ignoreOverflow)
Else
value = BASIC_TRUE
End If
End If
Return ConvertIntegralValue(value,
sourceValue.Discriminator,
targetType.GetConstantValueTypeDiscriminator(),
integerOverflow)
End If
ElseIf IsFloatingType(sourceType) Then
If IsNumericType(targetType) OrElse IsBooleanType(targetType) Then
Dim result = ConvertFloatingValue(
If(sourceValue.Discriminator = ConstantValueTypeDiscriminator.Double, sourceValue.DoubleValue, sourceValue.SingleValue),
targetType.GetConstantValueTypeDiscriminator(),
integerOverflow)
If result.IsBad Then
integerOverflow = False
End If
Return result
End If
ElseIf IsDecimalType(sourceType) Then
If IsNumericType(targetType) OrElse IsBooleanType(targetType) Then
Dim result = ConvertDecimalValue(
sourceValue.DecimalValue,
targetType.GetConstantValueTypeDiscriminator(),
integerOverflow)
If result.IsBad Then
integerOverflow = False
End If
Return result
End If
End If
Return Nothing
End Function
Public Shared Function TryFoldNothingReferenceConversion(
source As BoundExpression,
conversion As ConversionKind,
targetType As TypeSymbol
) As ConstantValue
Debug.Assert(source IsNot Nothing)
Debug.Assert(targetType IsNot Nothing)
Debug.Assert(targetType.Kind <> SymbolKind.ErrorType)
Dim sourceValue As ConstantValue = source.ConstantValueOpt
Return TryFoldNothingReferenceConversion(sourceValue, conversion, targetType)
End Function
Friend Shared Function TryFoldNothingReferenceConversion(
sourceValue As ConstantValue,
conversion As ConversionKind,
targetType As TypeSymbol
) As ConstantValue
Debug.Assert(targetType IsNot Nothing)
Debug.Assert(targetType.Kind <> SymbolKind.ErrorType)
If sourceValue Is Nothing OrElse Not sourceValue.IsNothing OrElse
targetType.IsTypeParameter() OrElse Not targetType.IsReferenceType() Then
Return Nothing
End If
If conversion = ConversionKind.WideningNothingLiteral OrElse
IsIdentityConversion(conversion) OrElse
(conversion And ConversionKind.WideningReference) = ConversionKind.WideningReference OrElse
(conversion And ConversionKind.WideningArray) = ConversionKind.WideningArray Then
Return sourceValue
End If
Return Nothing
End Function
''' <summary>
''' This function classifies all intrinsic language conversions and user-defined conversions.
''' </summary>
Public Shared Function ClassifyConversion(source As TypeSymbol, destination As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As KeyValuePair(Of ConversionKind, MethodSymbol)
Debug.Assert(source IsNot Nothing)
Debug.Assert(destination IsNot Nothing)
Debug.Assert(source.Kind <> SymbolKind.ErrorType)
Debug.Assert(Not TypeOf source Is ArrayLiteralTypeSymbol)
Debug.Assert(destination.Kind <> SymbolKind.ErrorType)
Dim predefinedConversion As ConversionKind = ClassifyPredefinedConversion(source, destination, useSiteDiagnostics)
If ConversionExists(predefinedConversion) Then
Return New KeyValuePair(Of ConversionKind, MethodSymbol)(predefinedConversion, Nothing)
End If
Return ClassifyUserDefinedConversion(source, destination, useSiteDiagnostics)
End Function
''' <summary>
''' This function classifies all intrinsic language conversions, such as inheritance,
''' implementation, array covariance, and conversions between intrinsic types.
''' </summary>
Public Shared Function ClassifyPredefinedConversion(source As BoundExpression, destination As TypeSymbol, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ConversionKind
Return ClassifyPredefinedConversion(source, destination, binder, userDefinedConversionsMightStillBeApplicable:=Nothing, useSiteDiagnostics:=useSiteDiagnostics)
End Function
Private Shared Function ClassifyPredefinedConversion(
source As BoundExpression,
destination As TypeSymbol,
binder As Binder,
<Out()> ByRef userDefinedConversionsMightStillBeApplicable As Boolean,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As ConversionKind
Debug.Assert(source IsNot Nothing)
Debug.Assert(destination IsNot Nothing)
Debug.Assert(destination.Kind <> SymbolKind.ErrorType)
userDefinedConversionsMightStillBeApplicable = False
Dim conv As ConversionKind
' Using source.IsConstant for field accesses can result in an infinite loop.
' To resolve the cycle, first call GetConstantValue with the already visited constants from the binder.
' The check for source.IsConstant is still necessary because the node might still
' be considered as a non-constant in some error conditions (a reference before declaration,
' for example).
Dim sourceIsConstant As Boolean = False
If source.Kind = BoundKind.FieldAccess Then
sourceIsConstant = DirectCast(source, BoundFieldAccess).FieldSymbol.GetConstantValue(binder.ConstantFieldsInProgress) IsNot Nothing AndAlso source.IsConstant
ElseIf source.Kind = BoundKind.Local Then
sourceIsConstant = DirectCast(source, BoundLocal).LocalSymbol.GetConstantValue(binder) IsNot Nothing AndAlso source.IsConstant
Else
sourceIsConstant = source.IsConstant
End If
If sourceIsConstant Then
'§8.8 Widening Conversions
'• From the literal Nothing to a type.
conv = ClassifyNothingLiteralConversion(source, destination)
If ConversionExists(conv) Then
Return conv
End If
'§8.8 Widening Conversions
'• From the literal 0 to an enumerated type.
'• From a constant expression of type ULong, Long, UInteger, Integer, UShort, Short, Byte, or SByte to
' a narrower type, provided the value of the constant expression is within the range of the destination type.
conv = ClassifyNumericConstantConversion(source, destination, binder)
If ConversionExists(conv) OrElse FailedDueToNumericOverflow(conv) Then
Return conv
End If
End If
If Not (source.IsValue) Then
Return Nothing 'ConversionKind.NoConversion
End If
Dim sourceType As TypeSymbol = source.Type
If sourceType Is Nothing Then
userDefinedConversionsMightStillBeApplicable = source.GetMostEnclosedParenthesizedExpression().Kind = BoundKind.ArrayLiteral
' The node doesn't have a type yet and reclassification failed.
Return Nothing ' No conversion
End If
If sourceType.Kind <> SymbolKind.ErrorType Then
Dim predefinedConversion As ConversionKind = ClassifyPredefinedConversion(sourceType, destination, useSiteDiagnostics)
If ConversionExists(predefinedConversion) Then
Return predefinedConversion
End If
userDefinedConversionsMightStillBeApplicable = True
End If
Return Nothing 'ConversionKind.NoConversion
End Function
''' <summary>
''' This function classifies all intrinsic language conversions and user-defined conversions.
''' </summary>
Public Shared Function ClassifyConversion(source As BoundExpression, destination As TypeSymbol, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As KeyValuePair(Of ConversionKind, MethodSymbol)
Debug.Assert(source IsNot Nothing)
Debug.Assert(destination IsNot Nothing)
Debug.Assert(destination.Kind <> SymbolKind.ErrorType)
Dim conv As ConversionKind
' Reclassify lambdas, array literals, etc.
conv = ClassifyExpressionReclassification(source, destination, binder, useSiteDiagnostics)
If ConversionExists(conv) OrElse FailedDueToQueryLambdaBodyMismatch(conv) OrElse
(conv And (ConversionKind.Lambda Or ConversionKind.FailedDueToArrayLiteralElementConversion)) <> 0 Then
Return New KeyValuePair(Of ConversionKind, MethodSymbol)(conv, Nothing)
End If
Dim userDefinedConversionsMightStillBeApplicable As Boolean = False
conv = ClassifyPredefinedConversion(source, destination, binder, userDefinedConversionsMightStillBeApplicable, useSiteDiagnostics)
If ConversionExists(conv) OrElse Not userDefinedConversionsMightStillBeApplicable Then
Return New KeyValuePair(Of ConversionKind, MethodSymbol)(conv, Nothing)
End If
' There could be some interesting conversions between the source expression
' and the input type of the conversion operator. We might need to keep track
' of them.
Return ClassifyUserDefinedConversion(source, destination, binder, useSiteDiagnostics)
End Function
''' <summary>
''' Reclassify lambdas, array literals, etc.
''' </summary>
Private Shared Function ClassifyExpressionReclassification(source As BoundExpression, destination As TypeSymbol, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ConversionKind
Select Case source.Kind
Case BoundKind.Parenthesized
If source.Type Is Nothing Then
' Try to reclassify enclosed expression.
Return ClassifyExpressionReclassification(DirectCast(source, BoundParenthesized).Expression, destination, binder, useSiteDiagnostics)
End If
Case BoundKind.UnboundLambda
Return ClassifyUnboundLambdaConversion(DirectCast(source, UnboundLambda), destination)
Case BoundKind.QueryLambda
Return ClassifyQueryLambdaConversion(DirectCast(source, BoundQueryLambda), destination, binder, useSiteDiagnostics)
Case BoundKind.GroupTypeInferenceLambda
Return ClassifyGroupTypeInferenceLambdaConversion(DirectCast(source, GroupTypeInferenceLambda), destination)
Case BoundKind.AddressOfOperator
Return ClassifyAddressOfConversion(DirectCast(source, BoundAddressOfOperator), destination)
Case BoundKind.ArrayLiteral
Return ClassifyArrayLiteralConversion(DirectCast(source, BoundArrayLiteral), destination, binder, useSiteDiagnostics)
Case BoundKind.InterpolatedStringExpression
Return ClassifyInterpolatedStringConversion(DirectCast(source, BoundInterpolatedStringExpression), destination, binder)
Case BoundKind.TupleLiteral
Return ClassifyTupleConversion(DirectCast(source, BoundTupleLiteral), destination, binder, useSiteDiagnostics)
End Select
Return Nothing 'ConversionKind.NoConversion
End Function
Private Shared Function ClassifyUnboundLambdaConversion(source As UnboundLambda, destination As TypeSymbol) As ConversionKind
Dim leastRelaxationLevel As ConversionKind = ConversionKind.DelegateRelaxationLevelNone
Dim conversionKindExpressionTree As ConversionKind = Nothing ' Set to ConversionKind.ConvertedToExpressionTree if expression tree involved.
Dim delegateInvoke As MethodSymbol = Nothing
' Dev10#626389, Dev10#693976: If you convert a lambda to Object/Delegate/MulticastDelegate, then
' the best it can ever be is DelegateRelaxationWideningToNonLambda.
' And if you drop the return value from a lambda, the best it can be is DelegateRelaxationLevelWideningDropReturnOrArgs...
If destination.IsStrictSupertypeOfConcreteDelegate() Then ' covers Object, System.Delegate, System.MulticastDelegate
leastRelaxationLevel = ConversionKind.DelegateRelaxationLevelWideningToNonLambda
' Infer Anonymous Delegate as the target for the lambda.
Dim anonymousDelegateInfo As KeyValuePair(Of NamedTypeSymbol, ImmutableArray(Of Diagnostic)) = source.InferredAnonymousDelegate
' If we have errors for the inference, we know that there is no conversion.
If Not anonymousDelegateInfo.Value.IsDefault AndAlso anonymousDelegateInfo.Value.HasAnyErrors() Then
Return ConversionKind.Lambda ' No conversion
End If
delegateInvoke = anonymousDelegateInfo.Key.DelegateInvokeMethod
Else
Dim wasExpressionTree As Boolean
Dim delegateType As NamedTypeSymbol = destination.DelegateOrExpressionDelegate(source.Binder, wasExpressionTree)
delegateInvoke = If(delegateType IsNot Nothing,
delegateType.DelegateInvokeMethod,
Nothing)
If wasExpressionTree Then
conversionKindExpressionTree = ConversionKind.ConvertedToExpressionTree
End If
If delegateInvoke Is Nothing OrElse delegateInvoke.GetUseSiteErrorInfo() IsNot Nothing Then
Return ConversionKind.Lambda Or conversionKindExpressionTree ' No conversion
End If
If source.IsInferredDelegateForThisLambda(delegateInvoke.ContainingType) Then
Dim inferenceDiagnostics As ImmutableArray(Of Diagnostic) = source.InferredAnonymousDelegate.Value
' If we have errors for the inference, we know that there is no conversion.
If Not inferenceDiagnostics.IsDefault AndAlso inferenceDiagnostics.HasAnyErrors() Then
Return ConversionKind.Lambda Or conversionKindExpressionTree ' No conversion
End If
End If
End If
Debug.Assert(delegateInvoke IsNot Nothing)
Dim bound As BoundLambda = source.Bind(New UnboundLambda.TargetSignature(delegateInvoke))
Debug.Assert(Not bound.Diagnostics.HasAnyErrors OrElse
bound.DelegateRelaxation = ConversionKind.DelegateRelaxationLevelInvalid)
If bound.DelegateRelaxation = ConversionKind.DelegateRelaxationLevelInvalid Then
Return ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelInvalid Or conversionKindExpressionTree ' No conversion
End If
Return ConversionKind.Lambda Or conversionKindExpressionTree Or
If(IsNarrowingMethodConversion(bound.MethodConversionKind, isForAddressOf:=False), ConversionKind.Narrowing, ConversionKind.Widening) Or
CType(Math.Max(bound.DelegateRelaxation, leastRelaxationLevel), ConversionKind)
End Function
Public Shared Function ClassifyArrayLiteralConversion(source As BoundArrayLiteral, destination As TypeSymbol, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ConversionKind
' § 11.1.1
' 9. An array literal can be reclassified as a value. The type of the value is determined as follows:
' 9.1. If the reclassification occurs in the context of a conversion where the target type is known and the target type is an array type,
' then the array literal is reclassified as a value of type T(). If the target type is System.Collections.Generic.IList(Of T),
' System.Collections.Generic.ICollection(Of T), or System.Collections.Generic.IEnumerable(Of T), and the array literal has one level of nesting,
' then the array literal is reclassified as a value of type T().
' 9.2. If the reclassification occurs in the context of a conversion where the target type is known and there is a user-defined conversion
' to the target type from an array type T() or from IList/ICollection/IEnumerable(Of T) as above, then the array literal is reclassified
' as a value of type T().
' 9.3. Otherwise, the array literal is reclassified to a value whose type is an array of rank equal to the level of nesting is used, with
' element type determined by the dominant type of the elements in the initializer; if no dominant type can be determined, Object is used.
' An array literal {e0,e1} can be converted to...
' * an array T() so long as each element can be converted to T
' * IEnumerable(Of T) / ICollection(Of T) / IList(Of T) so long as each element can be converted to T
' * IEnumerable / ICollection / IList
' * System.Array / System.Object
'
' Incidentally, it might be that all elements can each convert to T even though
' the array literal doesn't have a dominant type -- e.g. {lambda} or {} have no dominant type.
' And if there are two elements {e0,e1} such that e0 narrows to e1 and e1 narrows to e0 then
' again there's no dominant type.
'
' Observe that if every element has a reference conversion to T, then the conversions
' from {e0,e1} to T()/IEnumerable(Of T)/ICollection(Of T)/IList(Of T) are all predefined CLR conversions.
' Observe that the conversions to IEnumerable/ICollection/IList/System.Array/System.Object
' are always predefined CLR conversions.
Dim sourceType = source.InferredType
Dim targetType = TryCast(destination, NamedTypeSymbol)
Dim originalTargetType = If(targetType IsNot Nothing, targetType.OriginalDefinition, Nothing)
Dim targetElementType As TypeSymbol = Nothing
Dim targetArrayType As ArrayTypeSymbol = TryCast(destination, ArrayTypeSymbol)
If targetArrayType IsNot Nothing AndAlso (sourceType.Rank = targetArrayType.Rank OrElse source.IsEmptyArrayLiteral) Then
targetElementType = targetArrayType.ElementType
ElseIf (sourceType.Rank = 1 OrElse source.IsEmptyArrayLiteral) AndAlso
originalTargetType IsNot Nothing AndAlso
(originalTargetType.SpecialType = SpecialType.System_Collections_Generic_IEnumerable_T OrElse
originalTargetType.SpecialType = SpecialType.System_Collections_Generic_IList_T OrElse
originalTargetType.SpecialType = SpecialType.System_Collections_Generic_ICollection_T OrElse
originalTargetType.SpecialType = SpecialType.System_Collections_Generic_IReadOnlyList_T OrElse
originalTargetType.SpecialType = SpecialType.System_Collections_Generic_IReadOnlyCollection_T) Then
targetElementType = targetType.TypeArgumentsWithDefinitionUseSiteDiagnostics(useSiteDiagnostics)(0)
Else
Dim conv As ConversionKind = ClassifyStringConversion(sourceType, destination)
If Conversions.NoConversion(conv) Then
' No char() to string conversion
conv = ClassifyDirectCastConversion(sourceType, destination, useSiteDiagnostics)
End If
If Conversions.NoConversion(conv) Then
' If no predefined conversion then we're done
Return Nothing
End If
Dim arrayLiteralElementConv = ClassifyArrayInitialization(source.Initializer, sourceType.ElementType, binder, useSiteDiagnostics)
If Conversions.NoConversion(arrayLiteralElementConv) Then
' No conversion for array elements. Preserve ConversionKind.FailedDueToArrayLiteralElementConversion
Return arrayLiteralElementConv
End If
If Conversions.IsWideningConversion(conv) Then
' If the source to destination conversion is a widening then return the array literal element conversion.
' That conversion will never be better than widening and it preserves ConversionKind.InvolvesNarrowingFromNumericConstant.
Return arrayLiteralElementConv
End If
' Return the ConversionKind.Narrowing because we do not want to propagate any additional conversion kind information.
Return ConversionKind.Narrowing
End If
Return ClassifyArrayInitialization(source.Initializer, targetElementType, binder, useSiteDiagnostics)
End Function
Public Shared Function ClassifyInterpolatedStringConversion(source As BoundInterpolatedStringExpression, destination As TypeSymbol, binder As Binder) As ConversionKind
' A special conversion exist from an interpolated string expression to System.IFormattable or System.FormattableString.
If destination.Equals(binder.Compilation.GetWellKnownType(WellKnownType.System_FormattableString)) OrElse
destination.Equals(binder.Compilation.GetWellKnownType(WellKnownType.System_IFormattable)) _
Then
Return ConversionKind.InterpolatedString
End If
Return Nothing
End Function
Public Shared Function ClassifyTupleConversion(source As BoundTupleLiteral, destination As TypeSymbol, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ConversionKind
Dim arguments = source.Arguments
' check if the type is actually compatible type for a tuple of given cardinality
If Not destination.IsTupleOrCompatibleWithTupleOfCardinality(arguments.Length) Then
Return Nothing 'ConversionKind.NoConversion
End If
Dim targetElementTypes As ImmutableArray(Of TypeSymbol) = destination.GetElementTypesOfTupleOrCompatible()
Debug.Assert(arguments.Count = targetElementTypes.Length)
' check arguments against flattened list of target element types
Dim result As ConversionKind = ConversionKind.WideningTuple
For i As Integer = 0 To arguments.Length - 1
Dim argument = arguments(i)
Dim targetElementType = targetElementTypes(i)
If argument.HasErrors OrElse targetElementType.IsErrorType Then
Return Nothing 'ConversionKind.NoConversion
End If
Dim elementConversion = ClassifyConversion(argument, targetElementType, binder, useSiteDiagnostics).Key
If NoConversion(elementConversion) Then
Return Nothing 'ConversionKind.NoConversion
End If
If IsNarrowingConversion(elementConversion) Then
result = ConversionKind.NarrowingTuple
End If
Next
Return result
End Function
Private Shared Function ClassifyArrayInitialization(source As BoundArrayInitialization, targetElementType As TypeSymbol, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ConversionKind
' Now we have to check that every element converts to TargetElementType.
' It's tempting to say "if the dominant type converts to TargetElementType, then it must be true that
' every element converts." But this isn't true for several reasons. First, the dominant type might
' be the unique NARROWING candidate among the elements in the case that no widest elements existed.
If targetElementType.IsErrorType Then
Return ConversionKind.FailedDueToArrayLiteralElementConversion
End If
Dim result = ConversionKind.Widening
Dim mergedInvolvesNarrowingFromNumericConstant As ConversionKind = ConversionKind.InvolvesNarrowingFromNumericConstant
Dim propagateInvolvesNarrowingFromNumericConstant As Boolean = False 'Has a value been set in mergedInvolvesNarrowingFromNumericConstant?
' We need to propagate InvolvesNarrowingFromNumericConstant bit. If there is at least one narrowing without the bit,
' it shouldn't be propagated, otherwise if there was a widening or narrowing with this bit, it should be propagated.
For Each sourceElement In source.Initializers
Dim elementConv As ConversionKind
If sourceElement.Kind = BoundKind.ArrayInitialization Then
elementConv = ClassifyArrayInitialization(DirectCast(sourceElement, BoundArrayInitialization), targetElementType, binder, useSiteDiagnostics)
Else
elementConv = ClassifyConversion(sourceElement, targetElementType, binder, useSiteDiagnostics).Key
End If
If IsNarrowingConversion(elementConv) Then
result = ConversionKind.Narrowing
'If any narrowing conversion is missing InvolvesNarrowingFromNumericConstant then clear the bit.
mergedInvolvesNarrowingFromNumericConstant = mergedInvolvesNarrowingFromNumericConstant And elementConv
propagateInvolvesNarrowingFromNumericConstant = True
ElseIf NoConversion(elementConv) Then
result = ConversionKind.FailedDueToArrayLiteralElementConversion
propagateInvolvesNarrowingFromNumericConstant = False
Exit For
End If
If IsWideningConversion(result) AndAlso (elementConv And ConversionKind.InvolvesNarrowingFromNumericConstant) <> 0 Then
' If all conversions up to this point are widening and this element has InvolvesNarrowingFromNumericConstant then
' result should include InvolvesNarrowingFromNumericConstant.
Debug.Assert((mergedInvolvesNarrowingFromNumericConstant And ConversionKind.InvolvesNarrowingFromNumericConstant) <> 0)
propagateInvolvesNarrowingFromNumericConstant = True
End If
Next
If propagateInvolvesNarrowingFromNumericConstant Then
result = result Or mergedInvolvesNarrowingFromNumericConstant
End If
Return result
End Function
Private Shared Function ClassifyAddressOfConversion(source As BoundAddressOfOperator, destination As TypeSymbol) As ConversionKind
Return Binder.ClassifyAddressOfConversion(source, destination)
End Function
Private Shared Function ClassifyQueryLambdaConversion(source As BoundQueryLambda, destination As TypeSymbol, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ConversionKind
' The delegate type we're converting to (could be type argument of Expression(Of T)).
Dim wasExpressionTree As Boolean
Dim delegateDestination As NamedTypeSymbol = destination.DelegateOrExpressionDelegate(binder, wasExpressionTree)
If delegateDestination Is Nothing Then
Return Nothing ' No conversion
End If
Dim conversionKindExpressionTree As ConversionKind = If(wasExpressionTree, ConversionKind.ConvertedToExpressionTree, Nothing)
Dim invoke As MethodSymbol = delegateDestination.DelegateInvokeMethod
If invoke Is Nothing OrElse invoke.GetUseSiteErrorInfo() IsNot Nothing OrElse invoke.IsSub Then
Return Nothing ' No conversion
End If
' Parameter types should match.
If invoke.ParameterCount <> source.LambdaSymbol.ParameterCount Then
Return Nothing ' No conversion
End If
Dim lambdaParams As ImmutableArray(Of ParameterSymbol) = source.LambdaSymbol.Parameters
Dim invokeParams As ImmutableArray(Of ParameterSymbol) = invoke.Parameters
For i As Integer = 0 To lambdaParams.Length - 1
Dim lambdaParam = lambdaParams(i)
Dim invokeParam = invokeParams(i)
If lambdaParam.IsByRef <> invokeParam.IsByRef OrElse
Not lambdaParam.Type.IsSameTypeIgnoringCustomModifiers(invokeParam.Type) Then
Return Nothing ' No conversion
End If
Next
If source.LambdaSymbol.ReturnType Is LambdaSymbol.ReturnTypePendingDelegate Then
If Not invoke.ReturnType.IsErrorType() Then
' TODO: May need to do classification in a special way when ExprIsOperandOfConditionalBranch==True,
' because we may need to check for IsTrue operator.
Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol)
If source.ExprIsOperandOfConditionalBranch AndAlso invoke.ReturnType.IsBooleanType() Then
conv = ClassifyConversionOfOperandOfConditionalBranch(source.Expression, invoke.ReturnType, binder, Nothing, Nothing, useSiteDiagnostics)
Else
conv = ClassifyConversion(source.Expression, invoke.ReturnType, binder, useSiteDiagnostics)
End If
If IsIdentityConversion(conv.Key) Then
Return conv.Key And (Not ConversionKind.Identity) Or (ConversionKind.Widening Or ConversionKind.Lambda) Or conversionKindExpressionTree
ElseIf NoConversion(conv.Key) Then
Return conv.Key Or (ConversionKind.Lambda Or ConversionKind.FailedDueToQueryLambdaBodyMismatch) Or conversionKindExpressionTree
ElseIf conv.Value IsNot Nothing Then
Debug.Assert((conv.Key And ConversionKind.UserDefined) <> 0)
Return (conv.Key And (Not (ConversionKind.UserDefined Or ConversionKind.Nullable))) Or ConversionKind.Lambda Or conversionKindExpressionTree
Else
Debug.Assert((conv.Key And ConversionKind.UserDefined) = 0)
Return conv.Key Or ConversionKind.Lambda Or conversionKindExpressionTree
End If
End If
ElseIf invoke.ReturnType.IsSameTypeIgnoringCustomModifiers(source.LambdaSymbol.ReturnType) Then
Return ConversionKind.Widening Or ConversionKind.Lambda Or conversionKindExpressionTree
End If
Return Nothing ' No conversion
End Function
Public Shared Function ClassifyConversionOfOperandOfConditionalBranch(
operand As BoundExpression,
booleanType As TypeSymbol,
binder As Binder,
<Out> ByRef applyNullableIsTrueOperator As Boolean,
<Out> ByRef isTrueOperator As OverloadResolution.OverloadResolutionResult,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As KeyValuePair(Of ConversionKind, MethodSymbol)
Debug.Assert(operand IsNot Nothing)
Debug.Assert(booleanType IsNot Nothing)
Debug.Assert(booleanType.Kind <> SymbolKind.ErrorType)
Debug.Assert(booleanType.IsBooleanType())
' 11.19 Boolean Expressions
' A Boolean expression is an expression that can be tested to see if it is true or if it is false.
' A type T can be used in a Boolean expression if, in order of preference:
' - T is Boolean or Boolean?
' - T has a widening conversion to Boolean
' - T has a widening conversion to Boolean?
' - T defines two pseudo operators, IsTrue and IsFalse.
' - T has a narrowing conversion to Boolean? that does not involve a conversion from Boolean to Boolean?.
' - T has a narrowing conversion to Boolean.
'
' If a Boolean expression is typed as or converted to Boolean or Boolean?,
' then it is true if the value is True and false otherwise.
' Otherwise, a Boolean expression calls the IsTrue operator and returns True if the operator returned True;
' otherwise it is false (but never calls the IsFalse operator).
applyNullableIsTrueOperator = False
isTrueOperator = Nothing
Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(operand, booleanType, binder, useSiteDiagnostics)
' See if we need to use IsTrue operator.
If Conversions.IsWideningConversion(conv.Key) Then
' - T is Boolean
' - T has a widening conversion to Boolean
Return conv
End If
Dim sourceType = operand.Type
If sourceType IsNot Nothing AndAlso Not sourceType.IsErrorType() AndAlso Not sourceType.IsObjectType() Then
Dim nullableOfBoolean As TypeSymbol = Nothing
Dim convToNullableOfBoolean As KeyValuePair(Of ConversionKind, MethodSymbol) = Nothing
If sourceType.IsNullableOfBoolean() Then
' The source is Boolean?
convToNullableOfBoolean = Conversions.Identity
nullableOfBoolean = sourceType
Else
Dim nullableOfT As NamedTypeSymbol = booleanType.ContainingAssembly.GetSpecialType(SpecialType.System_Nullable_T)
If Not nullableOfT.IsErrorType() AndAlso
(sourceType.IsNullableType() OrElse sourceType.CanContainUserDefinedOperators(useSiteDiagnostics)) Then
nullableOfBoolean = nullableOfT.Construct(ImmutableArray.Create(Of TypeSymbol)(booleanType))
convToNullableOfBoolean = Conversions.ClassifyConversion(operand, nullableOfBoolean, binder, useSiteDiagnostics)
End If
End If
If Conversions.IsWideningConversion(convToNullableOfBoolean.Key) Then
' - T is Boolean?
' - T has a widening conversion to Boolean?
applyNullableIsTrueOperator = True
Return convToNullableOfBoolean
Else
' Is there IsTrue operator that we can use.
Dim results As OverloadResolution.OverloadResolutionResult = Nothing
If sourceType.CanContainUserDefinedOperators(useSiteDiagnostics) Then
results = OverloadResolution.ResolveIsTrueOperator(operand, binder, useSiteDiagnostics)
End If
If results.BestResult.HasValue Then
' - T defines two pseudo operators, IsTrue and IsFalse.
isTrueOperator = results
If results.BestResult.Value.Candidate.IsLifted Then
applyNullableIsTrueOperator = True
End If
Debug.Assert(Not results.BestResult.Value.RequiresNarrowingConversion)
Return New KeyValuePair(Of ConversionKind, MethodSymbol)(ConversionKind.Widening, Nothing)
ElseIf Conversions.IsNarrowingConversion(convToNullableOfBoolean.Key) AndAlso
Not ((convToNullableOfBoolean.Key And (ConversionKind.UserDefined Or ConversionKind.Nullable)) =
ConversionKind.UserDefined AndAlso
convToNullableOfBoolean.Value.ReturnType.IsBooleanType()) Then
' - T has a narrowing conversion to Boolean? that does not involve a conversion from Boolean to Boolean?.
applyNullableIsTrueOperator = True
Return convToNullableOfBoolean
End If
End If
End If
' - T has a narrowing conversion to Boolean.
' - No conversion
Return conv
End Function
Private Shared Function ClassifyGroupTypeInferenceLambdaConversion(source As GroupTypeInferenceLambda, destination As TypeSymbol) As ConversionKind
Debug.Assert(source.Type Is Nothing) ' Shouldn't try to convert already converted query lambda.
Dim delegateType As NamedTypeSymbol = destination.DelegateOrExpressionDelegate(source.Binder)
If delegateType Is Nothing Then
Return Nothing ' No conversion
End If
Dim invoke As MethodSymbol = delegateType.DelegateInvokeMethod
' Type of the first parameter of the delegate must be source.TypeOfGroupingKey.
' Return type of the delegate must be an Anonymous Type corresponding to the following initializer:
' New With {key .$VB$ItAnonymous = <delegates's second parameter> }
If invoke Is Nothing OrElse invoke.GetUseSiteErrorInfo() IsNot Nothing OrElse invoke.IsSub Then
Return Nothing ' No conversion
End If
' Parameter types should match.
Dim lambdaParams As ImmutableArray(Of ParameterSymbol) = source.Parameters
If invoke.ParameterCount <> lambdaParams.Length Then
Return Nothing ' No conversion
End If
Dim invokeParams As ImmutableArray(Of ParameterSymbol) = invoke.Parameters
For i As Integer = 0 To lambdaParams.Length - 1
Dim lambdaParam = lambdaParams(i)
Dim invokeParam = invokeParams(i)
If lambdaParam.IsByRef <> invokeParam.IsByRef OrElse
(lambdaParam.Type IsNot Nothing AndAlso Not lambdaParam.Type.IsSameTypeIgnoringCustomModifiers(invokeParam.Type)) Then
Return Nothing ' No conversion
End If
Next
If Not invoke.ReturnType.IsAnonymousType Then
Return Nothing ' No conversion
End If
Dim returnType = DirectCast(invoke.ReturnType, NamedTypeSymbol)
Dim anonymousType = DirectCast(returnType, AnonymousTypeManager.AnonymousTypePublicSymbol)
If anonymousType.Properties.Length <> 1 OrElse
anonymousType.Properties(0).SetMethod IsNot Nothing OrElse
Not anonymousType.Properties(0).Name.Equals(StringConstants.ItAnonymous) OrElse
Not invokeParams(1).Type.IsSameTypeIgnoringCustomModifiers(anonymousType.Properties(0).Type) Then
Return Nothing ' No conversion
End If
Return (ConversionKind.Widening Or ConversionKind.Lambda)
End Function
Private Shared Function ClassifyNumericConstantConversion(constantExpression As BoundExpression, destination As TypeSymbol, binder As Binder) As ConversionKind
Debug.Assert(constantExpression.ConstantValueOpt IsNot Nothing)
If constantExpression.ConstantValueOpt.IsBad Then
Return Nothing 'ConversionKind.NoConversion
End If
Dim targetDestinationType As TypeSymbol = destination.GetNullableUnderlyingTypeOrSelf()
'§8.8 Widening Conversions
'• From the literal 0 to an enumerated type.
If constantExpression.IsIntegerZeroLiteral() AndAlso targetDestinationType.IsEnumType() AndAlso
DirectCast(targetDestinationType, NamedTypeSymbol).EnumUnderlyingType.IsIntegralType() Then
If targetDestinationType Is destination Then
Return ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions
Else
' Target is nullable, conversion is narrowing, but we need to preserve the fact that it was from literal.
Return ConversionKind.NarrowingNullable Or ConversionKind.InvolvesNarrowingFromNumericConstant
End If
End If
Dim sourceType As TypeSymbol = constantExpression.Type
Debug.Assert(sourceType IsNot Nothing) ' Shouldn't this be a [Nothing] literal?
If sourceType Is Nothing Then
Return Nothing 'ConversionKind.NoConversion
End If
If sourceType Is destination Then
Return ConversionKind.Identity
End If
Dim conv As ConversionKind = Nothing 'ConversionKind.NoConversions
Dim integerOverflow As Boolean = False
Dim result As ConstantValue
If sourceType.IsIntegralType() Then
'§8.8 Widening Conversions
'• From a constant expression of type ULong, Long, UInteger, Integer, UShort, Short, Byte, or SByte to
' a narrower type, provided the value of the constant expression is within the range of the destination type.
If targetDestinationType.IsIntegralType() Then
conv = FastClassifyPredefinedConversion(sourceType, destination).Value
If IsNarrowingConversion(conv) Then
conv = conv Or ConversionKind.InvolvesNarrowingFromNumericConstant
' check if the value is within the target range
result = TryFoldConstantNumericOrBooleanConversion(constantExpression.ConstantValueOpt, sourceType, targetDestinationType,
integerOverflow)
Debug.Assert(Not result.IsBad)
If Not integerOverflow Then
' Reclassify as widening, but not for a Nullable target type
If targetDestinationType Is destination Then
conv = (conv And (Not ConversionKind.Narrowing)) Or ConversionKind.Widening
End If
ElseIf binder.CheckOverflow Then
' Compiler generated code (for example, implementation of GetHashCode for Anonymous Types)
' not always uses project level setting for the option.
Debug.Assert(sourceType.AllowsCompileTimeConversions() AndAlso targetDestinationType.AllowsCompileTimeConversions())
Return ConversionKind.FailedDueToIntegerOverflow
End If
Else
Debug.Assert(IsWideningConversion(conv))
End If
Return conv
End If
ElseIf sourceType.IsFloatingType() Then
If targetDestinationType.IsFloatingType() Then
conv = FastClassifyPredefinedConversion(sourceType, destination).Value
If IsNarrowingConversion(conv) Then
conv = conv Or ConversionKind.InvolvesNarrowingFromNumericConstant
Else
Debug.Assert(IsWideningConversion(conv))
End If
End If
End If
' We need to detect overflow errors for constant conversions during classification to make sure overload resolution
' takes the overflow errors into consideration.
If Not IsWideningConversion(conv) Then
Dim underlyingSourceType = sourceType.GetEnumUnderlyingTypeOrSelf()
Dim underlyingDestination = destination.GetNullableUnderlyingTypeOrSelf().GetEnumUnderlyingTypeOrSelf()
If underlyingSourceType.IsNumericType() AndAlso underlyingDestination.IsNumericType() Then
Debug.Assert(sourceType.AllowsCompileTimeConversions() AndAlso destination.GetNullableUnderlyingTypeOrSelf().AllowsCompileTimeConversions())
result = TryFoldConstantNumericOrBooleanConversion(constantExpression.ConstantValueOpt, underlyingSourceType, underlyingDestination,
integerOverflow)
If result.IsBad Then
conv = ConversionKind.FailedDueToNumericOverflow
ElseIf integerOverflow AndAlso binder.CheckOverflow Then
' Compiler generated code (for example, implementation of GetHashCode for Anonymous Types)
' not always uses project level setting for the option.
Return ConversionKind.FailedDueToIntegerOverflow
End If
End If
End If
Return conv
End Function
Private Shared Function ClassifyNothingLiteralConversion(constantExpression As BoundExpression, destination As TypeSymbol) As ConversionKind
'§8.8 Widening Conversions
'• From the literal Nothing to a type.
' We fold NOTHING conversions, as Dev10 does. And for the purpose of conversion classification,
' Dev10 ignores explicitly converted NOTHING.
If constantExpression.IsStrictNothingLiteral() Then
If destination.IsObjectType() AndAlso constantExpression.Type IsNot Nothing AndAlso
constantExpression.Type.IsObjectType() Then
Return ConversionKind.Identity
End If
Return ConversionKind.WideningNothingLiteral
End If
Return Nothing 'ConversionKind.NoConversion
End Function
Public Shared Function ClassifyDirectCastConversion(
source As TypeSymbol,
destination As TypeSymbol,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As ConversionKind
Debug.Assert(source IsNot Nothing)
Debug.Assert(destination IsNot Nothing)
Debug.Assert(source.Kind <> SymbolKind.ErrorType)
Debug.Assert(destination.Kind <> SymbolKind.ErrorType)
'§8.12 Native Conversions
'The conversions classified as native conversions are:
'identity conversions, default conversions, reference conversions,
'array conversions, value type conversions, and type parameter conversions.
Dim result As ConversionKind
'Identity/Default conversions
result = ClassifyIdentityConversion(source, destination)
If ConversionExists(result) Then
Return result
End If
' Numeric conversions
' CLI spec says "enums shall have a built-in integer type" (ECMA I $8.5.2) and gives
' a list of built-in types (ECMA I $8.2.2). The only built-in integer types are i8,ui8,i16,ui16,i32,ui32,i64,ui64
If source.IsIntegralType() Then
If destination.TypeKind = TypeKind.Enum AndAlso
DirectCast(destination, NamedTypeSymbol).EnumUnderlyingType.Equals(source) Then
Return ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions
End If
ElseIf destination.IsIntegralType() Then
If source.TypeKind = TypeKind.Enum AndAlso
DirectCast(source, NamedTypeSymbol).EnumUnderlyingType.Equals(destination) Then
Return ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions
End If
ElseIf source.TypeKind = TypeKind.Enum AndAlso destination.TypeKind = TypeKind.Enum Then
Dim srcUnderlying = DirectCast(source, NamedTypeSymbol).EnumUnderlyingType
If srcUnderlying.IsIntegralType() AndAlso
srcUnderlying.Equals(DirectCast(destination, NamedTypeSymbol).EnumUnderlyingType) Then
Return ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions
End If
End If
'Reference conversions
result = ClassifyReferenceConversion(source, destination, varianceCompatibilityClassificationDepth:=0, useSiteDiagnostics:=useSiteDiagnostics)
If ConversionExists(result) Then
Return result
End If
'Array conversions
result = ClassifyArrayConversion(source, destination, varianceCompatibilityClassificationDepth:=0, useSiteDiagnostics:=useSiteDiagnostics)
If ConversionExists(result) Then
Return result
End If
'Value Type conversions
result = ClassifyValueTypeConversion(source, destination, useSiteDiagnostics)
If ConversionExists(result) Then
Return result
End If
'Type Parameter conversions
result = ClassifyTypeParameterConversion(source, destination, varianceCompatibilityClassificationDepth:=0, useSiteDiagnostics:=useSiteDiagnostics)
Return result
End Function
Public Shared Function ClassifyDirectCastConversion(source As BoundExpression, destination As TypeSymbol, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ConversionKind
Debug.Assert(source IsNot Nothing)
Debug.Assert(destination IsNot Nothing)
Debug.Assert(destination.Kind <> SymbolKind.ErrorType)
Dim conv As ConversionKind
If source.IsConstant Then
conv = ClassifyNothingLiteralConversion(source, destination)
If ConversionExists(conv) Then
Return conv
End If
End If
' Reclassify lambdas, array literals, etc.
conv = ClassifyExpressionReclassification(source, destination, binder, useSiteDiagnostics)
If ConversionExists(conv) OrElse (conv And (ConversionKind.Lambda Or ConversionKind.FailedDueToArrayLiteralElementConversion)) <> 0 Then
Return conv
End If
If Not (source.IsValue) Then
Return Nothing 'ConversionKind.NoConversion
End If
Dim sourceType As TypeSymbol = source.Type
If sourceType Is Nothing Then
' The node doesn't have a type yet and reclassification failed.
Return Nothing ' No conversion
End If
If sourceType.Kind <> SymbolKind.ErrorType Then
Return ClassifyDirectCastConversion(sourceType, destination, useSiteDiagnostics)
End If
Return Nothing
End Function
Public Shared Function ClassifyTryCastConversion(source As TypeSymbol, destination As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ConversionKind
Debug.Assert(source IsNot Nothing)
Debug.Assert(destination IsNot Nothing)
Debug.Assert(source.Kind <> SymbolKind.ErrorType)
Debug.Assert(Not TypeOf source Is ArrayLiteralTypeSymbol)
Debug.Assert(destination.Kind <> SymbolKind.ErrorType)
Dim result As ConversionKind
result = ClassifyDirectCastConversion(source, destination, useSiteDiagnostics)
If ConversionExists(result) Then
Return result
End If
Return ClassifyTryCastConversionForTypeParameters(source, destination, useSiteDiagnostics)
End Function
Public Shared Function ClassifyTryCastConversion(source As BoundExpression, destination As TypeSymbol, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ConversionKind
Debug.Assert(source IsNot Nothing)
Debug.Assert(destination IsNot Nothing)
Debug.Assert(destination.Kind <> SymbolKind.ErrorType)
Dim conv As ConversionKind
If source.IsConstant Then
conv = ClassifyNothingLiteralConversion(source, destination)
If ConversionExists(conv) Then
Return conv
End If
End If
' Reclassify lambdas, array literals, etc.
conv = ClassifyExpressionReclassification(source, destination, binder, useSiteDiagnostics)
If ConversionExists(conv) OrElse (conv And (ConversionKind.Lambda Or ConversionKind.FailedDueToArrayLiteralElementConversion)) <> 0 Then
Return conv
End If
If Not (source.IsValue) Then
Return Nothing 'ConversionKind.NoConversion
End If
Dim sourceType As TypeSymbol = source.Type
If sourceType Is Nothing Then
' The node doesn't have a type yet and reclassification failed.
Return Nothing ' No conversion
End If
If sourceType.Kind <> SymbolKind.ErrorType Then
Return ClassifyTryCastConversion(sourceType, destination, useSiteDiagnostics)
End If
Return Nothing
End Function
Private Shared Function ClassifyTryCastConversionForTypeParameters(source As TypeSymbol, destination As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ConversionKind
Dim sourceKind = source.Kind
Dim destinationKind = destination.Kind
If sourceKind = SymbolKind.ArrayType AndAlso destinationKind = SymbolKind.ArrayType Then
Dim sourceArray = DirectCast(source, ArrayTypeSymbol)
Dim destinationArray = DirectCast(destination, ArrayTypeSymbol)
Dim sourceElement = sourceArray.ElementType
Dim destinationElement = destinationArray.ElementType
If sourceElement.IsReferenceType Then
If destinationElement.IsValueType Then
Return Nothing 'ConversionKind.NoConversion
End If
ElseIf sourceElement.IsValueType Then
If destinationElement.IsReferenceType Then
Return Nothing 'ConversionKind.NoConversion
End If
End If
' Note that Dev10 compiler does not require arrays rank to match, which is probably
' an oversight. Will match the same behavior for now.
Return ClassifyTryCastConversionForTypeParameters(sourceElement, destinationElement, useSiteDiagnostics)
End If
If sourceKind <> SymbolKind.TypeParameter AndAlso destinationKind <> SymbolKind.TypeParameter Then
Return Nothing 'ConversionKind.NoConversion
End If
' Notation:
' T - non class constrained type parameter
' TC - class constrained type parameter
' CC - Class constraint - eg: CC1 is class constraint of TC1
' C - class
' NC - Notinheritable class
'
' A - Conversions between Type parameters:
'
' 1. T1 -> T2 Conversion possible because T1 and T2 could be any types and thus be potentially related
'
' 2. TC1 -> T2 Conversion possible because T2 could be any type and thus be potentially related to TC1
'
' 3. T1 -> TC2 Conversion possible because T1 could be any type and thus be potentially related to TC2
'
' 4. TC1 -> TC2 Conversion possible only when CC1 and CC2 are related through inheritance, else
' TC1 and TC2 would always be guaranteed to be classes along 2 completely unrelated
' inheritance hierarchies.
'
'
' B - Conversions between Type parameter and a non-type parameter type:
'
' 1. T1 -> C2 Conversion possible because T1 could be any type and thus potentially related to C2
'
' 2. C1 -> T2 Conversion possible because T2 could be any type and thus potentially related to C1
'
' 3. TC1 -> C2 Conversion possible only when CC1 and C2 are related through inheritance, else
' TC1 and C2 would always be guaranteed to be classes along unrelated inheritance
' hierarchies.
'
' 4. C1 -> TC2 Conversion possible only when C1 and CC2 are related through inheritance, else
' C1 and CC2 would always be guaranteed to be classes along unrelated inheritance
' hierarchies.
'
' 5. NC1 -> TC2 Conversion possible only when one of NC1 or its bases satisfies constraints of TC2
' because those are the only types related to NC1 that could ever be passed to TC2.
'
' 6. TC1 -> NC2 Conversion possible only when one of NC2 or its bases satisfies constraints of TC1
' because those are the only types related to NC1 that could ever be passed to TC1.
'
'
' Both A and B above are unified conceptually by treating C1 and C2 to be type parameters constrained
' to class constraints C1 and C2 respectively.
'
' Note that type params with the value type constraint i.e "Structure" is treated as a param with a class
' constraint of System.ValueType.
'
' Note that the reference type constraint does not affect the try cast conversions because it does not prevent
' System.ValueType and System.Enum and so value types can still be related to type params with such constraints.
'
Dim src = GetNonInterfaceTypeConstraintOrSelf(source, useSiteDiagnostics)
Dim dst = GetNonInterfaceTypeConstraintOrSelf(destination, useSiteDiagnostics)
' If the class constraint is Nothing, then conversion is possible because the non-class constrained
' type parameter can be any type related to the other type or type parameter.
'
' Handles cases: A.1, A.2, A.3, B.1 and B.2
'
If src Is Nothing OrElse dst Is Nothing Then
Return ConversionKind.Narrowing
End If
Debug.Assert(src.Kind <> SymbolKind.TypeParameter)
Debug.Assert(dst.Kind <> SymbolKind.TypeParameter)
' partially handles cases: A.4, B.3, B.4, B.5 and B.6
'
Dim conv As ConversionKind = ClassifyDirectCastConversion(src, dst, useSiteDiagnostics)
If IsWideningConversion(conv) Then
Debug.Assert((conv And ConversionKind.VarianceConversionAmbiguity) = 0)
' Since NotInheritable classes cannot be inherited, more conversion possibilities
' could be ruled out at compiler time if the NotInheritable class or any of its
' base can never be used as a type argument for this type parameter during type
' instantiation.
'
' partially handles cases: B.5 and B.6
'
If destinationKind = SymbolKind.TypeParameter AndAlso
(src.TypeKind <> TypeKind.Class OrElse DirectCast(src, NamedTypeSymbol).IsNotInheritable) AndAlso
Not ClassOrBasesSatisfyConstraints(src, DirectCast(destination, TypeParameterSymbol), useSiteDiagnostics) Then
Return Nothing 'ConversionKind.NoConversion
End If
Return ConversionKind.Narrowing Or (conv And ConversionKind.InvolvesEnumTypeConversions)
End If
' partially handles cases: A.4, B.3 and B.4
conv = ClassifyDirectCastConversion(dst, src, useSiteDiagnostics)
If IsWideningConversion(conv) Then
Debug.Assert((conv And ConversionKind.VarianceConversionAmbiguity) = 0)
' Since NotInheritable classes cannot be inherited, more conversion possibilities
' could be rules out at compiler time if the NotInheritable class or any of its
' base can never be used as a type argument for this type parameter during type
' instantiation.
'
' partially handles cases: B.5 and B.6
'
If sourceKind = SymbolKind.TypeParameter AndAlso
(dst.TypeKind <> TypeKind.Class OrElse DirectCast(dst, NamedTypeSymbol).IsNotInheritable) AndAlso
Not ClassOrBasesSatisfyConstraints(dst, DirectCast(source, TypeParameterSymbol), useSiteDiagnostics) Then
Return Nothing 'ConversionKind.NoConversion
End If
Return ConversionKind.Narrowing Or (conv And ConversionKind.InvolvesEnumTypeConversions)
End If
' No conversion ever possible
Return Nothing 'ConversionKind.NoConversion
End Function
Private Shared Function ClassOrBasesSatisfyConstraints([class] As TypeSymbol, typeParam As TypeParameterSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As Boolean
Dim candidate As TypeSymbol = [class]
While candidate IsNot Nothing
If ConstraintsHelper.CheckConstraints(constructedSymbol:=Nothing,
substitution:=Nothing,
typeParameter:=typeParam,
typeArgument:=candidate,
diagnosticsBuilder:=Nothing,
useSiteDiagnostics:=useSiteDiagnostics) Then
Return True
End If
candidate = candidate.BaseTypeWithDefinitionUseSiteDiagnostics(useSiteDiagnostics)
End While
Return False
End Function
Private Shared Function GetNonInterfaceTypeConstraintOrSelf(type As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As TypeSymbol
If type.Kind = SymbolKind.TypeParameter Then
Dim typeParameter = DirectCast(type, TypeParameterSymbol)
If typeParameter.HasValueTypeConstraint Then
' This method returns System.ValueType if the type parameter has a 'Structure'
' constraint, even if there is a more specific constraint type. We could return
' typeParameter.GetNonInterfaceConstraint(), if not Nothing, but that would be
' a breaking change from Dev10. Specifically, in the following, "TypeOf _1 Is U2"
' would be reported (correctly) as an error ("BC31430: Expression of type 'U1'
' can never be of type 'U2'"). Dev10 does not report an error in this case.
'
' Public Overrides Sub M(Of U1 As {Structure, S1}, U2 As {Structure, S2})(_1 As U1)
' If TypeOf _1 Is U2 Then
' End If
' End Sub
Dim valueType = typeParameter.ContainingAssembly.GetSpecialType(SpecialType.System_ValueType)
Return If(valueType.Kind = SymbolKind.ErrorType, Nothing, valueType)
End If
Return typeParameter.GetNonInterfaceConstraint(useSiteDiagnostics)
End If
Return type
End Function
''' <summary>
''' This function classifies user-defined conversions between two types.
''' </summary>
''' <param name="source"></param>
''' <param name="destination"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Shared Function ClassifyUserDefinedConversion(source As TypeSymbol, destination As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As KeyValuePair(Of ConversionKind, MethodSymbol)
Debug.Assert(source IsNot Nothing)
Debug.Assert(destination IsNot Nothing)
Debug.Assert(source.Kind <> SymbolKind.ErrorType)
Debug.Assert(destination.Kind <> SymbolKind.ErrorType)
' ClassifyUserDefinedConversion is the only method that allows the source to be an ArrayLiteralTypeSymbol.
If IsInterfaceType(source) OrElse
IsInterfaceType(destination) OrElse
Not (source.CanContainUserDefinedOperators(useSiteDiagnostics) OrElse destination.CanContainUserDefinedOperators(useSiteDiagnostics)) Then
Return Nothing 'ConversionKind.NoConversion
End If
Return OverloadResolution.ResolveUserDefinedConversion(source, destination, useSiteDiagnostics)
End Function
''' <summary>
''' This function classifies user-defined conversions.
''' </summary>
''' <param name="source"></param>
''' <param name="destination"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Shared Function ClassifyUserDefinedConversion(source As BoundExpression, destination As TypeSymbol, binder As Binder, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As KeyValuePair(Of ConversionKind, MethodSymbol)
Debug.Assert(source IsNot Nothing)
Debug.Assert(destination IsNot Nothing)
Debug.Assert(destination.Kind <> SymbolKind.ErrorType)
Dim sourceType As TypeSymbol = source.Type
If sourceType Is Nothing Then
source = source.GetMostEnclosedParenthesizedExpression()
sourceType = If(source.Kind <> BoundKind.ArrayLiteral, source.Type, New ArrayLiteralTypeSymbol(DirectCast(source, BoundArrayLiteral)))
End If
Debug.Assert(sourceType IsNot Nothing)
Debug.Assert(sourceType.Kind <> SymbolKind.ErrorType)
Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = ClassifyUserDefinedConversion(sourceType, destination, useSiteDiagnostics)
If NoConversion(conv.Key) Then
Return conv
End If
If IsNarrowingConversion(conv.Key) Then
' Conversion between types can exist, but it might still be unsupported due to numeric overflow detected, etc.
Dim userDefinedInputType = conv.Value.Parameters(0).Type
Dim inConversion As ConversionKind
If (source.Kind <> BoundKind.ArrayLiteral) Then
inConversion = ClassifyPredefinedConversion(source, userDefinedInputType, binder, useSiteDiagnostics)
Else
inConversion = ClassifyArrayLiteralConversion(DirectCast(source, BoundArrayLiteral), userDefinedInputType, binder, useSiteDiagnostics)
End If
If NoConversion(inConversion) Then
Debug.Assert(FailedDueToNumericOverflow(inConversion))
' When we classify user-defined conversion from array literal, we are using the array literal
' rather than its inferred type and failure due to a numeric overflow should be detected then
' and ClassifyUserDefinedConversion should return NoConversion.
Debug.Assert(source.Kind <> BoundKind.ArrayLiteral)
If FailedDueToNumericOverflow(inConversion) Then
' Preserve the fact of numeric overflow.
conv = New KeyValuePair(Of ConversionKind, MethodSymbol)((conv.Key And Not ConversionKind.Narrowing) Or
(inConversion And ConversionKind.FailedDueToNumericOverflowMask),
conv.Value)
Debug.Assert(NoConversion(conv.Key))
Return conv
End If
Return Nothing
End If
' Need to keep track of the fact that narrowing is from numeric constant.
If (inConversion And ConversionKind.InvolvesNarrowingFromNumericConstant) <> 0 AndAlso
OverloadResolution.IsWidening(conv.Value) AndAlso
IsWideningConversion(ClassifyPredefinedConversion(conv.Value.ReturnType, destination, useSiteDiagnostics)) Then
Dim newConv As ConversionKind = conv.Key Or ConversionKind.InvolvesNarrowingFromNumericConstant
If IsWideningConversion(inConversion) Then
' Treat the whole conversion as widening.
newConv = (newConv And Not ConversionKind.Narrowing) Or ConversionKind.Widening
End If
conv = New KeyValuePair(Of ConversionKind, MethodSymbol)(newConv, conv.Value)
End If
End If
Return conv
End Function
''' <summary>
''' This function classifies all intrinsic language conversions, such as inheritance,
''' implementation, array covariance, and conversions between intrinsic types.
''' </summary>
Public Shared Function ClassifyPredefinedConversion(source As TypeSymbol, destination As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ConversionKind
Debug.Assert(source IsNot Nothing)
Debug.Assert(destination IsNot Nothing)
Debug.Assert(source.Kind <> SymbolKind.ErrorType)
Debug.Assert(Not TypeOf source Is ArrayLiteralTypeSymbol)
Debug.Assert(destination.Kind <> SymbolKind.ErrorType)
' Try using the short-circuit "fast-conversion" path.
Dim fastConversion = FastClassifyPredefinedConversion(source, destination)
If fastConversion.HasValue Then
Return fastConversion.Value
End If
Return ClassifyPredefinedConversionSlow(source, destination, useSiteDiagnostics)
End Function
Private Shared Function ClassifyPredefinedConversionSlow(source As TypeSymbol, destination As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ConversionKind
Dim result As ConversionKind
'Identity/Default conversions
result = ClassifyIdentityConversion(source, destination)
If ConversionExists(result) Then
Return result
End If
'Reference conversions
result = ClassifyReferenceConversion(source, destination, varianceCompatibilityClassificationDepth:=0, useSiteDiagnostics:=useSiteDiagnostics)
If ConversionExists(result) Then
Return AddDelegateRelaxationInformationForADelegate(source, destination, result)
End If
'Anonymous Delegate conversions
result = ClassifyAnonymousDelegateConversion(source, destination, useSiteDiagnostics)
If ConversionExists(result) Then
Return result
End If
'Array conversions
result = ClassifyArrayConversion(source, destination, varianceCompatibilityClassificationDepth:=0, useSiteDiagnostics:=useSiteDiagnostics)
If ConversionExists(result) Then
Return result
End If
'Tuple conversions
result = ClassifyTupleConversion(source, destination, useSiteDiagnostics)
If ConversionExists(result) Then
Return result
End If
'Value Type conversions
result = ClassifyValueTypeConversion(source, destination, useSiteDiagnostics)
If ConversionExists(result) Then
Return result
End If
'Nullable Value Type conversions
result = ClassifyNullableConversion(source, destination, useSiteDiagnostics)
If ConversionExists(result) Then
Return result
End If
'String conversions
result = ClassifyStringConversion(source, destination)
If ConversionExists(result) Then
Return result
End If
'Type Parameter conversions
result = ClassifyTypeParameterConversion(source, destination, varianceCompatibilityClassificationDepth:=0, useSiteDiagnostics:=useSiteDiagnostics)
Return AddDelegateRelaxationInformationForADelegate(source, destination, result)
End Function
Private Shared Function AddDelegateRelaxationInformationForADelegate(source As TypeSymbol, destination As TypeSymbol, convKind As ConversionKind) As ConversionKind
Debug.Assert((convKind And ConversionKind.DelegateRelaxationLevelMask) = 0)
' Dev10#703313: for e.g. Func(Of String)->Func(Of Object) we have to record it as DelegateRelaxationLevelWidening.
' for e.g. Func(Of String)->Object we have to record it as DelegateRelaxationLevelWideningToNonLambda
If source.IsDelegateType() Then
convKind = convKind And (Not ConversionKind.DelegateRelaxationLevelMask)
If Not ConversionExists(convKind) Then
Return convKind Or ConversionKind.DelegateRelaxationLevelInvalid
ElseIf IsWideningConversion(convKind) Then
If IsIdentityConversion(convKind) Then
Return convKind
ElseIf Not destination.IsDelegateType() OrElse destination.IsStrictSupertypeOfConcreteDelegate() Then
Return convKind Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda
Else
Return convKind Or ConversionKind.DelegateRelaxationLevelWidening
End If
Else
Debug.Assert(IsNarrowingConversion(convKind))
Return convKind Or ConversionKind.DelegateRelaxationLevelNarrowing
End If
End If
Return convKind
End Function
Private Shared Function ClassifyIdentityConversion(source As TypeSymbol, destination As TypeSymbol) As ConversionKind
'§8.8 Widening Conversions
'Identity/Default conversions
'• From a type to itself.
'• From an anonymous delegate type generated for a lambda method reclassification to any delegate type with an identical signature.
'From a type to itself
If source.IsSameTypeIgnoringCustomModifiers(destination) Then
Return ConversionKind.Identity
End If
'TODO: From an anonymous delegate type generated for a lambda method reclassification to any delegate type with an identical signature.
Return Nothing 'ConversionKind.NoConversion
End Function
Private Shared Function ClassifyReferenceConversion(
source As TypeSymbol,
destination As TypeSymbol,
varianceCompatibilityClassificationDepth As Integer,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As ConversionKind
'§8.8 Widening Conversions
'• From a reference type to a base type.
'• From a reference type to an interface type, provided that the type
' implements the interface or a variant compatible interface.
'• From an interface type to Object.
'• From an interface type to a variant compatible interface type.
'• From a delegate type to a variant compatible delegate type.
'§8.9 Narrowing Conversions
'• From a reference type to a more derived type.
'• From a class type to an interface type, provided the class type does not implement
' the interface type or an interface type variant compatible with it.
'• From an interface type to a class type.
'• From an interface type to another interface type, provided there is no inheritance
' relationship between the two types and provided they are not variant compatible.
If source.SpecialType = SpecialType.System_Void OrElse destination.SpecialType = SpecialType.System_Void Then
'CLR has nothing to say about conversions of these things.
Return Nothing 'ConversionKind.NoConversion
End If
Dim srcIsClassType As Boolean
Dim srcIsDelegateType As Boolean
Dim srcIsInterfaceType As Boolean
Dim srcIsArrayType As Boolean
Dim dstIsClassType As Boolean
Dim dstIsDelegateType As Boolean
Dim dstIsInterfaceType As Boolean
Dim dstIsArrayType As Boolean
If Not Conversions.ClassifyAsReferenceType(source, srcIsClassType, srcIsDelegateType, srcIsInterfaceType, srcIsArrayType) OrElse
Not Conversions.ClassifyAsReferenceType(destination, dstIsClassType, dstIsDelegateType, dstIsInterfaceType, dstIsArrayType) Then
Return Nothing 'ConversionKind.NoConversion
End If
If destination.SpecialType = SpecialType.System_Object Then
'From an interface type to Object.
'From a reference type to a base type (shortcut).
Return ConversionKind.WideningReference
End If
If srcIsInterfaceType Then
If dstIsClassType Then
'From an interface type to a class type.
Return ConversionKind.NarrowingReference
ElseIf dstIsArrayType Then
' !!! VB spec doesn't mention this explicitly, but
Dim conv As ConversionKind = ClassifyReferenceConversionFromArrayToAnInterface(destination, source, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
If NoConversion(conv) Then
Return Nothing 'ConversionKind.NoConversion
End If
' Possibly dropping ConversionKind.VarianceConversionAmbiguity because it is not
' the only reason for the narrowing.
Return ConversionKind.NarrowingReference Or (conv And ConversionKind.InvolvesEnumTypeConversions)
End If
End If
If dstIsInterfaceType Then
Debug.Assert(srcIsInterfaceType OrElse srcIsClassType OrElse srcIsArrayType)
If (srcIsInterfaceType OrElse srcIsClassType) Then
Dim conv As ConversionKind = ToInterfaceConversionClassifier.ClassifyConversionToVariantCompatibleInterface(DirectCast(source, NamedTypeSymbol),
DirectCast(destination, NamedTypeSymbol),
varianceCompatibilityClassificationDepth,
useSiteDiagnostics)
If ConversionExists(conv) Then
'From an interface type to a variant compatible interface type.
'From a reference type to an interface type, provided that the type implements the interface or a variant compatible interface.
Debug.Assert((conv And Not (ConversionKind.Widening Or ConversionKind.Narrowing Or
ConversionKind.InvolvesEnumTypeConversions Or
ConversionKind.VarianceConversionAmbiguity)) = 0)
Return conv Or ConversionKind.Reference
End If
'From a class type to an interface type, provided the class type does not implement
'the interface type or an interface type variant compatible with it.
'From an interface type to another interface type, provided there is no inheritance
'relationship between the two types and provided they are not variant compatible.
Return ConversionKind.NarrowingReference
ElseIf srcIsArrayType Then
' !!! Spec doesn't mention this conversion explicitly.
Return ClassifyReferenceConversionFromArrayToAnInterface(source, destination, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
End If
Else
Debug.Assert(dstIsClassType OrElse dstIsArrayType)
If (srcIsClassType OrElse srcIsArrayType) Then
If dstIsClassType AndAlso IsDerivedFrom(source, destination, useSiteDiagnostics) Then
'From a reference type to a base type.
Return ConversionKind.WideningReference
ElseIf srcIsClassType AndAlso IsDerivedFrom(destination, source, useSiteDiagnostics) Then
'From a reference type to a more derived type.
Return ConversionKind.NarrowingReference
ElseIf srcIsDelegateType AndAlso dstIsDelegateType Then
'From a delegate type to a variant compatible delegate type.
Dim conv As ConversionKind = ClassifyConversionToVariantCompatibleDelegateType(DirectCast(source, NamedTypeSymbol),
DirectCast(destination, NamedTypeSymbol),
varianceCompatibilityClassificationDepth,
useSiteDiagnostics)
If ConversionExists(conv) Then
Debug.Assert((conv And Not (ConversionKind.Widening Or ConversionKind.Narrowing Or
ConversionKind.InvolvesEnumTypeConversions Or
ConversionKind.NarrowingDueToContraVarianceInDelegate)) = 0)
Return conv Or ConversionKind.Reference
ElseIf (conv And ConversionKind.MightSucceedAtRuntime) <> 0 Then
Return ConversionKind.MightSucceedAtRuntime
End If
End If
End If
End If
Return Nothing 'ConversionKind.NoConversion
End Function
Private Shared Function ClassifyReferenceConversionFromArrayToAnInterface(
source As TypeSymbol,
destination As TypeSymbol,
varianceCompatibilityClassificationDepth As Integer,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As ConversionKind
Debug.Assert(source IsNot Nothing AndAlso Conversions.IsArrayType(source))
Debug.Assert(destination IsNot Nothing AndAlso Conversions.IsInterfaceType(destination))
'Check interfaces implemented by System.Array first.
Dim base = source.BaseTypeWithDefinitionUseSiteDiagnostics(useSiteDiagnostics)
If base IsNot Nothing Then
If Not base.IsErrorType() AndAlso base.TypeKind = TypeKind.Class AndAlso
IsWideningConversion(ClassifyDirectCastConversion(base, destination, useSiteDiagnostics)) Then
'From a reference type to an interface type, provided that the type implements the interface or a variant compatible interface.
Return ConversionKind.WideningReference
End If
End If
Dim array = DirectCast(source, ArrayTypeSymbol)
'For one-dimensional arrays, if the target interface is IList(Of U) or ICollection(Of U) or IEnumerable(Of U),
'look for any conversions that start with array covariance T()->U()
'and then have a single array-generic conversion step U()->IList/ICollection/IEnumerable(Of U)
If Not array.IsSZArray Then
Return Nothing 'ConversionKind.NoConversion
End If
Dim dstUnderlying = DirectCast(destination.OriginalDefinition, NamedTypeSymbol)
If dstUnderlying Is destination OrElse dstUnderlying.Kind = SymbolKind.ErrorType Then
Return Nothing 'ConversionKind.NoConversion
End If
Dim dstUnderlyingSpecial = dstUnderlying.SpecialType
If dstUnderlyingSpecial <> SpecialType.System_Collections_Generic_IList_T AndAlso
dstUnderlyingSpecial <> SpecialType.System_Collections_Generic_ICollection_T AndAlso
dstUnderlyingSpecial <> SpecialType.System_Collections_Generic_IEnumerable_T AndAlso
dstUnderlyingSpecial <> SpecialType.System_Collections_Generic_IReadOnlyList_T AndAlso
dstUnderlyingSpecial <> SpecialType.System_Collections_Generic_IReadOnlyCollection_T Then
Return Nothing 'ConversionKind.NoConversion
End If
Dim dstUnderlyingElement = DirectCast(destination, NamedTypeSymbol).TypeArgumentsWithDefinitionUseSiteDiagnostics(useSiteDiagnostics)(0)
If dstUnderlyingElement.Kind = SymbolKind.ErrorType Then
Return Nothing 'ConversionKind.NoConversion
End If
Dim arrayElement = array.ElementType
If arrayElement.Kind = SymbolKind.ErrorType Then
Return Nothing 'ConversionKind.NoConversion
End If
If arrayElement.IsSameTypeIgnoringCustomModifiers(dstUnderlyingElement) Then
Return ConversionKind.WideningReference
End If
Dim conv As ConversionKind = ClassifyArrayConversionBasedOnElementTypes(arrayElement, dstUnderlyingElement, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
If IsWideningConversion(conv) Then
Debug.Assert((conv And ConversionKind.VarianceConversionAmbiguity) = 0)
Return ConversionKind.WideningReference Or (conv And ConversionKind.InvolvesEnumTypeConversions)
ElseIf IsNarrowingConversion(conv) Then
Return ConversionKind.NarrowingReference Or
(conv And (ConversionKind.InvolvesEnumTypeConversions Or ConversionKind.VarianceConversionAmbiguity))
End If
' Dev10 #831390 Closely match Orcas behavior of this function to never return ConversionError.
' Note, because of this we don't need to do anything special about ConversionKind.MightSucceedAtRuntime bit,
' since we are returning narrowing anyway.
Return ConversionKind.NarrowingReference
End Function
Public Shared Function HasWideningDirectCastConversionButNotEnumTypeConversion(source As TypeSymbol, destination As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As Boolean
If source.IsErrorType() OrElse destination.IsErrorType Then
Return source.IsSameTypeIgnoringCustomModifiers(destination)
End If
Dim conv As ConversionKind = ClassifyDirectCastConversion(source, destination, useSiteDiagnostics)
If Conversions.IsWideningConversion(conv) AndAlso
(conv And ConversionKind.InvolvesEnumTypeConversions) = 0 Then
Return True
End If
Return False
End Function
Private Shared Function ClassifyConversionToVariantCompatibleDelegateType(
source As NamedTypeSymbol,
destination As NamedTypeSymbol,
varianceCompatibilityClassificationDepth As Integer,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As ConversionKind
Debug.Assert(source IsNot Nothing AndAlso Conversions.IsDelegateType(source))
Debug.Assert(destination IsNot Nothing AndAlso Conversions.IsDelegateType(destination))
Const validBits As ConversionKind = (ConversionKind.Widening Or ConversionKind.Narrowing Or
ConversionKind.InvolvesEnumTypeConversions Or
ConversionKind.VarianceConversionAmbiguity Or
ConversionKind.MightSucceedAtRuntime Or
ConversionKind.NarrowingDueToContraVarianceInDelegate)
Dim forwardConv As ConversionKind = ClassifyImmediateVarianceCompatibility(source, destination, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
Debug.Assert((forwardConv And Not validBits) = 0)
If ConversionExists(forwardConv) Then
Return forwardConv
End If
Dim backwardConv As ConversionKind = ClassifyImmediateVarianceCompatibility(destination, source, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
Debug.Assert((backwardConv And Not validBits) = 0)
If ConversionExists(backwardConv) Then
Return (backwardConv And Not (ConversionKind.Widening Or ConversionKind.NarrowingDueToContraVarianceInDelegate)) Or ConversionKind.Narrowing
End If
Return ((forwardConv Or backwardConv) And ConversionKind.MightSucceedAtRuntime)
End Function
''' <summary>
''' Helper structure to classify conversions from named types to interfaces
''' in accumulating fashion.
''' </summary>
Private Structure ToInterfaceConversionClassifier
Private _conv As ConversionKind
Private _match As NamedTypeSymbol
Public ReadOnly Property Result As ConversionKind
Get
If IsIdentityConversion(_conv) Then
Return ConversionKind.Widening
End If
Debug.Assert(_conv = Nothing OrElse
(_match.HasVariance() AndAlso
(_conv = ConversionKind.Widening OrElse
_conv = ConversionKind.Narrowing OrElse
_conv = (ConversionKind.Widening Or ConversionKind.InvolvesEnumTypeConversions) OrElse
_conv = (ConversionKind.Narrowing Or ConversionKind.InvolvesEnumTypeConversions) OrElse
_conv = (ConversionKind.Narrowing Or ConversionKind.VarianceConversionAmbiguity))))
Return _conv
End Get
End Property
<Conditional("DEBUG")>
Public Sub AssertFoundIdentity()
Debug.Assert(IsIdentityConversion(_conv))
End Sub
Public Shared Function ClassifyConversionToVariantCompatibleInterface(
source As NamedTypeSymbol,
destination As NamedTypeSymbol,
varianceCompatibilityClassificationDepth As Integer,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As ConversionKind
Dim helper As ToInterfaceConversionClassifier = Nothing
helper.AccumulateConversionClassificationToVariantCompatibleInterface(source, destination, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
Return helper.Result
End Function
''' <summary>
''' Accumulates classification information about conversion to interface.
''' Returns True when classification gets promoted to Identity, this method should not
''' be called after that.
''' </summary>
Public Function AccumulateConversionClassificationToVariantCompatibleInterface(
source As NamedTypeSymbol,
destination As NamedTypeSymbol,
varianceCompatibilityClassificationDepth As Integer,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As Boolean
Debug.Assert(source IsNot Nothing AndAlso
(Conversions.IsInterfaceType(source) OrElse Conversions.IsClassType(source) OrElse Conversions.IsValueType(source)))
Debug.Assert(destination IsNot Nothing AndAlso Conversions.IsInterfaceType(destination))
Debug.Assert(Not IsIdentityConversion(_conv))
If IsIdentityConversion(_conv) Then
Return True
End If
If Conversions.IsInterfaceType(source) Then
ClassifyInterfaceImmediateVarianceCompatibility(source, destination, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
Debug.Assert(Not IsIdentityConversion(_conv))
End If
For Each [interface] In source.AllInterfacesWithDefinitionUseSiteDiagnostics(useSiteDiagnostics)
If [interface].IsErrorType() Then
Continue For
End If
If ClassifyInterfaceImmediateVarianceCompatibility([interface], destination, varianceCompatibilityClassificationDepth, useSiteDiagnostics) Then
Return True
End If
Next
Return False
End Function
''' <summary>
''' Returns when classification gets promoted to Identity.
''' </summary>
Private Function ClassifyInterfaceImmediateVarianceCompatibility(
source As NamedTypeSymbol,
destination As NamedTypeSymbol,
varianceCompatibilityClassificationDepth As Integer,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As Boolean
Debug.Assert(Conversions.IsInterfaceType(source) AndAlso Conversions.IsInterfaceType(destination))
Debug.Assert(Not IsIdentityConversion(_conv))
Dim addConv As ConversionKind = ClassifyImmediateVarianceCompatibility(source, destination, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
Debug.Assert((addConv And ConversionKind.NarrowingDueToContraVarianceInDelegate) = 0)
If (addConv And ConversionKind.MightSucceedAtRuntime) <> 0 Then
' Treat conversions that possibly might succeed at runtime as at least narrowing.
addConv = ConversionKind.Narrowing Or (addConv And (ConversionKind.InvolvesEnumTypeConversions Or ConversionKind.VarianceConversionAmbiguity))
End If
Const validNonidentityBits As ConversionKind = (ConversionKind.Widening Or ConversionKind.Narrowing Or
ConversionKind.InvolvesEnumTypeConversions Or
ConversionKind.VarianceConversionAmbiguity)
Debug.Assert(IsIdentityConversion(addConv) OrElse (addConv And Not validNonidentityBits) = 0)
If ConversionExists(addConv) Then
If IsIdentityConversion(addConv) Then
_conv = ConversionKind.Identity
Return True
End If
If _match IsNot Nothing Then
Debug.Assert(ConversionExists(_conv))
If (_conv And ConversionKind.VarianceConversionAmbiguity) <> 0 Then
Debug.Assert(IsNarrowingConversion(_conv))
ElseIf Not _match.IsSameTypeIgnoringCustomModifiers(source) Then
' ambiguity
_conv = ConversionKind.Narrowing Or ConversionKind.VarianceConversionAmbiguity
Else
Debug.Assert(_conv = (addConv And validNonidentityBits))
End If
Else
_match = source
_conv = (addConv And validNonidentityBits)
End If
End If
Return False
End Function
End Structure
Private Shared Function ClassifyImmediateVarianceCompatibility(
source As NamedTypeSymbol,
destination As NamedTypeSymbol,
varianceCompatibilityClassificationDepth As Integer,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As ConversionKind
Debug.Assert(Conversions.IsInterfaceType(source) OrElse Conversions.IsDelegateType(source))
Debug.Assert(Conversions.IsInterfaceType(destination) OrElse Conversions.IsDelegateType(destination))
Debug.Assert(Conversions.IsInterfaceType(source) = Conversions.IsInterfaceType(destination))
If Not source.OriginalDefinition.IsSameTypeIgnoringCustomModifiers(destination.OriginalDefinition) Then
Return Nothing ' Incompatible.
End If
' *****************
' (*) STACK OVERFLOW
' There are some computations for variance that will result in an infinite recursion
' e.g. the conversion C -> N(Of C) given "Interface N(Of In X)" and "Class C : Implements N(Of N(Of C))"
' The CLR spec is recursive on this topic, hence ambiguous, so it's not known whether there
' is a conversion. Theoretically we should detect such cases by maintaining a set of all
' conversion-pairs (SourceType,TargetType) that we've visited so far in our quest to tell whether
' a given conversion is possible: if we revisit a given pair, then we've encountered an ambiguity.
' But maintaining such a set is too onerous. So instead we keep a simple "RecursionCount".
' Once that reaches above a certain arbitrary limit, we'll return "ConversionNarrowing". That's
' our way of saying that the conversion might be allowed by the CLR, or it might not, but we're not
' sure. Note that even though we use an arbitrary limit, we're still typesafe.
Const depthLimit As Integer = 20
If varianceCompatibilityClassificationDepth > depthLimit Then
Return ConversionKind.Narrowing
End If
varianceCompatibilityClassificationDepth += 1
' CLI I $8.7
' Given an arbitrary generic type signature X(Of X1,...,Xn), a value of type
' X(Of U1,...,Un) can be stored in a location of type X(Of T1,...,Tn) when all
' the following hold:
' * For each "in Xi" where Ti is not a value-type or generic parameter, we
' require that a value of type Ti can be stored in a location Ui. [Note: since
' Ti is not a value-type or generic parameter, it must be a reference type; and
' references can only be stored in locations that hold references; so we know that
' Ui is also a reference type.]
' * For each "out Xi" where Ti is not a value-type or generic parameter, we require
' that a value of type Ui can be stored in a location of type Ti. [Note: reference
' locations can only ever hold values that are references, so we know that Ui is
' also a reference type.]
' * For each "Xi" neither in nor out where Ti is not a value-type or generic parameter,
' we require that Ti must be the exact same type as Ui. [Note: therefore Ui is
' also a reference type.]
' * For each "Xi" where Ti is a value-type or generic parameter, we require that
' Ti must be the exact same type as Ui.
'
' e.g. a class that implements IReadOnly(Of Mammal) can be stored in a location
' that holds IReadOnly(Of Animal), by the second bullet point, given IReadOnly(Of Out T),
' since a Mammal can be stored in an Animal location.
' but IReadOnly(Of Car) cannot be stored, since a Car cannot be stored in an Animal location.
Dim conversionExists As Boolean = True
Dim identity As Boolean = True
Dim atMostNarrowingDueToContraVarianceInDelegate As Boolean = False
Dim involvesEnumTypeConversions As ConversionKind = Nothing
Dim varianceConversionAmbiguity As ConversionKind = ConversionKind.VarianceConversionAmbiguity
Dim classifyingInterfaceConversions As Boolean = Conversions.IsInterfaceType(source)
Do
Dim typeParameters As ImmutableArray(Of TypeParameterSymbol) = source.TypeParameters
Dim sourceArguments As ImmutableArray(Of TypeSymbol) = source.TypeArgumentsWithDefinitionUseSiteDiagnostics(useSiteDiagnostics)
Dim destinationArguments As ImmutableArray(Of TypeSymbol) = destination.TypeArgumentsWithDefinitionUseSiteDiagnostics(useSiteDiagnostics)
For i As Integer = 0 To typeParameters.Length - 1
Dim sourceArg As TypeSymbol = sourceArguments(i)
Dim destinationArg As TypeSymbol = destinationArguments(i)
If sourceArg.IsSameTypeIgnoringCustomModifiers(destinationArg) Then
Continue For
End If
If sourceArg.IsErrorType() OrElse destinationArg.IsErrorType() Then
Return Nothing ' Incompatible.
End If
If sourceArg.IsValueType OrElse destinationArg.IsValueType Then
Return Nothing ' Incompatible.
End If
identity = False
Dim conv As ConversionKind = Nothing
Select Case typeParameters(i).Variance
Case VarianceKind.Out
conv = Classify_Reference_Array_TypeParameterConversion(sourceArg, destinationArg, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
If Not classifyingInterfaceConversions AndAlso IsNarrowingConversion(conv) AndAlso
(conv And ConversionKind.NarrowingDueToContraVarianceInDelegate) <> 0 Then
' Dev10 #820752
atMostNarrowingDueToContraVarianceInDelegate = True
varianceConversionAmbiguity = Nothing
Continue For
End If
Case VarianceKind.In
conv = Classify_Reference_Array_TypeParameterConversion(destinationArg, sourceArg, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
If Not classifyingInterfaceConversions AndAlso Not IsWideningConversion(conv) AndAlso
destinationArg.IsReferenceType AndAlso sourceArg.IsReferenceType Then
' Dev10 #820752 For delegates, treat conversion as narrowing if both type arguments are reference types.
atMostNarrowingDueToContraVarianceInDelegate = True
varianceConversionAmbiguity = Nothing
Continue For
End If
Case Else
Return Nothing ' Incompatible.
End Select
If NoConversion(conv) Then
' Do not give up yet if conversion might succeed at runtime and thus might cause an ambiguity.
If (conv And ConversionKind.MightSucceedAtRuntime) = 0 Then
Return Nothing ' Incompatible.
End If
conversionExists = False
varianceConversionAmbiguity = Nothing
Else
If (conv And ConversionKind.InvolvesEnumTypeConversions) <> 0 Then
involvesEnumTypeConversions = ConversionKind.InvolvesEnumTypeConversions
End If
If IsNarrowingConversion(conv) Then
conversionExists = False
varianceConversionAmbiguity = varianceConversionAmbiguity And conv
Else
Debug.Assert(Not IsIdentityConversion(conv))
Debug.Assert((conv And ConversionKind.VarianceConversionAmbiguity) = 0)
End If
End If
Next
source = source.ContainingType
destination = destination.ContainingType
Loop While source IsNot Nothing
Debug.Assert((Not atMostNarrowingDueToContraVarianceInDelegate AndAlso involvesEnumTypeConversions = 0 AndAlso conversionExists) OrElse Not identity)
If identity Then
Return ConversionKind.Identity
ElseIf Not conversionExists Then
' Since we didn't return earlier, conversion might succeed at runtime
Return ConversionKind.MightSucceedAtRuntime Or varianceConversionAmbiguity Or involvesEnumTypeConversions
ElseIf atMostNarrowingDueToContraVarianceInDelegate Then
Debug.Assert(varianceConversionAmbiguity = Nothing)
Return ConversionKind.Narrowing Or ConversionKind.NarrowingDueToContraVarianceInDelegate Or involvesEnumTypeConversions
Else
Return ConversionKind.Widening Or involvesEnumTypeConversions
End If
End Function
Private Shared Function ClassifyAsReferenceType(
candidate As TypeSymbol,
ByRef isClassType As Boolean,
ByRef isDelegateType As Boolean,
ByRef isInterfaceType As Boolean,
ByRef isArrayType As Boolean
) As Boolean
Select Case candidate.TypeKind
Case TypeKind.Class,
TypeKind.Module
isClassType = True
isDelegateType = False
isInterfaceType = False
isArrayType = False
Case TypeKind.Delegate
isClassType = True
isDelegateType = True
isInterfaceType = False
isArrayType = False
Case TypeKind.Interface
isClassType = False
isDelegateType = False
isInterfaceType = True
isArrayType = False
Case TypeKind.Array
isClassType = False
isDelegateType = False
isInterfaceType = False
isArrayType = True
Case Else
isClassType = False
isDelegateType = False
isInterfaceType = False
isArrayType = False
Return False
End Select
Return True
End Function
Private Shared Function IsClassType(type As TypeSymbol) As Boolean
Dim typeKind = type.TypeKind
Return typeKind = TypeKind.Class OrElse typeKind = TypeKind.Module OrElse typeKind = TypeKind.Delegate
End Function
Private Shared Function IsValueType(type As TypeSymbol) As Boolean
Dim typeKind = type.TypeKind
Return typeKind = TypeKind.Enum OrElse typeKind = TypeKind.Structure
End Function
Private Shared Function IsDelegateType(type As TypeSymbol) As Boolean
Return type.TypeKind = TypeKind.Delegate
End Function
Private Shared Function IsArrayType(type As TypeSymbol) As Boolean
Return type.TypeKind = TypeKind.Array
End Function
Private Shared Function IsInterfaceType(type As TypeSymbol) As Boolean
Return type.IsInterfaceType()
End Function
''' <summary>
''' Returns true if and only if baseType is a base class of derivedType.
''' </summary>
''' <param name="derivedType">
''' Derived class type.
''' </param>
''' <param name="baseType">
''' Target base class type.
''' </param>
''' <returns></returns>
''' <remarks>
''' </remarks>
Public Shared Function IsDerivedFrom(derivedType As TypeSymbol, baseType As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As Boolean
Debug.Assert(derivedType IsNot Nothing AndAlso
(Conversions.IsClassType(derivedType) OrElse Conversions.IsArrayType(derivedType) OrElse Conversions.IsValueType(derivedType)))
Debug.Assert(baseType IsNot Nothing AndAlso Conversions.IsClassType(baseType))
Return baseType.IsBaseTypeOf(derivedType, useSiteDiagnostics)
End Function
Private Shared Function ClassifyAnonymousDelegateConversion(source As TypeSymbol, destination As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ConversionKind
'§8.8 Widening Conversions
'• From an anonymous delegate type generated for a lambda method reclassification to any wider delegate type.
'§8.9 Narrowing Conversions
'• From an anonymous delegate type generated for a lambda method reclassification to any narrower delegate type.
Debug.Assert(Not source.IsSameTypeIgnoringCustomModifiers(destination))
If source.IsAnonymousType AndAlso source.IsDelegateType() AndAlso destination.IsDelegateType() Then
Dim delegateInvoke As MethodSymbol = DirectCast(destination, NamedTypeSymbol).DelegateInvokeMethod
If delegateInvoke Is Nothing OrElse delegateInvoke.GetUseSiteErrorInfo() IsNot Nothing Then
Return Nothing ' No conversion
End If
Dim methodConversion As MethodConversionKind = ClassifyMethodConversionForLambdaOrAnonymousDelegate(delegateInvoke,
DirectCast(source, NamedTypeSymbol).DelegateInvokeMethod,
useSiteDiagnostics)
If Not IsDelegateRelaxationSupportedFor(methodConversion) Then
Return Nothing 'ConversionKind.NoConversion
End If
Dim additionalFlags As ConversionKind = DetermineDelegateRelaxationLevel(methodConversion)
If IsStubRequiredForMethodConversion(methodConversion) Then
additionalFlags = additionalFlags Or ConversionKind.NeedAStub
End If
' Note, intentional change in behavior from Dev10, using AddressOf semantics to detect narrowing.
' New behavior is more inline with the language spec:
' Section 8.4.2
' A compatible delegate type is any delegate type that can be created using a delegate creation
' expression with the anonymous delegate type's Invoke method as a parameter.
' As a result, "zero argument" relaxation is treated as narrowing conversion. Dev10 treats it as
' widening, but, with Option Strict On, reports a conversion error later.
If Conversions.IsNarrowingMethodConversion(methodConversion, isForAddressOf:=True) Then
Return ConversionKind.AnonymousDelegate Or ConversionKind.Narrowing Or additionalFlags
Else
Return ConversionKind.AnonymousDelegate Or ConversionKind.Widening Or additionalFlags
End If
End If
Return Nothing 'ConversionKind.NoConversion
End Function
Private Shared Function ClassifyArrayConversion(
source As TypeSymbol,
destination As TypeSymbol,
varianceCompatibilityClassificationDepth As Integer,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As ConversionKind
'§8.8 Widening Conversions
'• From an array type S with an element type SE to an array type T with an element type TE, provided all of the following are true:
' • S and T differ only in element type.
' • Both SE and TE are reference types or are type parameters known to be a reference type.
' • A widening reference, array, or type parameter conversion exists from SE to TE.
'• From an array type S with an enumerated element type SE to an array type T with an element type TE,
' provided all of the following are true:
' • S and T differ only in element type.
' • TE is the underlying type of SE.
'§8.9 Narrowing Conversions
'• From an array type S with an element type SE, to an array type T with an element type TE,
' provided that all of the following are true:
' • S and T differ only in element type.
' • Both SE and TE are reference types or are type parameters not known to be value types.
' • A narrowing reference, array, or type parameter conversion exists from SE to TE.
'• From an array type S with an element type SE to an array type T with an enumerated element type TE,
' provided all of the following are true:
' • S and T differ only in element type.
' • SE is the underlying type of TE.
If Not Conversions.IsArrayType(source) OrElse Not Conversions.IsArrayType(destination) Then
Return Nothing 'ConversionKind.NoConversion
End If
Dim srcArray = DirectCast(source, ArrayTypeSymbol)
Dim dstArray = DirectCast(destination, ArrayTypeSymbol)
If Not srcArray.HasSameShapeAs(dstArray) Then
Return Nothing 'ConversionKind.NoConversion
End If
Dim srcElem = srcArray.ElementType
Dim dstElem = dstArray.ElementType
If srcElem.Kind = SymbolKind.ErrorType OrElse dstElem.Kind = SymbolKind.ErrorType Then
Return Nothing 'ConversionKind.NoConversion
End If
Return ClassifyArrayConversionBasedOnElementTypes(srcElem, dstElem, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
End Function
Public Shared Function ClassifyArrayElementConversion(srcElem As TypeSymbol, dstElem As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ConversionKind
Dim result As ConversionKind
'Identity/Default conversions
result = ClassifyIdentityConversion(srcElem, dstElem)
If ConversionExists(result) Then
Return result
End If
Return ClassifyArrayConversionBasedOnElementTypes(srcElem, dstElem, varianceCompatibilityClassificationDepth:=0, useSiteDiagnostics:=useSiteDiagnostics)
End Function
Friend Shared Function Classify_Reference_Array_TypeParameterConversion(
srcElem As TypeSymbol,
dstElem As TypeSymbol,
varianceCompatibilityClassificationDepth As Integer,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As ConversionKind
Dim conv = ClassifyReferenceConversion(srcElem, dstElem, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
If NoConversion(conv) AndAlso (conv And ConversionKind.MightSucceedAtRuntime) = 0 Then
conv = ClassifyArrayConversion(srcElem, dstElem, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
If NoConversion(conv) AndAlso (conv And ConversionKind.MightSucceedAtRuntime) = 0 Then
conv = ClassifyTypeParameterConversion(srcElem, dstElem, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
Else
Debug.Assert(NoConversion(ClassifyTypeParameterConversion(srcElem, dstElem, varianceCompatibilityClassificationDepth, Nothing)))
End If
Else
Debug.Assert(NoConversion(ClassifyArrayConversion(srcElem, dstElem, varianceCompatibilityClassificationDepth, Nothing)))
Debug.Assert(NoConversion(ClassifyTypeParameterConversion(srcElem, dstElem, varianceCompatibilityClassificationDepth, Nothing)))
End If
Return conv
End Function
Private Shared Function ClassifyArrayConversionBasedOnElementTypes(
srcElem As TypeSymbol,
dstElem As TypeSymbol,
varianceCompatibilityClassificationDepth As Integer,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As ConversionKind
'§8.8 Widening Conversions
'• From an array type S with an element type SE to an array type T with an element type TE, provided all of the following are true:
' • S and T differ only in element type.
' • Both SE and TE are reference types or are type parameters known to be a reference type.
' • A widening reference, array, or type parameter conversion exists from SE to TE.
'• From an array type S with an enumerated element type SE to an array type T with an element type TE,
' provided all of the following are true:
' • S and T differ only in element type.
' • TE is the underlying type of SE.
'§8.9 Narrowing Conversions
'• From an array type S with an element type SE, to an array type T with an element type TE,
' provided that all of the following are true:
' • S and T differ only in element type.
' • Both SE and TE are reference types or are type parameters not known to be value types.
' • A narrowing reference, array, or type parameter conversion exists from SE to TE.
'• From an array type S with an element type SE to an array type T with an enumerated element type TE,
' provided all of the following are true:
' • S and T differ only in element type.
' • SE is the underlying type of TE.
'Shouldn't get here for identity conversion
Debug.Assert(Not srcElem.IsSameTypeIgnoringCustomModifiers(dstElem))
Dim srcElemIsValueType As Boolean = srcElem.IsValueType
Dim dstElemIsValueType As Boolean = dstElem.IsValueType
If Not srcElemIsValueType AndAlso Not dstElemIsValueType Then
Dim conv = Classify_Reference_Array_TypeParameterConversion(srcElem, dstElem, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
If IsWideningConversion(conv) Then
Debug.Assert((conv And ConversionKind.VarianceConversionAmbiguity) = 0)
If srcElem.IsReferenceType AndAlso dstElem.IsReferenceType Then
'Both SE and TE are reference types or are type parameters known to be a reference type.
'A widening reference, array, or type parameter conversion exists from SE to TE.
Return ConversionKind.WideningArray Or (conv And ConversionKind.InvolvesEnumTypeConversions)
ElseIf srcElem.Kind = SymbolKind.TypeParameter AndAlso
dstElem.Kind = SymbolKind.TypeParameter Then
' Important: We have widening conversion between two type parameters.
' This can happen only if srcElem is directly or indirectly constrained by dstElem.
If srcElem.IsReferenceType Then
Debug.Assert(Not dstElem.IsReferenceType)
'srcElem is constrained by dstElem and srcElem is a reference type.
'Therefore, we can infer that dstElem is known to be a reference type,
'assuming there are no conflicting constraints.
Debug.Assert(Not dstElemIsValueType) ' enforced by one of the outer "If"s
'Both SE and TE are reference types or are type parameters known to be a reference type.
'A widening reference, array, or type parameter conversion exists from SE to TE.
Return ConversionKind.WideningArray Or (conv And ConversionKind.InvolvesEnumTypeConversions)
ElseIf dstElem.IsReferenceType Then
'srcElem is constrained by dstElem
'srcElem is not known to be a reference type
'srcElem is not known to be a value type.
' !!! Spec doesn't mention this explicitly, but Dev10 compiler treats this
' !!! as narrowing conversion. BTW, it looks like C# compiler doesn't support this conversion.
Return ConversionKind.NarrowingArray Or (conv And ConversionKind.InvolvesEnumTypeConversions)
Else
'srcElem is constrained by dstElem
'Both are not known to be a reference type,
'both are not known to be a value type.
' !!! Spec doesn't mention this explicitly, but Dev10 compiler treats this
' !!! as narrowing conversion. BTW, it looks like C# compiler doesn't support this conversion.
Return ConversionKind.NarrowingArray Or (conv And ConversionKind.InvolvesEnumTypeConversions)
End If
ElseIf srcElem.Kind = SymbolKind.TypeParameter OrElse
dstElem.Kind = SymbolKind.TypeParameter Then
' One and only one is a type parameter
' !!! Spec doesn't mention this explicitly, but Dev10 compiler treats this
' !!! as narrowing conversion.
Return ConversionKind.NarrowingArray Or (conv And ConversionKind.InvolvesEnumTypeConversions)
End If
ElseIf IsNarrowingConversion(conv) Then
Debug.Assert(Not srcElemIsValueType AndAlso Not dstElemIsValueType)
'Both SE and TE are reference types or are type parameters not known to be value types.
'A narrowing reference, array, or type parameter conversion exists from SE to TE.
Return ConversionKind.NarrowingArray Or
(conv And (ConversionKind.InvolvesEnumTypeConversions Or ConversionKind.VarianceConversionAmbiguity))
ElseIf (conv And ConversionKind.MightSucceedAtRuntime) <> 0 Then
' Preserve the fact that conversion might succeed at runtime.
Return ConversionKind.MightSucceedAtRuntime
End If
Return Nothing 'ConversionKind.NoConversion
Else
' At least one of the elements is known to be a value type
Debug.Assert(srcElemIsValueType OrElse dstElemIsValueType)
If srcElemIsValueType Then
If dstElemIsValueType Then
Dim mightSucceedAtRuntime As ConversionKind = Nothing
If srcElem.Kind = SymbolKind.TypeParameter OrElse
dstElem.Kind = SymbolKind.TypeParameter Then
' Must be the same type if there is a conversion.
Dim conv = ClassifyTypeParameterConversion(srcElem, dstElem, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
Debug.Assert((conv And ConversionKind.VarianceConversionAmbiguity) = 0)
If IsWideningConversion(conv) Then
' !!! Spec doesn't mention this explicitly, but Dev10 compiler treats this
' !!! as widening conversion.
Return ConversionKind.WideningArray Or (conv And ConversionKind.InvolvesEnumTypeConversions)
ElseIf IsNarrowingConversion(conv) Then
' !!! Spec doesn't mention this explicitly, but Dev10 compiler treats this
' !!! as narrowing conversion.
Return ConversionKind.NarrowingArray Or (conv And ConversionKind.InvolvesEnumTypeConversions)
End If
If (conv And ConversionKind.MightSucceedAtRuntime) <> 0 Then
mightSucceedAtRuntime = ConversionKind.MightSucceedAtRuntime
End If
End If
Dim srcValueType As TypeSymbol = srcElem
Dim dstValueType As TypeSymbol = dstElem
If srcElem.Kind = SymbolKind.TypeParameter Then
Dim valueType = GetValueTypeConstraint(srcElem, useSiteDiagnostics)
If valueType IsNot Nothing Then
srcValueType = valueType
End If
End If
If dstElem.Kind = SymbolKind.TypeParameter Then
Dim valueType = GetValueTypeConstraint(dstElem, useSiteDiagnostics)
If valueType IsNot Nothing Then
dstValueType = valueType
End If
End If
Dim srcUnderlying As NamedTypeSymbol = GetNonErrorEnumUnderlyingType(srcValueType)
Dim dstUnderlying As NamedTypeSymbol = GetNonErrorEnumUnderlyingType(dstValueType)
'TODO:
' !!! The following logic is strange, it matches enums to enums and numeric types,
' !!! but it doesn't match numeric types to each other. Looks like an oversight
' !!! in Dev10 compiler. Follow the same logic for now.
If srcUnderlying IsNot Nothing Then
If IsNumericType(srcUnderlying) Then
If dstUnderlying IsNot Nothing Then
If srcUnderlying.Equals(dstUnderlying) Then
' !!! Spec doesn't mention this explicitly, but Dev10 supports narrowing conversion
' !!! between arrays of enums, as long as the underlying type is the same.
Return ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions
End If
ElseIf srcUnderlying.Equals(dstValueType) Then
'TE is the underlying type of SE.
If dstElem Is dstValueType Then
Return ConversionKind.WideningArray Or ConversionKind.InvolvesEnumTypeConversions
Else
' Dev10 degrades this to narrowing if dstElem is generic parameter
Return ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions
End If
End If
End If
ElseIf dstUnderlying IsNot Nothing Then
If IsNumericType(dstUnderlying) AndAlso dstUnderlying.Equals(srcValueType) Then
'SE is the underlying type of TE.
Return ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions
End If
End If
If mightSucceedAtRuntime = Nothing Then
' CLR spec $8.7 says that integral()->integral() is possible so long as they have the same bit size.
' It claims that bool is to be taken as the same size as int8/uint8, so allowing e.g. bool()->uint8().
' That isn't allowed in practice by the current CLR runtime, but since it's in the spec,
' we'll return "ConversionKind.MightSucceedAtRuntime" to mean that it might potentially possibly occur.
' Remember that we're in the business here of "OverestimateNarrowingConversions" after all.
Dim srcSize As Integer = ArrayElementBitSize(srcValueType)
If srcSize > 0 AndAlso srcSize = ArrayElementBitSize(dstValueType) Then
mightSucceedAtRuntime = ConversionKind.MightSucceedAtRuntime
End If
End If
Return mightSucceedAtRuntime
ElseIf dstElem.Kind = SymbolKind.TypeParameter AndAlso
Not dstElem.IsReferenceType Then
If srcElem.Kind = SymbolKind.TypeParameter Then
Dim conv = ClassifyTypeParameterConversion(srcElem, dstElem, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
If IsWideningConversion(conv) Then
' !!! Spec doesn't mention this explicitly, but Dev10 compiler treats this
' !!! as narrowing conversion.
Debug.Assert((conv And ConversionKind.VarianceConversionAmbiguity) = 0)
Return ConversionKind.NarrowingArray Or (conv And ConversionKind.InvolvesEnumTypeConversions)
End If
Debug.Assert(NoConversion(conv))
If (conv And ConversionKind.MightSucceedAtRuntime) <> 0 Then
Return ConversionKind.MightSucceedAtRuntime
End If
Return Nothing 'ConversionKind.NoConversion
ElseIf ArrayElementBitSize(srcElem) > 0 Then
Return ConversionKind.MightSucceedAtRuntime
End If
End If
ElseIf srcElem.Kind = SymbolKind.TypeParameter AndAlso Not srcElem.IsReferenceType Then
Debug.Assert(dstElemIsValueType)
If dstElem.Kind = SymbolKind.TypeParameter Then
Dim conv = ClassifyTypeParameterConversion(srcElem, dstElem, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
If IsNarrowingConversion(conv) Then
' !!! Spec doesn't mention this explicitly, but Dev10 compiler treats this
' !!! as narrowing conversion.
' Possibly dropping ConversionKind.VarianceConversionAmbiguity because it is not
' the only reason for the narrowing.
Return ConversionKind.NarrowingArray Or (conv And ConversionKind.InvolvesEnumTypeConversions)
End If
Debug.Assert(NoConversion(conv))
If (conv And ConversionKind.MightSucceedAtRuntime) <> 0 Then
Return ConversionKind.MightSucceedAtRuntime
End If
ElseIf ArrayElementBitSize(dstElem) > 0 Then
Return ConversionKind.MightSucceedAtRuntime
End If
End If
Return Nothing 'ConversionKind.NoConversion
End If
End Function
Private Shared Function ArrayElementBitSize(type As TypeSymbol) As Integer
Select Case type.GetEnumUnderlyingTypeOrSelf().SpecialType
Case SpecialType.System_Byte, SpecialType.System_SByte, SpecialType.System_Boolean
Return 8
Case SpecialType.System_Int16, SpecialType.System_UInt16
Return 16
Case SpecialType.System_Int32, SpecialType.System_UInt32
Return 32
Case SpecialType.System_Int64, SpecialType.System_UInt64
Return 64
Case Else
Return 0 ' Unknown
End Select
End Function
Private Shared Function GetValueTypeConstraint(typeParam As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As TypeSymbol
Dim constraint = DirectCast(typeParam, TypeParameterSymbol).GetNonInterfaceConstraint(useSiteDiagnostics)
If constraint IsNot Nothing AndAlso constraint.IsValueType Then
Return constraint
End If
Return Nothing
End Function
Private Shared Function GetNonErrorEnumUnderlyingType(type As TypeSymbol) As NamedTypeSymbol
If type.TypeKind = TypeKind.Enum Then
Dim underlying = DirectCast(type, NamedTypeSymbol).EnumUnderlyingType
If underlying.Kind <> SymbolKind.ErrorType Then
Return underlying
End If
End If
Return Nothing
End Function
Private Shared Function ClassifyValueTypeConversion(source As TypeSymbol, destination As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ConversionKind
'§8.8 Widening Conversions
'• From a value type to a base type.
'• From a value type to an interface type that the type implements.
'§8.9 Narrowing Conversions
'• From a reference type to a more derived value type.
'• From an interface type to a value type, provided the value type implements the interface type.
'System.Void is actually a value type.
If source.SpecialType = SpecialType.System_Void OrElse destination.SpecialType = SpecialType.System_Void Then
'CLR has nothing to say about conversions of these things.
Return Nothing 'ConversionKind.NoConversion
End If
If IsValueType(source) Then
' Disallow boxing of restricted types
If Not source.IsRestrictedType() Then
If destination.SpecialType = SpecialType.System_Object Then
'From a value type to a base type.
Return ConversionKind.WideningValue ' Shortcut
End If
If IsClassType(destination) Then
If IsDerivedFrom(source, destination, useSiteDiagnostics) Then
'From a value type to a base type.
Return ConversionKind.WideningValue
End If
ElseIf IsInterfaceType(destination) Then
Dim conv As ConversionKind = ToInterfaceConversionClassifier.ClassifyConversionToVariantCompatibleInterface(
DirectCast(source, NamedTypeSymbol),
DirectCast(destination, NamedTypeSymbol),
varianceCompatibilityClassificationDepth:=0,
useSiteDiagnostics:=useSiteDiagnostics)
If ConversionExists(conv) Then
'From a value type to an interface type that the type implements.
' !!! Note that the spec doesn't mention anything about variance, but
' !!! it appears to be taken into account by Dev10 compiler.
Debug.Assert((conv And Not (ConversionKind.Widening Or ConversionKind.Narrowing Or
ConversionKind.InvolvesEnumTypeConversions Or
ConversionKind.VarianceConversionAmbiguity)) = 0)
Return conv Or ConversionKind.Value
End If
End If
End If
ElseIf IsValueType(destination) Then
If source.SpecialType = SpecialType.System_Object Then
'From a reference type to a more derived value type.
Return ConversionKind.NarrowingValue ' Shortcut
End If
If IsClassType(source) Then
If IsDerivedFrom(destination, source, useSiteDiagnostics) Then
'From a reference type to a more derived value type.
Return ConversionKind.NarrowingValue
End If
ElseIf IsInterfaceType(source) Then
For Each [interface] In destination.AllInterfacesWithDefinitionUseSiteDiagnostics(useSiteDiagnostics)
If [interface].IsErrorType() Then
Continue For
ElseIf [interface].IsSameTypeIgnoringCustomModifiers(source) Then
' From an interface type to a value type, provided the value type implements the interface type.
' Note, variance is not taken into consideration here.
Return ConversionKind.NarrowingValue
End If
Next
End If
End If
Return Nothing 'ConversionKind.NoConversion
End Function
Private Shared Function ClassifyNullableConversion(source As TypeSymbol, destination As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ConversionKind
'§8.8 Widening Conversions
'• From a type T to the type T?.
'• From a type T? to a type S?, where there is a widening conversion from the type T to the type S.
'• From a type T to a type S?, where there is a widening conversion from the type T to the type S.
'• From a type T? to an interface type that the type T implements.
'§8.9 Narrowing Conversions
'• From a type T? to a type T.
'• From a type T? to a type S?, where there is a narrowing conversion from the type T to the type S.
'• From a type T to a type S?, where there is a narrowing conversion from the type T to the type S.
'• From a type S? to a type T, where there is a conversion from the type S to the type T.
Dim srcIsNullable As Boolean = source.IsNullableType()
Dim dstIsNullable As Boolean = destination.IsNullableType()
If Not srcIsNullable AndAlso Not dstIsNullable Then
Return Nothing 'ConversionKind.NoConversion
End If
Dim srcUnderlying As TypeSymbol = Nothing
Dim dstUnderlying As TypeSymbol = Nothing
If srcIsNullable Then
srcUnderlying = source.GetNullableUnderlyingType()
If srcUnderlying.Kind = SymbolKind.ErrorType OrElse Not srcUnderlying.IsValueType OrElse srcUnderlying.IsNullableType() Then
Return Nothing 'ConversionKind.NoConversion
End If
End If
If dstIsNullable Then
dstUnderlying = destination.GetNullableUnderlyingType()
If dstUnderlying.Kind = SymbolKind.ErrorType OrElse Not dstUnderlying.IsValueType OrElse dstUnderlying.IsNullableType() Then
Return Nothing 'ConversionKind.NoConversion
End If
End If
If srcIsNullable Then
Dim conv As ConversionKind
If dstIsNullable Then
'From a type T? to a type S?
conv = ClassifyPredefinedConversion(srcUnderlying, dstUnderlying, useSiteDiagnostics)
Debug.Assert((conv And ConversionKind.VarianceConversionAmbiguity) = 0)
If IsWideningConversion(conv) Then
'From a type T? to a type S?, where there is a widening conversion from the type T to the type S.
Return ConversionKind.WideningNullable
ElseIf IsNarrowingConversion(conv) Then
'From a type T? to a type S?, where there is a narrowing conversion from the type T to the type S.
Return ConversionKind.NarrowingNullable
End If
ElseIf IsInterfaceType(destination) Then
' !!! Note that the spec doesn't mention anything about variance, but
' !!! it appears to be taken into account by Dev10 compiler.
conv = ClassifyDirectCastConversion(srcUnderlying, destination, useSiteDiagnostics)
If IsWideningConversion(conv) Then
'From a type T? to an interface type that the type T implements.
Return ConversionKind.WideningNullable
ElseIf IsNarrowingConversion(conv) Then
' !!! Note, spec doesn't mention this conversion.
Return ConversionKind.NarrowingNullable
End If
ElseIf srcUnderlying.IsSameTypeIgnoringCustomModifiers(destination) Then
'From a type T? to a type T.
Return ConversionKind.NarrowingNullable
ElseIf ConversionExists(ClassifyPredefinedConversion(srcUnderlying, destination, useSiteDiagnostics)) Then
'From a type S? to a type T, where there is a conversion from the type S to the type T.
Return ConversionKind.NarrowingNullable
End If
Else
Debug.Assert(dstIsNullable)
'From a type T to a type S?
If source.IsSameTypeIgnoringCustomModifiers(dstUnderlying) Then
'From a type T to the type T?.
Return ConversionKind.WideningNullable
End If
Dim conv = ClassifyPredefinedConversion(source, dstUnderlying, useSiteDiagnostics)
Debug.Assert((conv And ConversionKind.VarianceConversionAmbiguity) = 0)
If IsWideningConversion(conv) Then
'From a type T to a type S?, where there is a widening conversion from the type T to the type S.
Return ConversionKind.WideningNullable
ElseIf IsNarrowingConversion(conv) Then
'From a type T to a type S?, where there is a narrowing conversion from the type T to the type S.
Return ConversionKind.NarrowingNullable
End If
End If
Return Nothing 'ConversionKind.NoConversion
End Function
Private Shared Function ClassifyTupleConversion(source As TypeSymbol, destination As TypeSymbol, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ConversionKind
If Not source.IsTupleType Then
Return Nothing 'ConversionKind.NoConversion
End If
Dim sourceElementTypes = DirectCast(source, TupleTypeSymbol).TupleElementTypes
' check if the type is actually compatible type for a tuple of given cardinality
If Not destination.IsTupleOrCompatibleWithTupleOfCardinality(sourceElementTypes.Length) Then
Return Nothing 'ConversionKind.NoConversion
End If
Dim targetElementTypes As ImmutableArray(Of TypeSymbol) = destination.GetElementTypesOfTupleOrCompatible()
Debug.Assert(sourceElementTypes.Count = targetElementTypes.Length)
' check arguments against flattened list of target element types
Dim result As ConversionKind = ConversionKind.WideningTuple
For i As Integer = 0 To sourceElementTypes.Length - 1
Dim argumentType = sourceElementTypes(i)
Dim targetType = targetElementTypes(i)
If argumentType.IsErrorType OrElse targetType.IsErrorType Then
Return Nothing 'ConversionKind.NoConversion
End If
Dim elementConversion = ClassifyConversion(argumentType, targetType, useSiteDiagnostics).Key
If NoConversion(elementConversion) Then
Return Nothing 'ConversionKind.NoConversion
End If
If IsNarrowingConversion(elementConversion) Then
result = ConversionKind.NarrowingTuple
End If
Next
Return result
End Function
Public Shared Function ClassifyStringConversion(source As TypeSymbol, destination As TypeSymbol) As ConversionKind
'§8.8 Widening Conversions
'• From Char() to String.
'§8.9 Narrowing Conversions
'• From String to Char().
Dim shouldBeArray As TypeSymbol
If source.SpecialType = SpecialType.System_String Then
shouldBeArray = destination
ElseIf destination.SpecialType = SpecialType.System_String Then
shouldBeArray = source
Else
Return Nothing 'ConversionKind.NoConversion
End If
If shouldBeArray.Kind = SymbolKind.ArrayType Then
Dim array = DirectCast(shouldBeArray, ArrayTypeSymbol)
If array.IsSZArray AndAlso array.ElementType.SpecialType = SpecialType.System_Char Then
If array Is source Then
Return ConversionKind.WideningString
Else
Return ConversionKind.NarrowingString
End If
End If
End If
Return Nothing 'ConversionKind.NoConversion
End Function
Private Shared Function ClassifyTypeParameterConversion(
source As TypeSymbol,
destination As TypeSymbol,
varianceCompatibilityClassificationDepth As Integer,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As ConversionKind
'§8.8 Widening Conversions
'• From a type parameter to Object.
'• From a type parameter to an interface type constraint or any interface variant compatible with an interface type constraint.
'• From a type parameter to an interface implemented by a class constraint.
'• From a type parameter to an interface variant compatible with an interface implemented by a class constraint.
'• From a type parameter to a class constraint, or a base type of the class constraint.
'• From a type parameter T to a type parameter constraint TX, or anything TX has a widening conversion to.
'§8.9 Narrowing Conversions
'• From Object to a type parameter.
'• From a type parameter to an interface type, provided the type parameter is not constrained
' to that interface or constrained to a class that implements that interface.
'• From an interface type to a type parameter.
' !!! The following two narrowing conversions aren't actually honored by VB/C# Dev10 compiler,
' !!! I am not going to honor them either.
'•- From a type parameter to a derived type of a class constraint.
'•- From a type parameter T to anything a type parameter constraint TX has a narrowing conversion to.
' !!! The following two narrowing conversions are not mentioned in the spec, but are honored in Dev10:
'• From a class constraint, or a base type of the class constraint to a type parameter.
'• From a type parameter constraint TX to a type parameter T, or from anything that has narrowing conversion to TX.
Dim conv As ConversionKind
If source.Kind = SymbolKind.TypeParameter Then
conv = ClassifyConversionFromTypeParameter(DirectCast(source, TypeParameterSymbol), destination, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
If ConversionExists(conv) Then
Return conv
End If
End If
If destination.Kind = SymbolKind.TypeParameter Then
conv = ClassifyConversionToTypeParameter(source, DirectCast(destination, TypeParameterSymbol), varianceCompatibilityClassificationDepth, useSiteDiagnostics)
If ConversionExists(conv) Then
Debug.Assert(IsNarrowingConversion(conv)) ' We are relying on this while classifying conversions from type parameter to avoid need for recursion.
Return conv
End If
End If
If source.Kind = SymbolKind.TypeParameter OrElse destination.Kind = SymbolKind.TypeParameter Then
Return ConversionKind.MightSucceedAtRuntime
End If
Return Nothing 'ConversionKind.NoConversion
End Function
Private Shared Function ClassifyConversionFromTypeParameter(
typeParameter As TypeParameterSymbol,
destination As TypeSymbol,
varianceCompatibilityClassificationDepth As Integer,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As ConversionKind
If destination.SpecialType = SpecialType.System_Object Then
'From a type parameter to Object.
Return ConversionKind.WideningTypeParameter
End If
Dim queue As ArrayBuilder(Of TypeParameterSymbol) = Nothing
Dim result As ConversionKind = ClassifyConversionFromTypeParameter(typeParameter, destination, queue, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
If queue IsNot Nothing Then
queue.Free()
End If
Return result
End Function
Private Shared Function ClassifyConversionFromTypeParameter(
typeParameter As TypeParameterSymbol,
destination As TypeSymbol,
<[In], Out> ByRef queue As ArrayBuilder(Of TypeParameterSymbol),
varianceCompatibilityClassificationDepth As Integer,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As ConversionKind
Dim queueIndex As Integer = 0
Dim checkedValueTypeConstraint As Boolean = False
Dim dstIsClassType As Boolean
Dim dstIsDelegateType As Boolean
Dim dstIsInterfaceType As Boolean
Dim dstIsArrayType As Boolean
Dim convToInterface As ToInterfaceConversionClassifier = Nothing
Dim destinationInterface As NamedTypeSymbol = Nothing
ClassifyAsReferenceType(destination, dstIsClassType, dstIsDelegateType, dstIsInterfaceType, dstIsArrayType)
If dstIsInterfaceType Then
destinationInterface = DirectCast(destination, NamedTypeSymbol)
End If
Do
If Not checkedValueTypeConstraint AndAlso typeParameter.HasValueTypeConstraint Then
If destination.SpecialType = SpecialType.System_ValueType Then
' !!! Not mentioned explicitly in the spec.
Return ConversionKind.WideningTypeParameter
End If
If dstIsInterfaceType Then
Dim valueType = typeParameter.ContainingAssembly.GetSpecialType(SpecialType.System_ValueType)
If valueType.Kind <> SymbolKind.ErrorType Then
' !!! Not mentioned explicitly in the spec.
If convToInterface.AccumulateConversionClassificationToVariantCompatibleInterface(valueType, destinationInterface,
varianceCompatibilityClassificationDepth,
useSiteDiagnostics) Then
convToInterface.AssertFoundIdentity()
Return ConversionKind.WideningTypeParameter
End If
End If
End If
checkedValueTypeConstraint = True
End If
' Iterate over the constraints
For Each constraint As TypeSymbol In typeParameter.ConstraintTypesWithDefinitionUseSiteDiagnostics(useSiteDiagnostics)
If constraint.Kind = SymbolKind.ErrorType Then
Continue For
End If
If constraint.IsSameTypeIgnoringCustomModifiers(destination) Then
'From a type parameter to an interface type constraint
'From a type parameter to a class constraint
'From a type parameter T to a type parameter constraint TX
Return ConversionKind.WideningTypeParameter
ElseIf constraint.TypeKind = TypeKind.Enum AndAlso
DirectCast(constraint, NamedTypeSymbol).EnumUnderlyingType.IsSameTypeIgnoringCustomModifiers(destination) Then
' !!! Spec doesn't mention this, but Dev10 allows conversion
' !!! to the underlying type of the enum
Return ConversionKind.WideningTypeParameter Or ConversionKind.InvolvesEnumTypeConversions
End If
Dim constraintIsClassType As Boolean
Dim constraintIsDelegateType As Boolean
Dim constraintIsInterfaceType As Boolean
Dim constraintIsArrayType As Boolean
Dim constraintIsValueType As Boolean = False
If Not ClassifyAsReferenceType(constraint, constraintIsClassType, constraintIsDelegateType, constraintIsInterfaceType, constraintIsArrayType) Then
constraintIsValueType = IsValueType(constraint)
End If
If dstIsInterfaceType Then
' Conversions to an interface
If (constraintIsClassType OrElse constraintIsInterfaceType OrElse constraintIsValueType) Then
If convToInterface.AccumulateConversionClassificationToVariantCompatibleInterface(DirectCast(constraint, NamedTypeSymbol),
destinationInterface,
varianceCompatibilityClassificationDepth,
useSiteDiagnostics) Then
convToInterface.AssertFoundIdentity()
'From a type parameter to any interface variant compatible with an interface type constraint.
'From a type parameter to an interface implemented by a class constraint.
'From a type parameter to an interface variant compatible with an interface implemented by a class constraint.
' !!! Spec doesn't explicitly mention interfaces implemented by interface constraints, but Dev10 compiler takes them
' !!! into consideration.
Return ConversionKind.WideningTypeParameter
End If
ElseIf constraintIsArrayType Then
Dim conv As ConversionKind = ClassifyReferenceConversionFromArrayToAnInterface(constraint, destination, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
If IsWideningConversion(conv) Then
'From a type parameter to an interface implemented by a class constraint.
'From a type parameter to an interface variant compatible with an interface implemented by a class constraint.
Debug.Assert((conv And ConversionKind.VarianceConversionAmbiguity) = 0)
Return ConversionKind.WideningTypeParameter Or (conv And ConversionKind.InvolvesEnumTypeConversions)
End If
End If
ElseIf dstIsClassType Then
If (constraintIsClassType OrElse constraintIsValueType OrElse constraintIsArrayType) AndAlso
IsDerivedFrom(constraint, destination, useSiteDiagnostics) Then
'From a type parameter to a base type of the class constraint.
Return ConversionKind.WideningTypeParameter
End If
ElseIf dstIsArrayType Then
If constraintIsArrayType Then
Dim conv As ConversionKind = ClassifyArrayConversion(constraint, destination, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
If IsWideningConversion(conv) Then
' !!! Spec doesn't explicitly mention array covariance, but Dev10 compiler takes them
' !!! into consideration.
Debug.Assert((conv And ConversionKind.VarianceConversionAmbiguity) = 0)
Return ConversionKind.WideningTypeParameter Or (conv And ConversionKind.InvolvesEnumTypeConversions)
End If
' We don't need to do anything special about ConversionKind.MightSucceedAtRuntime bit here
' because the caller of this function, ClassifyTypeParameterConversion, returns
' ConversionKind.MightSucceedAtRuntime on its own in case of NoConversion.
End If
' Unit test includes scenario for narrowing conversion between arrays. It produces expected result.
End If
If constraint.Kind = SymbolKind.TypeParameter Then
If queue Is Nothing Then
queue = ArrayBuilder(Of TypeParameterSymbol).GetInstance()
End If
'From a type parameter T to anything type parameter constraint TX has a widening conversion to.
queue.Add(DirectCast(constraint, TypeParameterSymbol))
End If
Next
If queue IsNot Nothing Then
If queueIndex < queue.Count Then
typeParameter = queue(queueIndex)
queueIndex += 1
Continue Do
End If
End If
Exit Do
Loop
If dstIsInterfaceType Then
Dim conv As ConversionKind = convToInterface.Result
If ConversionExists(conv) Then
'From a type parameter to any interface variant compatible with an interface type constraint.
'From a type parameter to an interface implemented by a class constraint.
'From a type parameter to an interface variant compatible with an interface implemented by a class constraint.
' !!! Spec doesn't explicitly mention interfaces implemented by interface constraints, but Dev10 compiler takes them
' !!! into consideration.
Debug.Assert((conv And Not (ConversionKind.Widening Or ConversionKind.Narrowing Or
ConversionKind.InvolvesEnumTypeConversions Or
ConversionKind.VarianceConversionAmbiguity)) = 0)
Return ConversionKind.TypeParameter Or conv
End If
'From a type parameter to an interface type, provided the type parameter is not constrained
'to that interface or constrained to a class that implements that interface.
Return ConversionKind.NarrowingTypeParameter
End If
Return Nothing 'ConversionKind.NoConversion
End Function
Private Shared Function ClassifyConversionToTypeParameter(
source As TypeSymbol,
typeParameter As TypeParameterSymbol,
varianceCompatibilityClassificationDepth As Integer,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As ConversionKind
If source.SpecialType = SpecialType.System_Object Then
'From Object to a type parameter.
Return ConversionKind.NarrowingTypeParameter
End If
If typeParameter.HasValueTypeConstraint Then
If source.SpecialType = SpecialType.System_ValueType Then
' !!! Not mentioned explicitly in the spec.
Return ConversionKind.NarrowingTypeParameter
End If
If IsClassType(source) Then
Dim valueType = typeParameter.ContainingAssembly.GetSpecialType(SpecialType.System_ValueType)
If valueType.Kind <> SymbolKind.ErrorType AndAlso IsDerivedFrom(valueType, source, useSiteDiagnostics) Then
' !!! Not mentioned explicitly in the spec.
Return ConversionKind.NarrowingTypeParameter
End If
End If
End If
Dim srcIsClassType As Boolean
Dim srcIsDelegateType As Boolean
Dim srcIsInterfaceType As Boolean
Dim srcIsArrayType As Boolean
ClassifyAsReferenceType(source, srcIsClassType, srcIsDelegateType, srcIsInterfaceType, srcIsArrayType)
If srcIsInterfaceType Then
'From an interface type to a type parameter.
Return ConversionKind.NarrowingTypeParameter
Else
' Iterate over constraints
For Each constraint As TypeSymbol In typeParameter.ConstraintTypesWithDefinitionUseSiteDiagnostics(useSiteDiagnostics)
If constraint.Kind = SymbolKind.ErrorType Then
Continue For
End If
If constraint.IsSameTypeIgnoringCustomModifiers(source) Then
'From a class constraint to a type parameter.
'From a type parameter constraint TX to a type parameter T
Return ConversionKind.NarrowingTypeParameter
ElseIf constraint.TypeKind = TypeKind.Enum AndAlso
DirectCast(constraint, NamedTypeSymbol).EnumUnderlyingType.IsSameTypeIgnoringCustomModifiers(source) Then
' !!! Spec doesn't mention this, but Dev10 allows conversion
' !!! from the underlying type of the enum
Return ConversionKind.NarrowingTypeParameter Or ConversionKind.InvolvesEnumTypeConversions
End If
Dim constraintIsClassType As Boolean
Dim constraintIsDelegateType As Boolean
Dim constraintIsInterfaceType As Boolean
Dim constraintIsArrayType As Boolean
Dim constraintIsValueType As Boolean = False
If Not ClassifyAsReferenceType(constraint, constraintIsClassType, constraintIsDelegateType, constraintIsInterfaceType, constraintIsArrayType) Then
constraintIsValueType = IsValueType(constraint)
End If
If (constraintIsClassType OrElse constraintIsValueType OrElse constraintIsArrayType) Then
If srcIsClassType Then
If IsDerivedFrom(constraint, source, useSiteDiagnostics) Then
'From a base type of the class constraint to a type parameter.
Return ConversionKind.NarrowingTypeParameter
End If
ElseIf srcIsArrayType Then
If constraintIsArrayType Then
Dim conv = ClassifyArrayConversion(constraint, source, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
If IsWideningConversion(conv) Then
' !!! Spec doesn't explicitly mention array covariance, but Dev10 compiler takes them
' !!! into consideration.
Debug.Assert((conv And ConversionKind.VarianceConversionAmbiguity) = 0)
Return ConversionKind.NarrowingTypeParameter Or (conv And ConversionKind.InvolvesEnumTypeConversions)
End If
' We don't need to do anything special about ConversionKind.MightSucceedAtRuntime bit here
' because the caller of this function, ClassifyTypeParameterConversion, returns
' ConversionKind.MightSucceedAtRuntime on its own in case of NoConversion.
End If
' Unit test includes scenario for narrowing conversion between arrays. It produces expected result.
End If
ElseIf constraint.Kind = SymbolKind.TypeParameter Then
Dim conv As ConversionKind = ClassifyTypeParameterConversion(source, constraint, varianceCompatibilityClassificationDepth, useSiteDiagnostics)
If IsNarrowingConversion(conv) Then
'From anything that has narrowing conversion to a type parameter constraint TX.
' Possibly dropping ConversionKind.VarianceConversionAmbiguity because it is not
' the only reason for the narrowing.
Return ConversionKind.NarrowingTypeParameter Or (conv And ConversionKind.InvolvesEnumTypeConversions)
End If
' We don't need to do anything special about ConversionKind.MightSucceedAtRuntime bit here
' because the caller of this function, ClassifyTypeParameterConversion, returns
' ConversionKind.MightSucceedAtRuntime on its own in case of NoConversion.
End If
Next
End If
Return Nothing 'ConversionKind.NoConversion
End Function
''' <summary>
''' Calculate MethodConversionKind based on required return type conversion.
'''
''' TODO: It looks like Dev10 MethodConversionKinds for return are badly named because
''' they appear to give classification in the direction opposite to the data
''' flow. This is very confusing. However, I am not going to rename them just yet.
''' Will do this when all parts are ported and working together, otherwise it will
''' be very hard to port the rest of the feature.
'''
''' We are trying to classify conversion between methods
''' ConvertFrom(...) As returnTypeOfConvertFromMethod -> ConvertTo(...) As returnTypeOfConvertToMethod
'''
''' The relaxation stub would look like:
''' Stub(...) As returnTypeOfConvertToMethod
''' Return ConvertFrom(...)
''' End ...
''' </summary>
Public Shared Function ClassifyMethodConversionBasedOnReturnType(
returnTypeOfConvertFromMethod As TypeSymbol,
returnTypeOfConvertToMethod As TypeSymbol,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As MethodConversionKind
Debug.Assert(returnTypeOfConvertFromMethod IsNot Nothing)
Debug.Assert(returnTypeOfConvertToMethod IsNot Nothing)
If returnTypeOfConvertToMethod.IsVoidType() Then
If returnTypeOfConvertFromMethod.IsVoidType() Then
Return MethodConversionKind.Identity
Else
Return MethodConversionKind.ReturnValueIsDropped
End If
ElseIf returnTypeOfConvertFromMethod.IsVoidType() Then
Return MethodConversionKind.Error_SubToFunction
End If
' Note: this check is done after the void check to still support
' comparison of two subs without error messages.
' this can happen if e.g. references are missing
If returnTypeOfConvertFromMethod.IsErrorType OrElse returnTypeOfConvertToMethod.IsErrorType Then
If returnTypeOfConvertFromMethod Is returnTypeOfConvertToMethod AndAlso
returnTypeOfConvertFromMethod Is LambdaSymbol.ReturnTypeVoidReplacement Then
Return MethodConversionKind.Identity
End If
Return MethodConversionKind.Error_Unspecified
End If
Dim typeConversion As ConversionKind = ClassifyConversion(returnTypeOfConvertFromMethod, returnTypeOfConvertToMethod, useSiteDiagnostics).Key
Dim result As MethodConversionKind
If IsNarrowingConversion(typeConversion) Then
result = MethodConversionKind.ReturnIsWidening
ElseIf IsWideningConversion(typeConversion) Then
If IsIdentityConversion(typeConversion) Then
result = MethodConversionKind.Identity
Else
' For return type, CLR will not relax on value types, only reference types
' so treat these as relaxations that needs a stub.
If Not (returnTypeOfConvertFromMethod.IsReferenceType AndAlso returnTypeOfConvertToMethod.IsReferenceType) OrElse
(typeConversion And ConversionKind.UserDefined) <> 0 Then
result = MethodConversionKind.ReturnIsIsVbOrBoxNarrowing
Else
Dim clrTypeConversion = ClassifyDirectCastConversion(returnTypeOfConvertFromMethod, returnTypeOfConvertToMethod, useSiteDiagnostics)
If IsWideningConversion(clrTypeConversion) Then
result = MethodConversionKind.ReturnIsClrNarrowing
Else
result = MethodConversionKind.ReturnIsIsVbOrBoxNarrowing
End If
End If
End If
Else
result = MethodConversionKind.Error_ReturnTypeMismatch
End If
Return result
End Function
''' <summary>
''' Returns the methods conversions for the given conversion kind
'''
''' We are trying to classify conversion between methods arguments
''' delegateInvoke(parameterConvertFrom) -> targetMethod(parameterConvertTo)
'''
''' The relaxation stub would look like (stub has same signature as delegate invoke):
''' Stub(parameterConvertFrom)
''' return targetMethod(parameterConvertTo)
''' End Method
''' </summary>
''' <param name="conversion">The conversion.</param>
''' <param name="delegateParameterType">The delegate parameter type.</param>
Public Shared Function ClassifyMethodConversionBasedOnArgumentConversion(
conversion As ConversionKind,
delegateParameterType As TypeSymbol
) As MethodConversionKind
If Conversions.NoConversion(conversion) Then
Return MethodConversionKind.Error_OverloadResolution
ElseIf Conversions.IsNarrowingConversion(conversion) Then
Return MethodConversionKind.OneArgumentIsNarrowing
ElseIf Not Conversions.IsIdentityConversion(conversion) Then
Debug.Assert(Conversions.IsWideningConversion(conversion))
If Conversions.IsCLRPredefinedConversion(conversion) AndAlso
delegateParameterType.IsReferenceType Then
Return MethodConversionKind.OneArgumentIsClrWidening
Else
Return MethodConversionKind.OneArgumentIsVbOrBoxWidening
End If
End If
Return MethodConversionKind.Identity
End Function
Public Shared Function ClassifyMethodConversionForLambdaOrAnonymousDelegate(
toMethod As MethodSymbol,
lambdaOrDelegateInvokeSymbol As MethodSymbol,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As MethodConversionKind
Return ClassifyMethodConversionForLambdaOrAnonymousDelegate(New UnboundLambda.TargetSignature(toMethod), lambdaOrDelegateInvokeSymbol, useSiteDiagnostics)
End Function
Public Shared Function ClassifyMethodConversionForLambdaOrAnonymousDelegate(
toMethodSignature As UnboundLambda.TargetSignature,
lambdaOrDelegateInvokeSymbol As MethodSymbol,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As MethodConversionKind
' determine conversions based on return type
Dim methodConversions = Conversions.ClassifyMethodConversionBasedOnReturnType(lambdaOrDelegateInvokeSymbol.ReturnType, toMethodSignature.ReturnType, useSiteDiagnostics)
' determine conversions based on arguments
methodConversions = methodConversions Or ClassifyMethodConversionForLambdaOrAnonymousDelegateBasedOnParameters(toMethodSignature, lambdaOrDelegateInvokeSymbol.Parameters, useSiteDiagnostics)
Return methodConversions
End Function
Public Shared Function ClassifyMethodConversionForEventRaise(
toDelegateInvokeMethod As MethodSymbol,
parameters As ImmutableArray(Of ParameterSymbol),
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As MethodConversionKind
Debug.Assert(toDelegateInvokeMethod.MethodKind = MethodKind.DelegateInvoke)
Return ClassifyMethodConversionForLambdaOrAnonymousDelegateBasedOnParameters(New UnboundLambda.TargetSignature(toDelegateInvokeMethod), parameters, useSiteDiagnostics)
End Function
Private Shared Function ClassifyMethodConversionForLambdaOrAnonymousDelegateBasedOnParameters(
toMethodSignature As UnboundLambda.TargetSignature,
parameters As ImmutableArray(Of ParameterSymbol),
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As MethodConversionKind
' TODO: Take custom modifiers into account, if needed.
Dim methodConversions As MethodConversionKind
' determine conversions based on arguments
If parameters.Length = 0 AndAlso toMethodSignature.ParameterTypes.Length > 0 Then
' special flag for ignoring all arguments (zero argument relaxation)
methodConversions = methodConversions Or MethodConversionKind.AllArgumentsIgnored
ElseIf parameters.Length <> toMethodSignature.ParameterTypes.Length Then
methodConversions = methodConversions Or MethodConversionKind.Error_OverloadResolution
Else
For parameterIndex As Integer = 0 To parameters.Length - 1
' Check ByRef
If toMethodSignature.IsByRef(parameterIndex) <> parameters(parameterIndex).IsByRef Then
methodConversions = methodConversions Or MethodConversionKind.Error_ByRefByValMismatch
End If
' Check conversion
Dim toParameterType As TypeSymbol = toMethodSignature.ParameterTypes(parameterIndex)
Dim lambdaParameterType As TypeSymbol = parameters(parameterIndex).Type
If Not toParameterType.IsErrorType() AndAlso Not lambdaParameterType.IsErrorType() Then
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnArgumentConversion(
Conversions.ClassifyConversion(toParameterType, lambdaParameterType, useSiteDiagnostics).Key,
toParameterType)
' Check copy back conversion.
If toMethodSignature.IsByRef(parameterIndex) Then
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnArgumentConversion(
Conversions.ClassifyConversion(lambdaParameterType, toParameterType, useSiteDiagnostics).Key,
lambdaParameterType)
End If
End If
Next
End If
Return methodConversions
End Function
''' <summary>
''' Will set only bits used for delegate relaxation level.
''' </summary>
Public Shared Function DetermineDelegateRelaxationLevelForLambdaReturn(
expressionOpt As BoundExpression,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)
) As ConversionKind
If expressionOpt Is Nothing OrElse expressionOpt.Kind <> BoundKind.Conversion OrElse expressionOpt.HasErrors Then
Return ConversionKind.DelegateRelaxationLevelNone
End If
Dim conversion = DirectCast(expressionOpt, BoundConversion)
If conversion.ExplicitCastInCode Then
Return ConversionKind.DelegateRelaxationLevelNone
End If
' It is tempting to use ConversionKind from this node, but this would produce incorrect result in some cases
' because conversion from an expression to a type and from a type to a type can have different kind.
' The node captures the former, but relaxation classification should use latter.
Dim methodConversion As MethodConversionKind
Dim operandType As TypeSymbol = conversion.Operand.Type
If operandType Is Nothing Then
Debug.Assert(conversion.Operand.IsNothingLiteral() OrElse conversion.Operand.Kind = BoundKind.Lambda)
methodConversion = MethodConversionKind.Identity
Else
methodConversion = ClassifyMethodConversionBasedOnReturnType(operandType, conversion.Type, useSiteDiagnostics)
End If
Return DetermineDelegateRelaxationLevel(methodConversion)
End Function
''' <summary>
''' Determine the relaxation level of a given conversion. This will be used by
''' overload resolution in case of conflict. This is to prevent applications that compiled in VB8
''' to fail in VB9 because there are more matches. And the same for flipping strict On to Off.
'''
''' Will set only bits used for delegate relaxation level.
''' </summary>
Public Shared Function DetermineDelegateRelaxationLevel(
methodConversion As MethodConversionKind
) As ConversionKind
Dim result As ConversionKind
If methodConversion = MethodConversionKind.Identity Then
result = ConversionKind.DelegateRelaxationLevelNone
ElseIf Not IsDelegateRelaxationSupportedFor(methodConversion) Then
result = ConversionKind.DelegateRelaxationLevelInvalid
ElseIf (methodConversion And (MethodConversionKind.OneArgumentIsNarrowing Or MethodConversionKind.ReturnIsWidening)) <> 0 Then
result = ConversionKind.DelegateRelaxationLevelNarrowing
ElseIf (methodConversion And (MethodConversionKind.ReturnValueIsDropped Or MethodConversionKind.AllArgumentsIgnored)) = 0 Then
result = ConversionKind.DelegateRelaxationLevelWidening
Else
result = ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs
End If
Return result
End Function
Public Shared Function IsDelegateRelaxationSupportedFor(methodConversion As MethodConversionKind) As Boolean
Return (methodConversion And MethodConversionKind.AllErrorReasons) = 0
End Function
''' <summary>
''' Determines whether a stub needed for the delegate creations conversion based on the given method conversions.
''' </summary>
''' <param name="methodConversions">The method conversions.</param><returns>
''' <c>true</c> if a stub needed for conversion; otherwise, <c>false</c>.
''' </returns>
Public Shared Function IsStubRequiredForMethodConversion(methodConversions As MethodConversionKind) As Boolean
Const methodConversionsRequiringStubs = (MethodConversionKind.OneArgumentIsNarrowing Or
MethodConversionKind.OneArgumentIsVbOrBoxWidening Or
MethodConversionKind.ReturnIsWidening Or
MethodConversionKind.ReturnIsIsVbOrBoxNarrowing Or
MethodConversionKind.ReturnValueIsDropped Or
MethodConversionKind.AllArgumentsIgnored Or
MethodConversionKind.ExcessOptionalArgumentsOnTarget)
Return (methodConversions And methodConversionsRequiringStubs) <> 0 AndAlso
(methodConversions And MethodConversionKind.AllErrorReasons) = 0
End Function
''' <summary>
''' Tells whether the method conversion is considered to be narrowing or not.
''' </summary>
Public Shared Function IsNarrowingMethodConversion(
methodConversion As MethodConversionKind,
isForAddressOf As Boolean
) As Boolean
Dim checkForBits As MethodConversionKind
If isForAddressOf Then
checkForBits = MethodConversionKind.OneArgumentIsNarrowing Or MethodConversionKind.ReturnIsWidening Or MethodConversionKind.AllArgumentsIgnored
Else
checkForBits = MethodConversionKind.OneArgumentIsNarrowing Or MethodConversionKind.ReturnIsWidening
End If
Return (methodConversion And checkForBits) <> 0
End Function
Public Shared Function InvertConversionRequirement(restriction As RequiredConversion) As RequiredConversion
Debug.Assert(RequiredConversion.Count = 8, "If you've updated the type argument inference restrictions, then please also update InvertConversionRequirement()")
' [reverse chain] [None] < AnyReverse < ReverseReference < Identity
' [middle chain] None < [Any,AnyReverse] < AnyConversionAndReverse < Identity
' [forward chain] [None] < Any < ArrayElement < Reference < Identity
' from reverse chain to forward chain:
If restriction = RequiredConversion.AnyReverse Then
Return RequiredConversion.Any
ElseIf restriction = RequiredConversion.ReverseReference Then
Return RequiredConversion.Reference
End If
' from forward chain to reverse chain:
If restriction = RequiredConversion.Any Then
Return RequiredConversion.AnyReverse
ElseIf restriction = RequiredConversion.ArrayElement Then
Debug.Assert(False, "unexpected: ArrayElementConversion restriction has no reverse")
Return RequiredConversion.ReverseReference
ElseIf restriction = RequiredConversion.Reference Then
Return RequiredConversion.ReverseReference
End If
' otherwise we're either in the middle chain, or identity
Return restriction
End Function
' Strengthens the restriction to at least ReferenceRestriction or ReverseReferenceRestriction
' Note: AnyConversionAndReverse strengthens to Identity
Public Shared Function StrengthenConversionRequirementToReference(restriction As RequiredConversion) As RequiredConversion
Debug.Assert(RequiredConversion.Count = 8, "If you've updated the type argument inference restrictions, then please also update StrengthenConversionRequirementToReference()")
' [reverse chain] [None] < AnyReverse < ReverseReference < Identity
' [middle chain] None < [Any,AnyReverse] < AnyConversionAndReverse < Identity
' [forward chain] [None] < Any < ArrayElement < Reference < Identity
If restriction = RequiredConversion.AnyReverse Then
Return RequiredConversion.ReverseReference
ElseIf restriction = RequiredConversion.Any OrElse restriction = RequiredConversion.ArrayElement Then
Return RequiredConversion.Reference
ElseIf restriction = RequiredConversion.AnyAndReverse Then
Return RequiredConversion.Identity
Else
Return restriction
End If
End Function
' Combining inference restrictions: the least upper bound of the two restrictions
Public Shared Function CombineConversionRequirements(
restriction1 As RequiredConversion,
restriction2 As RequiredConversion
) As RequiredConversion
Debug.Assert(RequiredConversion.Count = 8, "If you've updated the type argument inference restrictions, then please also update CombineInferenceRestrictions()")
' [reverse chain] [None] < AnyReverse < ReverseReference < Identity
' [middle chain] None < [Any,AnyReverse] < AnyConversionAndReverse < Identity
' [forward chain] [None] < Any < ArrayElement < Reference < Identity
' identical?
If restriction1 = restriction2 Then
Return restriction1
End If
' none?
If restriction1 = RequiredConversion.None Then
Return restriction2
ElseIf restriction2 = RequiredConversion.None Then
Return restriction1
End If
' forced to the top of the lattice?
If restriction1 = RequiredConversion.Identity OrElse restriction2 = RequiredConversion.Identity Then
Return RequiredConversion.Identity
End If
' within the reverse chain?
If (restriction1 = RequiredConversion.AnyReverse OrElse restriction1 = RequiredConversion.ReverseReference) AndAlso
(restriction2 = RequiredConversion.AnyReverse OrElse restriction2 = RequiredConversion.ReverseReference) Then
Return RequiredConversion.ReverseReference
End If
' within the middle chain?
If (restriction1 = RequiredConversion.Any OrElse restriction1 = RequiredConversion.AnyReverse OrElse restriction1 = RequiredConversion.AnyAndReverse) AndAlso
(restriction2 = RequiredConversion.Any OrElse restriction2 = RequiredConversion.AnyReverse OrElse restriction2 = RequiredConversion.AnyAndReverse) Then
Return RequiredConversion.AnyAndReverse
End If
' within the forward chain?
If (restriction1 = RequiredConversion.Any OrElse restriction1 = RequiredConversion.ArrayElement) AndAlso
(restriction2 = RequiredConversion.Any OrElse restriction2 = RequiredConversion.ArrayElement) Then
Return RequiredConversion.ArrayElement
ElseIf (restriction1 = RequiredConversion.Any OrElse restriction1 = RequiredConversion.ArrayElement OrElse restriction1 = RequiredConversion.Reference) AndAlso
(restriction2 = RequiredConversion.Any OrElse restriction2 = RequiredConversion.ArrayElement OrElse restriction2 = RequiredConversion.Reference) Then
Return RequiredConversion.Reference
End If
' otherwise we've crossed chains
Return RequiredConversion.Identity
End Function
Public Shared Function IsWideningConversion(conv As ConversionKind) As Boolean
Debug.Assert(NoConversion(conv) OrElse
((conv And ConversionKind.Widening) <> 0) <> ((conv And ConversionKind.Narrowing) <> 0))
Return (conv And ConversionKind.Widening) <> 0
End Function
Public Shared Function IsNarrowingConversion(conv As ConversionKind) As Boolean
Debug.Assert(NoConversion(conv) OrElse
((conv And ConversionKind.Widening) <> 0) <> ((conv And ConversionKind.Narrowing) <> 0))
Return (conv And ConversionKind.Narrowing) <> 0
End Function
Public Shared Function NoConversion(conv As ConversionKind) As Boolean
Return (conv And (ConversionKind.Narrowing Or ConversionKind.Widening)) = 0
End Function
Public Shared Function ConversionExists(conv As ConversionKind) As Boolean
Return (conv And (ConversionKind.Narrowing Or ConversionKind.Widening)) <> 0
End Function
Public Shared Function IsIdentityConversion(conv As ConversionKind) As Boolean
Debug.Assert(NoConversion(conv) OrElse
((conv And ConversionKind.Widening) <> 0) <> ((conv And ConversionKind.Narrowing) <> 0))
Return (conv And ConversionKind.Identity) = ConversionKind.Identity
End Function
Public Shared Function FailedDueToNumericOverflow(conv As ConversionKind) As Boolean
Return (conv And (ConversionKind.Narrowing Or ConversionKind.Widening Or ConversionKind.FailedDueToNumericOverflow)) = ConversionKind.FailedDueToNumericOverflow
End Function
Public Shared Function FailedDueToQueryLambdaBodyMismatch(conv As ConversionKind) As Boolean
Return (conv And (ConversionKind.Narrowing Or ConversionKind.Widening Or ConversionKind.FailedDueToQueryLambdaBodyMismatch)) = ConversionKind.FailedDueToQueryLambdaBodyMismatch
End Function
''' <summary>
''' Determines whether the given conversion is CLR supported conversion or not.
''' </summary>
''' <param name="conversion">The conversion.</param><returns>
''' <c>true</c> if the given conversion is a CLR supported conversion; otherwise, <c>false</c>.
''' </returns>
Public Shared Function IsCLRPredefinedConversion(conversion As ConversionKind) As Boolean
If IsIdentityConversion(conversion) Then
Return True
Else
Const combinedClrConversions = ConversionKind.Reference Or ConversionKind.Array Or ConversionKind.TypeParameter
If (conversion And combinedClrConversions) <> 0 Then
Return True
End If
End If
Return False
End Function
End Class
''' <summary>
''' Used by ClassifyUserDefinedConversion to pass an ArrayTypeSymbol that has a link back to the BoundArrayLiteral node.
''' This allows the ClassifyConversionOperatorInOutConversions to properly classify a conversion from the inferred array
''' type to the input type of a user defined conversion.
''' </summary>
''' <remarks></remarks>
Friend NotInheritable Class ArrayLiteralTypeSymbol
Inherits ArrayTypeSymbol
Private ReadOnly _arrayLiteral As BoundArrayLiteral
''' <summary>
''' Create a new ArrayTypeSymbol.
''' </summary>
Friend Sub New(arrayLiteral As BoundArrayLiteral)
Me._arrayLiteral = arrayLiteral
End Sub
Friend ReadOnly Property ArrayLiteral As BoundArrayLiteral
Get
Return _arrayLiteral
End Get
End Property
Friend Overrides ReadOnly Property IsSZArray As Boolean
Get
Return _arrayLiteral.InferredType.IsSZArray
End Get
End Property
Public Overrides ReadOnly Property Rank As Integer
Get
Return _arrayLiteral.InferredType.Rank
End Get
End Property
Friend Overrides ReadOnly Property HasDefaultSizesAndLowerBounds As Boolean
Get
Return _arrayLiteral.InferredType.HasDefaultSizesAndLowerBounds
End Get
End Property
Friend Overrides ReadOnly Property InterfacesNoUseSiteDiagnostics As ImmutableArray(Of NamedTypeSymbol)
Get
Return _arrayLiteral.InferredType.InterfacesNoUseSiteDiagnostics
End Get
End Property
Friend Overrides ReadOnly Property BaseTypeNoUseSiteDiagnostics As NamedTypeSymbol
Get
Return _arrayLiteral.InferredType.BaseTypeNoUseSiteDiagnostics
End Get
End Property
Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return _arrayLiteral.InferredType.CustomModifiers
End Get
End Property
Public Overrides ReadOnly Property ElementType As TypeSymbol
Get
Return _arrayLiteral.InferredType.ElementType
End Get
End Property
Friend Overrides Function InternalSubstituteTypeParameters(substitution As TypeSubstitution) As TypeWithModifiers
Throw ExceptionUtilities.Unreachable
End Function
End Class
End Namespace
|
KiloBravoLima/roslyn
|
src/Compilers/VisualBasic/Portable/Semantics/Conversions.vb
|
Visual Basic
|
apache-2.0
| 235,002
|
#Region "Copyright"
'
' Copyright (c) _YEAR_
' by _OWNER_
'
#End Region
#Region "Using Statements"
Imports System
Imports DotNetNuke.Entities.Modules
Imports DotNetNuke.Services.Exceptions
#End Region
Namespace _OWNER_._MODULE_
Partial Public Class Settings
Inherits ModuleSettingsBase
#Region "Base Method Implementations"
Public Overrides Sub LoadSettings()
Try
If Not Page.IsPostBack Then
txtField.Text = DirectCast(TabModuleSettings("field"), String)
End If
Catch exc As Exception
' Module failed to load
Exceptions.ProcessModuleLoadException(Me, exc)
End Try
End Sub
Public Overrides Sub UpdateSettings()
Try
ModuleController.Instance.UpdateTabModuleSetting(TabModuleId, "field", txtField.Text)
Catch exc As Exception
' Module failed to load
Exceptions.ProcessModuleLoadException(Me, exc)
End Try
End Sub
#End Region
End Class
End Namespace
|
raphael-m/Dnn.Platform
|
Website/DesktopModules/Admin/ModuleCreator/Templates/VB/Settings - User Control/Settings.ascx.vb
|
Visual Basic
|
mit
| 1,162
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.CodeRefactorings.InvertIf
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.Operations
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings.InvertIf
<ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.InvertIf), [Shared]>
Friend Class VisualBasicInvertIfCodeRefactoringProvider
Inherits AbstractInvertIfCodeRefactoringProvider
Private Shared ReadOnly s_ifNodeAnnotation As New SyntaxAnnotation
Protected Overrides Function GetSyntaxFactsService() As ISyntaxFactsService
Return VisualBasicSyntaxFactsService.Instance
End Function
Protected Overrides Function GetIfStatement(textSpan As TextSpan, token As SyntaxToken, cancellationToken As CancellationToken) As SyntaxNode
Dim relevantIfBlockOrIfStatement As ExecutableStatementSyntax = Nothing
Dim relevantSpan As TextSpan = Nothing
Dim singleLineIf = token.GetAncestor(Of SingleLineIfStatementSyntax)()
Dim multiLineIf = token.GetAncestor(Of MultiLineIfBlockSyntax)()
If singleLineIf IsNot Nothing AndAlso
singleLineIf.ElseClause IsNot Nothing Then
relevantIfBlockOrIfStatement = singleLineIf
relevantSpan = TextSpan.FromBounds(singleLineIf.IfKeyword.Span.Start, singleLineIf.Condition.Span.End)
ElseIf multiLineIf IsNot Nothing AndAlso
multiLineIf.ElseBlock IsNot Nothing AndAlso
multiLineIf.ElseIfBlocks.IsEmpty Then
relevantIfBlockOrIfStatement = multiLineIf
relevantSpan = TextSpan.FromBounds(multiLineIf.IfStatement.IfKeyword.Span.Start, multiLineIf.IfStatement.Condition.Span.End)
Else
Return Nothing
End If
If Not relevantSpan.IntersectsWith(textSpan.Start) Then
Return Nothing
End If
If token.SyntaxTree.OverlapsHiddenPosition(relevantSpan, cancellationToken) Then
Return Nothing
End If
Return relevantIfBlockOrIfStatement
End Function
Protected Overrides Function GetRootWithInvertIfStatement(document As Document, model As SemanticModel, ifStatement As SyntaxNode, cancellationToken As CancellationToken) As SyntaxNode
Dim generator = SyntaxGenerator.GetGenerator(document)
Dim result = UpdateSemanticModel(model, model.SyntaxTree.GetRoot().ReplaceNode(ifStatement, ifStatement.WithAdditionalAnnotations(s_ifNodeAnnotation)), cancellationToken)
Dim ifNode = result.Root.GetAnnotatedNodesAndTokens(s_ifNodeAnnotation).Single().AsNode()
'In order to add parentheses for SingleLineIfStatements with commas, such as
'Case Sub() [||]If True Then Dim x Else Return, Nothing
'complexify the top-most statement parenting this if-statement if necessary
Dim topMostExpression = ifNode.Ancestors().OfType(Of ExpressionSyntax).LastOrDefault()
If topMostExpression IsNot Nothing Then
Dim topMostStatement = topMostExpression.Ancestors().OfType(Of StatementSyntax).FirstOrDefault()
If topMostStatement IsNot Nothing Then
Dim explicitTopMostStatement = Simplifier.Expand(topMostStatement, result.Model, document.Project.Solution.Workspace, cancellationToken:=cancellationToken)
result = UpdateSemanticModel(result.Model, result.Root.ReplaceNode(topMostStatement, explicitTopMostStatement), cancellationToken)
ifNode = result.Root.GetAnnotatedNodesAndTokens(s_ifNodeAnnotation).Single().AsNode()
End If
End If
If (TypeOf ifNode Is SingleLineIfStatementSyntax) Then
model = InvertSingleLineIfStatement(document, DirectCast(ifNode, SingleLineIfStatementSyntax), generator, result.Model, cancellationToken)
Else
model = InvertMultiLineIfBlock(DirectCast(ifNode, MultiLineIfBlockSyntax), document, generator, result.Model, cancellationToken)
End If
' Complexify the inverted if node.
result = (model, model.SyntaxTree.GetRoot())
Dim invertedIfNode = result.Root.GetAnnotatedNodesAndTokens(s_ifNodeAnnotation).Single().AsNode()
Dim explicitInvertedIfNode = Simplifier.Expand(invertedIfNode, result.Model, document.Project.Solution.Workspace, cancellationToken:=cancellationToken)
result = UpdateSemanticModel(result.Model, result.Root.ReplaceNode(invertedIfNode, explicitInvertedIfNode), cancellationToken)
Return result.Root
End Function
Private Function UpdateSemanticModel(model As SemanticModel, root As SyntaxNode, cancellationToken As CancellationToken) As (Model As SemanticModel, Root As SyntaxNode)
Dim newModel = model.Compilation.ReplaceSyntaxTree(model.SyntaxTree, root.SyntaxTree).GetSemanticModel(root.SyntaxTree)
Return (newModel, newModel.SyntaxTree.GetRoot(cancellationToken))
End Function
Private Function InvertSingleLineIfStatement(
document As Document,
originalIfNode As SingleLineIfStatementSyntax,
generator As SyntaxGenerator,
model As SemanticModel,
cancellationToken As CancellationToken) As SemanticModel
Dim root = model.SyntaxTree.GetRoot()
Dim invertedIfNode = GetInvertedIfNode(originalIfNode, document, generator, model, cancellationToken)
Dim result = UpdateSemanticModel(model, root.ReplaceNode(originalIfNode, invertedIfNode), cancellationToken)
' Complexify the next statement if there is one.
invertedIfNode = DirectCast(result.Root.GetAnnotatedNodesAndTokens(s_ifNodeAnnotation).Single().AsNode(), SingleLineIfStatementSyntax)
Dim currentStatement As StatementSyntax = invertedIfNode
If currentStatement.HasAncestor(Of ExpressionSyntax)() Then
currentStatement = currentStatement _
.Ancestors() _
.OfType(Of ExpressionSyntax) _
.Last() _
.FirstAncestorOrSelf(Of StatementSyntax)()
End If
Dim nextStatement = currentStatement.GetNextStatement()
If nextStatement IsNot Nothing Then
Dim explicitNextStatement = Simplifier.Expand(nextStatement, result.Model, document.Project.Solution.Workspace, cancellationToken:=cancellationToken)
result = UpdateSemanticModel(result.Model, result.Root.ReplaceNode(nextStatement, explicitNextStatement), cancellationToken)
End If
Return result.Model
End Function
Private Function GetInvertedIfNode(
ifNode As SingleLineIfStatementSyntax,
document As Document,
generator As SyntaxGenerator,
semanticModel As SemanticModel,
cancellationToken As CancellationToken) As SingleLineIfStatementSyntax
Dim elseClause = ifNode.ElseClause
' If we're moving a single line if from the else body to the if body,
' and it is the last statement in the body, we have to introduce an extra
' StatementTerminator Colon and Else token.
Dim newIfStatements = elseClause.Statements
If newIfStatements.Count > 0 Then
newIfStatements = newIfStatements.Replace(
newIfStatements.Last,
newIfStatements.Last.WithTrailingTrivia(elseClause.ElseKeyword.GetPreviousToken().TrailingTrivia))
End If
If elseClause.Statements.Count > 0 AndAlso
elseClause.Statements.Last().Kind = SyntaxKind.SingleLineIfStatement Then
Dim singleLineIf = DirectCast(elseClause.Statements.Last, SingleLineIfStatementSyntax)
' Create an Extra 'Else'
If singleLineIf.ElseClause Is Nothing Then
' Replace the last EOL of the IfPart with a :
Dim trailing = singleLineIf.GetTrailingTrivia()
If trailing.Any(SyntaxKind.EndOfLineTrivia) Then
Dim eol = trailing.Last(Function(t) t.Kind = SyntaxKind.EndOfLineTrivia)
trailing = trailing.Select(Function(t) If(t = eol, SyntaxFactory.ColonTrivia(SyntaxFacts.GetText(SyntaxKind.ColonTrivia)), t)).ToSyntaxTriviaList()
End If
Dim withElsePart = singleLineIf.WithTrailingTrivia(trailing).WithElseClause(
SyntaxFactory.SingleLineElseClause(SyntaxFactory.List(Of StatementSyntax)()))
' Put the if statement with the else into the statement list
newIfStatements = elseClause.Statements.Replace(elseClause.Statements.Last, withElsePart)
End If
End If
Return ifNode.WithCondition(DirectCast(generator.Negate(ifNode.Condition, semanticModel, cancellationToken), ExpressionSyntax)) _
.WithStatements(newIfStatements) _
.WithElseClause(elseClause.WithStatements(ifNode.Statements).WithTrailingTrivia(elseClause.GetTrailingTrivia()))
End Function
#If False Then
' If we have a : following the outermost SingleLineIf, we'll want to remove it and use a statementterminator token instead.
' This ensures that the following statement will stand alone instead of becoming part of the if, as discussed in Bug 14259.
Private Function UpdateStatementList(invertedIfNode As SingleLineIfStatementSyntax, originalIfNode As SingleLineIfStatementSyntax, cancellationToken As CancellationToken) As SyntaxList(Of StatementSyntax)
Dim parentMultiLine = originalIfNode.GetContainingMultiLineExecutableBlocks().FirstOrDefault
Dim statements = parentMultiLine.GetExecutableBlockStatements()
Dim index = statements.IndexOf(originalIfNode)
If index < 0 Then
Return Nothing
End If
If Not invertedIfNode.GetTrailingTrivia().Any(Function(t) t.Kind = SyntaxKind.ColonTrivia) Then
Return Nothing
End If
' swap colon trivia to EOL
Return SyntaxFactory.List(
statements.Replace(
originalIfNode,
invertedIfNode.WithTrailingTrivia(
invertedIfNode.GetTrailingTrivia().Select(
Function(t) If(t.Kind = SyntaxKind.ColonTrivia, SyntaxFactory.ElasticCarriageReturnLineFeed, t)))))
End Function
#End If
Private Function InvertMultiLineIfBlock(originalIfNode As MultiLineIfBlockSyntax, document As Document, generator As SyntaxGenerator, model As SemanticModel, cancellationToken As CancellationToken) As SemanticModel
Dim invertedIfNode = GetInvertedIfNode(originalIfNode, document, generator, model, cancellationToken)
Dim result = UpdateSemanticModel(model, model.SyntaxTree.GetRoot().ReplaceNode(originalIfNode, invertedIfNode), cancellationToken)
Return result.Model
End Function
Private Function GetInvertedIfNode(
ifNode As MultiLineIfBlockSyntax,
document As Document,
generator As SyntaxGenerator,
semanticModel As SemanticModel,
cancellationToken As CancellationToken) As MultiLineIfBlockSyntax
Dim ifPart = ifNode
Dim elseBlock = ifNode.ElseBlock
Dim ifStatement = ifNode.IfStatement
Dim ifLeadingTrivia = ifNode.GetLeadingTrivia()
Dim endifTrailingTrivia = ifNode.EndIfStatement.GetTrailingTrivia()
Dim elseBlockLeadingTrivia = elseBlock.GetLeadingTrivia()
Dim endifLeadingTrivia = ifNode.EndIfStatement.GetLeadingTrivia()
Return ifNode _
.WithIfStatement(ifStatement.WithCondition(DirectCast(generator.Negate(ifStatement.Condition, semanticModel, cancellationToken), ExpressionSyntax))) _
.WithStatements(elseBlock.Statements) _
.WithElseBlock(elseBlock.WithStatements(ifPart.Statements).WithLeadingTrivia(endifLeadingTrivia)) _
.WithEndIfStatement(ifNode.EndIfStatement.WithTrailingTrivia(endifTrailingTrivia).WithLeadingTrivia(elseBlockLeadingTrivia)) _
.WithLeadingTrivia(ifLeadingTrivia)
End Function
Protected Overrides Function GetTitle() As String
Return VBFeaturesResources.Invert_If
End Function
End Class
End Namespace
|
AdamSpeight2008/roslyn-AdamSpeight2008
|
src/Features/VisualBasic/Portable/CodeRefactorings/InvertIf/InvertIfCodeRefactoringProvider.vb
|
Visual Basic
|
apache-2.0
| 13,315
|
' 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.Concurrent
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Collections.ObjectModel
Imports Microsoft.Cci
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting
Friend Enum RetargetOptions As Byte
RetargetPrimitiveTypesByName = 0
RetargetPrimitiveTypesByTypeCode = 1
End Enum
Partial Friend Class RetargetingModuleSymbol
''' <summary>
''' Retargeting map from underlying module to this one.
''' </summary>
Private ReadOnly _symbolMap As New ConcurrentDictionary(Of Symbol, Symbol)()
Private ReadOnly _createRetargetingMethod As Func(Of Symbol, RetargetingMethodSymbol)
Private ReadOnly _createRetargetingNamespace As Func(Of Symbol, RetargetingNamespaceSymbol)
Private ReadOnly _createRetargetingTypeParameter As Func(Of Symbol, RetargetingTypeParameterSymbol)
Private ReadOnly _createRetargetingNamedType As Func(Of Symbol, RetargetingNamedTypeSymbol)
Private ReadOnly _createRetargetingField As Func(Of Symbol, RetargetingFieldSymbol)
Private ReadOnly _createRetargetingProperty As Func(Of Symbol, RetargetingPropertySymbol)
Private ReadOnly _createRetargetingEvent As Func(Of Symbol, RetargetingEventSymbol)
Private Function CreateRetargetingMethod(symbol As Symbol) As RetargetingMethodSymbol
Debug.Assert(symbol.ContainingModule Is Me.UnderlyingModule)
Return New RetargetingMethodSymbol(Me, DirectCast(symbol, MethodSymbol))
End Function
Private Function CreateRetargetingNamespace(symbol As Symbol) As RetargetingNamespaceSymbol
Debug.Assert(symbol.ContainingModule Is Me.UnderlyingModule)
Return New RetargetingNamespaceSymbol(Me, DirectCast(symbol, NamespaceSymbol))
End Function
Private Function CreateRetargetingNamedType(symbol As Symbol) As RetargetingNamedTypeSymbol
Debug.Assert(symbol.ContainingModule Is Me.UnderlyingModule)
Return New RetargetingNamedTypeSymbol(Me, DirectCast(symbol, NamedTypeSymbol))
End Function
Private Function CreateRetargetingField(symbol As Symbol) As RetargetingFieldSymbol
Debug.Assert(symbol.ContainingModule Is Me.UnderlyingModule)
Return New RetargetingFieldSymbol(Me, DirectCast(symbol, FieldSymbol))
End Function
Private Function CreateRetargetingProperty(symbol As Symbol) As RetargetingPropertySymbol
Debug.Assert(symbol.ContainingModule Is Me.UnderlyingModule)
Return New RetargetingPropertySymbol(Me, DirectCast(symbol, PropertySymbol))
End Function
Private Function CreateRetargetingEvent(symbol As Symbol) As RetargetingEventSymbol
Debug.Assert(symbol.ContainingModule Is Me.UnderlyingModule)
Return New RetargetingEventSymbol(Me, DirectCast(symbol, EventSymbol))
End Function
Private Function CreateRetargetingTypeParameter(symbol As Symbol) As RetargetingTypeParameterSymbol
Dim typeParameter = DirectCast(symbol, TypeParameterSymbol)
Dim container = typeParameter.ContainingSymbol
Dim containingType = If(container.Kind = SymbolKind.Method,
container.ContainingType,
DirectCast(container, NamedTypeSymbol))
Debug.Assert(containingType.ContainingModule Is Me.UnderlyingModule)
Return New RetargetingTypeParameterSymbol(Me, typeParameter)
End Function
Friend Class RetargetingSymbolTranslator
Inherits VisualBasicSymbolVisitor(Of RetargetOptions, Symbol)
Private ReadOnly _retargetingModule As RetargetingModuleSymbol
Public Sub New(retargetingModule As RetargetingModuleSymbol)
Debug.Assert(retargetingModule IsNot Nothing)
_retargetingModule = retargetingModule
End Sub
''' <summary>
''' Retargeting map from underlying module to the retargeting module.
''' </summary>
Private ReadOnly Property SymbolMap As ConcurrentDictionary(Of Symbol, Symbol)
Get
Return _retargetingModule._symbolMap
End Get
End Property
''' <summary>
''' RetargetingAssemblySymbol owning retargeting module.
''' </summary>
Private ReadOnly Property RetargetingAssembly As RetargetingAssemblySymbol
Get
Return _retargetingModule._retargetingAssembly
End Get
End Property
''' <summary>
''' The map that captures information about what assembly should be retargeted
''' to what assembly. Key is the AssemblySymbol referenced by the underlying module,
''' value is the corresponding AssemblySymbol referenced by the retargeting module,
''' and corresponding retargeting map for symbols.
''' </summary>
Private ReadOnly Property RetargetingAssemblyMap As Dictionary(Of AssemblySymbol, DestinationData)
Get
Return _retargetingModule._retargetingAssemblyMap
End Get
End Property
''' <summary>
''' The underlying ModuleSymbol for the retargeting module.
''' </summary>
Private ReadOnly Property UnderlyingModule As SourceModuleSymbol
Get
Return _retargetingModule._underlyingModule
End Get
End Property
Public Function Retarget(symbol As Symbol) As Symbol
Debug.Assert(symbol.Kind <> SymbolKind.NamedType OrElse DirectCast(symbol, NamedTypeSymbol).PrimitiveTypeCode = PrimitiveTypeCode.NotPrimitive)
Return symbol.Accept(Me, RetargetOptions.RetargetPrimitiveTypesByName)
End Function
Public Function Retarget(marshallingInfo As MarshalPseudoCustomAttributeData) As MarshalPseudoCustomAttributeData
If marshallingInfo Is Nothing Then
Return Nothing
End If
' Retarget by type code - primitive types are encoded in short form in an attribute signature:
Return marshallingInfo.WithTranslatedTypes(Of TypeSymbol, RetargetingSymbolTranslator)(
Function(type, translator) translator.Retarget(DirectCast(type, TypeSymbol), RetargetOptions.RetargetPrimitiveTypesByTypeCode), Me)
End Function
Public Function Retarget(symbol As TypeSymbol, options As RetargetOptions) As TypeSymbol
Return DirectCast(symbol.Accept(Me, options), TypeSymbol)
End Function
Public Function Retarget(ns As NamespaceSymbol) As NamespaceSymbol
Return DirectCast(SymbolMap.GetOrAdd(ns, _retargetingModule._createRetargetingNamespace), NamespaceSymbol)
End Function
Private Function RetargetNamedTypeDefinition(type As NamedTypeSymbol, options As RetargetOptions) As NamedTypeSymbol
Debug.Assert(type Is type.OriginalDefinition)
' Before we do anything else, check if we need to do special retargeting
' for primitive type references encoded with enum values in metadata signatures.
If (options = RetargetOptions.RetargetPrimitiveTypesByTypeCode) Then
Dim typeCode As PrimitiveTypeCode = type.PrimitiveTypeCode
If typeCode <> PrimitiveTypeCode.NotPrimitive Then
Return RetargetingAssembly.GetPrimitiveType(typeCode)
End If
End If
If type.Kind = SymbolKind.ErrorType Then
Return Retarget(DirectCast(type, ErrorTypeSymbol))
End If
Dim retargetFrom As AssemblySymbol = type.ContainingAssembly
' Deal with "to be local" NoPia types leaking through source module.
' These are the types that are coming from assemblies linked (/l-ed)
' by the compilation that created the source module.
Dim isLocalType As Boolean
Dim useTypeIdentifierAttribute As Boolean = False
If retargetFrom Is RetargetingAssembly.UnderlyingAssembly Then
Debug.Assert(Not retargetFrom.IsLinked)
isLocalType = type.IsExplicitDefinitionOfNoPiaLocalType
Else
isLocalType = retargetFrom.IsLinked
End If
If isLocalType Then
Return RetargetNoPiaLocalType(type)
End If
' Perform general retargeting.
If retargetFrom Is RetargetingAssembly.UnderlyingAssembly Then
Return RetargetNamedTypeDefinitionFromUnderlyingAssembly(type)
End If
' Does this type come from one of the retargeted assemblies?
Dim destination As DestinationData = Nothing
If Not RetargetingAssemblyMap.TryGetValue(retargetFrom, destination) Then
' No need to retarget
Return type
End If
' Retarget from one assembly to another
Return PerformTypeRetargeting(destination, type)
End Function
Private Function RetargetNamedTypeDefinitionFromUnderlyingAssembly(type As NamedTypeSymbol) As NamedTypeSymbol
' The type is defined in the underlying assembly.
Dim [module] = type.ContainingModule
If [module] Is UnderlyingModule Then
Debug.Assert(Not type.IsExplicitDefinitionOfNoPiaLocalType)
Dim container = type.ContainingType
While container IsNot Nothing
If container.IsExplicitDefinitionOfNoPiaLocalType Then
' Types nested into local types are not supported.
Return DirectCast(Me.SymbolMap.GetOrAdd(type, New UnsupportedMetadataTypeSymbol()), NamedTypeSymbol)
End If
container = container.ContainingType
End While
Return DirectCast(Me.SymbolMap.GetOrAdd(type, _retargetingModule._createRetargetingNamedType), NamedTypeSymbol)
Else
' The type is defined in one of the added modules
Debug.Assert([module].Ordinal > 0)
Dim addedModule = DirectCast(RetargetingAssembly.Modules([module].Ordinal), PEModuleSymbol)
Debug.Assert(DirectCast([module], PEModuleSymbol).Module Is addedModule.Module)
Return RetargetNamedTypeDefinition(DirectCast(type, PENamedTypeSymbol), addedModule)
End If
End Function
Private Function RetargetNoPiaLocalType(type As NamedTypeSymbol) As NamedTypeSymbol
Dim cached As NamedTypeSymbol = Nothing
If RetargetingAssembly.m_NoPiaUnificationMap.TryGetValue(type, cached) Then
Return cached
End If
Dim result As NamedTypeSymbol
If type.ContainingSymbol.Kind <> SymbolKind.NamedType AndAlso
type.Arity = 0 Then
' Get type's identity
Dim isInterface As Boolean = (type.IsInterface)
Dim hasGuid = False
Dim interfaceGuid As String = Nothing
Dim scope As String = Nothing
If isInterface Then
' Get type's Guid
hasGuid = type.GetGuidString(interfaceGuid)
End If
Dim name = MetadataTypeName.FromFullName(type.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), forcedArity:=type.Arity)
Dim identifier As String = Nothing
If type.ContainingModule Is _retargetingModule.UnderlyingModule Then
' This is a local type explicitly declared in source. Get information from TypeIdentifier attribute.
For Each attrData In type.GetAttributes()
Dim signatureIndex = attrData.GetTargetAttributeSignatureIndex(type, AttributeDescription.TypeIdentifierAttribute)
If signatureIndex <> -1 Then
Debug.Assert(signatureIndex = 0 OrElse signatureIndex = 1)
If signatureIndex = 1 AndAlso attrData.CommonConstructorArguments.Length = 2 Then
scope = TryCast(attrData.CommonConstructorArguments(0).Value, String)
identifier = TryCast(attrData.CommonConstructorArguments(1).Value, String)
End If
Exit For
End If
Next
Else
Debug.Assert(type.ContainingAssembly IsNot RetargetingAssembly.UnderlyingAssembly)
' Note, this logic should match the one in EmbeddedType.Cci.IReference.GetAttributes.
' Here we are trying to predict what attributes we will emit on embedded type, which corresponds the
' type we are retargeting. That function actually emits the attributes.
If Not (hasGuid OrElse isInterface) Then
type.ContainingAssembly.GetGuidString(scope)
identifier = name.FullName
End If
End If
result = MetadataDecoder.SubstituteNoPiaLocalType(
name,
isInterface,
type.BaseTypeNoUseSiteDiagnostics,
interfaceGuid,
scope,
identifier,
RetargetingAssembly)
Debug.Assert(result IsNot Nothing)
Else
' TODO: report better error?
result = New UnsupportedMetadataTypeSymbol()
End If
cached = RetargetingAssembly.m_NoPiaUnificationMap.GetOrAdd(type, result)
Return cached
End Function
Private Shared Function RetargetNamedTypeDefinition(type As PENamedTypeSymbol, addedModule As PEModuleSymbol) As NamedTypeSymbol
Debug.Assert(Not type.ContainingModule.Equals(addedModule) AndAlso
DirectCast(type.ContainingModule, PEModuleSymbol).Module Is addedModule.Module)
Dim cached As TypeSymbol = Nothing
If addedModule.TypeHandleToTypeMap.TryGetValue(type.Handle, cached) Then
Return DirectCast(cached, NamedTypeSymbol)
End If
Dim result As NamedTypeSymbol
Dim containingType As NamedTypeSymbol = type.ContainingType
Dim mdName As MetadataTypeName
If containingType IsNot Nothing Then
' Nested type. We need to retarget
' the enclosing type and then go back and get the type we are interested in.
Dim scope As NamedTypeSymbol = RetargetNamedTypeDefinition(DirectCast(containingType, PENamedTypeSymbol), addedModule)
mdName = MetadataTypeName.FromTypeName(type.MetadataName, forcedArity:=type.Arity)
result = scope.LookupMetadataType(mdName)
Debug.Assert(result IsNot Nothing)
Debug.Assert(result.Arity = type.Arity)
Else
Dim namespaceName As String = If(type.GetEmittedNamespaceName(), type.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat))
mdName = MetadataTypeName.FromNamespaceAndTypeName(namespaceName, type.MetadataName, forcedArity:=type.Arity)
result = addedModule.LookupTopLevelMetadataType(mdName)
Debug.Assert(result.Arity = type.Arity)
End If
Return result
End Function
Private Shared Function PerformTypeRetargeting(
ByRef destination As DestinationData,
type As NamedTypeSymbol) As NamedTypeSymbol
Dim result As NamedTypeSymbol = Nothing
If Not destination.SymbolMap.TryGetValue(type, result) Then
' Lookup by name as a TypeRef.
Dim containingType As NamedTypeSymbol = type.ContainingType
Dim result1 As NamedTypeSymbol
Dim mdName As MetadataTypeName
If containingType IsNot Nothing Then
' This happens if type is a nested class. We need to retarget
' the enclosing class and then go back and get the type we are interested in.
Dim scope As NamedTypeSymbol = PerformTypeRetargeting(destination, containingType)
mdName = MetadataTypeName.FromTypeName(type.MetadataName, forcedArity:=type.Arity)
result1 = scope.LookupMetadataType(mdName)
Debug.Assert(result1 IsNot Nothing)
Debug.Assert(result1.Arity = type.Arity)
Else
Dim namespaceName As String = If(type.GetEmittedNamespaceName(), type.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat))
mdName = MetadataTypeName.FromNamespaceAndTypeName(namespaceName, type.MetadataName, forcedArity:=type.Arity)
result1 = destination.To.LookupTopLevelMetadataType(mdName, digThroughForwardedTypes:=True)
Debug.Assert(result1.Arity = type.Arity)
End If
result = destination.SymbolMap.GetOrAdd(type, result1)
Debug.Assert(result1.Equals(result))
End If
Return result
End Function
Public Function Retarget(type As NamedTypeSymbol, options As RetargetOptions) As NamedTypeSymbol
Dim originalDefinition As NamedTypeSymbol = type.OriginalDefinition
Dim newDefinition As NamedTypeSymbol = RetargetNamedTypeDefinition(originalDefinition, options)
If type Is originalDefinition Then
Return newDefinition
End If
If newDefinition.Kind = SymbolKind.ErrorType AndAlso Not newDefinition.IsGenericType Then
Return newDefinition
End If
' This must be a generic instantiation (i.e. constructed type).
Debug.Assert(originalDefinition.Arity = 0 OrElse type.ConstructedFrom IsNot type)
If type.IsUnboundGenericType Then
If newDefinition Is originalDefinition Then
Return type
End If
Return newDefinition.AsUnboundGenericType()
End If
Debug.Assert(type.ContainingType Is Nothing OrElse Not type.ContainingType.IsUnboundGenericType)
Dim genericType As NamedTypeSymbol = type
Dim oldArguments = ArrayBuilder(Of TypeWithModifiers).GetInstance()
Dim startOfNonInterfaceArguments As Integer = Integer.MaxValue
' Collect generic arguments for the type and its containers.
While genericType IsNot Nothing
If startOfNonInterfaceArguments = Integer.MaxValue AndAlso
Not genericType.IsInterface Then
startOfNonInterfaceArguments = oldArguments.Count
End If
Dim arity As Integer = genericType.Arity
If arity > 0 Then
Dim args = genericType.TypeArgumentsNoUseSiteDiagnostics
If genericType.HasTypeArgumentsCustomModifiers Then
Dim modifiers = genericType.TypeArgumentsCustomModifiers
For i As Integer = 0 To arity - 1
oldArguments.Add(New TypeWithModifiers(args(i), modifiers(i)))
Next
Else
For i As Integer = 0 To arity - 1
oldArguments.Add(New TypeWithModifiers(args(i)))
Next
End If
End If
genericType = genericType.ContainingType
End While
Dim anythingRetargeted As Boolean = Not originalDefinition.Equals(newDefinition)
' retarget the arguments
Dim newArguments = ArrayBuilder(Of TypeWithModifiers).GetInstance(oldArguments.Count)
For Each arg In oldArguments
Dim modifiersHaveChanged As Boolean = False
' generic instantiation is a signature
Dim newArg = New TypeWithModifiers(DirectCast(arg.Type.Accept(Me, RetargetOptions.RetargetPrimitiveTypesByTypeCode), TypeSymbol),
RetargetModifiers(arg.CustomModifiers, modifiersHaveChanged))
If Not anythingRetargeted AndAlso (modifiersHaveChanged OrElse newArg.Type <> arg.Type) Then
anythingRetargeted = True
End If
newArguments.Add(newArg)
Next
' See if it is or its enclosing type is a non-interface closed over NoPia local types.
Dim noPiaIllegalGenericInstantiation As Boolean = IsNoPiaIllegalGenericInstantiation(oldArguments, newArguments, startOfNonInterfaceArguments)
oldArguments.Free()
Dim constructedType As NamedTypeSymbol
If Not anythingRetargeted Then
' Nothing was retargeted, return original type symbol.
constructedType = [type]
Else
' Create symbol for new constructed type and return it.
' need to collect type parameters in the same order as we have arguments,
' but this should be done for the new definition.
genericType = newDefinition
Dim newParameters = ArrayBuilder(Of TypeParameterSymbol).GetInstance(newArguments.Count)
' Collect generic arguments for the type and its containers.
While genericType IsNot Nothing
If genericType.Arity > 0 Then
newParameters.AddRange(genericType.TypeParameters)
End If
genericType = genericType.ContainingType
End While
Debug.Assert(newParameters.Count = newArguments.Count)
newParameters.ReverseContents()
newArguments.ReverseContents()
Dim substitution As TypeSubstitution = TypeSubstitution.Create(newDefinition, newParameters.ToImmutableAndFree(), newArguments.ToImmutable())
constructedType = newDefinition.Construct(substitution)
End If
newArguments.Free()
If noPiaIllegalGenericInstantiation Then
constructedType = New NoPiaIllegalGenericInstantiationSymbol(constructedType)
End If
Return DirectCast(constructedType, NamedTypeSymbol)
End Function
Private Function IsNoPiaIllegalGenericInstantiation(oldArguments As ArrayBuilder(Of TypeWithModifiers), newArguments As ArrayBuilder(Of TypeWithModifiers), startOfNonInterfaceArguments As Integer) As Boolean
' TODO: Do we need to check constraints on type parameters as well?
If UnderlyingModule.ContainsExplicitDefinitionOfNoPiaLocalTypes Then
For i As Integer = startOfNonInterfaceArguments To oldArguments.Count - 1 Step 1
If IsOrClosedOverAnExplicitLocalType(oldArguments(i).Type) Then
Return True
End If
Next
End If
Dim assembliesToEmbedTypesFrom As ImmutableArray(Of AssemblySymbol) = UnderlyingModule.GetAssembliesToEmbedTypesFrom()
If assembliesToEmbedTypesFrom.Length > 0 Then
For i As Integer = startOfNonInterfaceArguments To oldArguments.Count - 1 Step 1
If MetadataDecoder.IsOrClosedOverATypeFromAssemblies(oldArguments(i).Type, assembliesToEmbedTypesFrom) Then
Return True
End If
Next
End If
Dim linkedAssemblies As ImmutableArray(Of AssemblySymbol) = RetargetingAssembly.GetLinkedReferencedAssemblies()
If Not linkedAssemblies.IsDefaultOrEmpty Then
For i As Integer = startOfNonInterfaceArguments To newArguments.Count - 1 Step 1
If MetadataDecoder.IsOrClosedOverATypeFromAssemblies(newArguments(i).Type, linkedAssemblies) Then
Return True
End If
Next
End If
Return False
End Function
''' <summary>
''' Perform a check whether the type or at least one of its generic arguments
''' is an explicitly defined local type. The check is performed recursively.
''' </summary>
Private Function IsOrClosedOverAnExplicitLocalType(symbol As TypeSymbol) As Boolean
Select Case symbol.Kind
Case SymbolKind.TypeParameter
Return False
Case SymbolKind.ArrayType
Return IsOrClosedOverAnExplicitLocalType(DirectCast(symbol, ArrayTypeSymbol).ElementType)
Case SymbolKind.ErrorType, SymbolKind.NamedType
Dim namedType = DirectCast(symbol, NamedTypeSymbol)
If symbol.OriginalDefinition.ContainingModule Is _retargetingModule.UnderlyingModule AndAlso
namedType.IsExplicitDefinitionOfNoPiaLocalType Then
Return True
End If
Do
For Each argument In namedType.TypeArgumentsNoUseSiteDiagnostics
If IsOrClosedOverAnExplicitLocalType(argument) Then
Return True
End If
Next
namedType = namedType.ContainingType
Loop While namedType IsNot Nothing
Return False
Case Else
Throw ExceptionUtilities.UnexpectedValue(symbol.Kind)
End Select
End Function
Public Overridable Function Retarget(typeParameter As TypeParameterSymbol) As TypeParameterSymbol
Return DirectCast(SymbolMap.GetOrAdd(typeParameter, _retargetingModule._createRetargetingTypeParameter), TypeParameterSymbol)
End Function
Public Function Retarget(type As ArrayTypeSymbol) As ArrayTypeSymbol
Dim oldElement As TypeSymbol = type.ElementType
Dim newElement As TypeSymbol = Retarget(oldElement, RetargetOptions.RetargetPrimitiveTypesByTypeCode)
Dim modifiersHaveChanged As Boolean = False
Dim newModifiers As ImmutableArray(Of CustomModifier) = RetargetModifiers(type.CustomModifiers, modifiersHaveChanged)
If Not modifiersHaveChanged AndAlso oldElement.Equals(newElement) Then
Return type
End If
Return New ArrayTypeSymbol(newElement, newModifiers, type.Rank, RetargetingAssembly)
End Function
Friend Function RetargetModifiers(oldModifiers As ImmutableArray(Of CustomModifier), ByRef modifiersHaveChanged As Boolean) As ImmutableArray(Of CustomModifier)
Dim i As Integer
Dim count As Integer = oldModifiers.Length
modifiersHaveChanged = False
If count <> 0 Then
Dim newModifiers As CustomModifier() = New CustomModifier(count - 1) {}
For i = 0 To count - 1 Step 1
Dim newModifier As NamedTypeSymbol = Retarget(DirectCast(oldModifiers(i).Modifier, NamedTypeSymbol), RetargetOptions.RetargetPrimitiveTypesByName) ' should be retargeted by name
If Not newModifier.Equals(oldModifiers(i).Modifier) Then
modifiersHaveChanged = True
newModifiers(i) = If(oldModifiers(i).IsOptional,
VisualBasicCustomModifier.CreateOptional(newModifier),
VisualBasicCustomModifier.CreateRequired(newModifier))
Else
newModifiers(i) = oldModifiers(i)
End If
Next
Return newModifiers.AsImmutableOrNull()
End If
Return oldModifiers
End Function
Friend Function RetargetModifiers(oldModifiers As ImmutableArray(Of CustomModifier), ByRef lazyCustomModifiers As ImmutableArray(Of CustomModifier)) As ImmutableArray(Of CustomModifier)
If lazyCustomModifiers.IsDefault Then
Dim modifiersHaveChanged As Boolean
Dim newModifiers = RetargetModifiers(oldModifiers, modifiersHaveChanged)
If Not modifiersHaveChanged Then
newModifiers = oldModifiers
End If
ImmutableInterlocked.InterlockedCompareExchange(lazyCustomModifiers, newModifiers, Nothing)
End If
Return lazyCustomModifiers
End Function
Private Function RetargetAttributes(oldAttributes As ImmutableArray(Of VisualBasicAttributeData)) As ImmutableArray(Of VisualBasicAttributeData)
Return oldAttributes.SelectAsArray(Function(a, t) t.RetargetAttributeData(a), Me)
End Function
Friend Iterator Function RetargetAttributes(attributes As IEnumerable(Of VisualBasicAttributeData)) As IEnumerable(Of VisualBasicAttributeData)
#If DEBUG Then
Dim x As SynthesizedAttributeData = Nothing
Dim y As SourceAttributeData = x ' Code below relies on the fact that SynthesizedAttributeData derives from SourceAttributeData.
x = DirectCast(y, SynthesizedAttributeData)
#End If
For Each attrData In attributes
Yield RetargetAttributeData(attrData)
Next
End Function
Private Function RetargetAttributeData(oldAttribute As VisualBasicAttributeData) As VisualBasicAttributeData
Dim oldAttributeCtor As MethodSymbol = oldAttribute.AttributeConstructor
Dim newAttributeCtor As MethodSymbol = If(oldAttributeCtor Is Nothing,
Nothing,
Retarget(oldAttributeCtor, MethodSignatureComparer.RetargetedExplicitMethodImplementationComparer))
Dim oldAttributeType As NamedTypeSymbol = oldAttribute.AttributeClass
Dim newAttributeType As NamedTypeSymbol
If newAttributeCtor IsNot Nothing Then
newAttributeType = newAttributeCtor.ContainingType
ElseIf oldAttributeType IsNot Nothing Then
newAttributeType = Retarget(oldAttributeType, RetargetOptions.RetargetPrimitiveTypesByTypeCode)
Else
newAttributeType = Nothing
End If
Dim oldCtorArguments = oldAttribute.CommonConstructorArguments
Dim newCtorArguments = RetargetAttributeConstructorArguments(oldCtorArguments)
Dim oldNamedArguments = oldAttribute.CommonNamedArguments
Dim newNamedArguments = RetargetAttributeNamedArguments(oldNamedArguments)
' Must create a RetargetingAttributeData even if the types and
' arguments are unchanged since the AttributeData instance is
' used to resolve System.Type which may require retargeting.
Return New RetargetingAttributeData(oldAttribute.ApplicationSyntaxReference,
newAttributeType,
newAttributeCtor,
newCtorArguments,
newNamedArguments,
oldAttribute.IsConditionallyOmitted,
oldAttribute.HasErrors)
End Function
Private Function RetargetAttributeConstructorArguments(constructorArguments As ImmutableArray(Of TypedConstant)) As ImmutableArray(Of TypedConstant)
Dim retargetedArguments = constructorArguments
Dim argumentsHaveChanged As Boolean = False
If Not constructorArguments.IsDefault AndAlso constructorArguments.Any() Then
Dim newArguments = ArrayBuilder(Of TypedConstant).GetInstance(constructorArguments.Length)
For Each oldArgument As TypedConstant In constructorArguments
Dim retargetedArgument As TypedConstant = RetargetTypedConstant(oldArgument, argumentsHaveChanged)
newArguments.Add(retargetedArgument)
Next
If argumentsHaveChanged Then
retargetedArguments = newArguments.ToImmutable()
End If
newArguments.Free()
End If
Return retargetedArguments
End Function
Private Function RetargetTypedConstant(oldConstant As TypedConstant, ByRef typedConstantChanged As Boolean) As TypedConstant
Dim oldConstantType As TypeSymbol = DirectCast(oldConstant.Type, TypeSymbol)
Dim newConstantType As TypeSymbol = If(oldConstantType Is Nothing,
Nothing,
Retarget(oldConstantType, RetargetOptions.RetargetPrimitiveTypesByTypeCode))
If oldConstant.Kind = TypedConstantKind.Array Then
Dim newArray = RetargetAttributeConstructorArguments(oldConstant.Values)
If newConstantType IsNot oldConstantType OrElse newArray <> oldConstant.Values Then
typedConstantChanged = True
Return New TypedConstant(newConstantType, newArray)
Else
Return oldConstant
End If
End If
Dim newConstantValue As Object
Dim oldConstantValue = oldConstant.Value
If (oldConstant.Kind = TypedConstantKind.Type) AndAlso (oldConstantValue IsNot Nothing) Then
newConstantValue = Retarget(DirectCast(oldConstantValue, TypeSymbol), RetargetOptions.RetargetPrimitiveTypesByTypeCode)
Else
newConstantValue = oldConstantValue
End If
If newConstantType IsNot oldConstantType OrElse newConstantValue IsNot oldConstantValue Then
typedConstantChanged = True
Return New TypedConstant(newConstantType, oldConstant.Kind, newConstantValue)
Else
Return oldConstant
End If
End Function
Private Function RetargetAttributeNamedArguments(namedArguments As ImmutableArray(Of KeyValuePair(Of String, TypedConstant))) As ImmutableArray(Of KeyValuePair(Of String, TypedConstant))
Dim retargetedArguments = namedArguments
Dim argumentsHaveChanged As Boolean = False
If namedArguments.Any() Then
Dim newArguments = ArrayBuilder(Of KeyValuePair(Of String, TypedConstant)).GetInstance(namedArguments.Length)
For Each oldArgument As KeyValuePair(Of String, TypedConstant) In namedArguments
Dim oldConstant As TypedConstant = oldArgument.Value
Dim typedConstantChanged As Boolean = False
Dim newConstant As TypedConstant = RetargetTypedConstant(oldConstant, typedConstantChanged)
If typedConstantChanged Then
newArguments.Add(New KeyValuePair(Of String, TypedConstant)(oldArgument.Key, newConstant))
argumentsHaveChanged = True
Else
newArguments.Add(oldArgument)
End If
Next
If argumentsHaveChanged Then
retargetedArguments = newArguments.ToImmutable()
End If
newArguments.Free()
End If
Return retargetedArguments
End Function
' Get the retargeted attributes
Friend Function GetRetargetedAttributes(underlyingSymbol As Symbol, ByRef lazyCustomAttributes As ImmutableArray(Of VisualBasicAttributeData), Optional getReturnTypeAttributes As Boolean = False) As ImmutableArray(Of VisualBasicAttributeData)
If lazyCustomAttributes.IsDefault Then
Dim oldAttributes As ImmutableArray(Of VisualBasicAttributeData)
If Not getReturnTypeAttributes Then
oldAttributes = underlyingSymbol.GetAttributes()
If underlyingSymbol.Kind = SymbolKind.Method Then
' Also compute the return type attributes here because GetAttributes
' is called during ForceComplete on the symbol.
Dim unused = DirectCast(underlyingSymbol, MethodSymbol).GetReturnTypeAttributes()
End If
Else
Debug.Assert(underlyingSymbol.Kind = SymbolKind.Method)
oldAttributes = DirectCast(underlyingSymbol, MethodSymbol).GetReturnTypeAttributes()
End If
Dim retargetedAttributes As ImmutableArray(Of VisualBasicAttributeData) = RetargetAttributes(oldAttributes)
ImmutableInterlocked.InterlockedCompareExchange(lazyCustomAttributes, retargetedAttributes, Nothing)
End If
Return lazyCustomAttributes
End Function
Public Function Retarget(type As ErrorTypeSymbol) As ErrorTypeSymbol
' TODO: if it is no longer missing in the target assembly, then we can resolve it here.
' A retargeted error symbol must trigger an error on use so that a dependent compilation won't
' improperly succeed. We therefore ensure we have a use-site diagnostic.
Dim useSiteDiagnostic = type.GetUseSiteErrorInfo
If useSiteDiagnostic IsNot Nothing Then
Return type
End If
Dim errorInfo = If(type.ErrorInfo, ErrorFactory.ErrorInfo(ERRID.ERR_InReferencedAssembly, If(type.ContainingAssembly?.Identity.GetDisplayName, "")))
Return New ExtendedErrorTypeSymbol(errorInfo, type.Name, type.Arity, type.CandidateSymbols, type.ResultKind, True)
End Function
Public Function Retarget(sequence As IEnumerable(Of NamedTypeSymbol)) As IEnumerable(Of NamedTypeSymbol)
Return sequence.Select(Function(s)
Debug.Assert(s.PrimitiveTypeCode = PrimitiveTypeCode.NotPrimitive)
Return Retarget(s, RetargetOptions.RetargetPrimitiveTypesByName)
End Function)
End Function
Public Function Retarget(arr As ImmutableArray(Of Symbol)) As ImmutableArray(Of Symbol)
Dim symbols = ArrayBuilder(Of Symbol).GetInstance(arr.Length)
For Each s As Symbol In arr
symbols.Add(Retarget(s))
Next
Return symbols.ToImmutableAndFree()
End Function
Public Function Retarget(sequence As ImmutableArray(Of NamedTypeSymbol)) As ImmutableArray(Of NamedTypeSymbol)
Dim result = ArrayBuilder(Of NamedTypeSymbol).GetInstance(sequence.Length)
For Each nts As NamedTypeSymbol In sequence
' We want this to be true in non-error cases, but it is not true in general.
' Debug.Assert(sequence(i).PrimitiveTypeCode = PrimitiveTypeCode.NotPrimitive)
result.Add(Retarget(nts, RetargetOptions.RetargetPrimitiveTypesByName))
Next
Return result.ToImmutableAndFree()
End Function
Public Function Retarget(sequence As ImmutableArray(Of TypeSymbol)) As ImmutableArray(Of TypeSymbol)
Dim result = ArrayBuilder(Of TypeSymbol).GetInstance(sequence.Length)
For Each ts As TypeSymbol In sequence
' We want this to be true in non-error cases, but it is not true in general.
' Debug.Assert(sequence(i).PrimitiveTypeCode = PrimitiveTypeCode.NotPrimitive)
result.Add(Retarget(ts, RetargetOptions.RetargetPrimitiveTypesByName))
Next
Return result.ToImmutableAndFree()
End Function
Public Function Retarget(list As ImmutableArray(Of TypeParameterSymbol)) As ImmutableArray(Of TypeParameterSymbol)
Dim parameters = ArrayBuilder(Of TypeParameterSymbol).GetInstance(list.Length)
For Each tps As TypeParameterSymbol In list
parameters.Add(Retarget(tps))
Next
Return parameters.ToImmutableAndFree()
End Function
Public Function Retarget(method As MethodSymbol) As RetargetingMethodSymbol
Return DirectCast(SymbolMap.GetOrAdd(method, _retargetingModule._createRetargetingMethod), RetargetingMethodSymbol)
End Function
Public Function Retarget(method As MethodSymbol, retargetedMethodComparer As IEqualityComparer(Of MethodSymbol)) As MethodSymbol
If method.ContainingModule Is Me.UnderlyingModule AndAlso method.IsDefinition Then
Return DirectCast(SymbolMap.GetOrAdd(method, _retargetingModule._createRetargetingMethod), RetargetingMethodSymbol)
End If
Dim containingType = method.ContainingType
Dim retargetedType = Retarget(containingType, RetargetOptions.RetargetPrimitiveTypesByName)
' NB: may return null if the method cannot be found in the retargeted type (e.g. removed in a subsequent version)
Return If(retargetedType Is containingType,
method,
FindMethodInRetargetedType(method, retargetedType, retargetedMethodComparer))
End Function
Private Function FindMethodInRetargetedType(method As MethodSymbol, retargetedType As NamedTypeSymbol, retargetedMethodComparer As IEqualityComparer(Of MethodSymbol)) As MethodSymbol
Return RetargetedTypeMethodFinder.Find(Me, method, retargetedType, retargetedMethodComparer)
End Function
Private Class RetargetedTypeMethodFinder
Inherits RetargetingSymbolTranslator
Private Sub New(retargetingModule As RetargetingModuleSymbol)
MyBase.New(retargetingModule)
End Sub
Public Shared Function Find(
translator As RetargetingSymbolTranslator,
method As MethodSymbol,
retargetedType As NamedTypeSymbol,
retargetedMethodComparer As IEqualityComparer(Of MethodSymbol)
) As MethodSymbol
If retargetedType.IsErrorType() Then
Return Nothing
End If
If Not method.IsGenericMethod Then
Return FindWorker(translator, method, retargetedType, retargetedMethodComparer)
End If
' We shouldn't run into a constructed method here because we are looking for a method
' among members of a type, constructed methods are never returned through GetMembers API.
Debug.Assert(method Is method.ConstructedFrom)
' A generic method needs special handling because its signature is very likely
' to refer to method's type parameters.
Dim finder = New RetargetedTypeMethodFinder(translator._retargetingModule)
Return FindWorker(finder, method, retargetedType, retargetedMethodComparer)
End Function
Private Shared Function FindWorker(
translator As RetargetingSymbolTranslator,
method As MethodSymbol,
retargetedType As NamedTypeSymbol,
retargetedMethodComparer As IEqualityComparer(Of MethodSymbol)
) As MethodSymbol
Dim modifiersHaveChanged As Boolean
Dim targetParamsBuilder = ArrayBuilder(Of ParameterSymbol).GetInstance(method.Parameters.Length)
For Each param As ParameterSymbol In method.Parameters
targetParamsBuilder.Add(New SignatureOnlyParameterSymbol(
translator.Retarget(param.Type, RetargetOptions.RetargetPrimitiveTypesByTypeCode),
translator.RetargetModifiers(param.CustomModifiers, modifiersHaveChanged),
param.ExplicitDefaultConstantValue, param.IsParamArray,
param.IsByRef, param.IsOut, param.IsOptional))
Next
' We will be using this symbol only for the purpose of method signature comparison,
' IndexedTypeParameterSymbols should work just fine as the type parameters for the method.
' We can't produce "real" TypeParameterSymbols without finding the method first and this
' is what we are trying to do right now.
Dim targetMethod = New SignatureOnlyMethodSymbol(method.Name, retargetedType, method.MethodKind,
method.CallingConvention,
IndexedTypeParameterSymbol.Take(method.Arity),
targetParamsBuilder.ToImmutableAndFree(),
translator.Retarget(method.ReturnType, RetargetOptions.RetargetPrimitiveTypesByTypeCode),
translator.RetargetModifiers(method.ReturnTypeCustomModifiers, modifiersHaveChanged),
ImmutableArray(Of MethodSymbol).Empty)
For Each retargetedMember As Symbol In retargetedType.GetMembers(method.Name)
If retargetedMember.Kind = SymbolKind.Method Then
Dim retargetedMethod = DirectCast(retargetedMember, MethodSymbol)
If retargetedMethodComparer.Equals(retargetedMethod, targetMethod) Then
Return retargetedMethod
End If
End If
Next
Return Nothing
End Function
Public Overrides Function Retarget(typeParameter As TypeParameterSymbol) As TypeParameterSymbol
If typeParameter.ContainingModule Is Me.UnderlyingModule Then
Return MyBase.Retarget(typeParameter)
End If
Debug.Assert(typeParameter.TypeParameterKind = TypeParameterKind.Method)
' The method symbol we are building will be using IndexedTypeParameterSymbols as
' its type parameters, therefore, we should return them here as well.
Return IndexedTypeParameterSymbol.GetTypeParameter(typeParameter.Ordinal)
End Function
End Class
Public Function Retarget(field As FieldSymbol) As RetargetingFieldSymbol
Return DirectCast(SymbolMap.GetOrAdd(field, _retargetingModule._createRetargetingField), RetargetingFieldSymbol)
End Function
Public Function Retarget([property] As PropertySymbol) As RetargetingPropertySymbol
Return DirectCast(SymbolMap.GetOrAdd([property], _retargetingModule._createRetargetingProperty), RetargetingPropertySymbol)
End Function
Public Function Retarget([event] As EventSymbol) As RetargetingEventSymbol
Return DirectCast(SymbolMap.GetOrAdd([event], _retargetingModule._createRetargetingEvent), RetargetingEventSymbol)
End Function
Public Function RetargetImplementedEvent([event] As EventSymbol) As EventSymbol
If ([event].ContainingModule Is Me.UnderlyingModule) AndAlso [event].IsDefinition Then
Return DirectCast(SymbolMap.GetOrAdd([event], _retargetingModule._createRetargetingEvent), RetargetingEventSymbol)
End If
Dim containingType = [event].ContainingType
Dim retargetedType = Retarget(containingType, RetargetOptions.RetargetPrimitiveTypesByName)
' NB: may return Nothing if the [event] cannot be found in the retargeted type (e.g. removed in a subsequent version)
Return If(retargetedType Is containingType,
[event],
FindEventInRetargetedType([event], retargetedType))
End Function
Private Function FindEventInRetargetedType([event] As EventSymbol,
retargetedType As NamedTypeSymbol) As EventSymbol
Dim retargetedEventType = Retarget([event].Type, RetargetOptions.RetargetPrimitiveTypesByName)
For Each retargetedMember As Symbol In retargetedType.GetMembers([event].Name)
If retargetedMember.Kind = SymbolKind.Event Then
Dim retargetedEvent = DirectCast(retargetedMember, EventSymbol)
If retargetedEvent.Type = retargetedEventType Then
Return retargetedEvent
End If
End If
Next
Return Nothing
End Function
Public Function Retarget([property] As PropertySymbol, retargetedPropertyComparer As IEqualityComparer(Of PropertySymbol)) As PropertySymbol
If ([property].ContainingModule Is Me.UnderlyingModule) AndAlso [property].IsDefinition Then
Return DirectCast(SymbolMap.GetOrAdd([property], _retargetingModule._createRetargetingProperty), RetargetingPropertySymbol)
End If
Dim containingType = [property].ContainingType
Dim retargetedType = Retarget(containingType, RetargetOptions.RetargetPrimitiveTypesByName)
' NB: may return Nothing if the [property] cannot be found in the retargeted type (e.g. removed in a subsequent version)
Return If(retargetedType Is containingType,
[property],
FindPropertyInRetargetedType([property], retargetedType, retargetedPropertyComparer))
End Function
Private Function FindPropertyInRetargetedType([property] As PropertySymbol, retargetedType As NamedTypeSymbol, retargetedPropertyComparer As IEqualityComparer(Of PropertySymbol)) As PropertySymbol
Dim modifiersHaveChanged As Boolean
Dim targetParamsBuilder = ArrayBuilder(Of ParameterSymbol).GetInstance()
For Each param As ParameterSymbol In [property].Parameters
targetParamsBuilder.Add(New SignatureOnlyParameterSymbol(
Retarget(param.Type, RetargetOptions.RetargetPrimitiveTypesByTypeCode),
RetargetModifiers(param.CustomModifiers, modifiersHaveChanged),
If(param.HasExplicitDefaultValue, param.ExplicitDefaultConstantValue, Nothing), param.IsParamArray,
param.IsByRef, param.IsOut, param.IsOptional))
Next
Dim targetProperty = New SignatureOnlyPropertySymbol([property].Name,
retargetedType,
[property].IsReadOnly,
[property].IsWriteOnly,
targetParamsBuilder.ToImmutableAndFree(),
Retarget([property].Type, RetargetOptions.RetargetPrimitiveTypesByTypeCode),
RetargetModifiers([property].TypeCustomModifiers, modifiersHaveChanged))
For Each retargetedMember As Symbol In retargetedType.GetMembers([property].Name)
If retargetedMember.Kind = SymbolKind.Property Then
Dim retargetedProperty = DirectCast(retargetedMember, PropertySymbol)
If retargetedPropertyComparer.Equals(retargetedProperty, targetProperty) Then
Return retargetedProperty
End If
End If
Next
Return Nothing
End Function
Public Overrides Function VisitModule(symbol As ModuleSymbol, options As RetargetOptions) As Symbol
' We shouldn't run into any other module, but the underlying module
Debug.Assert(symbol Is _retargetingModule.UnderlyingModule)
Return _retargetingModule
End Function
Public Overrides Function VisitNamespace(symbol As NamespaceSymbol, options As RetargetOptions) As Symbol
Return Retarget(symbol)
End Function
Public Overrides Function VisitNamedType(symbol As NamedTypeSymbol, options As RetargetOptions) As Symbol
Return Retarget(symbol, options)
End Function
Public Overrides Function VisitArrayType(symbol As ArrayTypeSymbol, arg As RetargetOptions) As Symbol
Return Retarget(symbol)
End Function
Public Overrides Function VisitMethod(symbol As MethodSymbol, options As RetargetOptions) As Symbol
Return Retarget(symbol)
End Function
Public Overrides Function VisitField(symbol As FieldSymbol, options As RetargetOptions) As Symbol
Return Retarget(symbol)
End Function
Public Overrides Function VisitProperty(symbol As PropertySymbol, arg As RetargetOptions) As Symbol
Return Retarget(symbol)
End Function
Public Overrides Function VisitEvent(symbol As EventSymbol, arg As RetargetOptions) As Symbol
Return Retarget(symbol)
End Function
Public Overrides Function VisitTypeParameter(symbol As TypeParameterSymbol, options As RetargetOptions) As Symbol
Return Retarget(symbol)
End Function
Public Overrides Function VisitErrorType(symbol As ErrorTypeSymbol, options As RetargetOptions) As Symbol
Return Retarget(symbol)
End Function
End Class
End Class
End Namespace
|
KevinRansom/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingSymbolTranslator.vb
|
Visual Basic
|
apache-2.0
| 58,182
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.DocumentationComments
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.SignatureHelp
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp
Partial Friend Class InvocationExpressionSignatureHelpProvider
Private Shared Function GetDelegateInvokeItems(invocationExpression As InvocationExpressionSyntax,
semanticModel As SemanticModel,
anonymousTypeDisplayService As IAnonymousTypeDisplayService,
documentationCommentFormattingService As IDocumentationCommentFormattingService,
delegateType As INamedTypeSymbol,
cancellationToken As CancellationToken) As IEnumerable(Of SignatureHelpItem)
Dim invokeMethod = delegateType.DelegateInvokeMethod
If invokeMethod Is Nothing Then
Return SpecializedCollections.EmptyEnumerable(Of SignatureHelpItem)()
End If
Dim position = invocationExpression.SpanStart
Dim item = CreateItem(
invokeMethod, semanticModel, position,
anonymousTypeDisplayService,
isVariadic:=invokeMethod.IsParams(),
documentationFactory:=Nothing,
prefixParts:=GetDelegateInvokePreambleParts(invokeMethod, semanticModel, position),
separatorParts:=GetSeparatorParts(),
suffixParts:=GetDelegateInvokePostambleParts(invokeMethod, semanticModel, position),
parameters:=GetDelegateInvokeParameters(invokeMethod, semanticModel, position, documentationCommentFormattingService, cancellationToken))
Return SpecializedCollections.SingletonEnumerable(item)
End Function
Private Shared Function GetDelegateInvokePreambleParts(invokeMethod As IMethodSymbol, semanticModel As SemanticModel, position As Integer) As IList(Of SymbolDisplayPart)
Dim displayParts = New List(Of SymbolDisplayPart)()
If invokeMethod.ContainingType.IsAnonymousType Then
displayParts.Add(New SymbolDisplayPart(SymbolDisplayPartKind.MethodName, invokeMethod, invokeMethod.Name))
Else
displayParts.AddRange(invokeMethod.ContainingType.ToMinimalDisplayParts(semanticModel, position))
End If
displayParts.Add(Punctuation(SyntaxKind.OpenParenToken))
Return displayParts
End Function
Private Shared Function GetDelegateInvokeParameters(invokeMethod As IMethodSymbol, semanticModel As SemanticModel, position As Integer, documentationCommentFormattingService As IDocumentationCommentFormattingService, cancellationToken As CancellationToken) As IList(Of SignatureHelpSymbolParameter)
Dim parameters = New List(Of SignatureHelpSymbolParameter)
For Each parameter In invokeMethod.Parameters
cancellationToken.ThrowIfCancellationRequested()
parameters.Add(New SignatureHelpSymbolParameter(
parameter.Name,
isOptional:=False,
documentationFactory:=parameter.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService),
displayParts:=parameter.ToMinimalDisplayParts(semanticModel, position)))
Next
Return parameters
End Function
Private Shared Function GetDelegateInvokePostambleParts(invokeMethod As IMethodSymbol,
semanticModel As SemanticModel,
position As Integer) As IList(Of SymbolDisplayPart)
Dim parts = New List(Of SymbolDisplayPart)
parts.Add(Punctuation(SyntaxKind.CloseParenToken))
If Not invokeMethod.ReturnsVoid Then
parts.Add(Space())
parts.Add(Keyword(SyntaxKind.AsKeyword))
parts.Add(Space())
parts.AddRange(invokeMethod.ReturnType.ToMinimalDisplayParts(semanticModel, position))
End If
Return parts
End Function
End Class
End Namespace
|
AlekseyTs/roslyn
|
src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.DelegateInvoke.vb
|
Visual Basic
|
mit
| 4,632
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.17929
'
' 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("VBMoveItem.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
|
age-killer/Electronic-invoice-document-processing
|
MailSort_CSHARP/packages/Independentsoft.Exchange.3.0.400/Tutorial/VBMoveItem/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,716
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class EgenErklaering8
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(EgenErklaering8))
Me.Label1 = New System.Windows.Forms.Label()
Me.Label2 = New System.Windows.Forms.Label()
Me.Label3 = New System.Windows.Forms.Label()
Me.Label4 = New System.Windows.Forms.Label()
Me.Label5 = New System.Windows.Forms.Label()
Me.Label6 = New System.Windows.Forms.Label()
Me.Label7 = New System.Windows.Forms.Label()
Me.Label8 = New System.Windows.Forms.Label()
Me.Label9 = New System.Windows.Forms.Label()
Me.Label10 = New System.Windows.Forms.Label()
Me.Label11 = New System.Windows.Forms.Label()
Me.Label12 = New System.Windows.Forms.Label()
Me.TextBox1 = New System.Windows.Forms.TextBox()
Me.radbtnnei50 = New System.Windows.Forms.RadioButton()
Me.radbtnja50 = New System.Windows.Forms.RadioButton()
Me.radbtnnei51 = New System.Windows.Forms.RadioButton()
Me.radbtnja51 = New System.Windows.Forms.RadioButton()
Me.radbtnnei52 = New System.Windows.Forms.RadioButton()
Me.radbtnja52 = New System.Windows.Forms.RadioButton()
Me.radbtnnei53 = New System.Windows.Forms.RadioButton()
Me.radbtnja53 = New System.Windows.Forms.RadioButton()
Me.radbtnnei54 = New System.Windows.Forms.RadioButton()
Me.radbtnja54 = New System.Windows.Forms.RadioButton()
Me.radbtnnei55 = New System.Windows.Forms.RadioButton()
Me.radbtnja55 = New System.Windows.Forms.RadioButton()
Me.radbtnnei56 = New System.Windows.Forms.RadioButton()
Me.radbtnja56 = New System.Windows.Forms.RadioButton()
Me.radbtnnei57 = New System.Windows.Forms.RadioButton()
Me.radbtnja57 = New System.Windows.Forms.RadioButton()
Me.radbtnnei58 = New System.Windows.Forms.RadioButton()
Me.radbtnja58 = New System.Windows.Forms.RadioButton()
Me.radbtnnei59 = New System.Windows.Forms.RadioButton()
Me.radbtnja59 = New System.Windows.Forms.RadioButton()
Me.btnTilbake = New System.Windows.Forms.Button()
Me.Button1 = New System.Windows.Forms.Button()
Me.GroupBox1 = New System.Windows.Forms.GroupBox()
Me.GroupBox2 = New System.Windows.Forms.GroupBox()
Me.GroupBox4 = New System.Windows.Forms.GroupBox()
Me.GroupBox5 = New System.Windows.Forms.GroupBox()
Me.GroupBox6 = New System.Windows.Forms.GroupBox()
Me.GroupBox7 = New System.Windows.Forms.GroupBox()
Me.GroupBox8 = New System.Windows.Forms.GroupBox()
Me.GroupBox9 = New System.Windows.Forms.GroupBox()
Me.GroupBox10 = New System.Windows.Forms.GroupBox()
Me.GroupBox11 = New System.Windows.Forms.GroupBox()
Me.headerpanel = New System.Windows.Forms.Panel()
Me.PictureBox6 = New System.Windows.Forms.PictureBox()
Me.btnLoggUt = New System.Windows.Forms.Button()
Me.lblAnsatt = New System.Windows.Forms.Label()
Me.sidepanel = New System.Windows.Forms.Panel()
Me.PictureBox5 = New System.Windows.Forms.PictureBox()
Me.GroupBox3 = New System.Windows.Forms.GroupBox()
Me.Panel9 = New System.Windows.Forms.Panel()
Me.Panel1 = New System.Windows.Forms.Panel()
Me.Panel2 = New System.Windows.Forms.Panel()
Me.PictureBox3 = New System.Windows.Forms.PictureBox()
Me.PictureBox1 = New System.Windows.Forms.PictureBox()
Me.PictureBox2 = New System.Windows.Forms.PictureBox()
Me.sidetoppanel = New System.Windows.Forms.Panel()
Me.logo = New System.Windows.Forms.PictureBox()
Me.btnTimeinfo = New System.Windows.Forms.Button()
Me.btnMinSide = New System.Windows.Forms.Button()
Me.btnEgenerklaring = New System.Windows.Forms.Button()
Me.btnBestill = New System.Windows.Forms.Button()
Me.GroupBox1.SuspendLayout()
Me.GroupBox2.SuspendLayout()
Me.GroupBox4.SuspendLayout()
Me.GroupBox5.SuspendLayout()
Me.GroupBox6.SuspendLayout()
Me.GroupBox7.SuspendLayout()
Me.GroupBox8.SuspendLayout()
Me.GroupBox9.SuspendLayout()
Me.GroupBox10.SuspendLayout()
Me.GroupBox11.SuspendLayout()
Me.headerpanel.SuspendLayout()
CType(Me.PictureBox6, System.ComponentModel.ISupportInitialize).BeginInit()
Me.sidepanel.SuspendLayout()
CType(Me.PictureBox5, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.PictureBox3, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.PictureBox2, System.ComponentModel.ISupportInitialize).BeginInit()
Me.sidetoppanel.SuspendLayout()
CType(Me.logo, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Font = New System.Drawing.Font("Century Gothic", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label1.ForeColor = System.Drawing.Color.FromArgb(CType(CType(42, Byte), Integer), CType(CType(88, Byte), Integer), CType(CType(125, Byte), Integer))
Me.Label1.Location = New System.Drawing.Point(172, 78)
Me.Label1.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(103, 21)
Me.Label1.TabIndex = 0
Me.Label1.Text = "Besvar også"
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.BackColor = System.Drawing.Color.Transparent
Me.Label2.Font = New System.Drawing.Font("Century Gothic", 9.0!)
Me.Label2.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.Label2.Location = New System.Drawing.Point(4, 12)
Me.Label2.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(308, 34)
Me.Label2.TabIndex = 1
Me.Label2.Text = "Har du brukt narkotika en eller flere ganger de siste" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "12 måneder?"
'
'Label3
'
Me.Label3.AutoSize = True
Me.Label3.BackColor = System.Drawing.Color.Transparent
Me.Label3.Font = New System.Drawing.Font("Century Gothic", 9.0!)
Me.Label3.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.Label3.Location = New System.Drawing.Point(8, 12)
Me.Label3.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label3.Name = "Label3"
Me.Label3.Size = New System.Drawing.Size(301, 34)
Me.Label3.TabIndex = 2
Me.Label3.Text = "Har du eller noen i familien hatt Creutzfeldt-Jakob" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "sykdom eller variant CJD?" & Global.Microsoft.VisualBasic.ChrW(13)
'
'Label4
'
Me.Label4.AutoSize = True
Me.Label4.Font = New System.Drawing.Font("Century Gothic", 9.0!)
Me.Label4.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.Label4.Location = New System.Drawing.Point(6, 9)
Me.Label4.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label4.Name = "Label4"
Me.Label4.Size = New System.Drawing.Size(305, 34)
Me.Label4.TabIndex = 4
Me.Label4.Text = "Har du i løpet av de siste tre år vært i område der " & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "malaria forekommer?"
'
'Label5
'
Me.Label5.AutoSize = True
Me.Label5.BackColor = System.Drawing.Color.Transparent
Me.Label5.Font = New System.Drawing.Font("Century Gothic", 9.0!)
Me.Label5.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.Label5.Location = New System.Drawing.Point(5, 13)
Me.Label5.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label5.Name = "Label5"
Me.Label5.Size = New System.Drawing.Size(310, 34)
Me.Label5.TabIndex = 3
Me.Label5.Text = "Har du oppholdt deg i Storbritannia i mer enn ett år" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "til sammen i perioden mello" &
"m 1980 og 1996?"
'
'Label6
'
Me.Label6.AutoSize = True
Me.Label6.Font = New System.Drawing.Font("Century Gothic", 9.0!)
Me.Label6.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.Label6.Location = New System.Drawing.Point(3, 9)
Me.Label6.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label6.Name = "Label6"
Me.Label6.Size = New System.Drawing.Size(286, 34)
Me.Label6.TabIndex = 6
Me.Label6.Text = "Har du oppholdt deg i Afrika i mer enn fem år til" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "sammen?"
'
'Label7
'
Me.Label7.AutoSize = True
Me.Label7.Font = New System.Drawing.Font("Century Gothic", 9.0!)
Me.Label7.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.Label7.Location = New System.Drawing.Point(2, 10)
Me.Label7.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label7.Name = "Label7"
Me.Label7.Size = New System.Drawing.Size(312, 34)
Me.Label7.TabIndex = 5
Me.Label7.Text = "Har du oppholdt deg sammenhengende i minst seks" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "måneder i områder der malaria fo" &
"rekommer?"
'
'Label8
'
Me.Label8.AutoSize = True
Me.Label8.Font = New System.Drawing.Font("Century Gothic", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label8.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.Label8.Location = New System.Drawing.Point(4, 9)
Me.Label8.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label8.Name = "Label8"
Me.Label8.Size = New System.Drawing.Size(311, 64)
Me.Label8.TabIndex = 8
Me.Label8.Text = resources.GetString("Label8.Text")
'
'Label9
'
Me.Label9.AutoSize = True
Me.Label9.Font = New System.Drawing.Font("Century Gothic", 9.0!)
Me.Label9.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.Label9.Location = New System.Drawing.Point(7, 12)
Me.Label9.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label9.Name = "Label9"
Me.Label9.Size = New System.Drawing.Size(271, 17)
Me.Label9.TabIndex = 7
Me.Label9.Text = "Er du eller din mor født i Amerika sør for USA?" & Global.Microsoft.VisualBasic.ChrW(13)
'
'Label10
'
Me.Label10.AutoSize = True
Me.Label10.Font = New System.Drawing.Font("Century Gothic", 9.0!)
Me.Label10.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.Label10.Location = New System.Drawing.Point(5, 11)
Me.Label10.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label10.Name = "Label10"
Me.Label10.Size = New System.Drawing.Size(278, 34)
Me.Label10.TabIndex = 9
Me.Label10.Text = "Har du deltatt i medikament forsøk de siste 12" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "måneder?"
'
'Label11
'
Me.Label11.AutoSize = True
Me.Label11.BackColor = System.Drawing.Color.Transparent
Me.Label11.Font = New System.Drawing.Font("Century Gothic", 9.0!)
Me.Label11.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.Label11.Location = New System.Drawing.Point(5, 6)
Me.Label11.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label11.Name = "Label11"
Me.Label11.Size = New System.Drawing.Size(320, 34)
Me.Label11.TabIndex = 10
Me.Label11.Text = "Jeg samtykker til at mitt plasma føres ut av Norge for" & Global.Microsoft.VisualBasic.ChrW(13) & Global.Microsoft.VisualBasic.ChrW(10) & "legemiddelproduksjon"
'
'Label12
'
Me.Label12.AutoSize = True
Me.Label12.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label12.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.Label12.Location = New System.Drawing.Point(188, 604)
Me.Label12.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label12.Name = "Label12"
Me.Label12.Size = New System.Drawing.Size(261, 17)
Me.Label12.TabIndex = 10
Me.Label12.Text = "I hvilke(t) land er du født og oppvokst?"
'
'TextBox1
'
Me.TextBox1.Font = New System.Drawing.Font("Century Gothic", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.TextBox1.Location = New System.Drawing.Point(525, 604)
Me.TextBox1.Margin = New System.Windows.Forms.Padding(4)
Me.TextBox1.Name = "TextBox1"
Me.TextBox1.Size = New System.Drawing.Size(247, 21)
Me.TextBox1.TabIndex = 60
'
'radbtnnei50
'
Me.radbtnnei50.AutoSize = True
Me.radbtnnei50.Checked = True
Me.radbtnnei50.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnnei50.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnnei50.Location = New System.Drawing.Point(543, 17)
Me.radbtnnei50.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnnei50.Name = "radbtnnei50"
Me.radbtnnei50.Size = New System.Drawing.Size(47, 21)
Me.radbtnnei50.TabIndex = 66
Me.radbtnnei50.TabStop = True
Me.radbtnnei50.Text = "Nei"
Me.radbtnnei50.UseVisualStyleBackColor = True
'
'radbtnja50
'
Me.radbtnja50.AutoSize = True
Me.radbtnja50.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnja50.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnja50.Location = New System.Drawing.Point(426, 17)
Me.radbtnja50.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnja50.Name = "radbtnja50"
Me.radbtnja50.Size = New System.Drawing.Size(41, 21)
Me.radbtnja50.TabIndex = 65
Me.radbtnja50.Text = "Ja"
Me.radbtnja50.UseVisualStyleBackColor = True
'
'radbtnnei51
'
Me.radbtnnei51.AutoSize = True
Me.radbtnnei51.BackColor = System.Drawing.Color.Transparent
Me.radbtnnei51.Checked = True
Me.radbtnnei51.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnnei51.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnnei51.Location = New System.Drawing.Point(543, 17)
Me.radbtnnei51.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnnei51.Name = "radbtnnei51"
Me.radbtnnei51.Size = New System.Drawing.Size(47, 21)
Me.radbtnnei51.TabIndex = 66
Me.radbtnnei51.TabStop = True
Me.radbtnnei51.Text = "Nei"
Me.radbtnnei51.UseVisualStyleBackColor = False
'
'radbtnja51
'
Me.radbtnja51.AutoSize = True
Me.radbtnja51.BackColor = System.Drawing.Color.Transparent
Me.radbtnja51.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnja51.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnja51.Location = New System.Drawing.Point(426, 17)
Me.radbtnja51.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnja51.Name = "radbtnja51"
Me.radbtnja51.Size = New System.Drawing.Size(41, 21)
Me.radbtnja51.TabIndex = 65
Me.radbtnja51.Text = "Ja"
Me.radbtnja51.UseVisualStyleBackColor = False
'
'radbtnnei52
'
Me.radbtnnei52.AutoSize = True
Me.radbtnnei52.Checked = True
Me.radbtnnei52.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnnei52.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnnei52.Location = New System.Drawing.Point(543, 17)
Me.radbtnnei52.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnnei52.Name = "radbtnnei52"
Me.radbtnnei52.Size = New System.Drawing.Size(47, 21)
Me.radbtnnei52.TabIndex = 66
Me.radbtnnei52.TabStop = True
Me.radbtnnei52.Text = "Nei"
Me.radbtnnei52.UseVisualStyleBackColor = True
'
'radbtnja52
'
Me.radbtnja52.AutoSize = True
Me.radbtnja52.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnja52.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnja52.Location = New System.Drawing.Point(426, 17)
Me.radbtnja52.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnja52.Name = "radbtnja52"
Me.radbtnja52.Size = New System.Drawing.Size(41, 21)
Me.radbtnja52.TabIndex = 65
Me.radbtnja52.Text = "Ja"
Me.radbtnja52.UseVisualStyleBackColor = True
'
'radbtnnei53
'
Me.radbtnnei53.AutoSize = True
Me.radbtnnei53.BackColor = System.Drawing.Color.Transparent
Me.radbtnnei53.Checked = True
Me.radbtnnei53.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnnei53.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnnei53.Location = New System.Drawing.Point(543, 17)
Me.radbtnnei53.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnnei53.Name = "radbtnnei53"
Me.radbtnnei53.Size = New System.Drawing.Size(47, 21)
Me.radbtnnei53.TabIndex = 66
Me.radbtnnei53.TabStop = True
Me.radbtnnei53.Text = "Nei"
Me.radbtnnei53.UseVisualStyleBackColor = False
'
'radbtnja53
'
Me.radbtnja53.AutoSize = True
Me.radbtnja53.BackColor = System.Drawing.Color.Transparent
Me.radbtnja53.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnja53.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnja53.Location = New System.Drawing.Point(426, 17)
Me.radbtnja53.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnja53.Name = "radbtnja53"
Me.radbtnja53.Size = New System.Drawing.Size(41, 21)
Me.radbtnja53.TabIndex = 65
Me.radbtnja53.Text = "Ja"
Me.radbtnja53.UseVisualStyleBackColor = False
'
'radbtnnei54
'
Me.radbtnnei54.AutoSize = True
Me.radbtnnei54.Checked = True
Me.radbtnnei54.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnnei54.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnnei54.Location = New System.Drawing.Point(543, 17)
Me.radbtnnei54.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnnei54.Name = "radbtnnei54"
Me.radbtnnei54.Size = New System.Drawing.Size(47, 21)
Me.radbtnnei54.TabIndex = 66
Me.radbtnnei54.TabStop = True
Me.radbtnnei54.Text = "Nei"
Me.radbtnnei54.UseVisualStyleBackColor = True
'
'radbtnja54
'
Me.radbtnja54.AutoSize = True
Me.radbtnja54.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnja54.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnja54.Location = New System.Drawing.Point(426, 17)
Me.radbtnja54.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnja54.Name = "radbtnja54"
Me.radbtnja54.Size = New System.Drawing.Size(41, 21)
Me.radbtnja54.TabIndex = 65
Me.radbtnja54.Text = "Ja"
Me.radbtnja54.UseVisualStyleBackColor = True
'
'radbtnnei55
'
Me.radbtnnei55.AutoSize = True
Me.radbtnnei55.BackColor = System.Drawing.Color.Transparent
Me.radbtnnei55.Checked = True
Me.radbtnnei55.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnnei55.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnnei55.Location = New System.Drawing.Point(543, 17)
Me.radbtnnei55.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnnei55.Name = "radbtnnei55"
Me.radbtnnei55.Size = New System.Drawing.Size(47, 21)
Me.radbtnnei55.TabIndex = 66
Me.radbtnnei55.TabStop = True
Me.radbtnnei55.Text = "Nei"
Me.radbtnnei55.UseVisualStyleBackColor = False
'
'radbtnja55
'
Me.radbtnja55.AutoSize = True
Me.radbtnja55.BackColor = System.Drawing.Color.Transparent
Me.radbtnja55.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnja55.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnja55.Location = New System.Drawing.Point(426, 17)
Me.radbtnja55.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnja55.Name = "radbtnja55"
Me.radbtnja55.Size = New System.Drawing.Size(41, 21)
Me.radbtnja55.TabIndex = 65
Me.radbtnja55.Text = "Ja"
Me.radbtnja55.UseVisualStyleBackColor = False
'
'radbtnnei56
'
Me.radbtnnei56.AutoSize = True
Me.radbtnnei56.Checked = True
Me.radbtnnei56.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnnei56.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnnei56.Location = New System.Drawing.Point(543, 8)
Me.radbtnnei56.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnnei56.Name = "radbtnnei56"
Me.radbtnnei56.Size = New System.Drawing.Size(47, 21)
Me.radbtnnei56.TabIndex = 66
Me.radbtnnei56.TabStop = True
Me.radbtnnei56.Text = "Nei"
Me.radbtnnei56.UseVisualStyleBackColor = True
'
'radbtnja56
'
Me.radbtnja56.AutoSize = True
Me.radbtnja56.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnja56.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnja56.Location = New System.Drawing.Point(426, 8)
Me.radbtnja56.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnja56.Name = "radbtnja56"
Me.radbtnja56.Size = New System.Drawing.Size(41, 21)
Me.radbtnja56.TabIndex = 65
Me.radbtnja56.Text = "Ja"
Me.radbtnja56.UseVisualStyleBackColor = True
'
'radbtnnei57
'
Me.radbtnnei57.AutoSize = True
Me.radbtnnei57.BackColor = System.Drawing.Color.Transparent
Me.radbtnnei57.Checked = True
Me.radbtnnei57.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnnei57.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnnei57.Location = New System.Drawing.Point(543, 32)
Me.radbtnnei57.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnnei57.Name = "radbtnnei57"
Me.radbtnnei57.Size = New System.Drawing.Size(47, 21)
Me.radbtnnei57.TabIndex = 66
Me.radbtnnei57.TabStop = True
Me.radbtnnei57.Text = "Nei"
Me.radbtnnei57.UseVisualStyleBackColor = False
'
'radbtnja57
'
Me.radbtnja57.AutoSize = True
Me.radbtnja57.BackColor = System.Drawing.Color.Transparent
Me.radbtnja57.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnja57.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnja57.Location = New System.Drawing.Point(426, 32)
Me.radbtnja57.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnja57.Name = "radbtnja57"
Me.radbtnja57.Size = New System.Drawing.Size(41, 21)
Me.radbtnja57.TabIndex = 65
Me.radbtnja57.Text = "Ja"
Me.radbtnja57.UseVisualStyleBackColor = False
'
'radbtnnei58
'
Me.radbtnnei58.AutoSize = True
Me.radbtnnei58.Checked = True
Me.radbtnnei58.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnnei58.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnnei58.Location = New System.Drawing.Point(543, 17)
Me.radbtnnei58.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnnei58.Name = "radbtnnei58"
Me.radbtnnei58.Size = New System.Drawing.Size(47, 21)
Me.radbtnnei58.TabIndex = 66
Me.radbtnnei58.TabStop = True
Me.radbtnnei58.Text = "Nei"
Me.radbtnnei58.UseVisualStyleBackColor = True
'
'radbtnja58
'
Me.radbtnja58.AutoSize = True
Me.radbtnja58.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnja58.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnja58.Location = New System.Drawing.Point(426, 17)
Me.radbtnja58.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnja58.Name = "radbtnja58"
Me.radbtnja58.Size = New System.Drawing.Size(41, 21)
Me.radbtnja58.TabIndex = 65
Me.radbtnja58.Text = "Ja"
Me.radbtnja58.UseVisualStyleBackColor = True
'
'radbtnnei59
'
Me.radbtnnei59.AutoSize = True
Me.radbtnnei59.Checked = True
Me.radbtnnei59.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnnei59.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnnei59.Location = New System.Drawing.Point(543, 17)
Me.radbtnnei59.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnnei59.Name = "radbtnnei59"
Me.radbtnnei59.Size = New System.Drawing.Size(47, 21)
Me.radbtnnei59.TabIndex = 66
Me.radbtnnei59.TabStop = True
Me.radbtnnei59.Text = "Nei"
Me.radbtnnei59.UseVisualStyleBackColor = True
'
'radbtnja59
'
Me.radbtnja59.AutoSize = True
Me.radbtnja59.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.radbtnja59.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.radbtnja59.Location = New System.Drawing.Point(426, 17)
Me.radbtnja59.Margin = New System.Windows.Forms.Padding(4)
Me.radbtnja59.Name = "radbtnja59"
Me.radbtnja59.Size = New System.Drawing.Size(41, 21)
Me.radbtnja59.TabIndex = 65
Me.radbtnja59.Text = "Ja"
Me.radbtnja59.UseVisualStyleBackColor = True
'
'btnTilbake
'
Me.btnTilbake.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.btnTilbake.FlatAppearance.BorderSize = 0
Me.btnTilbake.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(CType(CType(224, Byte), Integer), CType(CType(224, Byte), Integer), CType(CType(224, Byte), Integer))
Me.btnTilbake.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Silver
Me.btnTilbake.FlatStyle = System.Windows.Forms.FlatStyle.Popup
Me.btnTilbake.Font = New System.Drawing.Font("Century Gothic", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.btnTilbake.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.btnTilbake.Location = New System.Drawing.Point(454, 634)
Me.btnTilbake.Margin = New System.Windows.Forms.Padding(4)
Me.btnTilbake.Name = "btnTilbake"
Me.btnTilbake.Size = New System.Drawing.Size(155, 24)
Me.btnTilbake.TabIndex = 115
Me.btnTilbake.Text = "Tilbake"
Me.btnTilbake.UseVisualStyleBackColor = True
'
'Button1
'
Me.Button1.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.Button1.FlatAppearance.BorderSize = 0
Me.Button1.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(CType(CType(224, Byte), Integer), CType(CType(224, Byte), Integer), CType(CType(224, Byte), Integer))
Me.Button1.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Silver
Me.Button1.FlatStyle = System.Windows.Forms.FlatStyle.Popup
Me.Button1.Font = New System.Drawing.Font("Century Gothic", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Button1.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.Button1.Location = New System.Drawing.Point(617, 634)
Me.Button1.Margin = New System.Windows.Forms.Padding(4)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(155, 24)
Me.Button1.TabIndex = 114
Me.Button1.Text = "Fullfør"
Me.Button1.UseVisualStyleBackColor = True
'
'GroupBox1
'
Me.GroupBox1.Controls.Add(Me.radbtnja50)
Me.GroupBox1.Controls.Add(Me.radbtnnei50)
Me.GroupBox1.Controls.Add(Me.Label2)
Me.GroupBox1.Font = New System.Drawing.Font("Century Gothic", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.GroupBox1.Location = New System.Drawing.Point(188, 102)
Me.GroupBox1.Name = "GroupBox1"
Me.GroupBox1.Size = New System.Drawing.Size(601, 46)
Me.GroupBox1.TabIndex = 116
Me.GroupBox1.TabStop = False
'
'GroupBox2
'
Me.GroupBox2.Controls.Add(Me.Label3)
Me.GroupBox2.Controls.Add(Me.radbtnnei51)
Me.GroupBox2.Controls.Add(Me.radbtnja51)
Me.GroupBox2.Font = New System.Drawing.Font("Century Gothic", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.GroupBox2.Location = New System.Drawing.Point(188, 155)
Me.GroupBox2.Name = "GroupBox2"
Me.GroupBox2.Size = New System.Drawing.Size(601, 46)
Me.GroupBox2.TabIndex = 117
Me.GroupBox2.TabStop = False
'
'GroupBox4
'
Me.GroupBox4.Controls.Add(Me.radbtnja52)
Me.GroupBox4.Controls.Add(Me.Label5)
Me.GroupBox4.Controls.Add(Me.radbtnnei52)
Me.GroupBox4.Font = New System.Drawing.Font("Century Gothic", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.GroupBox4.Location = New System.Drawing.Point(188, 204)
Me.GroupBox4.Name = "GroupBox4"
Me.GroupBox4.Size = New System.Drawing.Size(601, 46)
Me.GroupBox4.TabIndex = 117
Me.GroupBox4.TabStop = False
'
'GroupBox5
'
Me.GroupBox5.Controls.Add(Me.Label4)
Me.GroupBox5.Controls.Add(Me.radbtnja53)
Me.GroupBox5.Controls.Add(Me.radbtnnei53)
Me.GroupBox5.Font = New System.Drawing.Font("Century Gothic", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.GroupBox5.Location = New System.Drawing.Point(188, 258)
Me.GroupBox5.Name = "GroupBox5"
Me.GroupBox5.Size = New System.Drawing.Size(601, 46)
Me.GroupBox5.TabIndex = 118
Me.GroupBox5.TabStop = False
'
'GroupBox6
'
Me.GroupBox6.Controls.Add(Me.Label7)
Me.GroupBox6.Controls.Add(Me.radbtnja54)
Me.GroupBox6.Controls.Add(Me.radbtnnei54)
Me.GroupBox6.Font = New System.Drawing.Font("Century Gothic", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.GroupBox6.Location = New System.Drawing.Point(188, 304)
Me.GroupBox6.Name = "GroupBox6"
Me.GroupBox6.Size = New System.Drawing.Size(601, 49)
Me.GroupBox6.TabIndex = 119
Me.GroupBox6.TabStop = False
'
'GroupBox7
'
Me.GroupBox7.Controls.Add(Me.Label6)
Me.GroupBox7.Controls.Add(Me.radbtnja55)
Me.GroupBox7.Controls.Add(Me.radbtnnei55)
Me.GroupBox7.Font = New System.Drawing.Font("Century Gothic", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.GroupBox7.Location = New System.Drawing.Point(188, 354)
Me.GroupBox7.Name = "GroupBox7"
Me.GroupBox7.Size = New System.Drawing.Size(601, 46)
Me.GroupBox7.TabIndex = 120
Me.GroupBox7.TabStop = False
'
'GroupBox8
'
Me.GroupBox8.Controls.Add(Me.Label9)
Me.GroupBox8.Controls.Add(Me.radbtnja56)
Me.GroupBox8.Controls.Add(Me.radbtnnei56)
Me.GroupBox8.Font = New System.Drawing.Font("Century Gothic", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.GroupBox8.Location = New System.Drawing.Point(188, 396)
Me.GroupBox8.Name = "GroupBox8"
Me.GroupBox8.Size = New System.Drawing.Size(601, 32)
Me.GroupBox8.TabIndex = 121
Me.GroupBox8.TabStop = False
'
'GroupBox9
'
Me.GroupBox9.Controls.Add(Me.Label8)
Me.GroupBox9.Controls.Add(Me.radbtnnei57)
Me.GroupBox9.Controls.Add(Me.radbtnja57)
Me.GroupBox9.Font = New System.Drawing.Font("Century Gothic", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.GroupBox9.Location = New System.Drawing.Point(188, 424)
Me.GroupBox9.Name = "GroupBox9"
Me.GroupBox9.Size = New System.Drawing.Size(601, 81)
Me.GroupBox9.TabIndex = 122
Me.GroupBox9.TabStop = False
'
'GroupBox10
'
Me.GroupBox10.Controls.Add(Me.radbtnja58)
Me.GroupBox10.Controls.Add(Me.radbtnnei58)
Me.GroupBox10.Controls.Add(Me.Label10)
Me.GroupBox10.Font = New System.Drawing.Font("Century Gothic", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.GroupBox10.Location = New System.Drawing.Point(188, 502)
Me.GroupBox10.Name = "GroupBox10"
Me.GroupBox10.Size = New System.Drawing.Size(601, 47)
Me.GroupBox10.TabIndex = 123
Me.GroupBox10.TabStop = False
'
'GroupBox11
'
Me.GroupBox11.Controls.Add(Me.radbtnnei59)
Me.GroupBox11.Controls.Add(Me.radbtnja59)
Me.GroupBox11.Controls.Add(Me.Label11)
Me.GroupBox11.Font = New System.Drawing.Font("Century Gothic", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.GroupBox11.Location = New System.Drawing.Point(188, 550)
Me.GroupBox11.Name = "GroupBox11"
Me.GroupBox11.Size = New System.Drawing.Size(601, 47)
Me.GroupBox11.TabIndex = 124
Me.GroupBox11.TabStop = False
'
'headerpanel
'
Me.headerpanel.BackColor = System.Drawing.Color.FromArgb(CType(CType(42, Byte), Integer), CType(CType(88, Byte), Integer), CType(CType(125, Byte), Integer))
Me.headerpanel.Controls.Add(Me.PictureBox6)
Me.headerpanel.Controls.Add(Me.btnLoggUt)
Me.headerpanel.Controls.Add(Me.lblAnsatt)
Me.headerpanel.Dock = System.Windows.Forms.DockStyle.Top
Me.headerpanel.Location = New System.Drawing.Point(172, 0)
Me.headerpanel.Name = "headerpanel"
Me.headerpanel.Size = New System.Drawing.Size(612, 75)
Me.headerpanel.TabIndex = 126
'
'PictureBox6
'
Me.PictureBox6.BackColor = System.Drawing.Color.Transparent
Me.PictureBox6.Image = CType(resources.GetObject("PictureBox6.Image"), System.Drawing.Image)
Me.PictureBox6.Location = New System.Drawing.Point(6, 24)
Me.PictureBox6.Name = "PictureBox6"
Me.PictureBox6.Size = New System.Drawing.Size(40, 40)
Me.PictureBox6.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage
Me.PictureBox6.TabIndex = 119
Me.PictureBox6.TabStop = False
'
'btnLoggUt
'
Me.btnLoggUt.BackColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.btnLoggUt.Cursor = System.Windows.Forms.Cursors.Hand
Me.btnLoggUt.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.btnLoggUt.FlatAppearance.BorderSize = 0
Me.btnLoggUt.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.btnLoggUt.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.btnLoggUt.FlatStyle = System.Windows.Forms.FlatStyle.Flat
Me.btnLoggUt.Font = New System.Drawing.Font("Century Gothic", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.btnLoggUt.ForeColor = System.Drawing.Color.White
Me.btnLoggUt.Location = New System.Drawing.Point(501, 19)
Me.btnLoggUt.Name = "btnLoggUt"
Me.btnLoggUt.Size = New System.Drawing.Size(99, 31)
Me.btnLoggUt.TabIndex = 6
Me.btnLoggUt.TabStop = False
Me.btnLoggUt.Text = "Logg ut"
Me.btnLoggUt.UseVisualStyleBackColor = False
'
'lblAnsatt
'
Me.lblAnsatt.AutoSize = True
Me.lblAnsatt.Font = New System.Drawing.Font("Century Gothic", 20.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.lblAnsatt.ForeColor = System.Drawing.Color.White
Me.lblAnsatt.Location = New System.Drawing.Point(52, 31)
Me.lblAnsatt.Name = "lblAnsatt"
Me.lblAnsatt.Size = New System.Drawing.Size(206, 33)
Me.lblAnsatt.TabIndex = 0
Me.lblAnsatt.Text = "Egenerklæring"
'
'sidepanel
'
Me.sidepanel.BackColor = System.Drawing.Color.FromArgb(CType(CType(42, Byte), Integer), CType(CType(88, Byte), Integer), CType(CType(125, Byte), Integer))
Me.sidepanel.Controls.Add(Me.PictureBox5)
Me.sidepanel.Controls.Add(Me.GroupBox3)
Me.sidepanel.Controls.Add(Me.Panel9)
Me.sidepanel.Controls.Add(Me.Panel1)
Me.sidepanel.Controls.Add(Me.Panel2)
Me.sidepanel.Controls.Add(Me.PictureBox3)
Me.sidepanel.Controls.Add(Me.PictureBox1)
Me.sidepanel.Controls.Add(Me.PictureBox2)
Me.sidepanel.Controls.Add(Me.sidetoppanel)
Me.sidepanel.Controls.Add(Me.btnTimeinfo)
Me.sidepanel.Controls.Add(Me.btnMinSide)
Me.sidepanel.Controls.Add(Me.btnEgenerklaring)
Me.sidepanel.Controls.Add(Me.btnBestill)
Me.sidepanel.Dock = System.Windows.Forms.DockStyle.Left
Me.sidepanel.Location = New System.Drawing.Point(0, 0)
Me.sidepanel.Name = "sidepanel"
Me.sidepanel.Size = New System.Drawing.Size(172, 661)
Me.sidepanel.TabIndex = 125
'
'PictureBox5
'
Me.PictureBox5.BackColor = System.Drawing.Color.Transparent
Me.PictureBox5.Cursor = System.Windows.Forms.Cursors.Default
Me.PictureBox5.Image = CType(resources.GetObject("PictureBox5.Image"), System.Drawing.Image)
Me.PictureBox5.Location = New System.Drawing.Point(146, 365)
Me.PictureBox5.Name = "PictureBox5"
Me.PictureBox5.Size = New System.Drawing.Size(20, 20)
Me.PictureBox5.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage
Me.PictureBox5.TabIndex = 121
Me.PictureBox5.TabStop = False
'
'GroupBox3
'
Me.GroupBox3.Location = New System.Drawing.Point(172, 200)
Me.GroupBox3.Name = "GroupBox3"
Me.GroupBox3.Size = New System.Drawing.Size(646, 46)
Me.GroupBox3.TabIndex = 117
Me.GroupBox3.TabStop = False
'
'Panel9
'
Me.Panel9.Location = New System.Drawing.Point(172, 437)
Me.Panel9.Name = "Panel9"
Me.Panel9.Size = New System.Drawing.Size(612, 27)
Me.Panel9.TabIndex = 110
'
'Panel1
'
Me.Panel1.Location = New System.Drawing.Point(172, 439)
Me.Panel1.Name = "Panel1"
Me.Panel1.Size = New System.Drawing.Size(612, 28)
Me.Panel1.TabIndex = 109
'
'Panel2
'
Me.Panel2.Location = New System.Drawing.Point(172, 365)
Me.Panel2.Name = "Panel2"
Me.Panel2.Size = New System.Drawing.Size(599, 39)
Me.Panel2.TabIndex = 105
'
'PictureBox3
'
Me.PictureBox3.BackColor = System.Drawing.Color.Transparent
Me.PictureBox3.Image = CType(resources.GetObject("PictureBox3.Image"), System.Drawing.Image)
Me.PictureBox3.Location = New System.Drawing.Point(146, 200)
Me.PictureBox3.Name = "PictureBox3"
Me.PictureBox3.Size = New System.Drawing.Size(20, 20)
Me.PictureBox3.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage
Me.PictureBox3.TabIndex = 119
Me.PictureBox3.TabStop = False
'
'PictureBox1
'
Me.PictureBox1.BackColor = System.Drawing.Color.Transparent
Me.PictureBox1.Image = CType(resources.GetObject("PictureBox1.Image"), System.Drawing.Image)
Me.PictureBox1.Location = New System.Drawing.Point(146, 278)
Me.PictureBox1.Name = "PictureBox1"
Me.PictureBox1.Size = New System.Drawing.Size(20, 20)
Me.PictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage
Me.PictureBox1.TabIndex = 1
Me.PictureBox1.TabStop = False
'
'PictureBox2
'
Me.PictureBox2.BackColor = System.Drawing.Color.Transparent
Me.PictureBox2.Image = CType(resources.GetObject("PictureBox2.Image"), System.Drawing.Image)
Me.PictureBox2.Location = New System.Drawing.Point(146, 114)
Me.PictureBox2.Name = "PictureBox2"
Me.PictureBox2.Size = New System.Drawing.Size(20, 20)
Me.PictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage
Me.PictureBox2.TabIndex = 118
Me.PictureBox2.TabStop = False
'
'sidetoppanel
'
Me.sidetoppanel.BackColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.sidetoppanel.Controls.Add(Me.logo)
Me.sidetoppanel.Dock = System.Windows.Forms.DockStyle.Top
Me.sidetoppanel.ForeColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.sidetoppanel.Location = New System.Drawing.Point(0, 0)
Me.sidetoppanel.Name = "sidetoppanel"
Me.sidetoppanel.Size = New System.Drawing.Size(172, 75)
Me.sidetoppanel.TabIndex = 17
'
'logo
'
Me.logo.Image = Global.Aorta_DB.My.Resources.Resources.Logomakr_2plwp5
Me.logo.Location = New System.Drawing.Point(39, 24)
Me.logo.Name = "logo"
Me.logo.Size = New System.Drawing.Size(89, 26)
Me.logo.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage
Me.logo.TabIndex = 0
Me.logo.TabStop = False
'
'btnTimeinfo
'
Me.btnTimeinfo.BackColor = System.Drawing.Color.Transparent
Me.btnTimeinfo.Cursor = System.Windows.Forms.Cursors.Hand
Me.btnTimeinfo.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.btnTimeinfo.FlatAppearance.BorderSize = 0
Me.btnTimeinfo.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.btnTimeinfo.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.btnTimeinfo.FlatStyle = System.Windows.Forms.FlatStyle.Flat
Me.btnTimeinfo.Font = New System.Drawing.Font("Century Gothic", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.btnTimeinfo.ForeColor = System.Drawing.Color.White
Me.btnTimeinfo.Location = New System.Drawing.Point(0, 345)
Me.btnTimeinfo.Name = "btnTimeinfo"
Me.btnTimeinfo.Size = New System.Drawing.Size(172, 54)
Me.btnTimeinfo.TabIndex = 8
Me.btnTimeinfo.TabStop = False
Me.btnTimeinfo.Text = "Timeinfo"
Me.btnTimeinfo.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
Me.btnTimeinfo.UseVisualStyleBackColor = False
'
'btnMinSide
'
Me.btnMinSide.BackColor = System.Drawing.Color.Transparent
Me.btnMinSide.Cursor = System.Windows.Forms.Cursors.Hand
Me.btnMinSide.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.btnMinSide.FlatAppearance.BorderSize = 0
Me.btnMinSide.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.btnMinSide.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.btnMinSide.FlatStyle = System.Windows.Forms.FlatStyle.Flat
Me.btnMinSide.Font = New System.Drawing.Font("Century Gothic", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.btnMinSide.ForeColor = System.Drawing.Color.White
Me.btnMinSide.Location = New System.Drawing.Point(0, 99)
Me.btnMinSide.Name = "btnMinSide"
Me.btnMinSide.Size = New System.Drawing.Size(172, 54)
Me.btnMinSide.TabIndex = 0
Me.btnMinSide.TabStop = False
Me.btnMinSide.Text = "Min side"
Me.btnMinSide.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
Me.btnMinSide.UseVisualStyleBackColor = False
'
'btnEgenerklaring
'
Me.btnEgenerklaring.BackColor = System.Drawing.Color.Transparent
Me.btnEgenerklaring.Cursor = System.Windows.Forms.Cursors.Hand
Me.btnEgenerklaring.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.btnEgenerklaring.FlatAppearance.BorderSize = 0
Me.btnEgenerklaring.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.btnEgenerklaring.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.btnEgenerklaring.FlatStyle = System.Windows.Forms.FlatStyle.Flat
Me.btnEgenerklaring.Font = New System.Drawing.Font("Century Gothic", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.btnEgenerklaring.ForeColor = System.Drawing.Color.White
Me.btnEgenerklaring.Location = New System.Drawing.Point(0, 184)
Me.btnEgenerklaring.Name = "btnEgenerklaring"
Me.btnEgenerklaring.Size = New System.Drawing.Size(172, 54)
Me.btnEgenerklaring.TabIndex = 7
Me.btnEgenerklaring.TabStop = False
Me.btnEgenerklaring.Text = "Egenerklæring"
Me.btnEgenerklaring.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
Me.btnEgenerklaring.UseVisualStyleBackColor = False
'
'btnBestill
'
Me.btnBestill.BackColor = System.Drawing.Color.Transparent
Me.btnBestill.Cursor = System.Windows.Forms.Cursors.Hand
Me.btnBestill.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.btnBestill.FlatAppearance.BorderSize = 0
Me.btnBestill.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.btnBestill.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(CType(CType(41, Byte), Integer), CType(CType(53, Byte), Integer), CType(CType(65, Byte), Integer))
Me.btnBestill.FlatStyle = System.Windows.Forms.FlatStyle.Flat
Me.btnBestill.Font = New System.Drawing.Font("Century Gothic", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.btnBestill.ForeColor = System.Drawing.Color.White
Me.btnBestill.Location = New System.Drawing.Point(0, 261)
Me.btnBestill.Name = "btnBestill"
Me.btnBestill.Size = New System.Drawing.Size(172, 54)
Me.btnBestill.TabIndex = 0
Me.btnBestill.TabStop = False
Me.btnBestill.Text = "Bestill time"
Me.btnBestill.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
Me.btnBestill.UseVisualStyleBackColor = False
'
'EgenErklaering8
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(8.0!, 19.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.BackColor = System.Drawing.Color.White
Me.ClientSize = New System.Drawing.Size(784, 661)
Me.ControlBox = False
Me.Controls.Add(Me.headerpanel)
Me.Controls.Add(Me.sidepanel)
Me.Controls.Add(Me.btnTilbake)
Me.Controls.Add(Me.Button1)
Me.Controls.Add(Me.TextBox1)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.Label12)
Me.Controls.Add(Me.GroupBox11)
Me.Controls.Add(Me.GroupBox10)
Me.Controls.Add(Me.GroupBox9)
Me.Controls.Add(Me.GroupBox8)
Me.Controls.Add(Me.GroupBox7)
Me.Controls.Add(Me.GroupBox6)
Me.Controls.Add(Me.GroupBox5)
Me.Controls.Add(Me.GroupBox4)
Me.Controls.Add(Me.GroupBox2)
Me.Controls.Add(Me.GroupBox1)
Me.Font = New System.Drawing.Font("Calibri", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None
Me.Margin = New System.Windows.Forms.Padding(4)
Me.MaximizeBox = False
Me.Name = "EgenErklaering8"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "Egenerklæring"
Me.GroupBox1.ResumeLayout(False)
Me.GroupBox1.PerformLayout()
Me.GroupBox2.ResumeLayout(False)
Me.GroupBox2.PerformLayout()
Me.GroupBox4.ResumeLayout(False)
Me.GroupBox4.PerformLayout()
Me.GroupBox5.ResumeLayout(False)
Me.GroupBox5.PerformLayout()
Me.GroupBox6.ResumeLayout(False)
Me.GroupBox6.PerformLayout()
Me.GroupBox7.ResumeLayout(False)
Me.GroupBox7.PerformLayout()
Me.GroupBox8.ResumeLayout(False)
Me.GroupBox8.PerformLayout()
Me.GroupBox9.ResumeLayout(False)
Me.GroupBox9.PerformLayout()
Me.GroupBox10.ResumeLayout(False)
Me.GroupBox10.PerformLayout()
Me.GroupBox11.ResumeLayout(False)
Me.GroupBox11.PerformLayout()
Me.headerpanel.ResumeLayout(False)
Me.headerpanel.PerformLayout()
CType(Me.PictureBox6, System.ComponentModel.ISupportInitialize).EndInit()
Me.sidepanel.ResumeLayout(False)
CType(Me.PictureBox5, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.PictureBox3, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.PictureBox2, System.ComponentModel.ISupportInitialize).EndInit()
Me.sidetoppanel.ResumeLayout(False)
CType(Me.logo, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents Label1 As Label
Friend WithEvents Label2 As Label
Friend WithEvents Label3 As Label
Friend WithEvents Label4 As Label
Friend WithEvents Label5 As Label
Friend WithEvents Label6 As Label
Friend WithEvents Label7 As Label
Friend WithEvents Label8 As Label
Friend WithEvents Label9 As Label
Friend WithEvents Label10 As Label
Friend WithEvents Label11 As Label
Friend WithEvents Label12 As Label
Friend WithEvents TextBox1 As TextBox
Friend WithEvents radbtnnei50 As RadioButton
Friend WithEvents radbtnja50 As RadioButton
Friend WithEvents radbtnnei51 As RadioButton
Friend WithEvents radbtnja51 As RadioButton
Friend WithEvents radbtnnei52 As RadioButton
Friend WithEvents radbtnja52 As RadioButton
Friend WithEvents radbtnnei53 As RadioButton
Friend WithEvents radbtnja53 As RadioButton
Friend WithEvents radbtnnei54 As RadioButton
Friend WithEvents radbtnja54 As RadioButton
Friend WithEvents radbtnnei55 As RadioButton
Friend WithEvents radbtnja55 As RadioButton
Friend WithEvents radbtnnei56 As RadioButton
Friend WithEvents radbtnja56 As RadioButton
Friend WithEvents radbtnnei57 As RadioButton
Friend WithEvents radbtnja57 As RadioButton
Friend WithEvents radbtnnei58 As RadioButton
Friend WithEvents radbtnja58 As RadioButton
Friend WithEvents radbtnnei59 As RadioButton
Friend WithEvents radbtnja59 As RadioButton
Friend WithEvents btnTilbake As Button
Friend WithEvents Button1 As Button
Friend WithEvents GroupBox1 As GroupBox
Friend WithEvents GroupBox2 As GroupBox
Friend WithEvents GroupBox4 As GroupBox
Friend WithEvents GroupBox5 As GroupBox
Friend WithEvents GroupBox6 As GroupBox
Friend WithEvents GroupBox7 As GroupBox
Friend WithEvents GroupBox8 As GroupBox
Friend WithEvents GroupBox9 As GroupBox
Friend WithEvents GroupBox10 As GroupBox
Friend WithEvents GroupBox11 As GroupBox
Friend WithEvents headerpanel As Panel
Friend WithEvents PictureBox6 As PictureBox
Friend WithEvents btnLoggUt As Button
Friend WithEvents lblAnsatt As Label
Friend WithEvents sidepanel As Panel
Friend WithEvents PictureBox5 As PictureBox
Friend WithEvents GroupBox3 As GroupBox
Friend WithEvents Panel9 As Panel
Friend WithEvents Panel1 As Panel
Friend WithEvents Panel2 As Panel
Friend WithEvents PictureBox3 As PictureBox
Friend WithEvents PictureBox1 As PictureBox
Friend WithEvents PictureBox2 As PictureBox
Friend WithEvents sidetoppanel As Panel
Friend WithEvents logo As PictureBox
Friend WithEvents btnTimeinfo As Button
Friend WithEvents btnMinSide As Button
Friend WithEvents btnEgenerklaring As Button
Friend WithEvents btnBestill As Button
End Class
|
helliio/Aorta-DB
|
Aorta-DB/Aorta-DB/EgenErklaering8.Designer.vb
|
Visual Basic
|
mit
| 61,050
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:2.0.50727.4952
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.EffectsVb.MainForm
End Sub
End Class
End Namespace
|
skor98/DtWPF
|
speechKit/Alvas.Audio/EffectsVb/My Project/Application.Designer.vb
|
Visual Basic
|
mit
| 1,477
|
Public Class frmComputer
Private Sub radDeluxe_CheckedChanged(sender As Object, e As EventArgs) Handles radDeluxe.CheckedChanged,
radSuper.CheckedChanged, chkVideo.CheckedChanged, chkInternet.CheckedChanged, chkMemory.CheckedChanged
Const DELUXE_COST As Double = 1000,
SUPER_COST As Double = 1500,
UPGRADE_VIDEO As Double = 200,
UPGRADE_INTERNET As Double = 30,
UPGRADE_MEMORY As Double = 120
Dim Cost As Double
If radDeluxe.Checked Then 'Deluxe model
Cost = DELUXE_COST
Else 'Super model
Cost = SUPER_COST
End If
If chkVideo.Checked Then
Cost += UPGRADE_VIDEO
End If
If chkInternet.Checked Then
Cost += UPGRADE_INTERNET
End If
If chkMemory.Checked Then
Cost += UPGRADE_MEMORY
End If
txtResult.Text = (Cost).ToString("C")
End Sub
End Class
|
patkub/visual-basic-intro
|
Cost of a Computer/Cost of a Computer/Form1.vb
|
Visual Basic
|
mit
| 997
|
Namespace Inspection
''' <summary>
''' Implementation of a Query Part that can be Handled Before Values have been Retrieved.
''' </summary>
''' <remarks></remarks>
Public Interface IPreQueryPart
''' <summary>
''' Retrieves the Binding Flags needed for a Reflection-Based Query.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
ReadOnly Property BindingFlags() As BindingFlags
End Interface
End Namespace
|
thiscouldbejd/Leviathan
|
_Inspection/Interfaces/IPreQueryPart.vb
|
Visual Basic
|
mit
| 524
|
Imports StaxRip.UI
Imports StaxRip.CommandLine
Imports System.Text.RegularExpressions
<Serializable()>
Public MustInherit Class VideoEncoder
Inherits Profile
Implements IComparable(Of VideoEncoder)
MustOverride Sub Encode()
MustOverride ReadOnly Property OutputExt As String
Overridable Property Passes As Integer
Overridable Property QualityMode As Boolean
Property AutoCompCheckValue As Integer = 50
Property Muxer As Muxer = New MkvMuxer
Public MustOverride Sub ShowConfigDialog()
Sub New()
CanEditValue = True
End Sub
ReadOnly Property OutputExtFull As String
Get
Return "." + OutputExt
End Get
End Property
Private OutputPathValue As String
Overridable ReadOnly Property OutputPath() As String
Get
If TypeOf Muxer Is NullMuxer Then
Return p.TargetFile
Else
Return p.TempDir + p.TargetFile.Base + "_out." + OutputExt
End If
End Get
End Property
Overridable Function GetMenu() As MenuList
End Function
Overridable Sub ImportCommandLine(commandLine As String)
End Sub
Sub SetMetaData(sourceFile As String)
If Not p.ImportVUIMetadata Then Exit Sub
Dim cl As String
Dim colour_primaries = MediaInfo.GetVideo(sourceFile, "colour_primaries")
Dim height = MediaInfo.GetVideo(sourceFile, "Height").ToInt
Select Case colour_primaries
Case "BT.2020"
cl += " --colorprim bt2020"
Case "BT.709"
If height <= 576 Then cl += " --colorprim bt709"
Case "BT.601 NTSC"
If height > 480 Then cl += " --colorprim bt470m"
Case "BT.601 PAL"
If height > 576 Then cl += " --colorprim bt470bg"
End Select
Dim transfer_characteristics = MediaInfo.GetVideo(sourceFile, "transfer_characteristics")
Select Case transfer_characteristics
Case "PQ", "SMPTE ST 2084"
cl += " --transfer smpte2084"
Case "BT.709"
If height <= 576 Then cl += " --transfer bt709"
Case "HLG"
cl += " --transfer arib-std-b67"
Case "BT.601 NTSC"
If height > 480 Then cl += " --transfer bt470m"
Case "BT.601 PAL"
If height > 576 Then cl += " --transfer bt470bg"
End Select
Dim matrix_coefficients = MediaInfo.GetVideo(sourceFile, "matrix_coefficients")
Select Case matrix_coefficients
Case "BT.2020 non-constant"
cl += " --colormatrix bt2020nc"
Case "BT.709"
cl += " --colormatrix bt709"
Case "BT.601 NTSC"
If height > 480 Then cl += " --colormatrix bt470m"
Case "BT.601 PAL"
If height > 576 Then cl += " --colormatrix bt470bg"
End Select
Dim MasteringDisplay_ColorPrimaries = MediaInfo.GetVideo(sourceFile, "MasteringDisplay_ColorPrimaries")
Dim MasteringDisplay_Luminance = MediaInfo.GetVideo(sourceFile, "MasteringDisplay_Luminance")
If MasteringDisplay_ColorPrimaries <> "" AndAlso MasteringDisplay_Luminance <> "" Then
Dim match1 = Regex.Match(MasteringDisplay_ColorPrimaries, "(BT.2020)")
Dim match2 = Regex.Match(MasteringDisplay_Luminance, "min: ([0-9\.]+) cd/m2, max: ([0-9\.]+) cd/m2")
Dim match3 = Regex.Match(MasteringDisplay_ColorPrimaries, "(Display P3)")
Dim match4 = Regex.Match(MasteringDisplay_ColorPrimaries, "(DCI P3)")
''DisPlay-P3
If match3.Success AndAlso match2.Success Then
Dim strings2 = match2.Groups.OfType(Of Group).Skip(1).Select(Function(group) CInt(group.Value.ToDouble * 10000).ToString)
cl += " --output-depth 10"
cl += " --master-display ""G(13250,34500)B(7500,3000)R(34000,16000)WP(15635,16450)L(10000000,1)"""
cl += " --hdr"
cl += " --repeat-headers"
cl += " --range limited"
cl += " --hrd"
cl += " --aud"
End If
''DCI-P3
If match4.Success AndAlso match2.Success Then
Dim strings2 = match2.Groups.OfType(Of Group).Skip(1).Select(Function(group) CInt(group.Value.ToDouble * 10000).ToString)
cl += " --output-depth 10"
cl += " --master-display ""G(13250,34500)B(7500,3000)R(34000,16000)WP(15700,17550)L(10000000,1)"""
cl += " --hdr"
cl += " --repeat-headers"
cl += " --range limited"
cl += " --hrd"
cl += " --aud"
End If
''BT.2020
If match1.Success AndAlso match2.Success Then
Dim strings2 = match2.Groups.OfType(Of Group).Skip(1).Select(Function(group) CInt(group.Value.ToDouble * 10000).ToString)
cl += " --output-depth 10"
cl += " --master-display ""G(8500,39850)B(6550,2300)R(35400,14600)WP(15635,16450)L(10000000,1)"""
cl += " --hdr"
cl += " --repeat-headers"
cl += " --range limited"
cl += " --hrd"
cl += " --aud"
End If
End If
Dim MaxCLL = MediaInfo.GetVideo(sourceFile, "MaxCLL").Trim.Left(" ").ToInt
Dim MaxFALL = MediaInfo.GetVideo(sourceFile, "MaxFALL").Trim.Left(" ").ToInt
If MaxCLL <> 0 OrElse MaxFALL <> 0 Then cl += $" --max-cll ""{MaxCLL},{MaxFALL}"""
ImportCommandLine(cl)
End Sub
Sub AfterEncoding()
If Not g.FileExists(OutputPath) Then
Throw New ErrorAbortException("Encoder output file is missing", OutputPath)
Else
Log.WriteLine(MediaInfo.GetSummary(OutputPath))
End If
End Sub
Overrides Function CreateEditControl() As Control
Dim ret As New ToolStripEx
ret.ShowItemToolTips = False
ret.GripStyle = ToolStripGripStyle.Hidden
ret.BackColor = SystemColors.Window
ret.Dock = DockStyle.Fill
ret.BackColor = SystemColors.Window
ret.LayoutStyle = ToolStripLayoutStyle.VerticalStackWithOverflow
ret.ShowControlBorder = True
ret.Font = New Font("Segoe UI", 9 * s.UIScaleFactor)
For Each i In GetMenu()
Dim b As New ToolStripButton
b.Margin = New Padding(2, 2, 0, 0)
b.Text = i.Key
b.Padding = New Padding(4)
Dim happy = i
AddHandler b.Click, Sub() happy.Value.Invoke()
b.TextAlign = ContentAlignment.MiddleLeft
ret.Items.Add(b)
Next
Return ret
End Function
Overridable ReadOnly Property IsCompCheckEnabled() As Boolean
Get
Return Not QualityMode
End Get
End Property
Protected Sub OnAfterCompCheck()
If p.CompCheckAction = CompCheckAction.AdjustFileSize Then
Dim oldSize = g.MainForm.tbTargetSize.Text
g.MainForm.tbTargetSize.Text = g.GetAutoSize(AutoCompCheckValue).ToString
Log.WriteLine("Target size: " & oldSize & " MB -> " + g.MainForm.tbTargetSize.Text + " MB")
ElseIf p.CompCheckAction = CompCheckAction.AdjustImageSize Then
AutoSetImageSize()
End If
End Sub
Sub AutoSetImageSize()
If p.VideoEncoder.AutoCompCheckValue > 0 AndAlso Calc.GetPercent <> 0 AndAlso
p.Script.IsFilterActive("Resize") Then
Dim oldWidth = p.TargetWidth
Dim oldHeight = p.TargetHeight
p.TargetWidth = Calc.FixMod16(CInt((p.SourceHeight - p.CropTop - p.CropBottom) * Calc.GetTargetDAR()))
Dim cropw = p.SourceWidth - p.CropLeft - p.CropRight
If p.TargetWidth > cropw Then
p.TargetWidth = cropw
End If
p.TargetHeight = Calc.FixMod16(CInt(p.TargetWidth / Calc.GetTargetDAR()))
While Calc.GetPercent < p.VideoEncoder.AutoCompCheckValue
If p.TargetWidth - 16 >= 320 Then
p.TargetWidth -= 16
p.TargetHeight = Calc.FixMod16(CInt(p.TargetWidth / Calc.GetTargetDAR()))
Else
Exit While
End If
End While
g.MainForm.tbTargetWidth.Text = p.TargetWidth.ToString
g.MainForm.tbTargetHeight.Text = p.TargetHeight.ToString
Log.WriteLine("Target image size: " & oldWidth.ToString & "x" & oldHeight.ToString & " -> " & p.TargetWidth.ToString & "x" & p.TargetHeight.ToString)
If p.AutoSmartCrop Then
g.MainForm.StartSmartCrop()
End If
End If
End Sub
Overrides Sub Clean()
Muxer.Clean()
End Sub
Overridable Function GetError() As String
Return Nothing
End Function
Sub OnStateChange()
g.MainForm.UpdateEncoderStateRelatedControls()
g.MainForm.SetEncoderControl(p.VideoEncoder.CreateEditControl)
g.MainForm.lgbEncoder.Text = g.ConvertPath(p.VideoEncoder.Name).Shorten(38)
g.MainForm.llMuxer.Text = p.VideoEncoder.Muxer.OutputExt.ToUpper
g.MainForm.UpdateSizeOrBitrate()
End Sub
Public Enum Modes
First = 1
Second = 2
CompCheck = 4
End Enum
Sub OpenMuxerConfigDialog()
Dim m = ObjectHelp.GetCopy(Of Muxer)(Muxer)
If m.Edit = DialogResult.OK Then
Muxer = m
g.MainForm.llMuxer.Text = Muxer.OutputExt.ToUpper
g.MainForm.Refresh()
g.MainForm.UpdateSizeOrBitrate()
g.MainForm.Assistant()
End If
End Sub
Function OpenMuxerProfilesDialog() As DialogResult
Using f As New ProfilesForm("Muxer Profiles", s.MuxerProfiles,
AddressOf LoadMuxer,
AddressOf GetMuxerProfile,
AddressOf Muxer.GetDefaults)
Return f.ShowDialog()
End Using
End Function
Public Sub LoadMuxer(profile As Profile)
Muxer = DirectCast(ObjectHelp.GetCopy(profile), Muxer)
Muxer.Init()
g.MainForm.llMuxer.Text = Muxer.OutputExt.ToUpper
Dim newPath = p.TargetFile.ChangeExt(Muxer.OutputExt)
If p.SourceFile <> "" AndAlso newPath.ToLower = p.SourceFile.ToLower Then newPath = newPath.Dir + newPath.Base + "_new" + newPath.ExtFull
g.MainForm.tbTargetFile.Text = newPath
g.MainForm.RecalcBitrate()
g.MainForm.Assistant()
End Sub
Private Function GetMuxerProfile() As Profile
Dim sb As New SelectionBox(Of Muxer)
sb.Title = "New Profile"
sb.Text = "Please select a profile."
sb.AddItem("Current Project", Muxer)
For Each i In StaxRip.Muxer.GetDefaults()
sb.AddItem(i)
Next
If sb.Show = DialogResult.OK Then Return sb.SelectedValue
Return Nothing
End Function
Shared Function GetDefaults() As List(Of VideoEncoder)
Dim ret As New List(Of VideoEncoder)
ret.Add(New x264Enc)
ret.Add(New x265Enc)
ret.Add(New Rav1e)
Dim nvidia264 As New NVEnc()
ret.Add(nvidia264)
Dim nvidia265 As New NVEnc()
nvidia265.Params.Codec.Value = 1
ret.Add(nvidia265)
ret.Add(New QSVEnc())
Dim intel265 As New QSVEnc()
intel265.Params.Codec.Value = 1
ret.Add(intel265)
ret.Add(New VCEEnc())
Dim amd265 As New VCEEnc()
amd265.Params.Codec.Value = 1
ret.Add(amd265)
Dim ffmpeg = New ffmpegEnc()
For x = 0 To ffmpeg.Params.Codec.Options.Length - 1
Dim ffmpeg2 = New ffmpegEnc()
ffmpeg2.Params.Codec.Value = x
ret.Add(ffmpeg2)
Next
Dim xvid As New BatchEncoder()
xvid.OutputFileTypeValue = "avi"
xvid.Name = "XviD"
xvid.Muxer = New ffmpegMuxer("AVI")
xvid.QualityMode = True
xvid.CommandLines = "xvid_encraw -cq 2 -smoother 0 -max_key_interval 250 -nopacked -vhqmode 4 -qpel -notrellis -max_bframes 1 -bvhq -bquant_ratio 162 -bquant_offset 0 -threads 1 -i ""%script_file%"" -avi ""%encoder_out_file%"" -par %target_sar%"
ret.Add(xvid)
ret.Add(New NullEncoder())
Return ret
End Function
Function CompareToVideoEncoder(other As VideoEncoder) As Integer Implements System.IComparable(Of VideoEncoder).CompareTo
Return Name.CompareTo(other.Name)
End Function
Overridable Sub RunCompCheck()
End Sub
Shared Sub SaveProfile(encoder As VideoEncoder)
Dim name = InputBox.Show("Please enter a profile name.", "Profile Name", encoder.Name)
If name <> "" Then
encoder.Name = name
For Each i In From prof In s.VideoEncoderProfiles.ToArray
Where prof.GetType Is encoder.GetType
If i.Name = name Then
s.VideoEncoderProfiles(s.VideoEncoderProfiles.IndexOf(i)) = encoder
Exit Sub
End If
Next
s.VideoEncoderProfiles.Insert(0, encoder)
End If
End Sub
Overrides Function Edit() As DialogResult
Using f As New ControlHostForm(Name)
f.AddControl(CreateEditControl, Nothing)
f.ShowDialog()
End Using
Return DialogResult.OK
End Function
Public Class MenuList
Inherits List(Of KeyValuePair(Of String, Action))
Overloads Sub Add(text As String, action As Action)
Add(New KeyValuePair(Of String, Action)(text, action))
End Sub
End Class
End Class
<Serializable()>
Public MustInherit Class BasicVideoEncoder
Inherits VideoEncoder
MustOverride ReadOnly Property CommandLineParams As CommandLineParams
Public Overrides Sub ImportCommandLine(commandLine As String)
ImportCommandLine(commandLine, CommandLineParams)
End Sub
Overloads Shared Sub ImportCommandLine(commandLine As String, params As CommandLineParams)
Try
If commandLine = "" Then Exit Sub
For Each i In {"tune", "preset", "profile"}
Dim match = Regex.Match(commandLine, "(.*)(--" + i + "\s\w+)(.*)")
If match.Success Then commandLine = match.Groups(2).Value + " " + match.Groups(1).Value + " " + match.Groups(3).Value
Next
Dim a = commandLine.SplitNoEmptyAndWhiteSpace(" ")
For x = 0 To a.Length - 1
For Each param In params.Items
If Not param.ImportAction Is Nothing AndAlso
param.GetSwitches.Contains(a(x)) AndAlso a.Length - 1 > x Then
param.ImportAction.Invoke(a(x + 1))
params.RaiseValueChanged(param)
Exit For
End If
If TypeOf param Is BoolParam Then
Dim boolParam = DirectCast(param, BoolParam)
If boolParam.GetSwitches.Contains(a(x)) Then
boolParam.Value = True
params.RaiseValueChanged(param)
Exit For
End If
ElseIf TypeOf param Is NumParam Then
Dim numParam = DirectCast(param, NumParam)
If numParam.GetSwitches.Contains(a(x)) AndAlso
a.Length - 1 > x AndAlso a(x + 1).IsDouble Then
numParam.Value = a(x + 1).ToDouble
params.RaiseValueChanged(param)
Exit For
End If
ElseIf TypeOf param Is OptionParam Then
Dim optionParam = DirectCast(param, OptionParam)
If optionParam.GetSwitches.Contains(a(x)) AndAlso a.Length - 1 > x Then
Dim exitFor As Boolean
If optionParam.IntegerValue Then
For xOpt = 0 To optionParam.Options.Length - 1
If a(x + 1) = xOpt.ToString Then
optionParam.Value = xOpt
params.RaiseValueChanged(param)
exitFor = True
Exit For
End If
Next
Else
For xOpt = 0 To optionParam.Options.Length - 1
If a(x + 1).Trim(""""c).ToLower = optionParam.Options(xOpt).ToLower.Replace(" ", "") Then
optionParam.Value = xOpt
params.RaiseValueChanged(param)
exitFor = True
Exit For
End If
Next
End If
If exitFor Then Exit For
End If
ElseIf TypeOf param Is StringParam Then
Dim stringParam = DirectCast(param, StringParam)
If stringParam.GetSwitches.Contains(a(x)) AndAlso a.Length - 1 > x Then
stringParam.Value = a(x + 1).Trim(""""c)
params.RaiseValueChanged(param)
Exit For
End If
End If
Next
Next
Catch ex As Exception
g.ShowException(ex)
End Try
End Sub
End Class
<Serializable()>
Public Class BatchEncoder
Inherits VideoEncoder
Sub New()
Name = "Command Line"
Muxer = New MkvMuxer()
End Sub
Property CommandLines As String = ""
Property CompCheckCommandLines As String = ""
Property OutputFileTypeValue As String
Overrides ReadOnly Property OutputExt As String
Get
If OutputFileTypeValue = "" Then OutputFileTypeValue = "h264"
Return OutputFileTypeValue
End Get
End Property
Overrides Sub ShowConfigDialog()
Using f As New BatchVideoEncoderForm(Me)
If f.ShowDialog() = DialogResult.OK Then
OnStateChange()
End If
End Using
End Sub
Overrides Function GetMenu() As MenuList
Dim ret As New MenuList
ret.Add("Codec Configuration", AddressOf ShowConfigDialog)
If IsCompCheckEnabled Then
ret.Add("Run Compressibility Check", AddressOf RunCompCheck)
End If
ret.Add("Container Configuration", AddressOf OpenMuxerConfigDialog)
Return ret
End Function
Function GetSkipStrings(commands As String) As String()
If commands.Contains("xvid_encraw") Then
Return {"key=", "frames("}
ElseIf commands.Contains("x264") Then
Return {"%]"}
ElseIf commands.Contains("NVEnc") Then
Return {"frames: "}
Else
Return {" [ETA ", ", eta ", "frames: ", "frame= "}
End If
End Function
Function GetBatchCode(value As String) As String
Dim ret = ""
For Each pack In Package.Items.Values
If TypeOf pack Is PluginPackage Then Continue For
Dim dir = pack.GetDir
If Not Directory.Exists(dir) Then Continue For
If Not dir.Contains(Folder.Startup) Then Continue For
If value.ToLower.Contains(pack.Name.ToLower) Then
ret += "@set PATH=" + dir + ";%PATH%" + BR
End If
Next
Return ret + BR + value
End Function
Overrides Sub Encode()
p.Script.Synchronize()
Dim batchPath = p.TempDir + p.TargetFile.Base + "_encode.bat"
Dim batchCode = Proc.WriteBatchFile(batchPath, GetBatchCode(Macro.Expand(CommandLines).Trim))
Using proc As New Proc
proc.Header = "Video encoding command line encoder: " + Name
proc.SkipStrings = GetSkipStrings(CommandLines)
proc.WriteLog(batchCode + BR2)
proc.File = "cmd.exe"
proc.Arguments = "/C call """ + batchPath + """"
Try
proc.Start()
Catch ex As AbortException
Throw ex
Catch ex As Exception
g.ShowException(ex)
Throw New AbortException
End Try
End Using
End Sub
Overrides Sub RunCompCheck()
If CompCheckCommandLines = "" OrElse CompCheckCommandLines.Trim = "" Then
ShowConfigDialog()
Exit Sub
End If
If Not g.VerifyRequirements Then Exit Sub
If Not g.IsValidSource Then Exit Sub
Dim script As New VideoScript
script.Engine = p.Script.Engine
script.Filters = p.Script.GetFiltersCopy
Dim code As String
Dim every = ((100 \ p.CompCheckRange) * 14).ToString
If script.Engine = ScriptEngine.AviSynth Then
code = "SelectRangeEvery(" + every + ",14)"
Else
code = "fpsnum = clip.fps_num" + BR + "fpsden = clip.fps_den" + BR +
"clip = core.std.SelectEvery(clip = clip, cycle = " + every + ", offsets = range(14))" + BR +
"clip = core.std.AssumeFPS(clip = clip, fpsnum = fpsnum, fpsden = fpsden)"
End If
script.Filters.Add(New VideoFilter("aaa", "aaa", code))
script.Path = p.TempDir + p.TargetFile.Base + "_CompCheck." + script.FileType
script.Synchronize()
Dim batchPath = p.TempDir + p.TargetFile.Base + "_CompCheck.bat"
Dim batchCode = Proc.WriteBatchFile(batchPath, GetBatchCode(Macro.Expand(CompCheckCommandLines)))
Using proc As New Proc
proc.Header = "Compressibility Check"
proc.WriteLog(code + BR2)
proc.WriteLog(batchCode + BR2)
proc.SkipStrings = GetSkipStrings(batchCode)
proc.File = "cmd.exe"
proc.Arguments = "/C call """ + batchPath + """"
Try
proc.Start()
Catch ex As AbortException
Exit Sub
Catch ex As Exception
g.ShowException(ex)
Exit Sub
End Try
End Using
Dim bits = (New FileInfo(p.TempDir + p.TargetFile.Base + "_CompCheck." + OutputExt).Length) * 8
p.Compressibility = (bits / script.GetFrames) / (p.TargetWidth * p.TargetHeight)
OnAfterCompCheck()
g.MainForm.Assistant()
Log.WriteLine(CInt(Calc.GetPercent).ToString() + " %")
Log.Save()
End Sub
End Class
<Serializable()>
Public Class NullEncoder
Inherits VideoEncoder
Sub New()
Name = "Copy/Mux"
Muxer = New MkvMuxer()
QualityMode = True
End Sub
Function GetSourceFile() As String
For Each i In {".h264", ".avc", ".h265", ".hevc", ".mpg", ".avi"}
If File.Exists(p.SourceFile.DirAndBase + "_out" + i) Then
Return p.SourceFile.DirAndBase + "_out" + i
ElseIf File.Exists(p.TempDir + p.TargetFile.Base + "_out" + i) Then
Return p.TempDir + p.TargetFile.Base + "_out" + i
End If
Next
If FileTypes.VideoText.Contains(p.SourceFile.Ext) Then
Return p.LastOriginalSourceFile
Else
Return p.SourceFile
End If
End Function
Overrides ReadOnly Property OutputPath As String
Get
Dim sourceFile = GetSourceFile()
If Not p.VideoEncoder.Muxer.IsSupported(sourceFile.Ext) Then
Select Case sourceFile.Ext
Case "mkv"
Dim streams = MediaInfo.GetVideoStreams(sourceFile)
If streams.Count = 0 Then Return sourceFile
Return p.TempDir + sourceFile.Base + streams(0).ExtFull
End Select
End If
Return sourceFile
End Get
End Property
Overrides ReadOnly Property OutputExt As String
Get
Return OutputPath.Ext
End Get
End Property
Overrides Sub Encode()
Dim sourceFile = GetSourceFile()
If Not p.VideoEncoder.Muxer.IsSupported(sourceFile.Ext) Then
Select Case FilePath.GetExt(sourceFile)
Case "mkv"
mkvDemuxer.Demux(sourceFile, Nothing, Nothing, Nothing, p, False, True)
End Select
End If
End Sub
Overrides Function GetMenu() As MenuList
Dim ret As New MenuList
ret.Add("Container Configuration", AddressOf OpenMuxerConfigDialog)
Return ret
End Function
Overrides Sub ShowConfigDialog()
End Sub
End Class
|
stax76/staxrip
|
Encoding/VideoEncoder.vb
|
Visual Basic
|
mit
| 26,000
|
Public Class ÖhmischerRechner
Dim Ergebnis As String
Dim Spannung As Single
Dim Stromstärke As Single
Dim Widerstand As Single
Private Sub cmd_Widerstand_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_Widerstand.Click
cmd_Widerstand.Visible = False
cmd_Spannung.Visible = False
cmd_Stromstärke.Visible = False
SpannungTEXT.Visible = True
StromstärkeTEXT.Visible = True
TextBox1.Visible = True
txt_Spannung.Visible = True
txt_Stromstärke.Visible = True
txt_Ergebnis.Visible = True
cmd_Teilen1.Visible = True
cmd_Hauptmenü.Visible = True
End Sub
Private Sub cmd_Spannung_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_Spannung.Click
cmd_Spannung.Visible = False
cmd_Stromstärke.Visible = False
cmd_Widerstand.Visible = False
WiderstandTEXT.Visible = True
StromstärkeTEXT.Visible = True
TextBox2.Visible = True
txt_Stromstärke.Visible = True
txt_Widerstand.Visible = True
txt_Ergebnis.Visible = True
cmd_Mal.Visible = True
cmd_Hauptmenü.Visible = True
End Sub
Private Sub cmd_Stromstärke_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_Stromstärke.Click
cmd_Stromstärke.Visible = False
cmd_Spannung.Visible = False
cmd_Widerstand.Visible = False
WiderstandTEXT.Visible = True
SpannungTEXT.Visible = True
TextBox3.Visible = True
txt_Spannung.Visible = True
txt_Widerstand.Visible = True
txt_Ergebnis.Visible = True
cmd_Teilen2.Visible = True
cmd_Hauptmenü.Visible = True
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cmd_Hauptmenü.Visible = False
cmd_Clear.Visible = False
txt_Ergebnis.Visible = False
txt_Spannung.Visible = False
txt_Stromstärke.Visible = False
txt_Widerstand.Visible = False
SpannungTEXT.Visible = True
StromstärkeTEXT.Visible = True
WiderstandTEXT.Visible = True
cmd_Mal.Visible = False
cmd_Teilen1.Visible = False
cmd_Teilen2.Visible = False
WiderstandTEXT.Visible = False
SpannungTEXT.Visible = False
StromstärkeTEXT.Visible = False
TextBox1.Visible = False
TextBox2.Visible = False
TextBox3.Visible = False
End Sub
Private Sub cmd_Beenden_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_Beenden.Click
End
End Sub
Private Sub cmd_Clear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_Clear.Click
txt_Spannung.Clear()
txt_Stromstärke.Clear()
txt_Widerstand.Clear()
txt_Ergebnis.Clear()
End Sub
Private Sub cmd_Hauptmenü_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_Hauptmenü.Click
cmd_Spannung.Visible = True
cmd_Stromstärke.Visible = True
cmd_Widerstand.Visible = True
txt_Ergebnis.Visible = False
txt_Spannung.Visible = False
txt_Stromstärke.Visible = False
txt_Widerstand.Visible = False
SpannungTEXT.Visible = True
StromstärkeTEXT.Visible = True
WiderstandTEXT.Visible = True
cmd_Mal.Visible = False
cmd_Teilen1.Visible = False
cmd_Teilen2.Visible = False
WiderstandTEXT.Visible = False
SpannungTEXT.Visible = False
StromstärkeTEXT.Visible = False
TextBox1.Visible = False
TextBox2.Visible = False
TextBox3.Visible = False
txt_Ergebnis.Text = ""
txt_Spannung.Text = ""
txt_Stromstärke.Text = ""
txt_Widerstand.Text = ""
End Sub
Private Sub cmd_Mal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_Mal.Click
Stromstärke = txt_Stromstärke.Text
Widerstand = txt_Widerstand.Text
Ergebnis = Stromstärke * Widerstand
txt_Ergebnis.Text = Ergebnis
End Sub
Private Sub cmd_Teilen1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_Teilen1.Click
Spannung = txt_Spannung.Text
Stromstärke = txt_Stromstärke.Text
Ergebnis = Spannung / Stromstärke
txt_Ergebnis.Text = Ergebnis
End Sub
Private Sub cmd_Teilen2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_Teilen2.Click
Spannung = txt_Spannung.Text
Widerstand = txt_Widerstand.Text
Ergebnis = Spannung / Widerstand
txt_Ergebnis.Text = Ergebnis
End Sub
End Class
|
KingJosy/ProjektD
|
Programmier Sammlung/Projektsammlung/Öhmischer Rechner.vb
|
Visual Basic
|
mit
| 4,955
|
Public Class Deafult
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
End Class
|
mmoyanom/tcc
|
webservice/ws/Deafult.aspx.vb
|
Visual Basic
|
apache-2.0
| 184
|
Imports System
Imports Microsoft.VisualBasic
Imports ChartDirector
Public Class polararea
Implements DemoModule
'Name of demo module
Public Function getName() As String Implements DemoModule.getName
Return "Polar Area 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
' Data for the chart
Dim data0() As Double = {5, 3, 10, 4, 3, 5, 2, 5}
Dim data1() As Double = {12, 6, 17, 6, 7, 9, 4, 7}
Dim data2() As Double = {17, 7, 22, 7, 18, 13, 5, 11}
Dim labels() As String = {"North", "North<*br*>East", "East", "South<*br*>East", "South", _
"South<*br*>West", "West", "North<*br*>West"}
' Create a PolarChart object of size 460 x 500 pixels, with a grey (e0e0e0) background and 1
' pixel 3D border
Dim c As PolarChart = New PolarChart(460, 500, &He0e0e0, &H000000, 1)
' Add a title to the chart at the top left corner using 15pt Arial Bold Italic font. Use a
' wood pattern as the title background.
c.addTitle("Polar Area Chart Demo", "Arial Bold Italic", 15).setBackground(c.patternColor( _
"wood.png"))
' Set center of plot area at (230, 280) with radius 180 pixels, and white (ffffff)
' background.
c.setPlotArea(230, 280, 180, &Hffffff)
' Set the grid style to circular grid
c.setGridStyle(False)
' Add a legend box at top-center of plot area (230, 35) using horizontal layout. Use 10pt
' Arial Bold font, with 1 pixel 3D border effect.
Dim b As LegendBox = c.addLegend(230, 35, False, "Arial Bold", 9)
b.setAlignment(Chart.TopCenter)
b.setBackground(Chart.Transparent, Chart.Transparent, 1)
' Set angular axis using the given labels
c.angularAxis().setLabels(labels)
' Specify the label format for the radial axis
c.radialAxis().setLabelFormat("{value}%")
' Set radial axis label background to semi-transparent grey (40cccccc)
c.radialAxis().setLabelStyle().setBackground(&H40cccccc, 0)
' Add the data as area layers
c.addAreaLayer(data2, -1, "5 m/s or above")
c.addAreaLayer(data1, -1, "1 - 5 m/s")
c.addAreaLayer(data0, -1, "less than 1 m/s")
' Output the chart
viewer.Chart = c
'include tool tip for the chart
viewer.ImageMap = c.getHTMLImageMap("clickable", "", _
"title='[{label}] {dataSetName}: {value}%'")
End Sub
End Class
|
jojogreen/Orbital-Mechanix-Suite
|
NetWinCharts/VBNetWinCharts/polararea.vb
|
Visual Basic
|
apache-2.0
| 2,869
|
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("ACSL-IDE")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("Microsoft")>
<Assembly: AssemblyProduct("ACSL-IDE")>
<Assembly: AssemblyCopyright("Copyright © Microsoft 2014")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("f1084f12-bb1f-429a-85a1-441b1fd0d210")>
' 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")>
|
Damillora/ascl
|
ACSL-IDE/My Project/AssemblyInfo.vb
|
Visual Basic
|
apache-2.0
| 1,152
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.CorrectNextControlVariable
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.CorrectNextControlVariable), [Shared]>
Partial Friend Class CorrectNextControlVariableCodeFixProvider
Inherits CodeFixProvider
Friend Const BC30070 As String = "BC30070" ' Next control variable does not match For loop control variable 'x'.
Friend Const BC30451 As String = "BC30451" 'BC30451: 'y' is not declared. It may be inaccessible due to its protection level.
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String)
Get
Return ImmutableArray.Create(BC30070, BC30451)
End Get
End Property
Public Overrides Function GetFixAllProvider() As FixAllProvider
' Fix All is not supported by this code fix
' https://github.com/dotnet/roslyn/issues/34470
Return Nothing
End Function
Public NotOverridable Overrides Async Function RegisterCodeFixesAsync(context As CodeFixContext) As Task
Dim root = Await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(False)
Dim node = root.FindNode(context.Span, getInnermostNodeForTie:=True)
Dim nextStatement = node.FirstAncestorOrSelf(Of NextStatementSyntax)()
If node Is Nothing OrElse nextStatement Is Nothing Then
Return
End If
' A Next statement could have multiple control variables. Find the index of the variable so that we
' can find the correct nested ForBlock and it's control variable.
' The span of the diagnostic could be over just part of the controlvariable in case of unbound identifiers
' and so find the full expression for the control variable to be replaced.
Dim indexOfControlVariable = nextStatement.ControlVariables.IndexOf(Function(n) n.Span.Contains(context.Span))
If indexOfControlVariable = -1 Then
Return
End If
Dim nodeToReplace = nextStatement.ControlVariables(indexOfControlVariable)
Dim controlVariable = FindControlVariable(nextStatement, indexOfControlVariable)
If controlVariable Is Nothing Then
Return
End If
Dim newNode = SyntaxFactory.IdentifierName(controlVariable.Value).
WithLeadingTrivia(nodeToReplace.GetLeadingTrivia()).
WithTrailingTrivia(nodeToReplace.GetTrailingTrivia())
context.RegisterCodeFix(New CorrectNextControlVariableCodeAction(context.Document, nodeToReplace, newNode), context.Diagnostics)
End Function
Private Function FindControlVariable(nextStatement As NextStatementSyntax, nestingLevel As Integer) As SyntaxToken?
Debug.Assert(nestingLevel >= 0)
' If we have code like this:
' For Each x In {1,2}
' For Each y in {1,3}
' Next y, x
' The Next statement is attached to the innermost for block. Starting from that block, the nesting level
' is the number of loops that we have to step up.
Dim currentNode As SyntaxNode = nextStatement
Dim forBlock As ForOrForEachBlockSyntax = Nothing
For i = 0 To nestingLevel
forBlock = currentNode.GetAncestor(Of ForOrForEachBlockSyntax)()
If forBlock Is Nothing Then
Return Nothing
End If
currentNode = forBlock
Next
' A ForBlockSyntax can either be a ForBlock or a ForEachBlock. Get the control variable
' from that.
Dim controlVariable As SyntaxNode = Nothing
Select Case forBlock.Kind()
Case SyntaxKind.ForBlock
Dim forStatement = DirectCast(forBlock.ForOrForEachStatement, ForStatementSyntax)
controlVariable = forStatement.ControlVariable
Exit Select
Case SyntaxKind.ForEachBlock
Dim forEachStatement = DirectCast(forBlock.ForOrForEachStatement, ForEachStatementSyntax)
controlVariable = forEachStatement.ControlVariable
Exit Select
Case Else
Debug.Assert(False, "Unknown next statement")
Return Nothing
End Select
' The control variable can either be:
' For x = 1 to 10
' For x As Integer = 1 to 10
Select Case controlVariable.Kind()
Case SyntaxKind.IdentifierName
Return DirectCast(controlVariable, IdentifierNameSyntax).Identifier
Case SyntaxKind.VariableDeclarator
Return DirectCast(controlVariable, VariableDeclaratorSyntax).Names.Single().Identifier
Case Else
Debug.Assert(False, "Unknown control variable expression")
Return Nothing
End Select
End Function
End Class
End Namespace
|
reaction1989/roslyn
|
src/Features/VisualBasic/Portable/CodeFixes/CorrectNextControlVariable/CorrectNextControlVariableCodeFixProvider.vb
|
Visual Basic
|
apache-2.0
| 5,942
|
Namespace Controls.TabEx
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class TabHeader
Inherits System.Windows.Forms.UserControl
'UserControl overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(TabHeader))
MainFlow = New System.Windows.Forms.FlowLayoutPanel()
BtnNew = New ExButton()
MainFlow.SuspendLayout()
SuspendLayout()
'
'MainFlow
'
MainFlow.BackColor = System.Drawing.Color.Transparent
MainFlow.Controls.Add(Me.BtnNew)
MainFlow.Dock = System.Windows.Forms.DockStyle.Fill
MainFlow.Location = New System.Drawing.Point(0, 0)
MainFlow.Name = "MainFlow"
MainFlow.Padding = New System.Windows.Forms.Padding(0, 3, 0, 0)
MainFlow.Size = New System.Drawing.Size(1151, 107)
MainFlow.TabIndex = 0
MainFlow.WrapContents = False
'
'btnNew
'
BtnNew.BackgroundImage = CType(resources.GetObject("btnNew.BackgroundImage"), System.Drawing.Image)
BtnNew.ImageDown = CType(resources.GetObject("btnNew.ImageDown"), System.Drawing.Image)
BtnNew.ImageNormal = CType(resources.GetObject("btnNew.ImageNormal"), System.Drawing.Image)
BtnNew.ImageOver = CType(resources.GetObject("btnNew.ImageOver"), System.Drawing.Image)
BtnNew.Location = New System.Drawing.Point(0, 3)
BtnNew.Margin = New System.Windows.Forms.Padding(0)
BtnNew.Name = "btnNew"
BtnNew.Size = New System.Drawing.Size(25, 28)
BtnNew.TabIndex = 0
'
'TabHeader
'
AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!)
AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
BackColor = Modules.ColorBackgroud
Controls.Add(Me.MainFlow)
Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Name = "TabHeader"
Size = New System.Drawing.Size(1151, 107)
MainFlow.ResumeLayout(False)
ResumeLayout(False)
End Sub
Friend WithEvents MainFlow As System.Windows.Forms.FlowLayoutPanel
Friend WithEvents BtnNew As ExButton
End Class
End Namespace
|
fakoua/ServicesPlus
|
ServicesPlus/Controls/TabEx/TabHeader.designer.vb
|
Visual Basic
|
bsd-3-clause
| 3,335
|
'------------------------------------------------------------------------------
' <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", "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("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
|
maria-shahid-aspose/Aspose.Email-for-.NET
|
Examples/VisualBasic/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,685
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.34003
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
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("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
|
hismightiness/dnnextensions
|
Library/oEmbed/WillStrohl.oEmbed/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,705
|
Imports Microsoft.AspNet.FriendlyUrls.ModelBinding
Public Partial Class Edit1
Inherits System.Web.UI.Page
Protected _db As New Samples.ApplicationDbContext()
Protected Sub Page_Load(sender As Object, e As EventArgs)
End Sub
' This is the Update methd to update the selected Book item
' USAGE: <asp:FormView UpdateMethod="UpdateItem">
Public Sub UpdateItem(Id As Integer)
Using _db
Dim item = _db.Books.Find(Id)
If item Is Nothing Then
' The item wasn't found
ModelState.AddModelError("", [String].Format("Item with id {0} was not found", Id))
Return
End If
TryUpdateModel(item)
If ModelState.IsValid Then
' Save changes here
_db.SaveChanges()
Response.Redirect("../Default")
End If
End Using
End Sub
' This is the Select method to selects a single Book item with the id
' USAGE: <asp:FormView SelectMethod="GetItem">
Public Function GetItem(<FriendlyUrlSegmentsAttribute(0)> Id As System.Nullable(Of Integer)) As Samples.Book
If Id Is Nothing Then
Return Nothing
End If
Using _db
Return _db.Books.Find(Id)
End Using
End Function
Protected Sub ItemCommand(sender As Object, e As FormViewCommandEventArgs)
If e.CommandName.Equals("Cancel", StringComparison.OrdinalIgnoreCase) Then
Response.Redirect("../Default")
End If
End Sub
End Class
|
neozhu/WebFormsScaffolding
|
Samples.VB/2_Validation/Books/Edit.aspx.vb
|
Visual Basic
|
apache-2.0
| 1,330
|
' 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.Editor.VisualBasic.KeywordHighlighting
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting
Public Class PropertyBlockHighlighterTests
Inherits AbstractVisualBasicKeywordHighlighterTests
Friend Overrides Function CreateHighlighter() As IHighlighter
Return New PropertyBlockHighlighter()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestPropertySample1_1() As Task
Await TestAsync(<Text>
Class C
{|Cursor:[|Public Property|]|} Goo As Integer [|Implements|] IGoo.Goo
Get
Return 1
End Get
Private Set(value As Integer)
Exit Property
End Set
[|End Property|]
End Class</Text>)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestPropertySample1_2() As Task
Await TestAsync(<Text>
Class C
[|Public Property|] Goo As Integer {|Cursor:[|Implements|]|} IGoo.Goo
Get
Return 1
End Get
Private Set(value As Integer)
Exit Property
End Set
[|End Property|]
End Class</Text>)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestPropertySample1_3() As Task
Await TestAsync(<Text>
Class C
[|Public Property|] Goo As Integer [|Implements|] IGoo.Goo
Get
Return 1
End Get
Private Set(value As Integer)
Exit Property
End Set
{|Cursor:[|End Property|]|}
End Class</Text>)
End Function
End Class
End Namespace
|
abock/roslyn
|
src/EditorFeatures/VisualBasicTest/KeywordHighlighting/PropertyBlockHighlighterTests.vb
|
Visual Basic
|
mit
| 1,870
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Metadata
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
''' <summary>
''' The class to represent all types imported from a PE/module.
''' </summary>
''' <remarks></remarks>
Friend NotInheritable Class PEParameterSymbol
Inherits ParameterSymbol
Private ReadOnly m_ContainingSymbol As Symbol
Private ReadOnly m_Name As String
Private ReadOnly m_Type As TypeSymbol
Private ReadOnly m_Handle As ParameterHandle
Private ReadOnly m_Flags As ParameterAttributes
Private ReadOnly m_CustomModifiers As ImmutableArray(Of CustomModifier)
Private ReadOnly m_Ordinal As UShort
' Layout
' |.....|c|h|r|
'
' r = isByRef - 1 bit (bool)
' h = hasByRefBeforeCustomModifiers - 1 bit (bool)
' c = hasOptionCompare - 1 bit (bool)
Private ReadOnly m_Packed As Byte
Private Const isByRefMask As Integer = &H1
Private Const hasByRefBeforeCustomModifiersMask As Integer = &H2
Private Const hasOptionCompareMask As Integer = &H4
Private m_lazyCustomAttributes As ImmutableArray(Of VisualBasicAttributeData)
Private m_lazyDefaultValue As ConstantValue = ConstantValue.Unset
' TODO: We should consider merging these in a single bit field
Private m_lazyHasIDispatchConstantAttribute As ThreeState = ThreeState.Unknown
Private m_lazyHasIUnknownConstantAttribute As ThreeState = ThreeState.Unknown
Private m_lazyHasCallerLineNumberAttribute As ThreeState = ThreeState.Unknown
Private m_lazyHasCallerMemberNameAttribute As ThreeState = ThreeState.Unknown
Private m_lazyHasCallerFilePathAttribute As ThreeState = ThreeState.Unknown
Private m_lazyIsParamArray As ThreeState
''' <summary>
''' Attributes filtered out from m_lazyCustomAttributes, ParamArray, etc.
''' </summary>
Private m_lazyHiddenAttributes As ImmutableArray(Of VisualBasicAttributeData)
Friend Sub New(
moduleSymbol As PEModuleSymbol,
containingSymbol As PEMethodSymbol,
ordinal As Integer,
ByRef parameter As ParamInfo(Of TypeSymbol),
<Out> ByRef isBad As Boolean
)
Me.New(moduleSymbol, containingSymbol, ordinal, parameter.IsByRef, parameter.HasByRefBeforeCustomModifiers, parameter.Type, parameter.Handle, parameter.CustomModifiers, isBad)
End Sub
Friend Sub New(
containingSymbol As Symbol,
name As String,
isByRef As Boolean,
hasByRefBeforeCustomModifiers As Boolean,
type As TypeSymbol,
handle As ParameterHandle,
flags As ParameterAttributes,
isParamArray As Boolean,
hasOptionCompare As Boolean,
ordinal As Integer,
defaultValue As ConstantValue,
customModifiers As ImmutableArray(Of CustomModifier))
Debug.Assert(containingSymbol IsNot Nothing)
Debug.Assert(ordinal >= 0)
Debug.Assert(type IsNot Nothing)
m_ContainingSymbol = containingSymbol
m_Name = EnsureParameterNameNotEmpty(name)
m_Type = type
m_Handle = handle
m_Ordinal = CType(ordinal, UShort)
m_Flags = flags
m_lazyIsParamArray = isParamArray.ToThreeState()
m_lazyDefaultValue = defaultValue
m_CustomModifiers = customModifiers
m_Packed = Pack(isByRef, hasByRefBeforeCustomModifiers, hasOptionCompare)
Debug.Assert(ordinal = Me.Ordinal)
Debug.Assert(isByRef = Me.IsByRef)
Debug.Assert(hasByRefBeforeCustomModifiers = Me.HasByRefBeforeCustomModifiers)
Debug.Assert(hasOptionCompare = Me.HasOptionCompare)
End Sub
Private Sub New(
moduleSymbol As PEModuleSymbol,
containingSymbol As Symbol,
ordinal As Integer,
isByRef As Boolean,
hasByRefBeforeCustomModifiers As Boolean,
type As TypeSymbol,
handle As ParameterHandle,
customModifiers As ImmutableArray(Of ModifierInfo(Of TypeSymbol)),
<Out> ByRef isBad As Boolean
)
Debug.Assert(moduleSymbol IsNot Nothing)
Debug.Assert(containingSymbol IsNot Nothing)
Debug.Assert(ordinal >= 0)
Debug.Assert(type IsNot Nothing)
isBad = False
m_ContainingSymbol = containingSymbol
m_Type = type
m_CustomModifiers = VisualBasicCustomModifier.Convert(customModifiers)
m_Ordinal = CType(ordinal, UShort)
m_Handle = handle
Dim hasOptionCompare As Boolean = False
If handle.IsNil Then
m_lazyCustomAttributes = ImmutableArray(Of VisualBasicAttributeData).Empty
m_lazyHiddenAttributes = ImmutableArray(Of VisualBasicAttributeData).Empty
m_lazyHasIDispatchConstantAttribute = ThreeState.False
m_lazyHasIUnknownConstantAttribute = ThreeState.False
m_lazyDefaultValue = ConstantValue.NotAvailable
m_lazyHasCallerLineNumberAttribute = ThreeState.False
m_lazyHasCallerMemberNameAttribute = ThreeState.False
m_lazyHasCallerFilePathAttribute = ThreeState.False
m_lazyIsParamArray = ThreeState.False
Else
Try
moduleSymbol.Module.GetParamPropsOrThrow(handle, m_Name, m_Flags)
Catch mrEx As BadImageFormatException
isBad = True
End Try
hasOptionCompare = moduleSymbol.Module.HasAttribute(handle, AttributeDescription.OptionCompareAttribute)
End If
m_Name = EnsureParameterNameNotEmpty(m_Name)
m_Packed = Pack(isByRef, hasByRefBeforeCustomModifiers, hasOptionCompare)
Debug.Assert(isByRef = Me.IsByRef)
Debug.Assert(hasByRefBeforeCustomModifiers = Me.HasByRefBeforeCustomModifiers)
Debug.Assert(hasOptionCompare = Me.HasOptionCompare)
End Sub
Private Shared Function Pack(isByRef As Boolean, hasByRefBeforeCustomModifiers As Boolean, hasOptionCompare As Boolean) As Byte
Debug.Assert((Not hasByRefBeforeCustomModifiers) OrElse isByRef)
Dim isByRefBits As Integer = If(isByRef, isByRefMask, 0)
Dim hasByRefBeforeCustomModifiersBits As Integer = If(hasByRefBeforeCustomModifiers, hasByRefBeforeCustomModifiersMask, 0)
Dim hasOptionCompareBits As Integer = If(hasOptionCompare, hasOptionCompareMask, 0)
Return CType(isByRefBits Or hasByRefBeforeCustomModifiersBits Or hasOptionCompareBits, Byte)
End Function
Private Shared Function EnsureParameterNameNotEmpty(name As String) As String
Return If(String.IsNullOrEmpty(name), "Param", name)
End Function
Public Overrides ReadOnly Property Name As String
Get
Return m_Name
End Get
End Property
Friend ReadOnly Property ParamFlags As ParameterAttributes
Get
Return m_Flags
End Get
End Property
Public Overrides ReadOnly Property Ordinal As Integer
Get
Return m_Ordinal
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return m_ContainingSymbol
End Get
End Property
Friend Overrides ReadOnly Property HasMetadataConstantValue As Boolean
Get
Return (m_Flags And ParameterAttributes.HasDefault) <> 0
End Get
End Property
Friend Overrides ReadOnly Property ExplicitDefaultConstantValue(inProgress As SymbolsInProgress(Of ParameterSymbol)) As ConstantValue
Get
If m_lazyDefaultValue Is ConstantValue.Unset Then
Debug.Assert(Not m_Handle.IsNil)
Dim defaultValue As ConstantValue = ConstantValue.NotAvailable
If IsOptional Then
Dim peModule = Me.PEModule
Dim handle = Me.m_Handle
If (m_Flags And ParameterAttributes.HasDefault) <> 0 Then
defaultValue = peModule.GetParamDefaultValue(handle)
Else
' Dev10 behavior just checks for Decimal then DateTime. If both are specified, DateTime wins
' regardless of the parameter's type.
If Not peModule.HasDateTimeConstantAttribute(handle, defaultValue) Then
peModule.HasDecimalConstantAttribute(handle, defaultValue)
End If
End If
End If
Interlocked.CompareExchange(m_lazyDefaultValue, defaultValue, ConstantValue.Unset)
End If
Return m_lazyDefaultValue
End Get
End Property
Friend Overrides ReadOnly Property IsMetadataOptional As Boolean
Get
Return (m_Flags And ParameterAttributes.Optional) <> 0
End Get
End Property
Public Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData)
If m_lazyCustomAttributes.IsDefault Then
Debug.Assert(Not m_Handle.IsNil)
Dim containingPEModuleSymbol = DirectCast(m_ContainingSymbol.ContainingModule, PEModuleSymbol)
' Filter out ParamArrayAttributes if necessary and cache the attribute handle
' for GetCustomAttributesToEmit
Dim filterOutParamArrayAttribute As Boolean = (Not m_lazyIsParamArray.HasValue() OrElse m_lazyIsParamArray.Value())
Dim defaultValue As ConstantValue = Me.ExplicitDefaultConstantValue
Dim filterOutConstantAttributeDescription As AttributeDescription = Nothing
If defaultValue IsNot Nothing Then
If defaultValue.Discriminator = ConstantValueTypeDiscriminator.DateTime Then
filterOutConstantAttributeDescription = AttributeDescription.DateTimeConstantAttribute
ElseIf defaultValue.Discriminator = ConstantValueTypeDiscriminator.Decimal Then
filterOutConstantAttributeDescription = AttributeDescription.DecimalConstantAttribute
End If
End If
If filterOutParamArrayAttribute OrElse filterOutConstantAttributeDescription.Signatures IsNot Nothing Then
Dim paramArrayAttribute As CustomAttributeHandle
Dim constantAttribute As CustomAttributeHandle
Dim attributes = containingPEModuleSymbol.GetCustomAttributesForToken(
m_Handle,
paramArrayAttribute,
If(filterOutParamArrayAttribute, AttributeDescription.ParamArrayAttribute, Nothing),
constantAttribute,
filterOutConstantAttributeDescription)
If Not paramArrayAttribute.IsNil OrElse Not constantAttribute.IsNil Then
Dim builder = ArrayBuilder(Of VisualBasicAttributeData).GetInstance()
If Not paramArrayAttribute.IsNil Then
builder.Add(New PEAttributeData(containingPEModuleSymbol, paramArrayAttribute))
End If
If Not constantAttribute.IsNil Then
builder.Add(New PEAttributeData(containingPEModuleSymbol, constantAttribute))
End If
ImmutableInterlocked.InterlockedInitialize(m_lazyHiddenAttributes, builder.ToImmutableAndFree())
Else
ImmutableInterlocked.InterlockedInitialize(m_lazyHiddenAttributes, ImmutableArray(Of VisualBasicAttributeData).Empty)
End If
If Not m_lazyIsParamArray.HasValue() Then
Debug.Assert(filterOutParamArrayAttribute)
m_lazyIsParamArray = (Not paramArrayAttribute.IsNil).ToThreeState()
End If
ImmutableInterlocked.InterlockedInitialize(m_lazyCustomAttributes, attributes)
Else
ImmutableInterlocked.InterlockedInitialize(m_lazyHiddenAttributes, ImmutableArray(Of VisualBasicAttributeData).Empty)
containingPEModuleSymbol.LoadCustomAttributes(m_Handle, m_lazyCustomAttributes)
End If
End If
Debug.Assert(Not m_lazyHiddenAttributes.IsDefault)
Return m_lazyCustomAttributes
End Function
Friend Overrides Iterator Function GetCustomAttributesToEmit(compilationState As ModuleCompilationState) As IEnumerable(Of VisualBasicAttributeData)
For Each attribute In GetAttributes()
Yield attribute
Next
' Yield hidden attributes last, order might be important.
For Each attribute In m_lazyHiddenAttributes
Yield attribute
Next
End Function
Public Overrides ReadOnly Property HasExplicitDefaultValue As Boolean
Get
Return IsOptional AndAlso ExplicitDefaultConstantValue IsNot Nothing
End Get
End Property
Public Overrides ReadOnly Property IsOptional As Boolean
Get
Return (m_Flags And ParameterAttributes.Optional) <> 0
End Get
End Property
Public Overrides ReadOnly Property IsParamArray As Boolean
Get
If Not m_lazyIsParamArray.HasValue() Then
m_lazyIsParamArray = Me.PEModule.HasParamsAttribute(m_Handle).ToThreeState()
End If
Return m_lazyIsParamArray.Value()
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return m_ContainingSymbol.Locations
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray(Of SyntaxReference).Empty
End Get
End Property
Public Overrides ReadOnly Property Type As TypeSymbol
Get
Return m_Type
End Get
End Property
Public Overrides ReadOnly Property IsByRef As Boolean
Get
Return (m_Packed And isByRefMask) <> 0
End Get
End Property
Friend Overrides ReadOnly Property IsExplicitByRef As Boolean
Get
Return IsByRef
End Get
End Property
Friend Overrides ReadOnly Property IsMetadataOut As Boolean
Get
Return (m_Flags And ParameterAttributes.Out) <> 0
End Get
End Property
Friend Overrides ReadOnly Property IsMetadataIn As Boolean
Get
Return (m_Flags And ParameterAttributes.In) <> 0
End Get
End Property
Friend Overrides ReadOnly Property HasOptionCompare As Boolean
Get
Return (m_Packed And hasOptionCompareMask) <> 0
End Get
End Property
Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return m_CustomModifiers
End Get
End Property
Friend Overrides ReadOnly Property IsMarshalledExplicitly As Boolean
Get
Return (m_Flags And ParameterAttributes.HasFieldMarshal) <> 0
End Get
End Property
Friend Overrides ReadOnly Property MarshallingInformation As MarshalPseudoCustomAttributeData
Get
' the compiler doesn't need full marshalling information, just the unmanaged type
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property MarshallingDescriptor As ImmutableArray(Of Byte)
Get
If (m_Flags And ParameterAttributes.HasFieldMarshal) = 0 Then
Return Nothing
End If
Debug.Assert(Not m_Handle.IsNil)
Return Me.PEModule.GetMarshallingDescriptor(m_Handle)
End Get
End Property
Friend Overrides ReadOnly Property MarshallingType As UnmanagedType
Get
If (m_Flags And ParameterAttributes.HasFieldMarshal) = 0 Then
Return Nothing
End If
Debug.Assert(Not m_Handle.IsNil)
Return Me.PEModule.GetMarshallingType(m_Handle)
End Get
End Property
' May be Nil
Friend ReadOnly Property Handle As ParameterHandle
Get
Return m_Handle
End Get
End Property
Friend Overrides ReadOnly Property IsIDispatchConstant As Boolean
Get
If m_lazyHasIDispatchConstantAttribute = ThreeState.Unknown Then
Debug.Assert(Not m_Handle.IsNil)
m_lazyHasIDispatchConstantAttribute = Me.PEModule.
HasAttribute(m_Handle, AttributeDescription.IDispatchConstantAttribute).ToThreeState()
End If
Return m_lazyHasIDispatchConstantAttribute.Value
End Get
End Property
Friend Overrides ReadOnly Property IsIUnknownConstant As Boolean
Get
If m_lazyHasIUnknownConstantAttribute = ThreeState.Unknown Then
Debug.Assert(Not m_Handle.IsNil)
m_lazyHasIUnknownConstantAttribute = Me.PEModule.
HasAttribute(m_Handle, AttributeDescription.IUnknownConstantAttribute).ToThreeState()
End If
Return m_lazyHasIUnknownConstantAttribute.Value
End Get
End Property
Friend Overrides ReadOnly Property IsCallerLineNumber As Boolean
Get
If m_lazyHasCallerLineNumberAttribute = ThreeState.Unknown Then
Debug.Assert(Not m_Handle.IsNil)
m_lazyHasCallerLineNumberAttribute = Me.PEModule.
HasAttribute(m_Handle, AttributeDescription.CallerLineNumberAttribute).ToThreeState()
End If
Return m_lazyHasCallerLineNumberAttribute.Value
End Get
End Property
Friend Overrides ReadOnly Property IsCallerMemberName As Boolean
Get
If m_lazyHasCallerMemberNameAttribute = ThreeState.Unknown Then
Debug.Assert(Not m_Handle.IsNil)
m_lazyHasCallerMemberNameAttribute = Me.PEModule.
HasAttribute(m_Handle, AttributeDescription.CallerMemberNameAttribute).ToThreeState()
End If
Return m_lazyHasCallerMemberNameAttribute.Value
End Get
End Property
Friend Overrides ReadOnly Property IsCallerFilePath As Boolean
Get
If m_lazyHasCallerFilePathAttribute = ThreeState.Unknown Then
Debug.Assert(Not m_Handle.IsNil)
m_lazyHasCallerFilePathAttribute = Me.PEModule.
HasAttribute(m_Handle, AttributeDescription.CallerFilePathAttribute).ToThreeState()
End If
Return m_lazyHasCallerFilePathAttribute.Value
End Get
End Property
Friend Overrides ReadOnly Property HasByRefBeforeCustomModifiers As Boolean
Get
Return (m_Packed And hasByRefBeforeCustomModifiersMask) <> 0
End Get
End Property
''' <remarks>
''' This is for perf, not for correctness.
''' </remarks>
Friend Overrides ReadOnly Property DeclaringCompilation As VisualBasicCompilation
Get
Return Nothing
End Get
End Property
Private ReadOnly Property PEModule As PEModule
Get
Return DirectCast(m_ContainingSymbol.ContainingModule, PEModuleSymbol).Module
End Get
End Property
End Class
End Namespace
|
ManishJayaswal/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEParameterSymbol.vb
|
Visual Basic
|
apache-2.0
| 21,376
|
'*********************************************************
'
' Copyright (c) Microsoft. All rights reserved.
' This code is licensed under the MIT License (MIT).
' THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
' ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
' IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
' PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
'
'*********************************************************
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Runtime.Serialization
Imports System.Text
Imports System.Threading.Tasks
Namespace Global.BackgroundAudioShared.Messages
<DataContract>
Public Class AppSuspendedMessage
Public Sub New()
Me.Timestamp = DateTime.Now
End Sub
Public Sub New(timestamp As DateTime)
Me.Timestamp = timestamp
End Sub
<DataMember>
Public Timestamp As DateTime
End Class
End Namespace
|
spratmannc/Windows-universal-samples
|
Samples/BackgroundAudio/vb/BackgroundAudioShared/Messages/AppSuspendedMessage.vb
|
Visual Basic
|
mit
| 959
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Expressions
Public Class NameOfKeywordRecommenderTests
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInClassDeclaration()
VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotAtStartOfStatement()
VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterReturn()
VerifyRecommendationsContain(<MethodBody>Return |</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub InArgumentList_Position1()
VerifyRecommendationsContain(<MethodBody>Foo(|</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub InArgumentList_Position2()
VerifyRecommendationsContain(<MethodBody>Foo(bar, |</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub InBinaryExpression()
VerifyRecommendationsContain(<MethodBody>Foo(bar + |</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterNot()
VerifyRecommendationsContain(<MethodBody>Foo(Not |</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterTypeOf()
VerifyRecommendationsContain(<MethodBody>If TypeOf |</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterDoWhile()
VerifyRecommendationsContain(<MethodBody>Do While |</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterDoUntil()
VerifyRecommendationsContain(<MethodBody>Do Until |</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterLoopWhile()
VerifyRecommendationsContain(<MethodBody>
Do
Loop While |</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterLoopUntil()
VerifyRecommendationsContain(<MethodBody>
Do
Loop Until |</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterIf()
VerifyRecommendationsContain(<MethodBody>If |</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterElseIf()
VerifyRecommendationsContain(<MethodBody>ElseIf |</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterElseSpaceIf()
VerifyRecommendationsContain(<MethodBody>Else If |</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterError()
VerifyRecommendationsContain(<MethodBody>Error |</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterThrow()
VerifyRecommendationsContain(<MethodBody>Throw |</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub InVariableInitializer()
VerifyRecommendationsContain(<MethodBody>Dim x = |</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub InArrayInitializer()
VerifyRecommendationsContain(<MethodBody>Dim x = {|</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub InArrayInitializerAfterComma()
VerifyRecommendationsContain(<MethodBody>Dim x = {0, |</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterWhile()
VerifyRecommendationsContain(<MethodBody>While |</MethodBody>, "NameOf")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterCall()
VerifyRecommendationsContain(<MethodBody>Call |</MethodBody>, "NameOf")
End Sub
End Class
End Namespace
|
droyad/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/Expressions/NameOfKeywordRecommenderTests.vb
|
Visual Basic
|
apache-2.0
| 5,081
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' Le informazioni generali relative a un assembly sono controllate dal seguente
' set di attributi. Modificare i valori di questi attributi per modificare le informazioni
' associate a un assembly.
' Rivedere i valori degli attributi degli assembly
<Assembly: AssemblyTitle("NuoDBProvider")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("NuoDBProvider")>
<Assembly: AssemblyCopyright("Copyright © 2015")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi
<Assembly: Guid("0471e3e2-7b78-404b-a86a-0d924fa92404")>
' Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori:
'
' Versione principale
' Versione secondaria
' Numero di build
' Revisione
'
' È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build
' usando l'asterisco '*' come illustrato di seguito:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.2015.0")>
<Assembly: AssemblyFileVersion("1.0.2015.0")>
|
michaelsogos/Dynamo
|
Providers/NuoDBProvider/Dynamo.Providers.NuoDBProvider/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,278
|
Imports Tests.Core
Imports MSProject = NetOffice.MSProjectApi
Imports NetOffice.MSProjectApi.Enums
Public Class Test02
Implements ITestPackage
Public ReadOnly Property Description As String Implements Tests.Core.ITestPackage.Description
Get
Return "Test 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 "Test02"
End Get
End Property
Public ReadOnly Property OfficeProduct As String Implements Tests.Core.ITestPackage.OfficeProduct
Get
Return "Project"
End Get
End Property
Private Sub ApplicationProjectTaskNewEvent(ByVal pj As MSProject.Project, ID As Integer)
TaskNewEventCalled = True
End Sub
Private Sub ApplicationProjectBeforeTaskChangeEvent(ByVal tsk As MSProject.Task, ByVal Field As PjField, ByVal NewVal As Object, ByRef Cancel As Boolean)
TaskChangeEventCalled = True
End Sub
Private Sub ApplicationProjectBeforeCloseEvent(ByVal pj As MSProject.Project, ByRef Cancel As Boolean)
BeforeCloseEventCalled = True
End Sub
Private Sub ApplicationProjectBeforeTaskDeleteEvent(ByVal tsk As MSProject.Task, ByRef Cancel As Boolean)
TaskDeleteEventCalled = True
End Sub
Public Function DoTest() As Tests.Core.TestResult Implements Tests.Core.ITestPackage.DoTest
Dim application As MSProject.Application = Nothing
Dim startTime As DateTime = DateTime.Now
Try
NetOffice.Settings.Default.MessageFilter.Enabled = True
application = New MSProject.Application()
Dim taskNewHandler As MSProject.Application_ProjectTaskNewEventHandler = AddressOf Me.ApplicationProjectTaskNewEvent
AddHandler application.ProjectTaskNewEvent, taskNewHandler
Dim projectBeforeCloseEventHandler As MSProject.Application_ProjectBeforeCloseEventHandler = AddressOf Me.ApplicationProjectBeforeCloseEvent
AddHandler application.ProjectBeforeCloseEvent, projectBeforeCloseEventHandler
Dim projectBeforeTaskChangeEventHandler As MSProject.Application_ProjectBeforeTaskChangeEventHandler = AddressOf Me.ApplicationProjectBeforeTaskChangeEvent
AddHandler application.ProjectBeforeTaskChangeEvent, projectBeforeTaskChangeEventHandler
Dim projectBeforeTaskDeleteHandler As MSProject.Application_ProjectBeforeTaskDeleteEventHandler = AddressOf Me.ApplicationProjectBeforeTaskDeleteEvent
AddHandler application.ProjectBeforeTaskDeleteEvent, projectBeforeTaskDeleteHandler
Dim newProject As MSProject.Project = application.Projects.Add()
Dim task1 As MSProject.Task = newProject.Tasks.Add("Task 1")
Dim task2 As MSProject.Task = newProject.Tasks.Add("Task 2")
task2.Delete()
application.FileCloseAll(False)
RemoveHandler application.ProjectTaskNewEvent, taskNewHandler
RemoveHandler application.ProjectBeforeCloseEvent, projectBeforeCloseEventHandler
RemoveHandler application.ProjectBeforeTaskChangeEvent, projectBeforeTaskChangeEventHandler
RemoveHandler application.ProjectBeforeTaskDeleteEvent, projectBeforeTaskDeleteHandler
If (TaskDeleteEventCalled And TaskChangeEventCalled And BeforeCloseEventCalled And TaskNewEventCalled) Then
Return New TestResult(True, DateTime.Now.Subtract(startTime), "", Nothing, "")
Else
Dim errorMessage As String = ""
If (Not TaskDeleteEventCalled) Then errorMessage += "ProjectTaskNewEvent failed "
If (Not TaskChangeEventCalled) Then errorMessage += "ProjectBeforeCloseEvent failed "
If (Not BeforeCloseEventCalled) Then errorMessage += "ProjectBeforeTaskChangeEvent failed "
If (Not TaskNewEventCalled) Then errorMessage += "ProjectBeforeTaskDeleteEvent failed "
Return New TestResult(False, DateTime.Now.Subtract(startTime), errorMessage, Nothing, "")
End If
Catch ex As Exception
Return New TestResult(False, DateTime.Now.Subtract(startTime), ex.Message, ex, "")
Finally
NetOffice.Settings.Default.MessageFilter.Enabled = False
If Not IsNothing(application) Then
application.Quit(False)
application.Dispose()
End If
End Try
End Function
Dim TaskDeleteEventCalled As Boolean
Dim TaskChangeEventCalled As Boolean
Dim BeforeCloseEventCalled As Boolean
Dim TaskNewEventCalled As Boolean
End Class
|
NetOfficeFw/NetOffice
|
Tests/Main Tests/ProjectTestsVB/Test02.vb
|
Visual Basic
|
mit
| 4,879
|
Public Class CondicionesContrato
Public Property IdCondicion As System.Nullable(Of Int32)
Public Property IdContrato As System.Nullable(Of Int32)
Public Property IdPeriodoLaboral As System.Nullable(Of Int32)
Public Property IdPosicion As System.Nullable(Of Int32)
Public Property IdSituacionEspecial As System.Nullable(Of Int32)
Public Property FechaCambio As System.Nullable(Of DateTime)
Public Property Sueldo As System.Nullable(Of Decimal)
Public Property FechaAmpliacionContrato As System.Nullable(Of DateTime)
Public Property cambioSueldo As System.Nullable(Of Boolean)
Public Property cambioCargo As System.Nullable(Of Boolean)
Public Property AmpliacionContrato As System.Nullable(Of Boolean)
Public Property CondicionDelCambio As String
Public Property NroAdemda As String
Public Property Posicion As Posicion
Public Property periodoLaboral As PeriodoLaboral
Public Property contrato As ContratoConvenio
Public Property situacionEspecial As SituacionEspecial
Public Property archivo As String
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.BussinessEntities/CondicionesContrato.vb
|
Visual Basic
|
mit
| 1,090
|
Imports WeifenLuo.WinFormsUI.Docking
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.Panel1 = New WeifenLuo.WinFormsUI.Docking.DockPanel()
Me.SuspendLayout
'
'Panel1
'
Me.Panel1.Dock = System.Windows.Forms.DockStyle.Fill
Me.Panel1.Location = New System.Drawing.Point(0, 0)
Me.Panel1.Name = "Panel1"
Me.Panel1.Size = New System.Drawing.Size(284, 261)
Me.Panel1.TabIndex = 1
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6!, 13!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(284, 261)
Me.Controls.Add(Me.Panel1)
Me.IsMdiContainer = true
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(false)
End Sub
Friend WithEvents Panel1 As DockPanel
End Class
|
Koopakiller/Forum-Samples
|
Other/0f323ad558c64fa6b792a7175daf8878/WindowsApp1/Form1.Designer.vb
|
Visual Basic
|
mit
| 1,739
|
'------------------------------------------------------------------------------
' <generado automáticamente>
' Este código fue generado por una herramienta.
'
' Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
' se vuelve a generar el código.
' </generado automáticamente>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Partial Public Class ReporteEstadoIngresosGastos
'''<summary>
'''Control Head1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents Head1 As Global.System.Web.UI.HtmlControls.HtmlHead
'''<summary>
'''Control form1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents form1 As Global.System.Web.UI.HtmlControls.HtmlForm
'''<summary>
'''Control ReportViewer1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents ReportViewer1 As Global.Telerik.ReportViewer.WebForms.ReportViewer
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.WebSite/Contabilidad/Formularios/ReporteEstadoIngresosGastos.aspx.designer.vb
|
Visual Basic
|
mit
| 1,520
|
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Namespace Objects.Positioners
Public Class BurchfieldCommand
Public Const PanAxis = "M1"
Public Const TiltAxis = "M2"
Public Const TiltAxis2 = "M3"
Public Const TopPlatform = "M4"
Public Const StabilizationCard = "SC"
Public Const Reset = "GOSUB4" 'EDITED
Public Const TurnOnStabilization = "GOSUB8" 'EDITED
Public Const TurnOffStabilization = "GOSUB9" 'EDITED
Public Const AwaitCommand = "A" 'NOT USED
Public Const Go = "G" 'EDITED
Public Const SetAbsolutePosition = "PT=" 'EDITED
Public Const SetRelativePosition = "PRT=" 'EDITED
Public Const GetPosition = "RPA" 'EDITED
Public Const GetTargetPosition = "RPT" 'EDITED
Public Const GetCommandedPosition = "RPC" 'EDITED
Public Const SetSpeed = "VT=" 'EDITED
Public Const GetCurrentSpeed = "RVA" 'EDITED
Public Const GetCommandedSpeed = "RVC" 'EDITED
Public Const GetTargetSpeed = "RVT" 'EDITED
Public Const SetAccelDecel = "ADT=" 'EDITED
Public Const SetAcceleration = "AT=" 'EDITED
Public Const SetDeceleration = "DT=" 'EDITED
Public Const GetTargetAcceleration = "RAT" 'EDITED
Public Const SetModePosition = "MP" 'EDITED
Public Const SetModeVelocity = "MV" 'EDITED
Public Const SetModeTourque = "MT" 'EDITED
Public Const EnablePositionLimits = "SLE" 'EDITED
Public Const DisablePositionLimits = "SLD" 'EDITED
Public Const SetPositiveLimit = "SLP=" 'EDITED
Public Const GetPositiveLimit = "RSLP" 'EDITED
Public Const SetNegativeLimit = "SLN=" 'EDITED
Public Const GetNegativeLimit = "RSLN" 'EDITED
Public Const Halt = "S" 'EDITED
Public Const Stow = SetAbsolutePosition & "0" 'EDITED
Public Const GetTemp = "RTEMP" 'EDITED
Public Const GetVoltage = "RUJA" 'EDITED
Public Const GetCurrent = "RUIA" 'EDITED
Public Const ClearErrors = "ZS" 'EDITED
Public Const GetResolution = "Rrr" 'EDITED
Public Const CheckHome = "Rh" 'EDITED
Public Const EnableTerseFeedback = "FT"
Public Const EnableVerboseFeedback = "FV"
Public Const QueryEchoMode = "E"
Public Const EnableEchoing = "EE"
Public Const DisableEchoing = "ED"
Public Const EnableContinuousPanRotation = "%%1CPT"
Public Const DisableContinuousPanRotation = "%%1CPF"
Public Const GetFirmwareVersion = "V"
Public Const RestoreFactoryDefaults = "DF"
End Class
End Namespace
|
wboxx1/85-EIS-PUMA
|
puma/src/Supporting Objects/Positioners/Burchfield/BurchfieldCommand.vb
|
Visual Basic
|
mit
| 2,688
|
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("TicTacToe")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("Microsoft")>
<Assembly: AssemblyProduct("TicTacToe")>
<Assembly: AssemblyCopyright("Copyright © Microsoft 2011")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("eb6788cc-d712-4a85-a20e-b042c1be8898")>
' 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")>
|
gumgl/VB.NET
|
TicTacToe/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,154
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB
Public Class PDBIteratorTests
Inherits BasicTestBase
<Fact, WorkItem(2736, "https://github.com/dotnet/roslyn/issues/2736")>
Public Sub SimpleIterator()
Dim source =
<compilation>
<file>
Imports System.Collections.Generic
Class C
Public Iterator Function F() As IEnumerable(Of Integer)
Yield 1
End Function
End Class
</file>
</compilation>
Dim v = CompileAndVerify(source, options:=TestOptions.DebugDll)
v.VerifyIL("C.VB$StateMachine_1_F.MoveNext", "
{
// Code size 63 (0x3f)
.maxstack 3
.locals init (Boolean V_0,
Integer V_1)
~IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_1_F.$State As Integer""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.1
IL_000d: ldc.i4.1
IL_000e: beq.s IL_0014
IL_0010: br.s IL_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_0034
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: dup
IL_001b: stloc.1
IL_001c: stfld ""C.VB$StateMachine_1_F.$State As Integer""
-IL_0021: nop
-IL_0022: ldarg.0
IL_0023: ldc.i4.1
IL_0024: stfld ""C.VB$StateMachine_1_F.$Current As Integer""
IL_0029: ldarg.0
IL_002a: ldc.i4.1
IL_002b: dup
IL_002c: stloc.1
IL_002d: stfld ""C.VB$StateMachine_1_F.$State As Integer""
IL_0032: ldc.i4.1
IL_0033: ret
IL_0034: ldarg.0
IL_0035: ldc.i4.m1
IL_0036: dup
IL_0037: stloc.1
IL_0038: stfld ""C.VB$StateMachine_1_F.$State As Integer""
-IL_003d: ldc.i4.0
IL_003e: ret
}
", sequencePoints:="C+VB$StateMachine_1_F.MoveNext")
End Sub
<Fact, WorkItem(651996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651996")>
Public Sub IteratorLambdaWithForEach()
Dim source =
<compilation>
<file>
Imports System
Imports System.Collections
Imports System.Collections.Generic
Module Program
Sub Main(args As String())
baz(Iterator Function(x)
Yield 1
Yield x
End Function)
End Sub
Public Sub baz(Of T)(x As Func(Of Integer, IEnumerable(Of T)))
For Each i In x(42)
Console.Write(i)
Next
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb("Program+_Closure$__+VB$StateMachine___Lambda$__0-0.MoveNext",
<symbols>
<entryPoint declaringType="Program" methodName="Main" parameterNames="args"/>
<methods>
<method containingType="Program+_Closure$__+VB$StateMachine___Lambda$__0-0" name="MoveNext">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="20" offset="4"/>
<slot kind="27" offset="4"/>
<slot kind="21" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true"/>
<entry offset="0x2c" startLine="7" startColumn="13" endLine="7" endColumn="33"/>
<entry offset="0x2d" startLine="8" startColumn="17" endLine="8" endColumn="24"/>
<entry offset="0x48" startLine="9" startColumn="17" endLine="9" endColumn="24"/>
<entry offset="0x68" startLine="10" startColumn="13" endLine="10" endColumn="25"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x6a">
<importsforward declaringType="Program" methodName="Main" parameterNames="args"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<Fact(), WorkItem(651996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651996"), WorkItem(789705, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/789705")>
Public Sub IteratorWithLiftedMultipleSameNameLocals()
Dim source =
<compilation>
<file>
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
For Each i In Foo
Console.Write(i)
Next
End Sub
Iterator Function Foo() As IEnumerable(Of Integer)
Dim arr(1) As Integer
arr(0) = 42
For Each x In arr
Yield x
Yield x
Next
For Each x In "abc"
Yield System.Convert.ToInt32(x)
Yield System.Convert.ToInt32(x)
Next
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.DebugExe)
' VERY IMPORTANT!!!! We must have locals named $VB$ResumableLocal_x$1 and $VB$ResumableLocal_x$2 here
' Even though they do not really exist in IL, EE will rely on them for scoping
compilation.VerifyPdb("Module1+VB$StateMachine_1_Foo.MoveNext",
<symbols>
<entryPoint declaringType="Module1" methodName="Main"/>
<methods>
<method containingType="Module1+VB$StateMachine_1_Foo" name="MoveNext">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="20" offset="-1"/>
<slot kind="27" offset="-1"/>
<slot kind="1" offset="54"/>
<slot kind="1" offset="139"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true"/>
<entry offset="0x41" startLine="12" startColumn="5" endLine="12" endColumn="55"/>
<entry offset="0x42" startLine="13" startColumn="13" endLine="13" endColumn="19"/>
<entry offset="0x4e" startLine="14" startColumn="9" endLine="14" endColumn="20"/>
<entry offset="0x58" startLine="16" startColumn="9" endLine="16" endColumn="26"/>
<entry offset="0x6b" hidden="true"/>
<entry offset="0x80" startLine="17" startColumn="13" endLine="17" endColumn="20"/>
<entry offset="0xa0" startLine="18" startColumn="13" endLine="18" endColumn="20"/>
<entry offset="0xc0" startLine="19" startColumn="9" endLine="19" endColumn="13"/>
<entry offset="0xc1" hidden="true"/>
<entry offset="0xcf" hidden="true"/>
<entry offset="0xe0" hidden="true"/>
<entry offset="0xe3" startLine="21" startColumn="9" endLine="21" endColumn="28"/>
<entry offset="0xf5" hidden="true"/>
<entry offset="0x10e" startLine="22" startColumn="13" endLine="22" endColumn="44"/>
<entry offset="0x133" startLine="23" startColumn="13" endLine="23" endColumn="44"/>
<entry offset="0x158" startLine="24" startColumn="9" endLine="24" endColumn="13"/>
<entry offset="0x159" hidden="true"/>
<entry offset="0x167" hidden="true"/>
<entry offset="0x17b" hidden="true"/>
<entry offset="0x181" startLine="26" startColumn="5" endLine="26" endColumn="17"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x183">
<importsforward declaringType="Module1" methodName="Main"/>
<scope startOffset="0x41" endOffset="0x182">
<local name="$VB$ResumableLocal_arr$0" il_index="0" il_start="0x41" il_end="0x182" attributes="0"/>
<scope startOffset="0x6d" endOffset="0xce">
<local name="$VB$ResumableLocal_x$3" il_index="3" il_start="0x6d" il_end="0xce" attributes="0"/>
</scope>
<scope startOffset="0xf7" endOffset="0x166">
<local name="$VB$ResumableLocal_x$6" il_index="6" il_start="0xf7" il_end="0x166" attributes="0"/>
</scope>
</scope>
</scope>
</method>
</methods>
</symbols>)
End Sub
<Fact(), WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337"), WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")>
Public Sub LocalCapturedAndHoisted()
Dim source =
<compilation>
<file>
Imports System
Imports System.Collections.Generic
Public Class C
Private Iterator Function Iterator_Lambda_Hoisted() As IEnumerable(Of Integer)
Dim x As Integer = 1
Dim y As Integer = 2
Dim a As Func(Of Integer) = Function() x + y
Yield x + y
x.ToString()
y.ToString()
End Function
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(
source,
TestOptions.ReleaseDll)
' Goal: We're looking for the double-mangled name "$VB$ResumableLocal_$VB$Closure_$0".
compilation.VerifyPdb("C+VB$StateMachine_1_Iterator_Lambda_Hoisted.MoveNext",
<symbols>
<methods>
<method containingType="C+VB$StateMachine_1_Iterator_Lambda_Hoisted" name="MoveNext">
<sequencePoints>
<entry offset="0x0" hidden="true"/>
<entry offset="0x19" hidden="true"/>
<entry offset="0x24" startLine="6" startColumn="13" endLine="6" endColumn="29"/>
<entry offset="0x30" startLine="7" startColumn="13" endLine="7" endColumn="29"/>
<entry offset="0x3c" startLine="9" startColumn="13" endLine="9" endColumn="53"/>
<entry offset="0x43" startLine="11" startColumn="9" endLine="11" endColumn="20"/>
<entry offset="0x74" startLine="12" startColumn="9" endLine="12" endColumn="21"/>
<entry offset="0x85" startLine="13" startColumn="9" endLine="13" endColumn="21"/>
<entry offset="0x96" startLine="14" startColumn="5" endLine="14" endColumn="17"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x98">
<importsforward declaringType="C+_Closure$__1-0" methodName="_Lambda$__0"/>
<scope startOffset="0x19" endOffset="0x97">
<local name="$VB$ResumableLocal_$VB$Closure_$0" il_index="0" il_start="0x19" il_end="0x97" attributes="0"/>
</scope>
</scope>
</method>
</methods>
</symbols>)
End Sub
<Fact(), WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337"), WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")>
Public Sub LocalCapturedAndNotHoisted()
Dim source =
<compilation>
<file>
Imports System
Imports System.Collections.Generic
Public Class C
Private Iterator Function Iterator_Lambda_NotHoisted() As IEnumerable(Of Integer)
Dim x As Integer = 1
Dim y As Integer = 2
Dim a As Func(Of Integer) = Function() x + y
Yield x + y
End Function
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(
source,
TestOptions.ReleaseDll)
' Goal: We're looking for the single-mangled name "$VB$Closure_0".
compilation.VerifyPdb("C+VB$StateMachine_1_Iterator_Lambda_NotHoisted.MoveNext",
<symbols>
<methods>
<method containingType="C+VB$StateMachine_1_Iterator_Lambda_NotHoisted" name="MoveNext">
<sequencePoints>
<entry offset="0x0" hidden="true"/>
<entry offset="0x19" hidden="true"/>
<entry offset="0x1f" startLine="6" startColumn="13" endLine="6" endColumn="29"/>
<entry offset="0x26" startLine="7" startColumn="13" endLine="7" endColumn="29"/>
<entry offset="0x2d" startLine="11" startColumn="9" endLine="11" endColumn="20"/>
<entry offset="0x54" startLine="12" startColumn="5" endLine="12" endColumn="17"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x56">
<importsforward declaringType="C+_Closure$__1-0" methodName="_Lambda$__0"/>
<scope startOffset="0x19" endOffset="0x55">
<local name="$VB$Closure_0" il_index="1" il_start="0x19" il_end="0x55" attributes="0"/>
</scope>
</scope>
</method>
</methods>
</symbols>)
End Sub
<Fact(), WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337"), WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")>
Public Sub LocalHoistedAndNotCapture()
Dim source =
<compilation>
<file>
Imports System
Imports System.Collections.Generic
Public Class C
Private Iterator Function Iterator_NoLambda_Hoisted() As IEnumerable(Of Integer)
Dim x As Integer = 1
Dim y As Integer = 2
Yield x + y
x.ToString()
y.ToString()
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseDll)
' Goal: We're looking for the single-mangled names "$VB$ResumableLocal_x$0" and "$VB$ResumableLocal_y$1".
compilation.VerifyPdb("C+VB$StateMachine_1_Iterator_NoLambda_Hoisted.MoveNext",
<symbols>
<methods>
<method containingType="C+VB$StateMachine_1_Iterator_NoLambda_Hoisted" name="MoveNext">
<sequencePoints>
<entry offset="0x0" hidden="true"/>
<entry offset="0x19" startLine="6" startColumn="13" endLine="6" endColumn="29"/>
<entry offset="0x20" startLine="7" startColumn="13" endLine="7" endColumn="29"/>
<entry offset="0x27" startLine="8" startColumn="9" endLine="8" endColumn="20"/>
<entry offset="0x4e" startLine="9" startColumn="9" endLine="9" endColumn="21"/>
<entry offset="0x5a" startLine="10" startColumn="9" endLine="10" endColumn="21"/>
<entry offset="0x66" startLine="11" startColumn="5" endLine="11" endColumn="17"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x68">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<scope startOffset="0x19" endOffset="0x67">
<local name="$VB$ResumableLocal_x$0" il_index="0" il_start="0x19" il_end="0x67" attributes="0"/>
<local name="$VB$ResumableLocal_y$1" il_index="1" il_start="0x19" il_end="0x67" attributes="0"/>
</scope>
</scope>
</method>
</methods>
</symbols>)
End Sub
<Fact(), WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337"), WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")>
Public Sub LocalNotHoistedAndNotCaptured()
Dim source =
<compilation>
<file>
Imports System
Imports System.Collections.Generic
Public Class C
Private Iterator Function Iterator_NoLambda_NotHoisted() As IEnumerable(Of Integer)
Dim x As Integer = 1
Dim y As Integer = 2
Yield x + y
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseDll)
' Goal: We're looking for the unmangled names "x" and "y".
compilation.VerifyPdb("C+VB$StateMachine_1_Iterator_NoLambda_NotHoisted.MoveNext",
<symbols>
<methods>
<method containingType="C+VB$StateMachine_1_Iterator_NoLambda_NotHoisted" name="MoveNext">
<sequencePoints>
<entry offset="0x0" hidden="true"/>
<entry offset="0x19" startLine="6" startColumn="13" endLine="6" endColumn="29"/>
<entry offset="0x1b" startLine="7" startColumn="13" endLine="7" endColumn="29"/>
<entry offset="0x1d" startLine="8" startColumn="9" endLine="8" endColumn="20"/>
<entry offset="0x3a" startLine="9" startColumn="5" endLine="9" endColumn="17"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x3c">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<scope startOffset="0x19" endOffset="0x3b">
<local name="x" il_index="1" il_start="0x19" il_end="0x3b" attributes="0"/>
<local name="y" il_index="2" il_start="0x19" il_end="0x3b" attributes="0"/>
</scope>
</scope>
</method>
</methods>
</symbols>)
End Sub
''' <summary>
''' Sequence points of MoveNext method shall not be affected by DebuggerHidden attribute.
''' The method contains user code that can be edited during debugging and might need remapping.
''' </summary>
<Fact, WorkItem(667579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667579")>
Public Sub DebuggerHiddenIterator()
Dim source =
<compilation>
<file>
Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Module Module1
Sub Main()
For Each i In Foo
Console.Write(i)
Next
End Sub
<DebuggerHidden>
Iterator Function Foo() As IEnumerable(Of Integer)
Yield 1
Yield 2
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb("Module1+VB$StateMachine_1_Foo.MoveNext",
<symbols>
<entryPoint declaringType="Module1" methodName="Main"/>
<methods>
<method containingType="Module1+VB$StateMachine_1_Foo" name="MoveNext">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="20" offset="-1"/>
<slot kind="27" offset="-1"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true"/>
<entry offset="0x2c" startLine="13" startColumn="5" endLine="13" endColumn="55"/>
<entry offset="0x2d" startLine="14" startColumn="9" endLine="14" endColumn="16"/>
<entry offset="0x48" startLine="15" startColumn="9" endLine="15" endColumn="16"/>
<entry offset="0x63" startLine="16" startColumn="5" endLine="16" endColumn="17"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x65">
<importsforward declaringType="Module1" methodName="Main"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
End Class
End Namespace
|
thomaslevesque/roslyn
|
src/Compilers/VisualBasic/Test/Emit/PDB/PDBIteratorTests.vb
|
Visual Basic
|
apache-2.0
| 19,467
|
Imports System
Imports Microsoft.VisualBasic
Imports ChartDirector
Public Class neonroundmeter
Implements DemoModule
'Name of demo module
Public Function getName() As String Implements DemoModule.getName
Return "Neon Round Meters"
End Function
'Number of charts produced in this demo module
Public Function getNoOfCharts() As Integer Implements DemoModule.getNoOfCharts
Return 4
End Function
'Main code for creating charts
Public Sub createChart(viewer As WinChartViewer, chartIndex As Integer) _
Implements DemoModule.createChart
' The value to display on the meter
Dim value As Double = 50
' The main color of the four meters in this example. The other colors and gradients are
' derived from the main color.
Dim colorList() As Integer = {&H007700, &H770077, &H0033dd, &H880000}
Dim mainColor As Integer = colorList(chartIndex)
'
' In this example, we demonstrate how to parameterized by size, so that the chart size can
' be changed by changing just one variable.
'
Dim size As Integer = 300
' The radius of the entire meter, which is size / 2, minus 2 pixels for margin
Dim outerRadius As Integer = Int(size / 2 - 2)
' The radius of the meter scale
Dim scaleRadius As Integer = Int(outerRadius * 92 / 100)
' The radius of the inner decorative circle
Dim innerRadius As Integer = Int(scaleRadius * 40 / 100)
' The width of the color scale
Dim colorScaleWidth As Integer = Int(scaleRadius * 10 / 100)
' Major tick length
Dim tickLength As Integer = Int(scaleRadius * 10 / 100)
' Major tick width
Dim tickWidth As Integer = Int(scaleRadius * 1 / 100 + 1)
' Label font size
Dim fontSize As Integer = Int(scaleRadius * 13 / 100)
'
' Create an angular meter based on the above parameters
'
' Create an AngularMeter object of the specified size. In this demo, we use black (0x000000)
' as the background color. You can also use transparent or other colors.
Dim m As AngularMeter = New AngularMeter(size, size, &H000000)
' Set the default text and line colors to white (0xffffff)
m.setColor(Chart.TextColor, &Hffffff)
m.setColor(Chart.LineColor, &Hffffff)
' Set meter center and scale radius, and set the scale angle from -180 to +90 degrees
m.setMeter(size / 2, size / 2, scaleRadius, -180, 90)
' Background gradient with the mainColor at the center and become darker near the border
Dim bgGradient() As Double = {0, mainColor, 0.5, m.adjustBrightness(mainColor, 0.75), 1, _
m.adjustBrightness(mainColor, 0.15)}
' Fill the meter background with the background gradient
m.addRing(0, outerRadius, m.relativeRadialGradient(bgGradient, outerRadius * 0.66))
' Fill the inner circle with the same background gradient for decoration
m.addRing(0, innerRadius, m.relativeRadialGradient(bgGradient, innerRadius * 0.8))
' Gradient for the neon backlight, with the main color at the scale radius fading to
' transparent
Dim neonGradient() As Double = {0.89, Chart.Transparent, 1, mainColor, 1.07, _
Chart.Transparent}
m.addRing(Int(scaleRadius * 85 / 100), outerRadius, m.relativeRadialGradient(neonGradient))
' The neon ring at the scale radius with width equal to 1/80 of the scale radius, creating
' using a brighter version of the main color
m.addRing(scaleRadius, Int(scaleRadius + scaleRadius / 80), m.adjustBrightness(mainColor, _
2))
' Meter scale is 0 - 100, with major/minor/micro ticks every 10/5/1 units
m.setScale(0, 100, 10, 5, 1)
' Set the scale label style, tick length and tick width. The minor and micro tick lengths
' are 80% and 60% of the major tick length, and their widths are around half of the major
' tick width.
m.setLabelStyle("Arial Italic", fontSize)
m.setTickLength(-tickLength, -Int(tickLength * 80 / 100), -Int(tickLength * 60 / 100))
m.setLineWidth(0, tickWidth, Int(tickWidth + 1 / 2), Int(tickWidth + 1 / 2))
' Demostrate different types of color scales and glare effects and putting them at different
' positions.
Dim smoothColorScale() As Double = {0, &H0000ff, 25, &H0088ff, 50, &H00ff00, 75, &Hdddd00, _
100, &Hff0000}
Dim stepColorScale() As Double = {0, &H00dd00, 60, &Hddaa00, 80, &Hdd0000, 100}
Dim highColorScale() As Double = {70, Chart.Transparent, 100, &Hff0000}
If chartIndex = 1 Then
' Add the smooth color scale just outside the inner circle
m.addColorScale(smoothColorScale, innerRadius + 1, colorScaleWidth)
' Add glare up to the scale radius, concave and spanning 190 degrees
m.addGlare(scaleRadius, -190)
ElseIf chartIndex = 2 Then
' Add the high color scale at the default position
m.addColorScale(highColorScale)
' Add glare up to the scale radius
m.addGlare(scaleRadius)
Else
' Add the step color scale just outside the inner circle
m.addColorScale(stepColorScale, innerRadius + 1, colorScaleWidth)
' Add glare up to the scale radius, concave and spanning 190 degrees and rotated by -45
' degrees
m.addGlare(scaleRadius, -190, -45)
End If
' Add a red (0xff0000) pointer at the specified value
m.addPointer2(value, &Hff0000)
' Set the cap background to a brighter version of the mainColor, and using black (0x000000)
' for the cap and grey (0x999999) for the cap border
m.setCap2(m.adjustBrightness(mainColor, 1.1), &H000000, &H999999)
' Output the chart
viewer.Chart = m
End Sub
End Class
|
jojogreen/Orbital-Mechanix-Suite
|
NetWinCharts/VBNetWinCharts/neonroundmeter.vb
|
Visual Basic
|
apache-2.0
| 6,017
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Composition
Imports System.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.Maintainability.Analyzers
''' <summary>
''' CA1806: Do not ignore method results
''' </summary>
<ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]>
Public NotInheritable Class BasicDoNotIgnoreMethodResultsFixer
Inherits DoNotIgnoreMethodResultsFixer
End Class
End Namespace
|
mattwar/roslyn-analyzers
|
src/Microsoft.Maintainability.Analyzers/VisualBasic/BasicDoNotIgnoreMethodResults.Fixer.vb
|
Visual Basic
|
apache-2.0
| 716
|
Imports bv.common.win
Imports bv.winclient.Core
Imports bv.common.Configuration
Public Class BaseTaskBarForm
Inherits DevExpress.XtraEditors.XtraForm
#Region "Decalrations"
Private AnimationDisabled As Boolean = False
Friend WithEvents DefaultLookAndFeel1 As DevExpress.LookAndFeel.DefaultLookAndFeel
Private Shared systemShutdown As Boolean = False
#End Region
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
Me.DefaultLookAndFeel1.LookAndFeel.SkinName = BaseSettings.SkinName '"Money Twins"
End Sub
'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
Me.NotifyIcon1.Dispose()
GC.Collect()
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents NotifyIcon1 As System.Windows.Forms.NotifyIcon
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(BaseTaskBarForm))
Me.NotifyIcon1 = New System.Windows.Forms.NotifyIcon(Me.components)
Me.DefaultLookAndFeel1 = New DevExpress.LookAndFeel.DefaultLookAndFeel(Me.components)
Me.SuspendLayout()
'
'NotifyIcon1
'
resources.ApplyResources(Me.NotifyIcon1, "NotifyIcon1")
'
'BaseTaskBarForm
'
resources.ApplyResources(Me, "$this")
Me.Name = "BaseTaskBarForm"
Me.ResumeLayout(False)
End Sub
#End Region
Private Sub Form_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Me.ShowInTaskbar = True
End Sub
Protected Overrides Sub OnClosing(ByVal e As System.ComponentModel.CancelEventArgs)
Try
If (systemShutdown = True) Then
e.Cancel = False
Else
e.Cancel = True
'Me.AnimateWindow()
Me.Visible = False
End If
Catch ex As Exception
End Try
MyBase.OnClosing(e)
End Sub
Protected Overrides Sub OnClosed(ByVal e As System.EventArgs)
Me.NotifyIcon1.Visible = False
Me.NotifyIcon1.Icon.Dispose()
Me.NotifyIcon1.Dispose()
MyBase.OnClosed(e)
End Sub
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
' Once the program recieves WM_QUERYENDSESSION message, set the boolean systemShutdown.
If (m.Msg = WindowsAPI.WM_QUERYENDSESSION) Then
systemShutdown = True
End If
MyBase.WndProc(m)
End Sub
Private m_ForceWindowShowing As Boolean = False
Protected Sub DefaultAction(ByVal sender As Object, ByVal e As System.EventArgs) Handles NotifyIcon1.DoubleClick
ShowMe()
End Sub
Protected Sub Finish()
Application.Exit()
End Sub
Public Sub ShowMe()
If Me.Visible = False Then
m_ForceWindowShowing = True
Me.Activate()
Me.Visible = True
End If
If (Me.WindowState = FormWindowState.Minimized) Then
Me.WindowState = FormWindowState.Normal
End If
Submain.ShowNotificationForm(Me)
If PopupMessage.Instance.Visible Then
PopupMessage.Instance.Hide()
End If
End Sub
End Class
|
EIDSS/EIDSS-Legacy
|
EIDSS v5/vb/EIDSS/EIDSS_ClientAgent/BaseTaskBarForm.vb
|
Visual Basic
|
bsd-2-clause
| 4,204
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.