code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax
Partial Public Class ArgumentSyntax
''' <summary>
''' Gets a value indicating whether this argument is a named argument.
''' </summary>
''' <returns>True if this argument is a named argument; otherwise false.</returns>
Public MustOverride ReadOnly Property IsNamed As Boolean
''' <summary>
''' Gets a value indicating whether this argument is an omitted argument.
''' </summary>
''' <returns>True if this argument is an omitted argument; otherwise false.</returns>
Public ReadOnly Property IsOmitted As Boolean
Get
Return Kind = SyntaxKind.OmittedArgument
End Get
End Property
''' <summary>
''' Gets the expression of this argument, if any.
''' </summary>
''' <returns>The expression of this argument if it is a simple argument; otherwise null.</returns>
Public MustOverride Function GetExpression() As ExpressionSyntax
End Class
Partial Public Class SimpleArgumentSyntax
Public NotOverridable Overrides ReadOnly Property IsNamed As Boolean
Get
Return NameColonEquals IsNot Nothing
End Get
End Property
<ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)>
Public NotOverridable Overrides Function GetExpression() As ExpressionSyntax
Return Expression
End Function
End Class
Partial Public Class OmittedArgumentSyntax
Public NotOverridable Overrides ReadOnly Property IsNamed As Boolean
Get
Return False
End Get
End Property
<ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)>
Public NotOverridable Overrides Function GetExpression() As ExpressionSyntax
Return Nothing
End Function
End Class
Partial Public Class RangeArgumentSyntax
Public NotOverridable Overrides ReadOnly Property IsNamed As Boolean
Get
Return False
End Get
End Property
<ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)>
Public NotOverridable Overrides Function GetExpression() As ExpressionSyntax
Return UpperBound
End Function
End Class
End Namespace
|
nagyistoce/roslyn
|
src/Compilers/VisualBasic/Portable/Syntax/ArgumentSyntax.vb
|
Visual Basic
|
apache-2.0
| 2,742
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.1
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("0")> _
Public Property Suspensions() As Integer
Get
Return CType(Me("Suspensions"),Integer)
End Get
Set
Me("Suspensions") = value
End Set
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.MathQuiz.My.MySettings
Get
Return Global.MathQuiz.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
gumgl/VB.NET
|
MathQuiz/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 3,366
|
#Region "Microsoft.VisualBasic::2c878083dddb015cbba3d7062a201c7e, src\mzmath\TargetedMetabolomics\GCMS\CDFReader\Vendors\agilentHPLC.vb"
' Author:
'
' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.)
'
' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD.
'
'
' MIT License
'
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
' /********************************************************************************/
' Summaries:
' Class agilentHPLC
'
'
'
'
' /********************************************************************************/
#End Region
Namespace GCMS.Vendors
Public Class agilentHPLC
End Class
End Namespace
|
xieguigang/MassSpectrum-toolkits
|
src/mzmath/TargetedMetabolomics/GCMS/CDFReader/Vendors/agilentHPLC.vb
|
Visual Basic
|
mit
| 1,834
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports System.Globalization
Imports System.Resources
Imports System.Windows
Imports System.Runtime.CompilerServices
' Allgemeine Informationen über eine Assembly werden über die folgenden
' Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
' die mit einer Assembly verknüpft sind.
' Die Werte der Assemblyattribute überprüfen
<Assembly: AssemblyTitle("PPC Manager")>
<Assembly: AssemblyDescription("Zum Verwalten und Durchführen des Ping Pong Café")>
<Assembly: AssemblyCompany("Marius Goppelt")>
<Assembly: AssemblyProduct("PPC Manager")>
<Assembly: AssemblyCopyright("Marius Goppelt 2010")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'Um mit dem Erstellen lokalisierbarer Anwendungen zu beginnen, legen Sie
'<UICulture>ImCodeVerwendeteKultur</UICulture> in der VBPROJ-Datei
'in einer <PropertyGroup> fest. Wenn Sie in den Quelldateien beispielsweise Deutsch
'(Deutschland) verwenden, legen Sie <UICulture> auf "de-DE" fest. Heben Sie dann die Auskommentierung
'des nachstehenden NeutralResourceLanguage-Attributs auf. Aktualisieren Sie "en-US" in der nachstehenden Zeile,
'sodass es mit der UICulture-Einstellung in der Projektdatei übereinstimmt.
'<Assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)>
'Das ThemeInfo-Attribut beschreibt, wo Sie designspezifische und generische Ressourcenwörterbücher finden.
'1. Parameter: Speicherort der designspezifischen Ressourcenwörterbücher
'(wird verwendet, wenn eine Ressource auf der Seite
' oder in den Anwendungsressourcen-Wörterbüchern nicht gefunden werden kann.)
'2. Parameter: Speicherort des generischen Ressourcenwörterbuchs
'(wird verwendet, wenn eine Ressource auf der Seite,
'in der Anwendung sowie in den designspezifischen Ressourcenwörterbüchern nicht gefunden werden kann)
<Assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)>
'Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
<Assembly: Guid("ab0ec590-3387-4cbe-8542-d63fedc5e375")>
' Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
'
' Hauptversion
' Nebenversion
' Buildnummer
' Revision
'
' Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
' übernehmen, indem Sie "*" eingeben:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
<Assembly: InternalsVisibleTo("PPC Manager Tests")>
|
GoppeltM/PPC-Manager
|
Trunk/PPC Manager/PPC Manager/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 2,688
|
Imports WordSearch.Utilities
Imports WordSearch.Common
Namespace Model
Public Class GuessedWords : Inherits BindableBase
#Region " Private Variables "
Private _secretWord As String = ""
Private _lastBeforeSecret As String = ""
Private _firstAfterSecret As String = ""
Private _wordBetween As String = GetBestGuesses()
Private _lastGuessWasCorrect As Boolean
Private _guessedWords As New ObservableRangeCollection(Of String)
Private _results As New ObservableRangeCollection(Of String)
Private _remainingWords As New ObservableRangeCollection(Of String)
Private _numberCharactersResolved As Integer
#End Region
#Region " Public Properties "
Public Property SecretWord As String
Get
Return _secretWord
End Get
Set(ByVal value As String)
SetProperty(_secretWord, value)
End Set
End Property
Public Property LastBeforeSecret As String
Get
Return _lastBeforeSecret
End Get
Set(ByVal value As String)
SetProperty(_lastBeforeSecret, value)
End Set
End Property
Public Property FirstAfterSecret As String
Get
Return _firstAfterSecret
End Get
Set(ByVal value As String)
SetProperty(_firstAfterSecret, value)
End Set
End Property
Public Property WordBetween As String
Get
Return _wordBetween
End Get
Set(ByVal value As String)
SetProperty(_wordBetween, value)
End Set
End Property
Public Property LastGuessWasCorrect As Boolean
Get
Return _lastGuessWasCorrect
End Get
Set(ByVal value As Boolean)
SetProperty(_lastGuessWasCorrect, value)
End Set
End Property
Public Property GuessedWords As ObservableRangeCollection(Of String)
Get
Return _guessedWords
End Get
Set(ByVal value As ObservableRangeCollection(Of String))
SetProperty(_guessedWords, value)
End Set
End Property
Public Property Results As ObservableRangeCollection(Of String)
Get
Return _results
End Get
Set(ByVal value As ObservableRangeCollection(Of String))
SetProperty(_results, value)
End Set
End Property
Public Property RemainingWords As ObservableRangeCollection(Of String)
Get
Return _remainingWords
End Get
Set(ByVal value As ObservableRangeCollection(Of String))
SetProperty(_remainingWords, value)
End Set
End Property
Public Property NumberCharactersResolved As Integer
Get
Return _numberCharactersResolved
End Get
Set(ByVal value As Integer)
_numberCharactersResolved = value
End Set
End Property
#End Region
#Region " Constructor "
Public Sub New(ByVal secret As String)
SecretWord = secret
End Sub
#End Region
#Region " Methods "
Public Sub AddGuess(ByVal value As String)
Dim remainingItems As List(Of String)
Dim lastGuessResult As String = ""
'fill remaining words if empty
If RemainingWords.Count = 0 Then RemainingWords.AddRange(AppCommon.WordList)
'compare word to secret
Select Case String.Compare(value, SecretWord, StringComparison.OrdinalIgnoreCase)
Case Is < 0
LastGuessWasCorrect = False
lastGuessResult = String.Format("Secret word is {0} '{1}'", "after", value)
Case Is > 0
LastGuessWasCorrect = False
lastGuessResult = String.Format("Secret word is {0} '{1}'", "before", value)
Case 0
LastGuessWasCorrect = True
lastGuessResult = "You guessed the secret word!"
End Select
'add result to beginning of collection
Results.Insert(0, lastGuessResult)
'add guessed word
GuessedWords.Add(value)
'calculate best guesses
LastBeforeSecret = GuessedWords.Where(Function(i) i.ToLower < SecretWord.ToLower).OrderBy(Function(i) i).DefaultIfEmpty("").LastOrDefault
FirstAfterSecret = GuessedWords.Where(Function(i) i.ToLower > SecretWord.ToLower).OrderBy(Function(i) i).DefaultIfEmpty("").FirstOrDefault
WordBetween = GetBestGuesses()
'calculate words that are still left
remainingItems = RemainingWords.Where(Function(w) (LastBeforeSecret = "" OrElse w > LastBeforeSecret) AndAlso _
(FirstAfterSecret = "" OrElse w < FirstAfterSecret)).ToList
RemainingWords.Clear()
RemainingWords.AddRange(remainingItems)
End Sub
Private Function GetBestGuesses() As String
Dim beforeWord As String = If(LastBeforeSecret <> "", LastBeforeSecret, "aardvark")
Dim afterWord As String = If(FirstAfterSecret <> "", FirstAfterSecret, "zymurgy")
NumberCharactersResolved = SetNumberOfCommonLetters(beforeWord, afterWord)
If NumberCharactersResolved <> 0 Then
beforeWord = String.Format("({0}){1}", beforeWord.Substring(0, NumberCharactersResolved), beforeWord.Substring(NumberCharactersResolved))
afterWord = String.Format("({0}){1}", afterWord.Substring(0, NumberCharactersResolved), afterWord.Substring(NumberCharactersResolved))
End If
Return String.Format("Word is between {0} and {1}", beforeWord, afterWord)
End Function
Private Function SetNumberOfCommonLetters(ByVal beforeWord As String, ByVal afterWord As String) As Integer
Dim commonLetters As Integer = 0
For i = 1 To beforeWord.Length
If afterWord.ToLower.StartsWith(beforeWord.ToLower.Substring(0, i)) Then
commonLetters = i
Else
Exit For
End If
Next
Return commonLetters
End Function
Public Sub ResetGuesses()
LastBeforeSecret = ""
FirstAfterSecret = ""
SecretWord = ""
LastGuessWasCorrect = False
WordBetween = GetBestGuesses()
GuessedWords.Clear()
Results.Clear()
RemainingWords.Clear()
RemainingWords.AddRange(AppCommon.WordList)
End Sub
#End Region
End Class
End Namespace
|
KyleMit/WordGuess
|
SourceCode/WordSearch/Model/GuessedWords.vb
|
Visual Basic
|
mit
| 7,027
|
Public Class Window_About
Private Sub Contact_MouseUp(sender As Object, e As MouseButtonEventArgs) Handles Contact.MouseUp
Process.Start("mailto:me@naseweis520.ml?subject=Contact%20|%20osu!Sync")
End Sub
Private Sub Feedback_MouseUp(sender As Object, e As MouseButtonEventArgs) Handles Feedback.MouseUp
MainWindow.Interface_ShowSettingsWindow(3)
End Sub
Private Sub GitHub_MouseUp(sender As Object, e As MouseButtonEventArgs) Handles GitHub.MouseUp
Process.Start("https://github.com/naseweis520/osu-Sync")
End Sub
Private Sub osuForum_MouseUp(sender As Object, e As MouseEventArgs) Handles osuForum.MouseUp
Process.Start("https://osu.ppy.sh/forum/t/270446")
End Sub
Private Sub TextBlock_Version_MouseUp(sender As Object, e As MouseButtonEventArgs) Handles TextBlock_Version.MouseUp
MainWindow.Interface_ShowUpdaterWindow()
End Sub
Private Sub Window_About_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
TextBlock_Version.Text = _e("WindowAbout_version").Replace("%0", My.Application.Info.Version.ToString).Replace("%1", GetTranslationName(Setting_Tool_Language))
End Sub
End Class
|
troke12/osu-Sync
|
osu!Sync/Window_About.xaml.vb
|
Visual Basic
|
mit
| 1,205
|
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
<Assembly: AssemblyTitle("InstallData")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyConfiguration("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("InstallData")>
<Assembly: AssemblyCopyright("Copyright © 2015")>
<Assembly: AssemblyTrademark("")>
<Assembly: AssemblyCulture("")>
' Setting ComVisible to false makes the types in this assembly not visible
' to COM components. If you need to access a type in this assembly from
' COM, set the ComVisible attribute to true on that type.
<Assembly: ComVisible(False)>
' The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("d9494ae2-ff80-45b8-ae17-0c41b0b44ca4")>
' 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")>
|
SolidEdgeCommunity/Samples
|
General/ReportInstallData/vb/ReportInstallData/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,384
|
'------------------------------------------------------------------------------
' <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("VBFindNote.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/VBFindNote/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,716
|
Imports System.Windows.Forms
Imports System.Drawing
Public Class ShowSymbol
Public Question As String
Public Symbol As Image
Shared Function ShowDialogPersonalized(item As String, symbol As SWClasses.SWSignSymbol) As DialogResult
Dim question = "Is this symbol " & item & "?"
Dim dialog = New ShowSymbol With {.Question = question, .Symbol = symbol.SignSymbol}
dialog.ShowDialog()
Return dialog.DialogResult
End Function
Private Sub ShowSymbol_Load(sender As Object, e As EventArgs) Handles Me.Load
Label1.Text = Question
PictureBox1.Image = Symbol
End Sub
Private Sub btnYes_Click(sender As Object, e As EventArgs) Handles btnYes.Click
DialogResult = DialogResult.Yes
Hide()
End Sub
Private Sub btnNo_Click(sender As Object, e As EventArgs) Handles btnNo.Click
DialogResult = DialogResult.No
Hide()
End Sub
Private Sub btnCancel_Click( sender As Object, e As EventArgs) Handles btnCancel.Click
DialogResult = DialogResult.Cancel
Hide()
End Sub
End Class
|
JonathanDDuncan/SignWriterStudio
|
SWEditor/ShowSymbol.vb
|
Visual Basic
|
mit
| 1,102
|
Imports System.Drawing
Namespace Articles
Public Class UsingCellsFactory
Public Shared Sub Run()
' ExStart:1
' The path to the documents directory.
Dim dataDir As String = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
' Create a Style object using CellsFactory class
Dim cf As New CellsFactory()
Dim st As Style = cf.CreateStyle()
' Set the Style fill color to Yellow
st.Pattern = BackgroundType.Solid
st.ForegroundColor = Color.Yellow
' Create a workbook and set its default style using the created Style object
Dim wb As New Workbook()
wb.DefaultStyle = st
' Save the workbook
wb.Save(dataDir & Convert.ToString("output_out.xlsx"))
' ExEnd:1
End Sub
End Class
End Namespace
|
maria-shahid-aspose/Aspose.Cells-for-.NET
|
Examples/VisualBasic/Articles/UsingCellsFactory.vb
|
Visual Basic
|
mit
| 928
|
Imports PlayerIOClient
Public Class BlockPlaceUploadMessage
Inherits UploadMessage
Public ReadOnly Layer As Layer
Public ReadOnly X As Integer
Public ReadOnly Y As Integer
Public ReadOnly Block As Block
Private ReadOnly myForced As Boolean
Protected UploadCheck As Byte
Public Sub New(layer As Layer, x As Integer, y As Integer, block As Block, Optional forced As Boolean = False)
Me.Layer = layer
Me.X = x
Me.Y = y
Me.Block = block
myForced = forced
End Sub
Friend Overrides Function GetMessage(game As IGame) As Message
Return Message.Create(game.Encryption, CInt(CorrectLayer(Block, Layer)), X, Y, CInt(Block))
End Function
Friend Overrides Function SendMessage(client As IClient(Of Player)) As Boolean
If Not client.World(X, Y, Layer).Block = Block OrElse myForced Then
client.Connection.Send(Me)
Return True
Else
Return False
End If
End Function
Friend Overrides Function IsUploaded(message As BlockPlaceReceiveMessage) As Boolean
If UploadCheck <= 100 Then
UploadCheck = CByte(UploadCheck + 1)
Return X = message.PosX AndAlso Y = message.PosY AndAlso Layer = message.Layer
Else
Cloud.Logger.Log(LogPriority.Warning, String.Format("Block failed to upload with ID {0}, at position {1} | {2}.", Block, X, Y))
Return True
End If
End Function
End Class
|
TeamEEDev/EECloud
|
EECloud.API/Messages/Upload/BlockPlaceUploadMessage.vb
|
Visual Basic
|
mit
| 1,503
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' 有关程序集的一般信息由以下
' 控制。更改这些特性值可修改
' 与程序集关联的信息。
'查看程序集特性的值
<Assembly: AssemblyTitle("ModelLib")>
<Assembly: AssemblyDescription("Licensed under the MIT license")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("LentilToolBox")>
<Assembly: AssemblyCopyright("Copyright © 2016 Lentil Sun")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
<Assembly: Guid("5e6e2634-6817-41a0-911f-712889274e86")>
' 程序集的版本信息由下列四个值组成:
'
' 主版本
' 次版本
' 生成号
' 修订号
'
'可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
' 方法是按如下所示使用“*”: :
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.1.0.0")>
<Assembly: AssemblyFileVersion("1.1.0.0")>
|
Lentil1016/LTB
|
v1.1/LentilToolbox/ModelLib/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,057
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.34014
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'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.Opaque.main
End Sub
End Class
End Namespace
|
Tux64/Opaque
|
Opaque/My Project/Application.Designer.vb
|
Visual Basic
|
bsd-3-clause
| 1,471
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.TextRecognitionExample.My.MySettings
Get
Return Global.TextRecognitionExample.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
bytescout/ByteScout-SDK-SourceCode
|
Text Recognition SDK/VB.NET/Use Text Auto Corrections/My Project/Settings.Designer.vb
|
Visual Basic
|
apache-2.0
| 2,950
|
' 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.OptionStatements
Public Class OptionKeywordRecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function OptionInBlankFileTest() As Task
Await VerifyRecommendationsContainAsync(<File>|</File>, "Option")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function OptionAfterAnotherOptionStatementTest() As Task
Await VerifyRecommendationsContainAsync(<File>
Option Strict On
|</File>, "Option")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function OptionAfterBlankLineTest() As Task
Await VerifyRecommendationsContainAsync(<File>
Option Strict On
|</File>, "Option")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function OptionNotAfterImportsTest() As Task
Await VerifyRecommendationsMissingAsync(<File>
Imports Goo
|</File>, "Option")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function OptionNotAfterTypeTest() As Task
Await VerifyRecommendationsMissingAsync(<File>
Class Goo
End Class
|</File>, "Option")
End Function
<WorkItem(543008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543008")>
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function OptionNotAfterRegionKeywordTest() As Task
Await VerifyRecommendationsMissingAsync(<File>
#Region |
</File>, "Option")
End Function
End Class
End Namespace
|
mmitche/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/OptionStatements/OptionKeywordRecommenderTests.vb
|
Visual Basic
|
apache-2.0
| 2,015
|
' 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
Imports System.Collections.Generic
Imports System.Linq
Imports System.Runtime.CompilerServices
Imports System.Text
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax
Friend Partial Class SyntaxList
Friend Class WeakSeparatedWithManyChildren
Inherits SyntaxList
Private ReadOnly _children As ArrayElement(Of WeakReference(Of SyntaxNode))()
Friend Sub New(green As InternalSyntax.SyntaxList, parent As SyntaxNode, position As Integer)
MyBase.New(green, parent, position)
Me._children = New ArrayElement(Of WeakReference(Of SyntaxNode))(((green.SlotCount + 1) >> 1) - 1) {}
End Sub
Friend Overrides Function GetNodeSlot(i As Integer) As SyntaxNode
Dim result As SyntaxNode = Nothing
If (i And 1) = 0 Then
'not a separator
result = GetWeakRedElement(Me._children(i >> 1).Value, i)
End If
Return result
End Function
Friend Overrides Function GetCachedSlot(i As Integer) As SyntaxNode
Dim result As SyntaxNode = Nothing
If (i And 1) = 0 Then
'not a separator
Dim weak = Me._children(i >> 1).Value
If weak IsNot Nothing Then
weak.TryGetTarget(result)
End If
End If
Return result
End Function
End Class
End Class
End Namespace
|
MatthieuMEZIL/roslyn
|
src/Compilers/VisualBasic/Portable/Syntax/SyntaxList.WeakSeparatedWithManyChildren.vb
|
Visual Basic
|
apache-2.0
| 1,896
|
Imports SistFoncreagro.BussinessEntities
Imports Microsoft.Practices.EnterpriseLibrary.Data
Partial Public Class ActividadRepository : Inherits MasterDataAccess : Implements IActividadRepository
Public Function GetActividadesByIdProycomp(idProycomp As Integer) As System.Collections.Generic.List(Of BussinessEntities.ActividadDto) Implements IActividadRepository.GetActividadesByIdProycomp
Dim query = db.ExecuteSprocAccessor(Of ActividadDto)("GetActividadesByIdProycomp", idProycomp)
Return query.ToList()
End Function
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.DataAccess/Actividades/ActividadRepositorySam.vb
|
Visual Basic
|
mit
| 561
|
Imports Telerik.Web.UI
Imports SistFoncreagro.BussinesLogic
Imports SistFoncreagro.BussinessEntities
Public Class FrmProveedores
Inherits System.Web.UI.Page
Dim proveedorCliente As ProveedorCliente
Dim proveedorBl As New ProveedorClienteBL
Private _userControl As Object
Protected Sub RadGrid2_ItemCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid2.ItemCommand
If e.CommandName = "InitInsert" Then
Dim cadena_java As String
cadena_java = "<script type='text/javascript'> " & _
" NuevoProveedor(); " & _
Chr(60) & "/script>"
ScriptManager.RegisterStartupScript(Page, GetType(Page), "Cerrar", cadena_java.ToString, False)
e.Canceled = True
ElseIf e.CommandName = "Anular" Then
Dim editedItem As GridEditableItem = CType(e.Item, GridEditableItem)
Dim IdProveedor As Int32 = editedItem.OwnerTableView.DataKeyValues(editedItem.ItemIndex)("IdProveedorCliente")
proveedorBl.DeleteProveedorCliente(IdProveedor)
Me.RadGrid2.DataBind()
End If
End Sub
Protected Sub RadGrid2_ItemCreated(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs) Handles RadGrid2.ItemCreated
If TypeOf e.Item Is GridDataItem Then
Dim imageButon As ImageButton = DirectCast(e.Item.FindControl("EditButton"), ImageButton)
Dim idProveedor = e.Item.OwnerTableView.DataKeyValues(e.Item.ItemIndex)("IdProveedorCliente")
imageButon.Attributes.Add("onClick", "CargarVentanaProveedor(" & idProveedor & ", 'editar'); return false;")
End If
End Sub
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.WebSite/Logistica/FrmProveedores.aspx.vb
|
Visual Basic
|
mit
| 1,752
|
Imports System
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim documents As SolidEdgeFramework.Documents = Nothing
Dim partDocument As SolidEdgePart.PartDocument = Nothing
Dim refPlanes As SolidEdgePart.RefPlanes = Nothing
Dim profileSets As SolidEdgePart.ProfileSets = Nothing
Dim profileSet As SolidEdgePart.ProfileSet = Nothing
Dim profiles As SolidEdgePart.Profiles = Nothing
Dim profile As SolidEdgePart.Profile = Nothing
Dim ellipses2d As SolidEdgeFrameworkSupport.Ellipses2d = Nothing
Dim ellipse2d As SolidEdgeFrameworkSupport.Ellipse2d = Nothing
Try
' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register()
' Attempt to connect to a running instance of Solid Edge.
application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application)
documents = application.Documents
partDocument = CType(documents.Add("SolidEdge.PartDocument"), SolidEdgePart.PartDocument)
refPlanes = partDocument.RefPlanes
profileSets = partDocument.ProfileSets
profileSet = profileSets.Add()
profiles = profileSet.Profiles
profile = profiles.Add(refPlanes.Item(1))
ellipses2d = profile.Ellipses2d
Dim Orientation = SolidEdgeFrameworkSupport.Geom2dOrientationConstants.igGeom2dOrientClockwise
ellipse2d = ellipses2d.AddByCenter(0, 0, 0.01, 0, 0.5, Orientation)
Dim x As Double = Nothing
Dim y As Double = Nothing
ellipse2d.GetMajorAxis(x, y)
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.Ellipse2d.GetMajorAxis.vb
|
Visual Basic
|
mit
| 2,241
|
Imports System.Runtime.Serialization
<DataContract>
Public Class AccountObject
<DataMember(Name:="always_use_https")>
Public Property IsAlwaysUseHttps As Boolean?
<DataMember(Name:="discoverable_by_email")>
Public Property IsDiscoverableByEmail As Boolean?
<DataMember(Name:="geo_enabled")>
Public Property IsGeoEnabled As Boolean?
<DataMember(Name:="language")>
Public Property Language As String
<DataMember(Name:="protected")>
Public Property IsProtected As Boolean?
<DataMember(Name:="screen_name")>
Public Property ScreenName As String
<DataMember(Name:="show_all_inline_media")>
Public Property IsShowAllInlineMedia As Boolean?
<DataMember(Name:="use_cookie_personalization")>
Public Property IsUseCookiePersonalization As Boolean?
<DataMember(Name:="sleep_time")>
Public Property SleepTime As SleepTimeObject
<DataMember(Name:="time_zone")>
Public Property TimeZone As TimeZoneObject
End Class
<DataContract>
Public Class SleepTimeObject
<DataMember(Name:="enabled")>
Public Property IsEnabled As Boolean?
<DataMember(Name:="end_time")>
Public Property EndTime As String
<DataMember(Name:="start_time")>
Public Property StartTime As String
End Class
<DataContract>
Public Class TimeZoneObject
<DataMember(Name:="name")>
Public Property Name As String
<DataMember(Name:="tzinfo_name")>
Public Property TzinfoName As String
<DataMember(Name:="utc_offset")>
Public Property UtcOffset As String
End Class
<DataContract>
Public Class TrendLocationObject
<DataMember(Name:="country")>
Public Property Country As String
<DataMember(Name:="countryCode")>
Public Property CountryCode As String
<DataMember(Name:="name")>
Public Property Name As String
<DataMember(Name:="parentid")>
Public Property ParentId As Decimal?
<DataMember(Name:="url")>
Public Property Url As String
<DataMember(Name:="woeid")>
Public Property Woeid As String
End Class
|
szr2000/FistTwit
|
FistTwit/Objects/AccountObject.vb
|
Visual Basic
|
mit
| 2,050
|
Public Enum CharRegionType
[Char]
Space
End Enum
Public Class CharRegion
Public deleted As Boolean = False
Public LeftOffset = 0, RightOffset = 0
Public Type As CharRegionType
Public Function Length() As Integer
Return RightOffset - LeftOffset + 1
End Function
Public Sub Combine(b As CharRegion)
If RightOffset + 1 <> b.LeftOffset Then
Throw New Exception("Cannot combine")
End If
RightOffset = b.RightOffset
b.deleted = True
End Sub
Public Shared Function Read(blackcount As Integer(), start As Integer, Optional T As Integer = 0) As CharRegion
Dim cr As New CharRegion
Dim counting = False
If blackcount(start) >= T Then
cr.Type = CharRegionType.Char
For i = start To blackcount.Length - 1
If Not counting AndAlso blackcount(i) >= T Then 'Char
counting = True
cr.LeftOffset = i
End If
If counting Then
If blackcount(i) < T Then
cr.RightOffset = i - 1
Exit For
End If
End If
Next
Else
cr.Type = CharRegionType.Space
For i = start To blackcount.Length - 1
If Not counting AndAlso blackcount(i) < T Then 'Space
counting = True
cr.LeftOffset = i
End If
If counting Then
If blackcount(i) >= T Then
cr.RightOffset = i - 1
Exit For
End If
End If
Next
End If
If cr.RightOffset <= 0 Then
cr.RightOffset = cr.LeftOffset
End If
Return cr
End Function
End Class
|
twd2/HandWritingGenerator
|
HandWritingGenerator/CharRegion.vb
|
Visual Basic
|
mit
| 1,890
|
'------------------------------------------------------------------------------
' <auto-generated>
' 此代码由工具生成。
' 运行时版本:4.0.30319.42000
'
' 对此文件的更改可能会导致不正确的行为,并且如果
' 重新生成代码,这些更改将会丢失。
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Imports System
Namespace My.Resources
'此类是由 StronglyTypedResourceBuilder
'类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
'若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
'(以 /str 作为命令选项),或重新生成 VS 项目。
'''<summary>
''' 一个强类型的资源类,用于查找本地化的字符串等。
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' 返回此类使用的缓存的 ResourceManager 实例。
'''</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("CLI.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' 使用此强类型资源类,为所有资源查找
''' 重写当前线程的 CurrentUICulture 属性。
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
xieguigang/spectrum
|
src/metadb/MetabolomeXchange/CLI/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,722
|
Option Infer On
Imports System
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As RevisionManager.Application = Nothing
Dim insight As RevisionManager.Insight = Nothing
Try
application = New RevisionManager.Application()
insight = CType(application.Insight, RevisionManager.Insight)
Dim ListOfDocuments = New Object(1){}
ListOfDocuments(0) = "http://solidvm/Engineering/PreReleased/PreReleasedDocLib/Summit.par"
ListOfDocuments(1) = "http://solidvm/Engineering/PreReleased/PreReleasedDocLib/Summit-1.par"
' Checkout the documents first.
insight.CheckOutDocumentsFromServer(ListOfDocuments.Length, ListOfDocuments)
' Now undo the checkout of the documents first.
insight.UndoCheckOutDocumentsFromServer(ListOfDocuments.Length, ListOfDocuments)
Catch ex As System.Exception
Console.WriteLine(ex)
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/RevisionManager.IInsight.UndoCheckOutDocumentsFromServer.vb
|
Visual Basic
|
mit
| 1,193
|
Imports System.Collections.Generic
Imports Rstyx.Utilities.StringUtils
Namespace Collections
''' <summary> Shortcut for a <see cref="IDCollection(Of String, TItem)"/>, representing the most usual case: objects with a string identifier. </summary>
''' <typeparam name="TItem"> Type of collection items. It has to implement the <see cref="IIdentifiable(Of TKey)"/> interface. </typeparam>
''' <remarks> The key for the collection will always be the <b>ID</b> property of <b>TItem</b>, which is a String. </remarks>
Public Class IDCollection(Of TItem As IIdentifiable(Of String))
Inherits IDCollection(Of String, TItem)
#Region "Constructors"
''' <summary> Creates a new, empty IDCollection. </summary>
Public Sub New
MyBase.New()
End Sub
Public Sub New(InitialMembers As IEnumerable(Of IIdentifiable(Of String)))
MyBase.New(InitialMembers)
End Sub
#End Region
End Class
''' <summary> A generic, ready for use sorted keyed collection for all objects that implement the <see cref="IIdentifiable(Of TKey)"/> interface. </summary>
''' <typeparam name="TKey"> Type of collection keys. It's the type of the item's <see cref="IIdentifiable(Of TKey).ID"/> property. </typeparam>
''' <typeparam name="TItem"> Type of collection items. It has to implement the <see cref="IIdentifiable(Of TKey)"/> interface. </typeparam>
''' <remarks> The key for the collection will always be the <b>ID</b> property of <b>TItem</b>. </remarks>
Public Class IDCollection(Of TKey, TItem As IIdentifiable(Of TKey))
Inherits Rstyx.Utilities.Collections.SortedKeyedCollectionBase(Of TKey, TItem)
#Region "Private Fields"
Private Logger As Rstyx.LoggingConsole.Logger = Rstyx.LoggingConsole.LogBox.getLogger("Rstyx.Utilities.Domain.IDCollection")
#End Region
#Region "Constructors"
''' <summary> Creates a new, empty IDCollection. </summary>
Public Sub New
MyBase.New()
End Sub
''' <summary> Creates a new IDCollection, initiated with items of <paramref name="InitialMembers"/>. </summary>
Public Sub New(InitialMembers As IEnumerable(Of IIdentifiable(Of TKey)))
Me.New()
For Each NewItem As IIdentifiable(Of TKey) In InitialMembers
Me.Add(NewItem)
Next
End Sub
#End Region
#Region "Collection Implementation"
''' <summary> Gets the <see cref="IIdentifiable(Of TKey)"/>.<b>ID</b> as collection key. </summary>
''' <param name="Item"> The identifyable object of interest. </param>
''' <returns> The ID as key. </returns>
Protected Overrides Function GetKeyForItem(ByVal Item As TItem) As TKey
Dim Key As TKey = Nothing
If (Item IsNot Nothing) Then Key = Item.ID
Return Key
End Function
''' <summary> This is called by <see cref="IDCollection(Of String, TItem).Add"/> and changes it's default behavior. </summary>
''' <param name="Index"> Collection index. </param>
''' <param name="Item"> The item to add. </param>
''' <remarks> Checks if <paramref name="Item"/> is <see langword="null"/> or if it's <c>ID</c> property already exists in this list. </remarks>
''' <exception cref="System.ArgumentNullException"> <paramref name="Item"/> is <see langword="null"/>. </exception>
''' <exception cref="System.ArgumentOutOfRangeException"> <paramref name="Index"/> is less than 0, or greater than <see cref="KeyedCollectionBase(Of TKey, TItem).Count"/>. </exception>
''' <exception cref="InvalidIDException"> <paramref name="Item"/>.<c>ID</c> is empty or does already exist. </exception>
Protected Overrides Sub InsertItem(Index As Integer, Item As TItem)
If (Item Is Nothing) Then Throw New System.ArgumentNullException("Item")
If (Item.ID.ToString().IsEmptyOrWhiteSpace()) Then Throw New InvalidIDException(Rstyx.Utilities.Resources.Messages.IDCollection_MissingID)
If (MyClass.Contains(Item.ID)) Then Throw New InvalidIDException(sprintf(Rstyx.Utilities.Resources.Messages.IDCollection_RepeatedID, Item.ID.ToString()))
MyBase.InsertItem(Index, Item)
End Sub
#End Region
End Class
End Namespace
' for jEdit: :collapseFolds=2::tabSize=4::indentSize=4:
|
rschwenn/Rstyx.Utilities
|
Utilities/source/Collections/IDCollection.vb
|
Visual Basic
|
mit
| 4,966
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.34003
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.Feedbo.My.MySettings
Get
Return Global.Feedbo.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
feedbo/feedbo
|
Feedbo/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,991
|
Option Explicit On
Option Strict On
' The errors dictionary, now private in GrblGcodeView, need to be also used in GrblStatus, as these errors are reported only as digits
' So, as only one dictionary is usefull, and will need to be called from different places, it seems the singleton pattern is the best and 'lightest' way
' to implement it.
Imports GrblPanel.My.Resources
Public Class GrblErrorsSingleton
'Using SyncLock make this thread safe
Private Shared _instance As GrblErrorsSingleton = Nothing
Private Shared ReadOnly _mylock As New Object()
Private Shared _errors As Dictionary(Of String, String)
Private Sub New()
End Sub
Public Shared Function GetInstance() As GrblErrorsSingleton
SyncLock(_mylock)
If _instance Is Nothing
_instance = New GrblErrorsSingleton
End If
Return _instance
End SyncLock
End Function
''' <summary>
''' This Function returns a Dictionary of Grbl error codes in plain text
''' </summary>
''' <returns></returns>
Public Function GetErrorsDct() As Dictionary(Of String, String)
_errors = New Dictionary(Of String, String) From {
{"0", "ok"},
{"1", GrblGcodeView_ExpectedCommandLetter},
{"2", GrblGcodeView_BadNumberFormat},
{"3", GrblGcodeView_InvalidStatement},
{"4", GrblGcodeView_Value0},
{"5", Resources.GrblGcodeView_SettingDisabled},
{"6", Resources.GrblGcodeView_Value3Usec},
{"7", Resources.GrblGcodeView_EEPROMReadFailUsingDefaults},
{"8", Resources.GrblGcodeView_NotIdle},
{"9", Resources.GrblGcodeView_AlarmLock},
{"10", Resources.GrblGcodeView_HomingIsNotEnabled},
{"11", Resources.GrblGcodeView_LineOverflow},
{"12", Resources.GrblGcodeView_StepRate30kHz},
{"13", Resources.GrblGcodeView_CheckDoor},
{"14", Resources.GrblGcodeView_BuildInfoLength},
{"15", Resources.GrblGcodeView_JogTravel},
{"16", Resources.GrblGcodeView_JogFormat},
{"20", Resources.GrblGcodeView_UnsupportedCommand},
{"21", Resources.GrblGcodeView_ModalGroupViolation},
{"22", Resources.GrblGcodeView_UndefinedFeedRate},
{"23", Resources.GrblGcodeView_CommandValueIsNotInteger},
{"24", Resources.GrblGcodeView_AxisCommandConflict},
{"25", Resources.GrblGcodeView_WordRepeated},
{"26", Resources.GrblGcodeView_NoAxisWords},
{"27", Resources.GrblGcodeView_InvalidLineNumber},
{"28", Resources.GrblGcodeView_ValueWordMissing},
{"29", Resources.GrblGcodeView_UnsupportedCoordinateSystem},
{"30", Resources.GrblGcodeView_G53InvalidMotionMode},
{"31", Resources.GrblGcodeView_AxisWordsExist},
{"32", Resources.GrblGcodeView_NoAxisWordsInPlane},
{"33", Resources.GrblGcodeView_InvalidTarget},
{"34", Resources.GrblGcodeView_ArcRadiusError},
{"35", Resources.GrblGcodeView_NoOffsetsInPlane},
{"36", Resources.GrblGcodeView_UnusedWords},
{"37", Resources.GrblGcodeView_G43DynamicAxisError},
{"38", Resources.GrblGcodeView_InvalidToolNumber}
}
Return _errors
End Function
End Class
|
gerritv/Grbl-Panel
|
Grbl-Panel/GrblErrorsSingleton.vb
|
Visual Basic
|
mit
| 3,332
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Reflection.Metadata
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Emit
Friend NotInheritable Class PEDeltaAssemblyBuilder
Inherits PEAssemblyBuilderBase
Implements IPEDeltaAssemblyBuilder
Private ReadOnly _previousGeneration As EmitBaseline
Private ReadOnly _previousDefinitions As VisualBasicDefinitionMap
Private ReadOnly _changes As SymbolChanges
Public Sub New(sourceAssembly As SourceAssemblySymbol,
emitOptions As EmitOptions,
outputKind As OutputKind,
serializationProperties As ModulePropertiesForSerialization,
manifestResources As IEnumerable(Of ResourceDescription),
previousGeneration As EmitBaseline,
edits As IEnumerable(Of SemanticEdit),
isAddedSymbol As Func(Of ISymbol, Boolean))
MyBase.New(sourceAssembly, emitOptions, outputKind, serializationProperties, manifestResources, assemblySymbolMapper:=Nothing, additionalTypes:=ImmutableArray(Of NamedTypeSymbol).Empty)
Dim context = New EmitContext(Me, Nothing, New DiagnosticBag())
Dim [module] = previousGeneration.OriginalMetadata
Dim compilation = sourceAssembly.DeclaringCompilation
Dim metadataAssembly = compilation.GetBoundReferenceManager().CreatePEAssemblyForAssemblyMetadata(AssemblyMetadata.Create([module]), MetadataImportOptions.All)
Dim metadataDecoder = New Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE.MetadataDecoder(metadataAssembly.PrimaryModule)
previousGeneration = EnsureInitialized(previousGeneration, metadataDecoder)
Dim matchToMetadata = New VisualBasicSymbolMatcher(previousGeneration.AnonymousTypeMap, sourceAssembly, context, metadataAssembly)
Dim matchToPrevious As VisualBasicSymbolMatcher = Nothing
If previousGeneration.Ordinal > 0 Then
Dim previousAssembly = DirectCast(previousGeneration.Compilation, VisualBasicCompilation).SourceAssembly
Dim previousContext = New EmitContext(DirectCast(previousGeneration.PEModuleBuilder, PEModuleBuilder), Nothing, New DiagnosticBag())
matchToPrevious = New VisualBasicSymbolMatcher(
previousGeneration.AnonymousTypeMap,
sourceAssembly:=sourceAssembly,
sourceContext:=context,
otherAssembly:=previousAssembly,
otherContext:=previousContext,
otherSynthesizedMembersOpt:=previousGeneration.SynthesizedMembers)
End If
Me._previousDefinitions = New VisualBasicDefinitionMap(previousGeneration.OriginalMetadata.Module, edits, metadataDecoder, matchToMetadata, matchToPrevious)
Me._previousGeneration = previousGeneration
Me._changes = New SymbolChanges(_previousDefinitions, edits, isAddedSymbol)
End Sub
Public Overrides ReadOnly Property CurrentGenerationOrdinal As Integer
Get
Return _previousGeneration.Ordinal + 1
End Get
End Property
Private Overloads Shared Function GetAnonymousTypeMapFromMetadata(
reader As MetadataReader,
metadataDecoder As Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE.MetadataDecoder) As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue)
Dim result = New Dictionary(Of AnonymousTypeKey, AnonymousTypeValue)
For Each handle In reader.TypeDefinitions
Dim def = reader.GetTypeDefinition(handle)
If Not def.Namespace.IsNil Then
Continue For
End If
If Not reader.StringComparer.StartsWith(def.Name, GeneratedNames.AnonymousTypeOrDelegateCommonPrefix) Then
Continue For
End If
Dim metadataName = reader.GetString(def.Name)
Dim arity As Short = 0
Dim name = MetadataHelpers.InferTypeArityAndUnmangleMetadataName(metadataName, arity)
Dim index As Integer = 0
If GeneratedNames.TryParseAnonymousTypeTemplateName(GeneratedNames.AnonymousTypeTemplateNamePrefix, name, index) Then
Dim type = DirectCast(metadataDecoder.GetTypeOfToken(handle), NamedTypeSymbol)
Dim key = GetAnonymousTypeKey(type)
Dim value = New AnonymousTypeValue(name, index, type)
result.Add(key, value)
ElseIf GeneratedNames.TryParseAnonymousTypeTemplateName(GeneratedNames.AnonymousDelegateTemplateNamePrefix, name, index) Then
Dim type = DirectCast(metadataDecoder.GetTypeOfToken(handle), NamedTypeSymbol)
Dim key = GetAnonymousDelegateKey(type)
Dim value = New AnonymousTypeValue(name, index, type)
result.Add(key, value)
End If
Next
Return result
End Function
Private Shared Function GetAnonymousTypeKey(type As NamedTypeSymbol) As AnonymousTypeKey
' The key is the set of properties that correspond to type parameters.
' For each type parameter, get the name of the property of that type.
Dim n = type.TypeParameters.Length
If n = 0 Then
Return New AnonymousTypeKey(ImmutableArray(Of AnonymousTypeKeyField).Empty)
End If
' Properties indexed by type parameter ordinal.
Dim properties = New AnonymousTypeKeyField(n - 1) {}
For Each member In type.GetMembers()
If member.Kind <> SymbolKind.Property Then
Continue For
End If
Dim [property] = DirectCast(member, PropertySymbol)
Dim propertyType = [property].Type
If propertyType.TypeKind = TypeKind.TypeParameter Then
Dim typeParameter = DirectCast(propertyType, TypeParameterSymbol)
Debug.Assert(typeParameter.ContainingSymbol = type)
Dim index = typeParameter.Ordinal
Debug.Assert(properties(index).Name Is Nothing)
' ReadOnly anonymous type properties were 'Key' properties.
properties(index) = AnonymousTypeKeyField.CreateField([property].Name, isKey:=[property].IsReadOnly)
End If
Next
Debug.Assert(properties.All(Function(f) Not String.IsNullOrEmpty(f.Name)))
Return New AnonymousTypeKey(ImmutableArray.Create(properties))
End Function
Private Shared Function GetAnonymousDelegateKey(type As NamedTypeSymbol) As AnonymousTypeKey
Debug.Assert(type.BaseTypeNoUseSiteDiagnostics.SpecialType = SpecialType.System_MulticastDelegate)
' The key is the set of parameter names to the Invoke method,
' where the parameters are of the type parameters.
Dim members = type.GetMembers(WellKnownMemberNames.DelegateInvokeName)
Debug.Assert(members.Length = 1 AndAlso members(0).Kind = SymbolKind.Method)
Dim method = DirectCast(members(0), MethodSymbol)
Debug.Assert(method.Parameters.Count + If(method.IsSub, 0, 1) = type.TypeParameters.Length)
Dim parameters = ArrayBuilder(Of AnonymousTypeKeyField).GetInstance()
parameters.AddRange(method.Parameters.SelectAsArray(Function(p) AnonymousTypeKeyField.CreateField(p.Name, isKey:=False)))
parameters.Add(AnonymousTypeKeyField.CreateField(AnonymousTypeDescriptor.GetReturnParameterName(Not method.IsSub), isKey:=False))
Return New AnonymousTypeKey(parameters.ToImmutableAndFree(), isDelegate:=True)
End Function
Private Shared Function EnsureInitialized(previousGeneration As EmitBaseline,
metadataDecoder As Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE.MetadataDecoder) As EmitBaseline
If previousGeneration.AnonymousTypeMap IsNot Nothing Then
Return previousGeneration
End If
Dim anonymousTypeMap = GetAnonymousTypeMapFromMetadata(previousGeneration.MetadataReader, metadataDecoder)
Return previousGeneration.WithAnonymousTypeMap(anonymousTypeMap)
End Function
Friend ReadOnly Property PreviousGeneration As EmitBaseline
Get
Return _previousGeneration
End Get
End Property
Friend ReadOnly Property PreviousDefinitions As VisualBasicDefinitionMap
Get
Return _previousDefinitions
End Get
End Property
Friend Overrides ReadOnly Property SupportsPrivateImplClass As Boolean
Get
' Disable <PrivateImplementationDetails> in ENC since the
' CLR does Not support adding non-private members.
Return False
End Get
End Property
Friend Overloads Function GetAnonymousTypeMap() As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue) Implements IPEDeltaAssemblyBuilder.GetAnonymousTypeMap
Dim anonymousTypes = Compilation.AnonymousTypeManager.GetAnonymousTypeMap()
' Should contain all entries in previous generation.
Debug.Assert(_previousGeneration.AnonymousTypeMap.All(Function(p) anonymousTypes.ContainsKey(p.Key)))
Return anonymousTypes
End Function
Friend Overrides Function TryCreateVariableSlotAllocator(method As MethodSymbol, topLevelMethod As MethodSymbol) As VariableSlotAllocator
Return _previousDefinitions.TryCreateVariableSlotAllocator(_previousGeneration, method, topLevelMethod)
End Function
Friend Overrides Function GetPreviousAnonymousTypes() As ImmutableArray(Of AnonymousTypeKey)
Return ImmutableArray.CreateRange(_previousGeneration.AnonymousTypeMap.Keys)
End Function
Friend Overrides Function GetNextAnonymousTypeIndex(fromDelegates As Boolean) As Integer
Return _previousGeneration.GetNextAnonymousTypeIndex(fromDelegates)
End Function
Friend Overrides Function TryGetAnonymousTypeName(template As NamedTypeSymbol, <Out()> ByRef name As String, <Out()> ByRef index As Integer) As Boolean
Debug.Assert(Compilation Is template.DeclaringCompilation)
Return _previousDefinitions.TryGetAnonymousTypeName(template, name, index)
End Function
Friend ReadOnly Property Changes As SymbolChanges
Get
Return _changes
End Get
End Property
Friend Overrides Function GetTopLevelTypesCore(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition)
Return _changes.GetTopLevelTypes(context)
End Function
Friend Sub OnCreatedIndices(diagnostics As DiagnosticBag) Implements IPEDeltaAssemblyBuilder.OnCreatedIndices
Dim embeddedTypesManager = Me.EmbeddedTypesManagerOpt
If embeddedTypesManager IsNot Nothing Then
For Each embeddedType In embeddedTypesManager.EmbeddedTypesMap.Keys
diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.ERR_EncNoPIAReference, embeddedType), Location.None)
Next
End If
End Sub
Friend Overrides ReadOnly Property AllowOmissionOfConditionalCalls As Boolean
Get
Return True
End Get
End Property
Protected Overrides ReadOnly Property LinkedAssembliesDebugInfo As IEnumerable(Of String)
Get
' This debug information is only emitted for the benefit of legacy EE.
' Since EnC requires Roslyn and Roslyn doesn't need this information we don't emit it during EnC.
Return SpecializedCollections.EmptyEnumerable(Of String)()
End Get
End Property
End Class
End Namespace
|
paladique/roslyn
|
src/Compilers/VisualBasic/Portable/Emit/EditAndContinue/PEDeltaAssemblyBuilder.vb
|
Visual Basic
|
apache-2.0
| 12,636
|
Public Class LogViewer
End Class
|
QMDevTeam/QMDesigner
|
DataManager/Dialogs/LogViewer.vb
|
Visual Basic
|
apache-2.0
| 33
|
Imports System.Data.Objects
Imports Proes.Data
Public MustInherit Class BaseEntityRepository(Of TType As {TSet, Class}, TSet As Class, TKey As Structure, TContext As IObjectContext)
Implements IEntityRepository(Of TType, TKey)
Private ReadOnly _context As TContext
Protected Sub New(ByVal context As TContext)
_context = context
End Sub
Protected MustOverride ReadOnly Property ObjectSets As ICollection(Of ObjectSet(Of TSet))
Protected MustOverride ReadOnly Property MainObjectSet As ObjectSet(Of TSet)
Protected ReadOnly Property Context As TContext
Get
Return _context
End Get
End Property
Public Overridable Function Create() As TType Implements IEntityRepository(Of TType, TKey).Create
Return Context.CreateObject(Of TType)()
End Function
Public Overridable Function Copy(other As TType) As TType Implements IEntityRepository(Of TType, TKey).Copy
Dim newObject = Create()
other.CopyEntityTo(newObject, "id")
Add(newObject)
Return newObject
End Function
Protected MustOverride Function GetQueryById(ByVal query As IQueryable(Of TType), ByVal id As TKey) As IQueryable(Of TType)
Protected Function TryCache(id As TKey) As TType
Dim osquery = Context _
.ObjectStateManager _
.GetObjectStateEntries(EntityState.Unchanged) _
.Select(Function(ose) ose.Entity) _
.OfType(Of TType) _
.AsQueryable()
Return GetQueryById(osquery, id).SingleOrDefault
End Function
Public Function GetById(ByVal id As TKey?, Optional bypassCache As Boolean = False, Optional ByVal includePath As String = Nothing) As TType Implements IEntityRepository(Of TType, TKey).GetById
If id.HasValue Then
If Not bypassCache Then
Dim objCached = TryCache(id.Value)
If objCached IsNot Nothing Then
Return objCached
End If
End If
If includePath Is Nothing Then
Return GetQueryById(MainObjectSet.OfType(Of TType), id.Value).SingleOrDefault()
Else
Return GetQueryById(MainObjectSet.OfType(Of TType), id.Value).Include(includePath).SingleOrDefault()
End If
Else
Return Nothing
End If
End Function
Public Function GetByIdOrCreate(ByVal id As TKey?, Optional bypassCache As Boolean = False, Optional ByVal includePath As String = Nothing) As TType Implements IEntityRepository(Of TType, TKey).GetByIdOrCreate
Dim obj = GetById(id, bypassCache, includePath)
If obj Is Nothing Then
obj = Create()
End If
Return obj
End Function
Public Sub Add(ByVal entity As TType) Implements IEntityRepository(Of TType, TKey).Add
MainObjectSet.AddObject(entity)
End Sub
Public Function DeleteById(ByVal id As TKey) As TType Implements IEntityRepository(Of TType, TKey).DeleteById
Dim result = GetById(id)
MainObjectSet.DeleteObject(result)
Return result
End Function
Public Sub Delete(ByVal entity As TType) Implements IEntityRepository(Of TType, TKey).Delete
MainObjectSet.DeleteObject(entity)
End Sub
Private Function All() As IEnumerable(Of TType)
Return MainObjectSet.OfType(Of TType)()
End Function
Public Sub Save() Implements IEntityRepository(Of TType, TKey).Save
Context.SaveChanges()
End Sub
Private Function GetEnumerator() As IEnumerator(Of TType) Implements IEnumerable(Of TType).GetEnumerator
Return All.GetEnumerator
End Function
Private Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator
Return All.GetEnumerator
End Function
End Class
|
icalvo/Icm.Data
|
Src/Icm.Data/Repositories/BaseEntityRepository.vb
|
Visual Basic
|
apache-2.0
| 3,838
|
' Copyright (c) Microsoft Corporation. All rights reserved.
Imports Microsoft.VisualBasic
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
<Assembly: AssemblyTitle("D3D10Tutorial04_WinFormsControl")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyConfiguration("")>
<Assembly: AssemblyCompany("Microsoft")>
<Assembly: AssemblyProduct("Microsoft Windows API Code Pack for .NET Framework")>
<Assembly: AssemblyCopyright("Copyright © Microsoft 2009")>
<Assembly: AssemblyTrademark("")>
<Assembly: AssemblyCulture("")>
' Setting ComVisible to false makes the types in this assembly not visible
' to COM components. If you need to access a type in this assembly from
' COM, set the ComVisible attribute to true on that type.
<Assembly: ComVisible(False)>
' The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("c4d21605-d6db-4779-a72c-4cca985fa5cf")>
' 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")>
|
devkimchi/Windows-API-Code-Pack-1.1
|
source/Samples/DirectX/VB/Direct3D10/Tutorials/D3D10Tutorial04_WinFormsControl/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,551
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.VisualStudio.Debugger.Clr
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
Friend MustInherit Class PlaceholderLocalSymbol
Inherits EELocalSymbolBase
Private ReadOnly _name As String
Friend ReadOnly DisplayName As String
Friend Sub New(method As MethodSymbol, name As String, displayName As String, type As TypeSymbol)
MyBase.New(method, type)
_name = name
Me.DisplayName = displayName
End Sub
Friend Overloads Shared Function Create(
typeNameDecoder As TypeNameDecoder(Of PEModuleSymbol, TypeSymbol),
containingMethod As MethodSymbol,
[alias] As [Alias]) As PlaceholderLocalSymbol
Dim typeName = [alias].Type
Debug.Assert(typeName.Length > 0)
Dim type = typeNameDecoder.GetTypeSymbolForSerializedType(typeName)
Debug.Assert(type IsNot Nothing)
Dim name = [alias].FullName
Dim displayName = [alias].Name
Select Case [alias].Kind
Case DkmClrAliasKind.Exception
Return New ExceptionLocalSymbol(containingMethod, name, displayName, type, ExpressionCompilerConstants.GetExceptionMethodName)
Case DkmClrAliasKind.StowedException
Return New ExceptionLocalSymbol(containingMethod, name, displayName, type, ExpressionCompilerConstants.GetStowedExceptionMethodName)
Case DkmClrAliasKind.ReturnValue
Dim index As Integer = 0
PseudoVariableUtilities.TryParseReturnValueIndex(name, index)
Return New ReturnValueLocalSymbol(containingMethod, name, displayName, type, index)
Case DkmClrAliasKind.ObjectId
Debug.Assert(name.Length > 0 AndAlso name(0) <> "$"c)
Return New ObjectIdLocalSymbol(containingMethod, type, "$" + name, displayName, isReadOnly:=True)
Case DkmClrAliasKind.Variable
Return New ObjectIdLocalSymbol(containingMethod, type, name, displayName, isReadOnly:=False)
Case Else
Throw ExceptionUtilities.UnexpectedValue([alias].Kind)
End Select
End Function
Friend Overrides ReadOnly Property DeclarationKind As LocalDeclarationKind
Get
Return LocalDeclarationKind.Variable
End Get
End Property
Friend Overrides ReadOnly Property IdentifierToken As SyntaxToken
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property IdentifierLocation As Location
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return NoLocations
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _name
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray(Of SyntaxReference).Empty
End Get
End Property
Friend Overrides Function ToOtherMethod(method As MethodSymbol, typeMap As TypeSubstitution) As EELocalSymbolBase
' Pseudo-variables should be rewritten in PlaceholderLocalRewriter
' rather than copied as locals to the target method.
Throw ExceptionUtilities.Unreachable
End Function
Friend MustOverride Overrides ReadOnly Property IsReadOnly As Boolean
Friend MustOverride Function RewriteLocal(
compilation As VisualBasicCompilation,
container As EENamedTypeSymbol,
syntax As VisualBasicSyntaxNode,
isLValue As Boolean,
diagnostics As DiagnosticBag) As BoundExpression
Friend Shared Function ConvertToLocalType(
compilation As VisualBasicCompilation,
expr As BoundExpression,
type As TypeSymbol,
diagnostics As DiagnosticBag) As BoundExpression
Dim syntax = expr.Syntax
Dim exprType = expr.Type
Dim conversionKind As ConversionKind
If type.IsErrorType() Then
diagnostics.Add(type.GetUseSiteErrorInfo(), syntax.GetLocation())
conversionKind = Nothing
ElseIf exprType.IsErrorType() Then
diagnostics.Add(exprType.GetUseSiteErrorInfo(), syntax.GetLocation())
conversionKind = Nothing
Else
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Dim pair = Conversions.ClassifyConversion(exprType, type, useSiteDiagnostics)
Debug.Assert(useSiteDiagnostics Is Nothing, "If this happens, please add a test")
diagnostics.Add(syntax, useSiteDiagnostics)
Debug.Assert(pair.Value Is Nothing) ' Conversion method.
conversionKind = pair.Key
End If
Return New BoundDirectCast(
syntax,
expr,
conversionKind,
type,
hasErrors:=Not Conversions.ConversionExists(conversionKind)).MakeCompilerGenerated()
End Function
Friend Shared Function GetIntrinsicMethod(compilation As VisualBasicCompilation, methodName As String) As MethodSymbol
Dim type = compilation.GetTypeByMetadataName(ExpressionCompilerConstants.IntrinsicAssemblyTypeMetadataName)
Dim members = type.GetMembers(methodName)
Debug.Assert(members.Length = 1)
Return DirectCast(members(0), MethodSymbol)
End Function
End Class
End Namespace
|
paladique/roslyn
|
src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/PlaceholderLocalSymbol.vb
|
Visual Basic
|
apache-2.0
| 6,379
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.IO
Imports System.Linq
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Public Class OptionalArgumentsTests
Inherits BasicTestBase
Private ReadOnly _librarySource As XElement =
<compilation>
<file name="library.vb">
<![CDATA[
Imports System
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
Imports System.Reflection
Public Class CBase
Public Overridable Sub SubWithOptionalInteger(Optional i As Integer = 13)
End Sub
End Class
Public Module Library
Dim cul = System.Globalization.CultureInfo.InvariantCulture
Sub DumpMetadata(a As [Assembly], memberName As String)
If a Is Nothing Then
a = Assembly.GetExecutingAssembly()
End If
Dim t As Type
For Each t In a.GetExportedTypes()
' For each type, show its members & their custom attributes.
For Each mi In t.GetMembers()
If memberName Is Nothing OrElse mi.Name = memberName Then
' If the member is a method, display information about its parameters.
If mi.MemberType = MemberTypes.Method Then
Console.WriteLine("Member: {0}", mi.Name)
For Each pi In CType(mi, MethodInfo).GetParameters()
Dim defval As Object = pi.DefaultValue
If pi.DefaultValue Is Nothing Then
defval = "No Default"
Else
Dim vType = pi.DefaultValue.GetType()
If vType Is GetType(DateTime) Then
defval = DirectCast(pi.DefaultValue, DateTime).ToString("M/d/yyyy h:mm:ss tt", cul)
ElseIf vType Is GetType(Single) Then
defval = DirectCast(pi.DefaultValue, Single).ToString(cul)
ElseIf vType Is GetType(Double) Then
defval = DirectCast(pi.DefaultValue, Double).ToString(cul)
ElseIf vType Is GetType(Decimal) Then
defval = DirectCast(pi.DefaultValue, Decimal).ToString(cul)
End If
End If
Console.WriteLine("Parameter: Type={0}, Name={1}, Optional={2}, DefaultValue={3}", pi.ParameterType, pi.Name, pi.IsOptional, defval)
DisplayAttributes(pi.GetCustomAttributes(False))
Next
If memberName IsNot Nothing Then
Exit For
End If
End If
End If
Next
Next
End Sub
Sub DisplayAttributes(attrs() As Object)
If attrs.Length = 0 Then Return
' Display the custom attributes applied to this member.
Dim o As Object
For Each o In attrs
Dim dateTimeAttribute = TryCast(o, DateTimeConstantAttribute)
Dim decimalAttribute = TryCast(o, DecimalConstantAttribute)
If dateTimeAttribute IsNot Nothing Then
Console.WriteLine("Attribute: {0}({1})", o.ToString(), DirectCast(dateTimeAttribute.Value, DateTime).ToString("M/d/yyyy h:mm:ss tt", cul))
ElseIf decimalAttribute IsNot Nothing Then
Console.WriteLine("Attribute: {0}({1})", o.ToString(), decimalAttribute.Value.ToString(cul))
End If
Next
End Sub
' 634631328000000000 = #1/26/2012#.Ticks. Optional pseudo attribute is missing.
Sub DateTimeUsingConstantAttribute(<DateTimeConstantAttribute(634631328000000000)> i As DateTime)
Console.WriteLine(i.ToString("M/d/yyyy h:mm:ss tt", cul))
End Sub
Sub DateTimeUsingOptionalAttribute(<[Optional]()> i As DateTime)
Console.WriteLine(i.ToString("M/d/yyyy h:mm:ss tt", cul))
End Sub
' Optional and default value specified with attributes. This should work when called from another assembly
Sub DateTimeUsingOptionalAndConstantAttributes(<[Optional]()> <DateTimeConstantAttribute(634631328000000000)> i As DateTime)
Console.WriteLine(i.ToString("M/d/yyyy h:mm:ss tt", cul))
End Sub
' Optional and default value specified with attributes. This should work when called from another assembly
Sub DecimalUsingOptionalAndConstantAttributes(<[Optional]()> <DecimalConstant(2, 0, 0, 0, 99999)> i As Decimal)
Console.WriteLine(i.ToString(cul))
End Sub
Sub IntegerUsingOptionalAttribute(<[Optional]()> i As Integer)
Console.WriteLine(i)
End Sub
Sub StringUsingOptionalAttribute(<[Optional]()> i As String)
Console.WriteLine(i IsNot Nothing)
End Sub
' DateTime constant with a string parameter.
' Valid to call with strict off. Error with strict on
Sub StringWithOptionalDateTimeValue(<[Optional]()> <DateTimeConstantAttribute(634631328000000000)> i As String)
Console.WriteLine(i)
End Sub
' DateTime constant with a integer parameter.
' Always an error
Sub IntegerWithDateTimeOptionalValue(<[Optional]()> <DateTimeConstantAttribute(634631328000000000)> i As Integer)
Console.WriteLine(i.ToString("M/d/yyyy h:mm:ss tt", cul))
End Sub
' Property with optional parameter
Property PropertyIntegerOptionalDouble(i As Integer, Optional j As Double = 100)
Get
Return j
End Get
Set(ByVal value)
End Set
End Property
Public Enum Animal
Dog
Cat
Fish
End Enum
Sub TestWithMultipleOptionalEnumValues(Optional e1 As Animal = Animal.Dog, Optional e2 As Animal = Animal.Cat)
End Sub
End Module
]]></file>
</compilation>
Private ReadOnly _classLibrary As MetadataReference = CreateHelperLibrary(_librarySource.Value)
Public Function CreateHelperLibrary(source As String) As MetadataReference
Dim libraryCompilation = VisualBasicCompilation.Create("library",
{VisualBasicSyntaxTree.ParseText(source)},
{MsvbRef, MscorlibRef, SystemCoreRef},
TestOptions.ReleaseDll)
Return MetadataReference.CreateFromImage(libraryCompilation.EmitToArray())
End Function
<Fact()>
Public Sub TestOptionalInteger()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
Shared Sub OptionalArg(Optional i As Integer = 1)
Console.WriteLine("i = {0}", i)
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
C1.OptionalArg()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]></file>
</compilation>
CompileAndVerify(source,
additionalRefs:={_classLibrary},
expectedOutput:=<![CDATA[
i = 1
Member: OptionalArg
Parameter: Type=System.Int32, Name=i, Optional=True, DefaultValue=1
]]>)
End Sub
<Fact()>
Public Sub TestIntegerOptionalAttribute()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
Shared Sub OptionalArg(<[Optional]()> i As Integer)
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
additionalRefs:={_classLibrary},
expectedOutput:=<![CDATA[
Member: OptionalArg
Parameter: Type=System.Int32, Name=i, Optional=True, DefaultValue=System.Reflection.Missing
]]>)
End Sub
<Fact()>
Public Sub TestOptionalString()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
Shared Sub OptionalArg(Optional i As String = "hello world")
Console.WriteLine("i = {0}", i)
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
C1.OptionalArg()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
additionalRefs:={_classLibrary},
expectedOutput:=<![CDATA[
i = hello world
Member: OptionalArg
Parameter: Type=System.String, Name=i, Optional=True, DefaultValue=hello world
]]>)
End Sub
<Fact()>
Public Sub TestOptionalDateTime()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
Shared Sub OptionalArg(Optional i As DateTime = #1/26/2012#)
Console.WriteLine("i = {0}", i.ToString("M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture))
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
C1.OptionalArg()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
additionalRefs:={_classLibrary},
expectedOutput:=<![CDATA[
i = 1/26/2012 12:00:00 AM
Member: OptionalArg
Parameter: Type=System.DateTime, Name=i, Optional=True, DefaultValue=1/26/2012 12:00:00 AM
Attribute: System.Runtime.CompilerServices.DateTimeConstantAttribute(1/26/2012 12:00:00 AM)
]]>)
End Sub
<Fact()>
Public Sub TestOptionalDecimal()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
Shared Sub OptionalArg(Optional i As Decimal = 999.99D)
Console.WriteLine("i = {0}", i.ToString(System.Globalization.CultureInfo.InvariantCulture))
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
C1.OptionalArg()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
additionalRefs:={_classLibrary},
expectedOutput:=<![CDATA[
i = 999.99
Member: OptionalArg
Parameter: Type=System.Decimal, Name=i, Optional=True, DefaultValue=999.99
Attribute: System.Runtime.CompilerServices.DecimalConstantAttribute(999.99)
]]>)
End Sub
<WorkItem(543530, "DevDiv")>
<Fact()>
Public Sub OptionalForConstructorofAttribute()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class Base1
Inherits Attribute
Sub New(Optional x As System.Type = Nothing)
Me.Result = If(x Is Nothing, "Nothing", x.ToString())
End Sub
Public Result As String
End Class
Class C1
<Base1()>
Shared Sub A()
End Sub
<Base1(Nothing)>
Shared Sub B(name As String)
Dim m = GetType(C1).GetMethod(name)
Console.Write(DirectCast(m.GetCustomAttributes(GetType(Base1), False)(0), Base1).Result)
Console.Write(";")
End Sub
<Base1(GetType(C1))>
Shared Sub Main()
B("A")
B("B")
B("Main")
End Sub
End Class
</file>
</compilation>
CompileAndVerify(source,
additionalRefs:={_classLibrary},
expectedOutput:="Nothing;Nothing;C1;")
End Sub
<Fact()>
Public Sub TestDateTimeConstantAttribute()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
' 634631328000000000 = #1/26/2012#.Ticks
Shared Sub OptionalArg(<DateTimeConstantAttribute(634631328000000000)> i As DateTime)
Console.WriteLine(i)
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
additionalRefs:={_classLibrary},
expectedOutput:=<![CDATA[
Member: OptionalArg
Parameter: Type=System.DateTime, Name=i, Optional=False, DefaultValue=1/26/2012 12:00:00 AM
Attribute: System.Runtime.CompilerServices.DateTimeConstantAttribute(1/26/2012 12:00:00 AM)
]]>)
End Sub
<Fact()>
Public Sub TestDateTimeOptionalAttributeConstantAttribute()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C1
' 634631328000000000 = #1/26/2012#.Ticks
Shared Sub OptionalArg(<[Optional]()> <DateTimeConstantAttribute(634631328000000000)> i As DateTime)
End Sub
End Class
Module Module1
Sub Main()
Console.WriteLine()
DumpMetadata(Assembly.GetExecutingAssembly(), "OptionalArg")
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
additionalRefs:={_classLibrary},
expectedOutput:=<![CDATA[
Member: OptionalArg
Parameter: Type=System.DateTime, Name=i, Optional=True, DefaultValue=1/26/2012 12:00:00 AM
Attribute: System.Runtime.CompilerServices.DateTimeConstantAttribute(1/26/2012 12:00:00 AM)
]]>)
End Sub
<Fact()>
Public Sub TestDateTimeMissingOptionalFromMetadata()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Sub Main()
DateTimeUsingConstantAttribute() ' This should error. Optional pseudo attribute is missing from metadata.
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, additionalRefs:={_classLibrary})
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_OmittedArgument2, "DateTimeUsingConstantAttribute").WithArguments("i", "Public Sub DateTimeUsingConstantAttribute(i As Date)"))
End Sub
<Fact()>
Public Sub TestDateTimeFromMetadataAttributes()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
DateTimeUsingOptionalAndConstantAttributes() ' This should work both optional and datetimeconstant attributes are in metadata.
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
additionalRefs:={_classLibrary},
expectedOutput:=<![CDATA[
1/26/2012 12:00:00 AM
]]>)
End Sub
<Fact()>
Public Sub TestDecimalFromMetadataAttributes()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
DecimalUsingOptionalAndConstantAttributes()
' Dev10 does not pick up the DecimalConstantAttribute because it uses the
' Integer constructor instead of the UInteger constructor.
' Roslyn honours both constructors.
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
additionalRefs:={_classLibrary},
expectedOutput:=<![CDATA[
999.99
]]>)
End Sub
<Fact()>
Public Sub TestDateTimeFromMetadataOptionalAttributeOnly()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
DateTimeUsingOptionalAttribute() ' Metadata only has the optional attribute.
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
additionalRefs:={_classLibrary},
expectedOutput:=<![CDATA[
1/1/0001 12:00:00 AM
]]>)
End Sub
<Fact()>
Public Sub TestOptionalWithNothing()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Class C1
End Class
Structure S1
dim i as integer
End Structure
Module Module1
Sub s1(optional s as byte = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s2(optional s as boolean = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s3(optional s as integer = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s4(optional s as long = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s5(optional s as double = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s6(optional s as datetime = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s7(optional s as decimal = nothing)
Console.WriteLine(s = nothing)
end sub
Sub s8(optional s as string = nothing)
Console.WriteLine(s = nothing)
end Sub
Sub s9(optional s as C1 = nothing)
Console.WriteLine(s is nothing)
end Sub
Sub s10(optional s as S1 = nothing)
dim t as S1 = nothing
Console.WriteLine(s.Equals(t))
end Sub
Sub Main()
s1()
s2()
s3()
s4()
s5()
s6()
s7()
s8()
s9()
s10()
End Sub
End Module
]]>
</file>
</compilation>
CompileAndVerify(source,
additionalRefs:={_classLibrary},
expectedOutput:=<![CDATA[
True
True
True
True
True
True
True
True
True
True
]]>)
End Sub
<Fact()>
Public Sub TestBadDefaultValue()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Sub s(optional i as integer = p) ' p is undefined and will be a BadExpression.
End Sub
Sub Main()
s()
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, additionalRefs:={_classLibrary})
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_NameNotDeclared1, "p").WithArguments("p"))
End Sub
<Fact()>
Public Sub ParamArrayAndAttribute()
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface I
Sub M1(ParamArray o As Object())
Sub M2(<[ParamArray]()> o As Object())
Sub M3(<[ParamArray]()> ParamArray o As Object())
Property P1(ParamArray o As Object())
Property P2(<[ParamArray]()> o As Object())
Property P3(<[ParamArray]()> ParamArray o As Object())
End Interface
]]>
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors/>)
CompileAndVerify(comp, sourceSymbolValidator:=Sub([module])
Dim type = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("I")
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("M1").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("M2").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("M3").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of PropertySymbol)("P1").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("get_P1").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("set_P1").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of PropertySymbol)("P2").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("get_P2").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("set_P2").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of PropertySymbol)("P3").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("get_P3").Parameters(0)))
Assert.Equal(1, CountParamArrayAttributes(type.GetMember(Of MethodSymbol)("set_P3").Parameters(0)))
End Sub)
End Sub
Private Shared Function CountParamArrayAttributes(parameter As ParameterSymbol) As Integer
Dim attributes = parameter.GetCustomAttributesToEmit(New ModuleCompilationState)
Return attributes.Where(Function(a) a.AttributeClass.Name = "ParamArrayAttribute").Count()
End Function
<WorkItem(529684, "DevDiv")>
<Fact()>
Public Sub TestDuplicateConstantAttributesMetadata()
Dim ilSource = <![CDATA[
.assembly extern System {}
.class public C
{
.method public static object F0([opt] object o)
{
.param [1]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = {string('s')} // [DefaultParameterValue('s')]
ldarg.0
ret
}
.method public static object F1([opt] object o)
{
.param [1]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = {string('s')} // [DefaultParameterValue('s')]
.custom instance void [System]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 ) // [DecimalConstant(2)]
.custom instance void [System]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 03 00 00 00 00 00 00 00 00 00 ) // [DateTimeConstant(3)]
ldarg.0
ret
}
.method public static object F2([opt] object o)
{
.param [1]
.custom instance void [System]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 ) // [DecimalConstant(2)]
.custom instance void [System]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 03 00 00 00 00 00 00 00 00 00 ) // [DateTimeConstant(3)]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = {string('s')} // [DefaultParameterValue('s')]
ldarg.0
ret
}
.method public static object F3([opt] object o)
{
.param [1]
.custom instance void [System]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 03 00 00 00 00 00 00 00 00 00 ) // [DateTimeConstant(3)]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = {string('s')} // [DefaultParameterValue('s')]
.custom instance void [System]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 ) // [DecimalConstant(2)]
ldarg.0
ret
}
.method public static int32 F4([opt] int32 i)
{
.param [1]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = ( 01 00 08 01 00 00 00 00 00 ) // [DefaultParameterValue(1)]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = ( 01 00 08 02 00 00 00 00 00 ) // [DefaultParameterValue(2)]
.custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = ( 01 00 08 03 00 00 00 00 00 ) // [DefaultParameterValue(3)]
ldarg.0
ret
}
.method public static valuetype [mscorlib]System.DateTime F5([opt] valuetype [mscorlib]System.DateTime d)
{
.param [1]
.custom instance void [System]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 01 00 00 00 00 00 00 00 00 00 ) // [DateTimeConstant(3)]
.custom instance void [System]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 02 00 00 00 00 00 00 00 00 00 ) // [DateTimeConstant(3)]
.custom instance void [System]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 03 00 00 00 00 00 00 00 00 00 ) // [DateTimeConstant(3)]
ldarg.0
ret
}
.method public static valuetype [mscorlib]System.Decimal F6([opt] valuetype [mscorlib]System.Decimal d)
{
.param [1]
.custom instance void [System]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 ) // [DecimalConstant(2)]
.custom instance void [System]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 ) // [DecimalConstant(2)]
.custom instance void [System]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 00 00 ) // [DecimalConstant(2)]
ldarg.0
ret
}
}
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Class P
Shared Sub Main()
Report(C.F0())
Report(C.F1())
Report(C.F2())
Report(C.F3())
Report(C.F4())
Report(C.F5().Ticks)
Report(C.F6())
End Sub
Shared Sub Report(o As Object)
System.Console.WriteLine("{0}: {1}", o.GetType(), o)
End Sub
End Class
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.DebugExe)
comp.AssertTheseDiagnostics(<errors/>)
CompileAndVerify(comp, expectedOutput:=<![CDATA[
System.Reflection.Missing: System.Reflection.Missing
System.DateTime: 01/01/0001 00:00:00
System.DateTime: 01/01/0001 00:00:00
System.DateTime: 01/01/0001 00:00:00
System.Int32: 0
System.Int64: 3
System.Decimal: 3
]]>)
End Sub
<WorkItem(529684, "DevDiv")>
<Fact()>
Public Sub TestDuplicateConstantAttributesSameValues()
Dim source1 =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C
Public Shared Function F1(Optional o As Integer = 1)
Return o
End Function
Public Shared Function F2(<[Optional](), DefaultParameterValue(2)> o As Integer)
Return o
End Function
Public Shared Function F3(<DefaultParameterValue(3)> Optional o As Integer = 3)
Return o
End Function
Public Shared Function F4(Optional o As Decimal = 4)
Return o
End Function
Public Shared Function F5(<[Optional](), DecimalConstant(0, 0, 0, 0, 5)> o As Decimal)
Return o
End Function
Public Shared Function F6(<DecimalConstant(0, 0, 0, 0, 6)> Optional o As Decimal = 6)
Return o
End Function
Public Shared Function F7(Optional o As DateTime = #7/24/2013#)
Return o
End Function
Public Shared Function F8(<[Optional](), DateTimeConstant(635102208000000000)> o As DateTime)
Return o
End Function
Public Shared Function F9(<DateTimeConstant(635102208000000000)> Optional o As DateTime = #7/24/2013#)
Return o
End Function
Public Shared Property P(<DecimalConstant(0, 0, 0, 0, 10)> Optional o As Decimal = 10)
Get
Return o
End Get
Set
End Set
End Property
End Class
]]>
</file>
</compilation>
Dim comp1 = CreateCompilationWithMscorlibAndVBRuntime(source1)
comp1.AssertTheseDiagnostics(<errors/>)
CompileAndVerify(comp1, sourceSymbolValidator:=Sub([module])
Dim type = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F1").Parameters(0), Nothing, 1, True)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F2").Parameters(0), "DefaultParameterValueAttribute", 2, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F3").Parameters(0), "DefaultParameterValueAttribute", 3, True)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F4").Parameters(0), "DecimalConstantAttribute", 4UI, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F5").Parameters(0), "DecimalConstantAttribute", 5, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F6").Parameters(0), "DecimalConstantAttribute", 6, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F7").Parameters(0), "DateTimeConstantAttribute", 635102208000000000L, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F8").Parameters(0), "DateTimeConstantAttribute", 635102208000000000L, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F9").Parameters(0), "DateTimeConstantAttribute", 635102208000000000L, False)
VerifyDefaultValueAttribute(type.GetMember(Of PropertySymbol)("P").Parameters(0), "DecimalConstantAttribute", 10, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("get_P").Parameters(0), "DecimalConstantAttribute", 10, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("set_P").Parameters(0), "DecimalConstantAttribute", 10, False)
End Sub)
Dim source2 =
<compilation>
<file name="a.vb"><![CDATA[
Class P
Shared Sub Main()
Report(C.F1())
Report(C.F2())
Report(C.F3())
Report(C.F4())
Report(C.F5())
Report(C.F6())
Report(C.F7().Ticks)
Report(C.F8().Ticks)
Report(C.F9().Ticks)
Report(C.P)
End Sub
Shared Sub Report(o As Object)
System.Console.WriteLine(o)
End Sub
End Class
]]>
</file>
</compilation>
Dim comp2a = CreateCompilationWithMscorlibAndVBRuntime(
source2,
additionalRefs:={New VisualBasicCompilationReference(comp1)},
options:=TestOptions.DebugExe)
comp2a.AssertTheseDiagnostics(
<errors>
BC30455: Argument not specified for parameter 'o' of 'Public Shared Function F2(o As Integer) As Object'.
Report(C.F2())
~~
BC30455: Argument not specified for parameter 'o' of 'Public Shared Function F5(o As Decimal) As Object'.
Report(C.F5())
~~
BC30455: Argument not specified for parameter 'o' of 'Public Shared Function F8(o As Date) As Object'.
Report(C.F8().Ticks)
~~
</errors>)
Dim comp2b = CreateCompilationWithMscorlibAndVBRuntime(
source2,
additionalRefs:={MetadataReference.CreateFromImage(comp1.EmitToArray())},
options:=TestOptions.DebugExe)
comp2b.AssertTheseDiagnostics(<errors/>)
CompileAndVerify(comp2b, expectedOutput:=
<![CDATA[
1
0
3
4
5
6
635102208000000000
635102208000000000
635102208000000000
10
]]>)
End Sub
<WorkItem(529684, "DevDiv")>
<Fact()>
Public Sub TestDuplicateConstantAttributesSameValues_PartialMethods()
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Partial Class C
Private Sub F1(<DefaultParameterValue(1)> Optional o As Integer = 1)
End Sub
Private Sub F2(Optional o As Decimal = 2)
End Sub
Private Partial Sub F3(<DateTimeConstant(635102208000000000)> Optional o As DateTime = #7/24/2013#)
End Sub
End Class
Partial Class C
Private Partial Sub F1(Optional o As Integer = 1)
End Sub
Private Partial Sub F2(<DecimalConstant(0, 0, 0, 0, 2)> Optional o As Decimal = 2)
End Sub
Private Sub F3(Optional o As DateTime = #7/24/2013#)
End Sub
End Class
]]>
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors/>)
CompileAndVerify(comp, sourceSymbolValidator:=Sub([module])
Dim type = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F1").Parameters(0), "DefaultParameterValueAttribute", 1, True)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F2").Parameters(0), "DecimalConstantAttribute", 2, False)
VerifyDefaultValueAttribute(type.GetMember(Of MethodSymbol)("F3").Parameters(0), "DateTimeConstantAttribute", 635102208000000000L, False)
End Sub)
End Sub
Private Shared Sub VerifyDefaultValueAttribute(parameter As ParameterSymbol, expectedAttributeName As String, expectedDefault As Object, hasDefault As Boolean)
Dim attributes = parameter.GetCustomAttributesToEmit(New ModuleCompilationState).ToArray()
If expectedAttributeName Is Nothing Then
Assert.Equal(attributes.Length, 0)
Else
Assert.Equal(attributes.Length, 1)
Dim attribute = DirectCast(attributes(0), VisualBasicAttributeData)
Dim argument = attribute.ConstructorArguments.Last()
Assert.Equal(expectedAttributeName, attribute.AttributeClass.Name)
Assert.Equal(expectedDefault, argument.Value)
Assert.Equal(hasDefault, DirectCast(parameter, Cci.IParameterDefinition).HasDefaultValue)
End If
If hasDefault Then
Assert.Equal(expectedDefault, parameter.ExplicitDefaultValue)
End If
End Sub
<WorkItem(529684, "DevDiv")>
<Fact()>
Public Sub TestDuplicateConstantAttributesDifferentValues()
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Interface I
Sub F1(<DefaultParameterValue(1)> Optional o As Integer = 2)
Sub F2(<DefaultParameterValue(1)> Optional o As Decimal = 2)
Sub F3(<DefaultParameterValue(0)> Optional o As DateTime = #7/24/2013#)
Sub F4(<DecimalConstant(0, 0, 0, 0, 1)> Optional o As Decimal = 2)
Sub F5(<DateTimeConstant(0)> Optional o As DateTime = #7/24/2013#)
Sub F6(<DefaultParameterValue(1), DateTimeConstant(1), DecimalConstant(0, 0, 0, 0, 1)> Optional o As Integer = 1)
Sub F7(<DateTimeConstant(2), DecimalConstant(0, 0, 0, 0, 2), DefaultParameterValue(2)> Optional o As Decimal = 2)
Sub F8(<DecimalConstant(0, 0, 0, 0, 3), DateTimeConstant(3), DefaultParameterValue(3)> Optional o As DateTime = #1/1/2000#)
Property P(<DefaultParameterValue(1)> Optional a As Integer = 2,
<DefaultParameterValue(3)> Optional b As Decimal = 4,
<DefaultParameterValue(5)> Optional c As DateTime = #7/24/2013#)
Property Q(<DefaultParameterValue(0), DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> o As Integer)
End Interface
Delegate Sub D(<DateTimeConstant(1), DefaultParameterValue(2)> o As DateTime)
]]>
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC37226: The parameter has multiple distinct default values.
Sub F1(<DefaultParameterValue(1)> Optional o As Integer = 2)
~
BC37226: The parameter has multiple distinct default values.
Sub F2(<DefaultParameterValue(1)> Optional o As Decimal = 2)
~
BC37226: The parameter has multiple distinct default values.
Sub F3(<DefaultParameterValue(0)> Optional o As DateTime = #7/24/2013#)
~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F4(<DecimalConstant(0, 0, 0, 0, 1)> Optional o As Decimal = 2)
~
BC37226: The parameter has multiple distinct default values.
Sub F5(<DateTimeConstant(0)> Optional o As DateTime = #7/24/2013#)
~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F6(<DefaultParameterValue(1), DateTimeConstant(1), DecimalConstant(0, 0, 0, 0, 1)> Optional o As Integer = 1)
~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F6(<DefaultParameterValue(1), DateTimeConstant(1), DecimalConstant(0, 0, 0, 0, 1)> Optional o As Integer = 1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F7(<DateTimeConstant(2), DecimalConstant(0, 0, 0, 0, 2), DefaultParameterValue(2)> Optional o As Decimal = 2)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F7(<DateTimeConstant(2), DecimalConstant(0, 0, 0, 0, 2), DefaultParameterValue(2)> Optional o As Decimal = 2)
~~~~~~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F7(<DateTimeConstant(2), DecimalConstant(0, 0, 0, 0, 2), DefaultParameterValue(2)> Optional o As Decimal = 2)
~
BC37226: The parameter has multiple distinct default values.
Sub F8(<DecimalConstant(0, 0, 0, 0, 3), DateTimeConstant(3), DefaultParameterValue(3)> Optional o As DateTime = #1/1/2000#)
~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F8(<DecimalConstant(0, 0, 0, 0, 3), DateTimeConstant(3), DefaultParameterValue(3)> Optional o As DateTime = #1/1/2000#)
~~~~~~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Sub F8(<DecimalConstant(0, 0, 0, 0, 3), DateTimeConstant(3), DefaultParameterValue(3)> Optional o As DateTime = #1/1/2000#)
~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Property P(<DefaultParameterValue(1)> Optional a As Integer = 2,
~
BC37226: The parameter has multiple distinct default values.
<DefaultParameterValue(3)> Optional b As Decimal = 4,
~
BC37226: The parameter has multiple distinct default values.
<DefaultParameterValue(5)> Optional c As DateTime = #7/24/2013#)
~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Property Q(<DefaultParameterValue(0), DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> o As Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Property Q(<DefaultParameterValue(0), DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> o As Integer)
~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Delegate Sub D(<DateTimeConstant(1), DefaultParameterValue(2)> o As DateTime)
~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<WorkItem(529684, "DevDiv")>
<Fact()>
Public Sub TestDuplicateConstantAttributesDifferentValues_PartialMethods()
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Partial Class C
Private Sub F1(<DefaultParameterValue(1)> Optional o As Integer = 2)
End Sub
Private Partial Sub F9(<DefaultParameterValue(0)> o As Integer)
End Sub
End Class
Partial Class C
Private Partial Sub F1(Optional o As Integer = 2)
End Sub
Private Sub F9(<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> o As Integer)
End Sub
End Class
]]>
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC37226: The parameter has multiple distinct default values.
Private Sub F1(<DefaultParameterValue(1)> Optional o As Integer = 2)
~
BC37226: The parameter has multiple distinct default values.
Private Partial Sub F1(Optional o As Integer = 2)
~
BC37226: The parameter has multiple distinct default values.
Private Sub F9(<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> o As Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37226: The parameter has multiple distinct default values.
Private Sub F9(<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> o As Integer)
~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
''' <summary>
''' Should not report differences if either value is bad.
''' </summary>
<WorkItem(529684, "DevDiv")>
<Fact()>
Public Sub TestDuplicateConstantAttributesDifferentValues_BadValue()
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Interface I
Sub M1(<DefaultParameterValue(GetType(C)), DecimalConstant(0, 0, 0, 0, 0)> o As Decimal)
Sub M2(<DefaultParameterValue(0), DecimalConstant(0, 0, 0, 0, GetType(C))> o As Decimal)
End Interface
]]>
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC30002: Type 'C' is not defined.
Sub M1(<DefaultParameterValue(GetType(C)), DecimalConstant(0, 0, 0, 0, 0)> o As Decimal)
~
BC30002: Type 'C' is not defined.
Sub M2(<DefaultParameterValue(0), DecimalConstant(0, 0, 0, 0, GetType(C))> o As Decimal)
~
]]></errors>)
End Sub
<Fact()>
Public Sub TestOptionalAttributeWithoutDefaultValue()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
IntegerUsingOptionalAttribute()
StringUsingOptionalAttribute()
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, additionalRefs:={_classLibrary})
CompileAndVerify(source,
additionalRefs:={_classLibrary},
expectedOutput:=<![CDATA[
0
False
]]>)
End Sub
<WorkItem(543076, "DevDiv")>
<Fact()>
Public Sub TestPropertyIntegerOptionalDouble()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
DumpMetadata(nothing, "get_PropertyIntegerOptionalDouble")
End Sub
End Module
]]></file>
</compilation>
CompileAndVerify(source,
additionalRefs:={_classLibrary},
expectedOutput:=<![CDATA[
Member: get_PropertyIntegerOptionalDouble
Parameter: Type=System.Int32, Name=i, Optional=False, DefaultValue=
Parameter: Type=System.Double, Name=j, Optional=True, DefaultValue=100
]]>)
End Sub
<WorkItem(543093, "DevDiv")>
<Fact()>
Public Sub TestIntegerWithDateTimeOptionalValue()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Sub Main()
IntegerWithDateTimeOptionalValue()
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, additionalRefs:={_classLibrary})
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_TypeMismatch2, "IntegerWithDateTimeOptionalValue()").WithArguments("Date", "Integer"))
End Sub
<WorkItem(543093, "DevDiv")>
<Fact()>
Public Sub TestStringWithOptionalDateTimeValue()
' Error when option strict is on
' No error when option strict is off
Dim expectedDiagnostics = {
Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "StringWithOptionalDateTimeValue()").WithArguments("Date", "String"),
Nothing}
Dim i = 0
For Each o In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option Strict <%= o %>
Module Module1
Sub Main()
StringWithOptionalDateTimeValue()
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, additionalRefs:={_classLibrary})
Dim diag = expectedDiagnostics(i)
If diag IsNot Nothing Then
comp.VerifyDiagnostics(diag)
Else
comp.VerifyDiagnostics()
End If
i += 1
Next
End Sub
<WorkItem(543139, "DevDiv")>
<Fact()>
Public Sub TestOverrideOptionalArgumentFromMetadata()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Public Class CDerived
Inherits CBase
Public Overrides Sub SubWithOptionalInteger(Optional i As Integer = 13)
End Sub
End Class
Module Module1
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, additionalRefs:={_classLibrary})
comp.VerifyDiagnostics()
CompileAndVerify(source,
additionalRefs:={_classLibrary},
expectedOutput:=<![CDATA[
]]>)
End Sub
<WorkItem(543227, "DevDiv")>
<Fact()>
Public Sub TestMultpleEnumDefaultValuesFromMetadata()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Sub Main()
TestWithMultipleOptionalEnumValues()
DumpMetadata(nothing, "TestWithMultipleOptionalEnumValues")
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, additionalRefs:={_classLibrary})
comp.VerifyDiagnostics()
CompileAndVerify(source,
additionalRefs:={_classLibrary},
expectedOutput:=<![CDATA[
Member: TestWithMultipleOptionalEnumValues
Parameter: Type=Library+Animal, Name=e1, Optional=True, DefaultValue=Dog
Parameter: Type=Library+Animal, Name=e2, Optional=True, DefaultValue=Cat
]]>)
End Sub
' Test with omitted argument syntax and an error
' Test without omitted argument syntax and an error
<Fact()>
Public Sub TestExplicitConstantAttributesOnFields()
Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Class C
<DecimalConstant(0, 0, 0, 0, 0)> Public F0 As DateTime
<DateTimeConstant(0)> Public F1 As DateTime
<DecimalConstant(0, 0, 0, 0, 0), DecimalConstant(0, 0, 0, 0, 0)> Public F2 As DateTime
<DateTimeConstant(0), DateTimeConstant(0)> Public F3 As DateTime
<DecimalConstant(0, 0, 0, 0, 0), DecimalConstant(0, 0, 0, 0, 1)> Public F4 As DateTime
<DateTimeConstant(1), DateTimeConstant(0)> Public F5 As DateTime
<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> Public F6 As DateTime
<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> Public F7 As Decimal
<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> Public F8 As Integer
<DecimalConstant(0, 0, 0, 0, 0)> Public Const F9 As Integer = 0
<DateTimeConstant(0)> Public Const F10 As Integer = 0
<DateTimeConstant(0)> Public Const F11 As DateTime = #1/1/2013#
<DateTimeConstant(0)> Public Const F12 As Decimal = 0
<DecimalConstant(0, 0, 0, 0, 0)> Public Const F13 As DateTime = #1/1/2013#
<DecimalConstant(0, 0, 0, 0, 0)> Public Const F14 As Decimal = 1
<DecimalConstantAttribute(0, 128, 0, 0, 7)> Public Const F15 as Decimal = -7
<DateTimeConstantAttribute(634925952000000000)> Public Const F16 as Date = #1/1/2013#
End Class
]]>
</file>
</compilation>)
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC30663: Attribute 'DecimalConstantAttribute' cannot be applied multiple times.
<DecimalConstant(0, 0, 0, 0, 0), DecimalConstant(0, 0, 0, 0, 0)> Public F2 As DateTime
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30663: Attribute 'DateTimeConstantAttribute' cannot be applied multiple times.
<DateTimeConstant(0), DateTimeConstant(0)> Public F3 As DateTime
~~~~~~~~~~~~~~~~~~~
BC30663: Attribute 'DecimalConstantAttribute' cannot be applied multiple times.
<DecimalConstant(0, 0, 0, 0, 0), DecimalConstant(0, 0, 0, 0, 1)> Public F4 As DateTime
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30663: Attribute 'DateTimeConstantAttribute' cannot be applied multiple times.
<DateTimeConstant(1), DateTimeConstant(0)> Public F5 As DateTime
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> Public F6 As DateTime
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> Public F7 As Decimal
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DecimalConstant(0, 0, 0, 0, 0), DateTimeConstant(0)> Public F8 As Integer
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DecimalConstant(0, 0, 0, 0, 0)> Public Const F9 As Integer = 0
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DateTimeConstant(0)> Public Const F10 As Integer = 0
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DateTimeConstant(0)> Public Const F11 As DateTime = #1/1/2013#
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DateTimeConstant(0)> Public Const F12 As Decimal = 0
~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DecimalConstant(0, 0, 0, 0, 0)> Public Const F13 As DateTime = #1/1/2013#
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37228: The field has multiple distinct constant values.
<DecimalConstant(0, 0, 0, 0, 0)> Public Const F14 As Decimal = 1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
Dim c = comp.GetTypeByMetadataName("C")
Dim context = New ModuleCompilationState()
Assert.Equal(1, c.GetMember("F15").GetCustomAttributesToEmit(context).Count())
Assert.Equal(1, c.GetMember("F16").GetCustomAttributesToEmit(context).Count())
End Sub
End Class
End Namespace
|
furesoft/roslyn
|
src/Compilers/VisualBasic/Test/Emit/Emit/OptionalArgumentsTests.vb
|
Visual Basic
|
apache-2.0
| 55,786
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Reflection
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
' This class tests binding of various statements; i.e., the code in Binder_Statements.vb
'
' Tests should be added here for every construct that can be bound
' correctly, with a test that compiles, verifies, and runs code for that construct.
' Tests should also be added here for every diagnostic that can be generated.
Public Class Binder_Statements_Tests
Inherits BasicTestBase
<Fact>
Public Sub HelloWorld1()
CompileAndVerify(
<compilation name="HelloWorld1">
<file name="a.vb">
Module M
Sub Main()
System.Console.WriteLine("Hello, world!")
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Hello, world!")
End Sub
<Fact>
Public Sub HelloWorld2()
CompileAndVerify(
<compilation name="HelloWorld2">
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim x as object
x = 42
Console.WriteLine("Hello, world {0} {1}", 135.2.ToString(System.Globalization.CultureInfo.InvariantCulture), x)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Hello, world 135.2 42")
End Sub
<Fact>
Public Sub LocalWithSimpleInitialization()
CompileAndVerify(
<compilation name="LocalWithSimpleInitialization">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim s As String = "Hello world"
Console.WriteLine(s)
s = nothing
Console.WriteLine(s)
Dim i As Integer = 1
Console.WriteLine(i)
Dim d As Double = 1.5
Console.WriteLine(d.ToString(System.Globalization.CultureInfo.InvariantCulture))
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hello world
1
1.5
]]>)
End Sub
<Fact>
Public Sub LocalAsNew()
CompileAndVerify(
<compilation name="LocalAsNew">
<file name="a.vb">
Imports System
Class C
Sub New (msg as string)
Me.msg = msg
End Sub
Sub Report()
Console.WriteLine(msg)
End Sub
private msg as string
End Class
Module M1
Sub Main()
dim myC as New C("hello")
myC.Report()
End Sub
End Module
</file>
</compilation>,
expectedOutput:="hello")
End Sub
<Fact>
Public Sub LocalAsNewArrayError()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LocalAsNewArrayError">
<file name="a.vb">
Imports System
Class C
Sub New()
End Sub
End Class
Module M1
Sub Main()
' Arrays cannot be declared with 'New'.
dim c1() as new C()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30053: Arrays cannot be declared with 'New'.
dim c1() as new C()
~~~
</expected>)
End Sub
<Fact>
Public Sub LocalAsNewArrayError001()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LocalAsNewArrayError">
<file name="a.vb">
Imports System
Class X
Dim a(), b As New S
End Class
Class X1
Dim a, b() As New S
End Class
Class X2
Dim a, b(3) As New S
End Class
Class X3
Dim a, b As New S(){}
End Class
Structure S
End Structure
Module M1
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30053: Arrays cannot be declared with 'New'.
Dim a(), b As New S
~~~
BC30053: Arrays cannot be declared with 'New'.
Dim a, b() As New S
~~~
BC30053: Arrays cannot be declared with 'New'.
Dim a, b(3) As New S
~~~~
BC30205: End of statement expected.
Dim a, b As New S(){}
~
</expected>)
End Sub
<WorkItem(545766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545766")>
<Fact>
Public Sub LocalSameNameAsOperatorAllowed()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LocalSameNameAsOperatorAllowed">
<file name="a.vb">
Imports System
Class C
Public Shared Operator IsTrue(ByVal w As C) As Boolean
Dim IsTrue As Boolean = True
Return IsTrue
End Operator
Public Shared Operator IsFalse(ByVal w As C) As Boolean
Dim IsFalse As Boolean = True
Return IsFalse
End Operator
End Class
Module M1
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub ParameterlessSub()
CompileAndVerify(
<compilation name="ParameterlessSub">
<file name="a.vb">
Imports System
Module M1
Sub Goo()
Console.WriteLine("Hello, world")
Console.WriteLine()
Console.WriteLine("Goodbye, world")
End Sub
Sub Main()
Goo
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hello, world
Goodbye, world
]]>)
End Sub
<Fact>
Public Sub CallStatement()
CompileAndVerify(
<compilation name="CallStatement">
<file name="a.vb">
Imports System
Module M1
Sub Goo()
Console.WriteLine("Call without parameters")
End Sub
Sub Goo(s as string)
Console.WriteLine(s)
End Sub
Function SayHi as string
return "Hi"
End Function
Function One as integer
return 1
End Function
Sub Main()
Goo(SayHi)
goo
call goo
call goo("call with parameters")
dim i = One + One
Console.WriteLine(i)
i = One
Console.WriteLine(i)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hi
Call without parameters
Call without parameters
call with parameters
2
1
]]>)
End Sub
<Fact>
Public Sub CallStatementMethodNotFound()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodNotFound">
<file name="a.vb">
Imports System
Module M1
Sub Main()
call goo
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'goo' is not declared. It may be inaccessible due to its protection level.
call goo
~~~
</expected>)
End Sub
<WorkItem(538590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538590")>
<Fact>
Public Sub CallStatementNothingAsInvocationExpression_Bug_4247()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodIsNothing">
<file name="goo.vb">
Module M1
Sub Main()
Dim myLocalArr as Integer()
Dim myLocalVar as Integer = 42
call myLocalArr(0)
call myLocalVar
call Nothing
call 911
call new Integer
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30454: Expression is not a method.
call myLocalArr(0)
~~~~~~~~~~
BC42104: Variable 'myLocalArr' is used before it has been assigned a value. A null reference exception could result at runtime.
call myLocalArr(0)
~~~~~~~~~~
BC30454: Expression is not a method.
call myLocalVar
~~~~~~~~~~
BC30454: Expression is not a method.
call Nothing
~~~~~~~
BC30454: Expression is not a method.
call 911
~~~
BC30454: Expression is not a method.
call new Integer
~~~~~~~~~~~
</expected>)
End Sub
' related to bug 4247
<Fact>
Public Sub CallStatementNamespaceAsInvocationExpression()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodIsNothing">
<file name="goo.vb">
Namespace N1.N2
Module M1
Sub Main()
call N1
call N1.N2
End Sub
End Module
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30112: 'N1' is a namespace and cannot be used as an expression.
call N1
~~
BC30112: 'N1.N2' is a namespace and cannot be used as an expression.
call N1.N2
~~~~~
</expected>)
End Sub
' related to bug 4247
<WorkItem(545166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545166")>
<Fact>
Public Sub CallStatementTypeAsInvocationExpression()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodIsNothing">
<file name="goo.vb">
Class Class1
End Class
Module M1
Sub Main()
call Class1
call Integer
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30109: 'Class1' is a class type and cannot be used as an expression.
call Class1
~~~~~~
BC30110: 'Integer' is a structure type and cannot be used as an expression.
call Integer
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub AssignmentStatement()
CompileAndVerify(
<compilation name="AssignmentStatement1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim s As String
s = "Hello world"
Console.WriteLine(s)
Dim i As Integer
i = 1
Console.WriteLine(i)
Dim d As Double
d = 1.5
Console.WriteLine(d.ToString(System.Globalization.CultureInfo.InvariantCulture))
d = i
Console.WriteLine(d)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hello world
1
1.5
1
]]>)
End Sub
<Fact>
Public Sub FieldAssignmentStatement()
CompileAndVerify(
<compilation name="FieldAssignmentStatement">
<file name="a.vb">
Imports System
Class C1
public i as integer
End class
Structure S1
public s as string
End Structure
Module M1
Sub Main()
dim myC as C1 = new C1
myC.i = 10
Console.WriteLine(myC.i)
dim myS as S1 = new S1
myS.s = "a"
Console.WriteLine(MyS.s)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
10
a
]]>)
End Sub
<Fact>
Public Sub AssignmentWithBadLValue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AssignmentWithBadLValue">
<file name="a.vb">
Imports System
Module M1
Function f as integer
return 0
End function
Sub s
End Sub
Sub Main()
f = 0
s = 1
dim i as integer
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30068: Expression is a value and therefore cannot be the target of an assignment.
f = 0
~
BC30068: Expression is a value and therefore cannot be the target of an assignment.
s = 1
~
BC42024: Unused local variable: 'i'.
dim i as integer
~
</expected>)
End Sub
<Fact>
Public Sub MultilineIfStatement1()
CompileAndVerify(
<compilation name="MultilineIfStatement1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim cond As Boolean
Dim cond2 As Boolean
Dim cond3 As Boolean
cond = True
cond2 = True
cond3 = True
If cond Then
Console.WriteLine("1. ThenPart")
End If
If cond Then
Console.WriteLine("2. ThenPart")
Else
Console.WriteLine("2. ElsePart")
End If
If cond Then
Console.WriteLine("3. ThenPart")
Else If cond2
Console.WriteLine("3. ElseIfPart")
End If
If cond Then
Console.WriteLine("4. ThenPart")
Else If cond2
Console.WriteLine("4. ElseIf1Part")
Else If cond3
Console.WriteLine("4. ElseIf2Part")
Else
Console.WriteLine("4. ElsePart")
End If
cond = False
If cond Then
Console.WriteLine("5. ThenPart")
End If
If cond Then
Console.WriteLine("6. ThenPart")
Else
Console.WriteLine("6. ElsePart")
End If
If cond Then
Console.WriteLine("7. ThenPart")
Else If cond2
Console.WriteLine("7. ElseIfPart")
End If
If cond Then
Console.WriteLine("8. ThenPart")
Else If cond2
Console.WriteLine("8. ElseIf1Part")
Else If cond3
Console.WriteLine("8. ElseIf2Part")
Else
Console.WriteLine("8. ElsePart")
End If
cond2 = false
If cond Then
Console.WriteLine("9. ThenPart")
Else If cond2
Console.WriteLine("9. ElseIfPart")
End If
If cond Then
Console.WriteLine("10. ThenPart")
Else If cond2
Console.WriteLine("10. ElseIf1Part")
Else If cond3
Console.WriteLine("10. ElseIf2Part")
Else
Console.WriteLine("10. ElsePart")
End If
cond3 = false
If cond Then
Console.WriteLine("11. ThenPart")
Else If cond2
Console.WriteLine("11. ElseIf1Part")
Else If cond3
Console.WriteLine("11. ElseIf2Part")
Else
Console.WriteLine("11. ElsePart")
End If
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1. ThenPart
2. ThenPart
3. ThenPart
4. ThenPart
6. ElsePart
7. ElseIfPart
8. ElseIf1Part
10. ElseIf2Part
11. ElsePart
]]>)
End Sub
<Fact>
Public Sub SingleLineIfStatement1()
CompileAndVerify(
<compilation name="SingleLineIfStatement1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim cond As Boolean
cond = True
If cond Then Console.WriteLine("1. ThenPart")
If cond Then Console.WriteLine("2. ThenPartA"): COnsole.WriteLine("2. ThenPartB")
If cond Then Console.WriteLine("3. ThenPartA"): COnsole.WriteLine("3. ThenPartB") Else Console.WriteLine("3. ElsePartA"): Console.WriteLine("3. ElsePartB")
If cond Then Console.WriteLine("4. ThenPart") Else Console.WriteLine("4. ElsePartA"): Console.WriteLine("4. ElsePartB")
If cond Then Console.WriteLine("5. ThenPartA"): Console.WriteLine("5. ThenPartB") Else Console.WriteLine("5. ElsePart")
If cond Then Console.WriteLine("6. ThenPart") Else Console.WriteLine("6. ElsePart")
cond = false
If cond Then Console.WriteLine("7. ThenPart")
If cond Then Console.WriteLine("8. ThenPartA"): COnsole.WriteLine("8. ThenPartB")
If cond Then Console.WriteLine("9. ThenPart"): COnsole.WriteLine("9. ThenPartB") Else Console.WriteLine("9. ElsePartA"): Console.WriteLine("9. ElsePartB")
If cond Then Console.WriteLine("10. ThenPart") Else Console.WriteLine("10. ElsePartA"): Console.WriteLine("10. ElsePartB")
If cond Then Console.WriteLine("11. ThenPartA"): Console.WriteLine("11. ThenPartB") Else Console.WriteLine("11. ElsePart")
If cond Then Console.WriteLine("12. ThenPart") Else Console.WriteLine("12. ElsePart")
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1. ThenPart
2. ThenPartA
2. ThenPartB
3. ThenPartA
3. ThenPartB
4. ThenPart
5. ThenPartA
5. ThenPartB
6. ThenPart
9. ElsePartA
9. ElsePartB
10. ElsePartA
10. ElsePartB
11. ElsePart
12. ElsePart
]]>)
End Sub
<Fact>
Public Sub DoLoop1()
CompileAndVerify(
<compilation name="DoLoop1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = true
Do While breakLoop
Console.WriteLine("Iterate {0}", x)
breakLoop = false
Loop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub DoLoop2()
CompileAndVerify(
<compilation name="DoLoop2">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = false
Do Until breakLoop
Console.WriteLine("Iterate {0}", x)
breakLoop = true
Loop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub DoLoop3()
CompileAndVerify(
<compilation name="DoLoop3">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = true
Do
Console.WriteLine("Iterate {0}", x)
breakLoop = false
Loop While breakLoop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub DoLoop4()
CompileAndVerify(
<compilation name="DoLoop4">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = false
Do
Console.WriteLine("Iterate {0}", x)
breakLoop = true
Loop Until breakLoop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub WhileLoop1()
CompileAndVerify(
<compilation name="WhileLoop1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = false
While not breakLoop
Console.WriteLine("Iterate {0}", x)
breakLoop = true
End While
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub ExitContinueDoLoop1()
CompileAndVerify(
<compilation name="ExitContinueDoLoop1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim breakLoop as Boolean
dim continueLoop as Boolean
breakLoop = True: continueLoop = true
Do While breakLoop
Console.WriteLine("Stmt1")
If continueLoop Then
Console.WriteLine("Continuing")
continueLoop = false
Continue Do
End If
Console.WriteLine("Exiting")
Exit Do
Console.WriteLine("Stmt2")
Loop
Console.WriteLine("After Loop")
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Stmt1
Continuing
Stmt1
Exiting
After Loop
]]>)
End Sub
<Fact>
Public Sub ExitSub()
CompileAndVerify(
<compilation name="ExitSub">
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim breakLoop as Boolean
breakLoop = True
Do While breakLoop
Console.WriteLine("Stmt1")
Console.WriteLine("Exiting")
Exit Sub
Console.WriteLine("Stmt2") 'should not output
Loop
Console.WriteLine("After Loop") 'should not output
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Stmt1
Exiting
]]>)
End Sub
<Fact>
Public Sub ExitFunction()
CompileAndVerify(
<compilation name="ExitFunction">
<file name="a.vb">
Imports System
Module M1
Function Fact(i as integer) as integer
fact = 1
do
if i <= 0 then
exit function
else
fact = i * fact
i = i - 1
end if
loop
End Function
Sub Main()
Console.WriteLine(Fact(0))
Console.WriteLine(Fact(3))
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1
6
]]>)
End Sub
<Fact>
Public Sub BadExit()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadExit">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Do
Exit Do ' ok
Exit For
Exit Try
Exit Select
Exit While
Loop
Exit Do ' outside loop
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30096: 'Exit For' can only appear inside a 'For' statement.
Exit For
~~~~~~~~
BC30393: 'Exit Try' can only appear inside a 'Try' statement.
Exit Try
~~~~~~~~
BC30099: 'Exit Select' can only appear inside a 'Select' statement.
Exit Select
~~~~~~~~~~~
BC30097: 'Exit While' can only appear inside a 'While' statement.
Exit While
~~~~~~~~~~
BC30089: 'Exit Do' can only appear inside a 'Do' statement.
Exit Do ' outside loop
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub BadContinue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadContinue">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Do
Continue Do ' ok
Continue For
Continue While
Loop
Continue Do ' outside loop
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30783: 'Continue For' can only appear inside a 'For' statement.
Continue For
~~~~~~~~~~~~
BC30784: 'Continue While' can only appear inside a 'While' statement.
Continue While
~~~~~~~~~~~~~~
BC30782: 'Continue Do' can only appear inside a 'Do' statement.
Continue Do ' outside loop
~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub Return1()
CompileAndVerify(
<compilation name="Return1">
<file name="a.vb">
Imports System
Module M1
Function F1 as Integer
F1 = 1
End Function
Function F2 as Integer
if true then
F2 = 2
else
return 3
end if
End Function
Function F3 as Integer
return 3
End Function
Sub S1
return
End Sub
Sub Main()
dim result as integer
result = F1()
Console.WriteLine(result)
result = F2()
Console.WriteLine(result)
result = F3()
Console.WriteLine(result)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1
2
3
]]>)
End Sub
<Fact>
Public Sub BadReturn()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadReturn">
<file name="a.vb">
Imports System
Module M1
Function F1 as Integer
return
End Function
Sub S1
return 1
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30654: 'Return' statement in a Function, Get, or Operator must return a value.
return
~~~~~~
BC30647: 'Return' statement in a Sub or a Set cannot return a value.
return 1
~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub NoReturnUnreachableEnd()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NoReturnUnreachableEnd">
<file name="a.vb">
Imports System
Module M1
Function goo() As Boolean
While True
End While
End Function
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42353: Function 'goo' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function
~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub BadArrayInitWithExplicitArraySize()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayInitWithExplicitArraySize">
<file name="a.vb">
Imports System
Module M1
Sub S1
dim a(3) as integer = 1
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds.
dim a(3) as integer = 1
~~~~
BC30311: Value of type 'Integer' cannot be converted to 'Integer()'.
dim a(3) as integer = 1
~
</expected>)
End Sub
<Fact>
Public Sub BadArrayWithNegativeSize()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayWithNegativeSize">
<file name="a.vb">
Imports System
Module M1
Sub S1
dim a(-3) as integer
dim b = new integer(-3){}
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30611: Array dimensions cannot have a negative size.
dim a(-3) as integer
~~
BC30611: Array dimensions cannot have a negative size.
dim b = new integer(-3){}
~~
</expected>)
End Sub
<Fact>
Public Sub ArrayWithMinusOneUpperBound()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayWithNegativeSize">
<file name="a.vb">
Imports System
Module M1
Sub S1
dim a(-1) as integer
dim b = new integer(-1){}
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<WorkItem(542987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542987")>
<Fact()>
Public Sub MultiDimensionalArrayWithTooFewInitializers()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MultiDimensionalArrayWithTooFewInitializers">
<file name="Program.vb">
Module Program
Sub Main()
Dim x = New Integer(0, 1) {{}}
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30567: Array initializer is missing 2 elements.
Dim x = New Integer(0, 1) {{}}
~~
</expected>)
End Sub
<WorkItem(542988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542988")>
<Fact()>
Public Sub Max32ArrayDimensionsAreAllowed()
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Max32ArrayDimensionsAreAllowed">
<file name="Program.vb">
Module Program
Sub Main()
Dim z1(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) As Integer = Nothing
Dim z2(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) As Integer = Nothing
Dim x1 = New Integer(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) {}
Dim x2 = New Integer(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) {}
Dim y1 = New Integer(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) {}
Dim y2 = New Integer(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) {}
End Sub
End Module
</file>
</compilation>).
VerifyDiagnostics(
Diagnostic(ERRID.ERR_ArrayRankLimit, "(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)"),
Diagnostic(ERRID.ERR_ArrayRankLimit, "(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)"),
Diagnostic(ERRID.ERR_ArrayRankLimit, "(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)"))
End Sub
<Fact>
Public Sub GotoIf()
CompileAndVerify(
<compilation name="GotoIf">
<file name="a.vb">
Imports System
Module M1
Sub GotoIf()
GoTo l1
If False Then
l1:
Console.WriteLine("Jump into If")
End If
End Sub
Sub GotoWhile()
GoTo l1
While False
l1:
Console.WriteLine("Jump into While")
End While
End Sub
Sub GotoDo()
GoTo l1
Do While False
l1:
Console.WriteLine("Jump into Do")
Loop
End Sub
Sub GotoSelect()
Dim i As Integer = 0
GoTo l1
Select Case i
Case 0
l1:
Console.WriteLine("Jump into Select")
End Select
End Sub
Sub Main()
GotoIf()
GotoWhile()
GotoDo()
GotoSelect()
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Jump into If
Jump into While
Jump into Do
Jump into Select
]]>)
End Sub
<Fact()>
Public Sub GotoIntoBlockErrors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoIntoBlockErrors">
<file name="a.vb">
Imports System
Module M1
Sub GotoFor()
For i as Integer = 0 To 10
l1:
Console.WriteLine()
Next
GoTo l1
End Sub
Sub GotoWith()
Dim c1 = New C()
With c1
l1:
Console.WriteLine()
End With
GoTo l1
End Sub
Sub GotoUsing()
Using c1 as IDisposable = nothing
l1:
Console.WriteLine()
End Using
GoTo l1
End Sub
Sub GotoTry()
Try
l1:
Console.WriteLine()
Finally
End Try
GoTo l1
End Sub
Sub GotoLambda()
Dim x = Sub()
l1:
End Sub
GoTo l1
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30757: 'GoTo l1' is not valid because 'l1' is inside a 'For' or 'For Each' statement that does not contain this statement.
GoTo l1
~~
BC30002: Type 'C' is not defined.
Dim c1 = New C()
~
BC30756: 'GoTo l1' is not valid because 'l1' is inside a 'With' statement that does not contain this statement.
GoTo l1
~~
BC36009: 'GoTo l1' is not valid because 'l1' is inside a 'Using' statement that does not contain this statement.
GoTo l1
~~
BC30754: 'GoTo l1' is not valid because 'l1' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.
GoTo l1
~~
BC30132: Label 'l1' is not defined.
GoTo l1
~~
</expected>)
End Sub
<Fact()>
Public Sub GotoDecimalLabels()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoDecimalLabels">
<file name="a.vb">
Imports System
Module M
Sub Main()
1 : Goto &H2
2 : Goto 01
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<WorkItem(543381, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543381")>
<Fact()>
Public Sub GotoUndefinedLabel()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoUndefinedLabel">
<file name="a.vb">
Imports System
Class c1
Shared Sub Main()
GoTo lab1
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30132: Label 'lab1' is not defined.
GoTo lab1
~~~~
</expected>)
End Sub
<WorkItem(538574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538574")>
<Fact()>
Public Sub ArrayModifiersOnVariableAndType()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ArrayModifiersOnVariableAndType">
<file name="a.vb">
Imports System
Module M1
public a() as integer()
public b(1) as integer()
Sub S1
dim a() as integer() = nothing
dim b(1) as string()
End Sub
Sub S2(x() as integer())
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <errors>
BC31087: Array modifiers cannot be specified on both a variable and its type.
public a() as integer()
~~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
public b(1) as integer()
~~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
dim a() as integer() = nothing
~~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
dim b(1) as string()
~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
Sub S2(x() as integer())
~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub Bug6663()
' Test dependent on referenced mscorlib, but NOT system.dll.
Dim comp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="Bug6663">
<file name="a.vb">
Imports System
Module Program
Sub Main()
Console.WriteLine("".ToString() = "".ToString())
End Sub
End Module
</file>
</compilation>, options:=TestOptions.ReleaseExe)
CompileAndVerify(comp, expectedOutput:="True")
End Sub
<WorkItem(540390, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540390")>
<Fact()>
Public Sub Bug6637()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayInitWithExplicitArraySize">
<file name="a.vb">
Option Infer Off
Imports System
Module M1
Sub Main()
Dim a(3) As Integer
For i = 0 To 3
Next
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
For i = 0 To 3
~
</expected>)
End Sub
<WorkItem(540412, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540412")>
<Fact()>
Public Sub Bug6662()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadArrayInitWithExplicitArraySize">
<file name="a.vb">
Option Infer Off
Class C
Shared Sub M()
For i = Nothing To 10
Dim d as System.Action = Sub() i = i + 1
Next
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
For i = Nothing To 10
~
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
Dim d as System.Action = Sub() i = i + 1
~
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
Dim d as System.Action = Sub() i = i + 1
~
</expected>)
End Sub
<WorkItem(542801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542801")>
<Fact()>
Public Sub ExtTryFromFinally()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Class BaseClass
Function Method() As String
Dim x = New Integer() {}
Try
Exit Try
Catch ex1 As Exception When True
Exit Try
Finally
Exit Try
End Try
Return "x"
End Function
End Class
Class DerivedClass
Inherits BaseClass
Shared Sub Main()
End Sub
End Class
</file>
</compilation>, {SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30393: 'Exit Try' can only appear inside a 'Try' statement.
Exit Try
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchNotLocal()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotLocal">
<file name="goo.vb">
Module M1
Private ex as System.Exception
Sub Main()
Try
Catch ex
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'ex' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch ex
~~
</expected>)
End Sub
<Fact(), WorkItem(651622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651622")>
Public Sub Bug651622()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="goo.vb">
Module Module1
Sub Main()
Try
Catch Main
Catch x as System.Exception
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'Main' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch Main
~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchStatic()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchStatic">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Static ex as exception = nothing
Try
Catch ex
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'ex' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch ex
~~
</expected>)
End Sub
<Fact()>
Public Sub CatchUndeclared()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchUndeclared">
<file name="goo.vb">
Option Explicit Off
Module M1
Sub Main()
Try
' Explicit off does not have effect on Catch - ex is still undefined.
Catch ex
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'ex' is not declared. It may be inaccessible due to its protection level.
Catch ex
~~
</expected>)
End Sub
<Fact()>
Public Sub CatchNotException()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Option Explicit Off
Module M1
Sub Main()
Dim ex as String = "qq"
Try
Catch ex
End Try
Try
Catch ex1 as String
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30392: 'Catch' cannot catch type 'String' because it is not 'System.Exception' or a class that inherits from 'System.Exception'.
Catch ex
~~
BC30392: 'Catch' cannot catch type 'String' because it is not 'System.Exception' or a class that inherits from 'System.Exception'.
Catch ex1 as String
~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchNotVariableOrParameter()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotVariableOrParameter">
<file name="goo.vb">
Option Explicit Off
Module M1
Sub Goo
End Sub
Sub Main()
Try
Catch Goo
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'Goo' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch Goo
~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchDuplicate()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex as Exception = Nothing
Try
Catch ex
Catch ex1 as Exception
Catch
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception
~~~~~~~~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch
~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchDuplicate1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex as Exception = Nothing
Try
Catch
Catch ex
Catch ex1 as Exception
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex
~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception
~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchDuplicate2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex as Exception = Nothing
Try
' the following is NOT considered as catching all System.Exceptions
Catch When true
Catch ex
' filter does NOT make this reachable.
Catch ex1 as Exception When true
' implicitly this is a "Catch ex As Exception When true" so still unreachable
Catch When true
Catch ex1 as Exception
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception When true
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch When true
~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception
~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchOverlapped()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex As SystemException = Nothing
Try
' the following is NOT considered as catching all System.Exceptions
Catch When True
Catch ex
' filter does NOT make this reachable.
Catch ex1 As ArgumentException When True
' implicitly this is a "Catch ex As Exception When true"
Catch When True
' this is ok since it is not derived from SystemException
' and catch above has a filter
Catch ex1 As ApplicationException
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42029: 'Catch' block never reached, because 'ArgumentException' inherits from 'SystemException'.
Catch ex1 As ArgumentException When True
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchShadowing()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Dim field As String
Function Goo(Of T)(ex As Exception) As Exception
Dim ex1 As SystemException = Nothing
Try
Dim ex2 As Exception = nothing
Catch ex As Exception
Catch ex1 As Exception
Catch Goo As ArgumentException When True
' this is ok
Catch ex2 As exception
Dim ex3 As exception = nothing
'this is ok
Catch ex3 As ApplicationException
' this is ok
Catch field As Exception
End Try
return nothing
End Function
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30734: 'ex' is already declared as a parameter of this method.
Catch ex As Exception
~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 As Exception
~~~~~~~~~~~~~~~~~~~~~~
BC30616: Variable 'ex1' hides a variable in an enclosing block.
Catch ex1 As Exception
~~~
BC42029: 'Catch' block never reached, because 'ArgumentException' inherits from 'Exception'.
Catch Goo As ArgumentException When True
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30290: Local variable cannot have the same name as the function containing it.
Catch Goo As ArgumentException When True
~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex2 As exception
~~~~~~~~~~~~~~~~~~~~~~
BC42029: 'Catch' block never reached, because 'ApplicationException' inherits from 'Exception'.
Catch ex3 As ApplicationException
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch field As Exception
~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<WorkItem(837820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837820")>
<Fact()>
Public Sub CatchShadowingGeneric()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Class cls3(Of T As NullReferenceException)
Sub scen3()
Try
Catch ex As T
Catch ex As NullReferenceException
End Try
End Sub
Sub scen4()
Try
Catch ex As NullReferenceException
'COMPILEWarning: BC42029 ,"Catch ex As T"
Catch ex As T
End Try
End Sub
End Class
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42029: 'Catch' block never reached, because 'T' inherits from 'NullReferenceException'.
Catch ex As T
~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub GotoOutOfFinally()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoOutOfFinally">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
l1:
Try
Finally
try
goto l1
catch
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30101: Branching out of a 'Finally' is not valid.
goto l1
~~
</expected>)
End Sub
<Fact()>
Public Sub BranchOutOfFinally1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BranchOutOfFinally1">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
for i as integer = 1 to 10
Try
Finally
continue for
End Try
Next
End Sub
Function Goo() as integer
l1:
Try
Finally
try
return 1
catch
return 1
End Try
End Try
End Function
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30101: Branching out of a 'Finally' is not valid.
continue for
~~~~~~~~~~~~
BC30101: Branching out of a 'Finally' is not valid.
return 1
~~~~~~~~
BC30101: Branching out of a 'Finally' is not valid.
return 1
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub GotoFromCatchToTry()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoFromCatchToTry">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Try
Catch ex As Exception
l1:
Try
GoTo l1
Catch ex2 As Exception
GoTo l1
Finally
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub GotoFromCatchToTry1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoFromCatchToTry">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Try
l1:
Catch ex As Exception
Try
GoTo l1
Catch ex2 As Exception
GoTo l1
Finally
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInLateAddressOf()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter">
<file name="goo.vb">
Option Strict Off
Imports System
Module Program
Delegate Sub d1(ByRef x As Integer, y As Integer)
Sub Main()
Dim obj As Object '= New cls1
Dim o As d1 = AddressOf obj.goo
Dim l As Integer = 0
o(l, 2)
Console.WriteLine(l)
End Sub
Class cls1
Shared Sub goo(ByRef x As Integer, y As Integer)
x = 42
Console.WriteLine(x + y)
End Sub
End Class
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'obj' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim o As d1 = AddressOf obj.goo
~~~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Dim B as StackOverflowException
Dim C as Exception
Try
A = new ApplicationException
B = new StackOverflowException
C = new Exception
Console.Writeline(A) 'this is ok
Catch ex as NullReferenceException When A.Message isnot nothing
Catch ex as DivideByZeroException
Console.Writeline(B)
Finally
Console.Writeline(C)
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Catch ex as NullReferenceException When A.Message isnot nothing
~
BC42104: Variable 'B' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(B)
~
BC42104: Variable 'C' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(C)
~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter1">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
' ok , A is assigned in the filter and in the catch
Catch A When A.Message isnot nothing
Console.Writeline(A)
Catch ex as Exception
A = new ApplicationException
Finally
'error
Console.Writeline(A)
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(A)
~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter2">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
A = new ApplicationException
Catch A
Catch
End Try
Console.Writeline(A)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(A)
~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter3">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
A = new ApplicationException
Catch A
Catch
try
Finally
A = new ApplicationException
End Try
End Try
Console.Writeline(A)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter4()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter4">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
A = new ApplicationException
Catch A
Catch
try
Finally
A = new ApplicationException
End Try
Finally
Console.Writeline(A)
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(A)
~
</expected>)
End Sub
<Fact()>
Public Sub ThrowNotValue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ThrowNotValue">
<file name="goo.vb">
Imports System
Module M1
ReadOnly Property Moo As Exception
Get
Return New Exception
End Get
End Property
WriteOnly Property Boo As Exception
Set(value As Exception)
End Set
End Property
Sub Main()
Throw Moo
Throw Boo
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30524: Property 'Boo' is 'WriteOnly'.
Throw Boo
~~~
</expected>)
End Sub
<Fact()>
Public Sub ThrowNotException()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ThrowNotValue">
<file name="goo.vb">
Imports System
Module M1
ReadOnly e as new Exception
ReadOnly s as string = "qq"
Sub Main()
Throw e
Throw s
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30665: 'Throw' operand must derive from 'System.Exception'.
Throw s
~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub RethrowNotInCatch()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="RethrowNotInCatch">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Throw
Try
Throw
Catch ex As Exception
Throw
Dim a As Action = Sub()
ex.ToString()
Throw
End Sub
Try
Throw
Catch
Throw
Finally
Throw
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
</expected>)
End Sub
<Fact()>
Public Sub ForNotValue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ThrowNotValue">
<file name="goo.vb">
Imports System
Module M1
ReadOnly Property Moo As Integer
Get
Return 1
End Get
End Property
WriteOnly Property Boo As integer
Set(value As integer)
End Set
End Property
Sub Main()
For Moo = 1 to Moo step Moo
Next
For Boo = 1 to Boo step Boo
Next
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30039: Loop control variable cannot be a property or a late-bound indexed array.
For Moo = 1 to Moo step Moo
~~~
BC30039: Loop control variable cannot be a property or a late-bound indexed array.
For Boo = 1 to Boo step Boo
~~~
BC30524: Property 'Boo' is 'WriteOnly'.
For Boo = 1 to Boo step Boo
~~~
BC30524: Property 'Boo' is 'WriteOnly'.
For Boo = 1 to Boo step Boo
~~~
</expected>)
End Sub
<Fact()>
Public Sub CustomDatatypeForLoop()
Dim source =
<compilation>
<file name="goo.vb"><![CDATA[
Imports System
Module Module1
Public Sub Main()
Dim x As New c1
For x = 1 To 3
Console.WriteLine("hi")
Next
End Sub
End Module
Public Class c1
Public val As Integer
Public Shared Widening Operator CType(ByVal arg1 As Integer) As c1
Console.WriteLine("c1::CType(Integer) As c1")
Dim c As New c1
c.val = arg1 'what happens if this is last statement?
Return c
End Operator
Public Shared Widening Operator CType(ByVal arg1 As c1) As Integer
Console.WriteLine("c1::CType(c1) As Integer")
Dim x As Integer
x = arg1.val
Return x
End Operator
Public Shared Operator +(ByVal arg1 As c1, ByVal arg2 As c1) As c1
Console.WriteLine("c1::+(c1, c1) As c1")
Dim c As New c1
c.val = arg1.val + arg2.val
Return c
End Operator
Public Shared Operator -(ByVal arg1 As c1, ByVal arg2 As c1) As c1
Console.WriteLine("c1::-(c1, c1) As c1")
Dim c As New c1
c.val = arg1.val - arg2.val
Return c
End Operator
Public Shared Operator >=(ByVal arg1 As c1, ByVal arg2 As Integer) As Boolean
Console.WriteLine("c1::>=(c1, Integer) As Boolean")
If arg1.val >= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator <=(ByVal arg1 As c1, ByVal arg2 As Integer) As Boolean
Console.WriteLine("c1::<=(c1, Integer) As Boolean")
If arg1.val <= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator <=(ByVal arg2 As Integer, ByVal arg1 As c1) As Boolean
Console.WriteLine("c1::<=(Integer, c1) As Boolean")
If arg1.val <= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator >=(ByVal arg2 As Integer, ByVal arg1 As c1) As Boolean
Console.WriteLine("c1::>=(Integer, c1) As Boolean")
If arg1.val <= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator <=(ByVal arg1 As c1, ByVal arg2 As c1) As Boolean
Console.WriteLine("c1::<=(c1, c1) As Boolean")
If arg1.val <= arg2.val Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator >=(ByVal arg1 As c1, ByVal arg2 As c1) As Boolean
Console.WriteLine("c1::>=(c1, c1) As Boolean")
If arg1.val >= arg2.val Then
Return True
Else
Return False
End If
End Operator
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, <![CDATA[c1::CType(Integer) As c1
c1::CType(Integer) As c1
c1::CType(Integer) As c1
c1::-(c1, c1) As c1
c1::>=(c1, c1) As Boolean
c1::<=(c1, c1) As Boolean
hi
c1::+(c1, c1) As c1
c1::<=(c1, c1) As Boolean
hi
c1::+(c1, c1) As c1
c1::<=(c1, c1) As Boolean
hi
c1::+(c1, c1) As c1
c1::<=(c1, c1) As Boolean
]]>)
End Sub
<Fact()>
Public Sub SelectCase1_SwitchTable()
CompileAndVerify(
<compilation name="SelectCase1">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(number as Integer)
Select Case number
Case 0
Console.WriteLine("Equal to 0")
Case 1, 2, 3, 4, 5
Console.WriteLine("Between 1 and 5, inclusive")
Case 6, 7, 8
Console.WriteLine("Between 6 and 8, inclusive")
Case 9, 10
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[0:Equal to 0
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>)
End Sub
<Fact()>
Public Sub SelectCase2_IfList()
CompileAndVerify(
<compilation name="SelectCase2">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(number as Integer)
Select Case number
Case Is < 1
Console.WriteLine("Less than 1")
Case 1 To 5
Console.WriteLine("Between 1 and 5, inclusive")
Case 6, 7, 8
Console.WriteLine("Between 6 and 8, inclusive")
Case 9 To 10
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[0:Less than 1
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>)
End Sub
<WorkItem(542156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542156")>
<Fact()>
Public Sub ImplicitVarInRedim()
CompileAndVerify(
<compilation name="HelloWorld1">
<file name="a.vb">
Option Explicit Off
Module M
Sub Main()
Redim x(10)
System.Console.WriteLine("OK")
End Sub
End Module
</file>
</compilation>,
expectedOutput:="OK")
End Sub
<Fact()>
Public Sub EndStatementsInMethodBodyShouldNotThrowNYI()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EndStatementsInMethodBodyShouldNotThrowNYI">
<file name="a.vb">
Namespace N1
Public Class C1
Public Sub S1()
for i as integer = 23 to 42
next
next
do
loop while true
loop
end if
end select
end try
end using
end while
end with
end synclock
Try
Catch ex As System.Exception
End Try
catch
Try
Catch ex As System.Exception
finally
finally
End Try
finally
End Sub
Public Sub S2
end namespace
end module
end class
end structure
end interface
end enum
end function
end operator
end property
end get
end set
end event
end addhandler
end removehandler
end raiseevent
End Sub
end Class
end Namespace
Namespace N2
Class C2
function F1() as integer
end sub
return 42
end function
End Class
End Namespace
</file>
</compilation>)
Dim expectedErrors1 = <errors>
BC30481: 'Class' statement must end with a matching 'End Class'.
Public Class C1
~~~~~~~~~~~~~~~
BC30092: 'Next' must be preceded by a matching 'For'.
next
~~~~
BC30091: 'Loop' must be preceded by a matching 'Do'.
loop
~~~~
BC30087: 'End If' must be preceded by a matching 'If'.
end if
~~~~~~
BC30088: 'End Select' must be preceded by a matching 'Select Case'.
end select
~~~~~~~~~~
BC30383: 'End Try' must be preceded by a matching 'Try'.
end try
~~~~~~~
BC36007: 'End Using' must be preceded by a matching 'Using'.
end using
~~~~~~~~~
BC30090: 'End While' must be preceded by a matching 'While'.
end while
~~~~~~~~~
BC30093: 'End With' must be preceded by a matching 'With'.
end with
~~~~~~~~
BC30674: 'End SyncLock' must be preceded by a matching 'SyncLock'.
end synclock
~~~~~~~~~~~~
BC30380: 'Catch' cannot appear outside a 'Try' statement.
catch
~~~~~
BC30381: 'Finally' can only appear once in a 'Try' statement.
finally
~~~~~~~
BC30382: 'Finally' cannot appear outside a 'Try' statement.
finally
~~~~~~~
BC30026: 'End Sub' expected.
Public Sub S2
~~~~~~~~~~~~~
BC30622: 'End Module' must be preceded by a matching 'Module'.
end module
~~~~~~~~~~
BC30460: 'End Class' must be preceded by a matching 'Class'.
end class
~~~~~~~~~
BC30621: 'End Structure' must be preceded by a matching 'Structure'.
end structure
~~~~~~~~~~~~~
BC30252: 'End Interface' must be preceded by a matching 'Interface'.
end interface
~~~~~~~~~~~~~
BC30184: 'End Enum' must be preceded by a matching 'Enum'.
end enum
~~~~~~~~
BC30430: 'End Function' must be preceded by a matching 'Function'.
end function
~~~~~~~~~~~~
BC33007: 'End Operator' must be preceded by a matching 'Operator'.
end operator
~~~~~~~~~~~~
BC30431: 'End Property' must be preceded by a matching 'Property'.
end property
~~~~~~~~~~~~
BC30630: 'End Get' must be preceded by a matching 'Get'.
end get
~~~~~~~
BC30632: 'End Set' must be preceded by a matching 'Set'.
end set
~~~~~~~
BC31123: 'End Event' must be preceded by a matching 'Custom Event'.
end event
~~~~~~~~~
BC31124: 'End AddHandler' must be preceded by a matching 'AddHandler' declaration.
end addhandler
~~~~~~~~~~~~~~
BC31125: 'End RemoveHandler' must be preceded by a matching 'RemoveHandler' declaration.
end removehandler
~~~~~~~~~~~~~~~~~
BC31126: 'End RaiseEvent' must be preceded by a matching 'RaiseEvent' declaration.
end raiseevent
~~~~~~~~~~~~~~
BC30429: 'End Sub' must be preceded by a matching 'Sub'.
End Sub
~~~~~~~
BC30460: 'End Class' must be preceded by a matching 'Class'.
end Class
~~~~~~~~~
BC30623: 'End Namespace' must be preceded by a matching 'Namespace'.
end Namespace
~~~~~~~~~~~~~
BC30429: 'End Sub' must be preceded by a matching 'Sub'.
end sub
~~~~~~~
</errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub AddHandlerMissingStuff()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim del As System.EventHandler =
Sub(sender As Object, a As EventArgs) Console.Write("unload")
Dim v = AppDomain.CreateDomain("qq")
AddHandler v.DomainUnload,
AddHandler , del
AddHandler
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30201: Expression expected.
AddHandler v.DomainUnload,
~
BC30201: Expression expected.
AddHandler , del
~
BC30196: Comma expected.
AddHandler
~
BC30201: Expression expected.
AddHandler
~
BC30201: Expression expected.
AddHandler
~
</expected>)
End Sub
<Fact()>
Public Sub AddHandlerUninitialized()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
' no warnings here, variable is used
Dim del As System.EventHandler
' warning here
Dim v = AppDomain.CreateDomain("qq")
AddHandler v.DomainUnload, del
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'del' is used before it has been assigned a value. A null reference exception could result at runtime.
AddHandler v.DomainUnload, del
~~~
</expected>)
End Sub
<Fact()>
Public Sub AddHandlerNotSimple()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim del As System.EventHandler =
Sub(sender As Object, a As EventArgs) Console.Write("unload")
Dim v = AppDomain.CreateDomain("qq")
' real event with arg list
AddHandler (v.DomainUnload()), del
' not an event
AddHandler (v.GetType()), del
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30677: 'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name.
AddHandler (v.DomainUnload()), del
~~~~~~~~~~~~~~~~
BC30677: 'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name.
AddHandler (v.GetType()), del
~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub RemoveHandlerLambda()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim v = AppDomain.CreateDomain("qq")
RemoveHandler v.DomainUnload, Sub(sender As Object, a As EventArgs) Console.Write("unload")
AppDomain.Unload(v)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42326: Lambda expression will not be removed from this event handler. Assign the lambda expression to a variable and use the variable to add and remove the event.
RemoveHandler v.DomainUnload, Sub(sender As Object, a As EventArgs) Console.Write("unload")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub RemoveHandlerNotEvent()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim del As System.EventHandler =
Sub(sender As Object, a As EventArgs) Console.Write("unload")
Dim v = AppDomain.CreateDomain("qq")
' not an event
AddHandler (v.GetType), del
' not anything
AddHandler v.GetTyp, del
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30676: 'GetType' is not an event of 'AppDomain'.
AddHandler (v.GetType), del
~~~~~~~
BC30456: 'GetTyp' is not a member of 'AppDomain'.
AddHandler v.GetTyp, del
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AddHandlerNoConversion()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim v = AppDomain.CreateDomain("qq")
AddHandler (v.DomainUnload), Sub(sender As Object, sender1 As Object, sender2 As Object) Console.Write("unload")
AddHandler v.DomainUnload, AddressOf H
Dim del as Action(of Object, EventArgs) = Sub(sender As Object, a As EventArgs) Console.Write("unload")
AddHandler v.DomainUnload, del
End Sub
Sub H(i as integer)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36670: Nested sub does not have a signature that is compatible with delegate 'EventHandler'.
AddHandler (v.DomainUnload), Sub(sender As Object, sender1 As Object, sender2 As Object) Console.Write("unload")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31143: Method 'Public Sub H(i As Integer)' does not have a signature compatible with delegate 'Delegate Sub EventHandler(sender As Object, e As EventArgs)'.
AddHandler v.DomainUnload, AddressOf H
~
BC30311: Value of type 'Action(Of Object, EventArgs)' cannot be converted to 'EventHandler'.
AddHandler v.DomainUnload, del
~~~
</expected>)
End Sub
<Fact()>
Public Sub LegalGotoCasesTryCatchFinally()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LegalGotoCasesTryCatchFinally">
<file name="a.vb">
Module M1
Sub Main()
dim x1 = function()
labelOK6:
goto labelok7
if true then
goto labelok6
labelok7:
end if
return 23
end function
dim x2 = sub()
labelOK8:
goto labelok9
if true then
goto labelok8
labelok9:
end if
end sub
Try
Goto LabelOK1
LabelOK1:
Catch
Goto LabelOK2
LabelOK2:
Try
goto LabelOK1
goto LabelOK2:
LabelOK5:
Catch
goto LabelOK1
goto LabelOK5
goto LabelOK2
Finally
End Try
Finally
Goto LabelOK3
LabelOK3:
End Try
Exit Sub
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<WorkItem(543055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543055")>
<Fact()>
Public Sub Bug10583()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LegalGotoCasesTryCatchFinally">
<file name="a.vb">
Imports System
Module Program
Sub Main(args As String())
Try
GoTo label
GoTo label5
Catch ex As Exception
label:
Finally
label5:
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30754: 'GoTo label' is not valid because 'label' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.
GoTo label
~~~~~
BC30754: 'GoTo label5' is not valid because 'label5' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.
GoTo label5
~~~~~~
</expected>)
End Sub
<WorkItem(543060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543060")>
<Fact()>
Public Sub SelectCase_ImplicitOperator()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="SelectCase">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Class X
Public Shared Operator =(left As X, right As X) As Boolean
Return True
End Operator
Public Shared Operator <>(left As X, right As X) As Boolean
Return True
End Operator
Public Shared Widening Operator CType(expandedName As String) As X
Return New X()
End Operator
End Class
Sub Main()
End Sub
Sub Test(x As X)
Select Case x
Case "a"
Console.WriteLine("Equal to a")
Case "s"
Console.WriteLine("Equal to A")
Case "3"
Console.WriteLine("Error")
Case "5"
Console.WriteLine("Error")
Case "6"
Console.WriteLine("Error")
Case "9"
Console.WriteLine("Error")
Case "11"
Console.WriteLine("Error")
Case "12"
Console.WriteLine("Error")
Case "13"
Console.WriteLine("Error")
Case Else
Console.WriteLine("Error")
End Select
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
</expected>)
End Sub
<WorkItem(543333, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543333")>
<Fact()>
Public Sub Binding_Return_As_Declaration()
Dim compilation1 = CreateCompilationWithMscorlib40(
<compilation name="SelectCase">
<file name="a.vb"><![CDATA[
Class Program
Shared Main()
Return Nothing
End sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30689: Statement cannot appear outside of a method body.
Return Nothing
~~~~~~~~~~~~~~
BC30429: 'End Sub' must be preceded by a matching 'Sub'.
End sub
~~~~~~~
</expected>)
End Sub
<WorkItem(529050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529050")>
<Fact>
Public Sub WhileOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
While (true)
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "While (true)"))
End Sub
<WorkItem(529050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529050")>
<Fact>
Public Sub WhileOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
While (true)
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "While (true)"))
End Sub
<WorkItem(529051, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529051")>
<Fact>
Public Sub IfOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
If (true)
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "If (true)"))
End Sub
<WorkItem(529051, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529051")>
<Fact>
Public Sub IfOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
If (true)
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "If (true)"))
End Sub
<WorkItem(529052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529052")>
<Fact>
Public Sub TryOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
Try
Catch
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Try"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Catch"))
End Sub
<WorkItem(529052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529052")>
<Fact>
Public Sub TryOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
Try
Catch
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Try"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Catch"))
End Sub
<WorkItem(529053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529053")>
<Fact>
Public Sub DoOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
Do
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Do"))
End Sub
<WorkItem(529053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529053")>
<Fact>
Public Sub DoOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
Do
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Do"))
End Sub
<WorkItem(11031, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub ElseOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
Else
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Else"))
End Sub
<WorkItem(11031, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub ElseOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
Else
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Else"))
End Sub
<WorkItem(544465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544465")>
<Fact()>
Public Sub DuplicateNullableLocals()
Dim source =
<compilation>
<file name="a.vb">
Option Explicit Off
Module M
Sub S()
Dim A? As Integer = 1
Dim A? As Integer? = 1
End Sub
End Module
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_CantSpecifyNullableOnBoth, "As Integer?"),
Diagnostic(ERRID.ERR_DuplicateLocals1, "A?").WithArguments("A"))
End Sub
<WorkItem(544431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544431")>
<Fact()>
Public Sub IllegalModifiers()
Dim source =
<compilation>
<file name="a.vb">
Class C
Public Custom E
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidUseOfCustomModifier, "Custom"))
End Sub
<Fact()>
Public Sub InvalidCode_ConstInterface()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Const Interface
</file>
</compilation>)
compilation.AssertTheseDiagnostics(<errors>
BC30397: 'Const' is not valid on an Interface declaration.
Const Interface
~~~~~
BC30253: 'Interface' must end with a matching 'End Interface'.
Const Interface
~~~~~~~~~~~~~~~
BC30203: Identifier expected.
Const Interface
~
</errors>)
End Sub
<WorkItem(545196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545196")>
<Fact()>
Public Sub InvalidCode_Event()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Event
</file>
</compilation>)
compilation.AssertTheseParseDiagnostics(<errors>
BC30203: Identifier expected.
Event
~
</errors>)
End Sub
<Fact>
Public Sub StopAndEnd_1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Public Sub Main()
Dim m = GetType(Module1)
System.Console.WriteLine(m.GetMethod("TestEnd").GetMethodImplementationFlags)
System.Console.WriteLine(m.GetMethod("TestStop").GetMethodImplementationFlags)
System.Console.WriteLine(m.GetMethod("Dummy").GetMethodImplementationFlags)
Try
System.Console.WriteLine("Before End")
TestEnd()
System.Console.WriteLine("After End")
Finally
System.Console.WriteLine("In Finally")
End Try
System.Console.WriteLine("After Try")
End Sub
Sub TestEnd()
End
End Sub
Sub TestStop()
Stop
End Sub
Sub Dummy()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
Dim compilationVerifier = CompileAndVerify(compilation,
symbolValidator:=Sub(m As ModuleSymbol)
Dim m1 = m.ContainingAssembly.GetTypeByMetadataName("Module1")
Assert.Equal(MethodImplAttributes.Managed Or MethodImplAttributes.NoInlining Or MethodImplAttributes.NoOptimization,
DirectCast(m1.GetMembers("TestEnd").Single(), PEMethodSymbol).ImplementationAttributes)
Assert.Equal(MethodImplAttributes.Managed,
DirectCast(m1.GetMembers("TestStop").Single(), PEMethodSymbol).ImplementationAttributes)
Assert.Equal(MethodImplAttributes.Managed,
DirectCast(m1.GetMembers("Dummy").Single(), PEMethodSymbol).ImplementationAttributes)
End Sub)
compilationVerifier.VerifyIL("Module1.TestEnd",
<![CDATA[
{
// Code size 6 (0x6)
.maxstack 0
IL_0000: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.EndApp()"
IL_0005: ret
}
]]>)
compilationVerifier.VerifyIL("Module1.TestStop",
<![CDATA[
{
// Code size 6 (0x6)
.maxstack 0
IL_0000: call "Sub System.Diagnostics.Debugger.Break()"
IL_0005: ret
}
]]>)
compilation = compilation.WithOptions(compilation.Options.WithOutputKind(OutputKind.DynamicallyLinkedLibrary))
AssertTheseDiagnostics(compilation,
<expected>
BC30615: 'End' statement cannot be used in class library projects.
End
~~~
</expected>)
End Sub
<Fact>
Public Sub StopAndEnd_2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Public Sub Main()
Dim x As Object
Dim y As Object
Stop
x.ToString()
End
y.ToString()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime.
x.ToString()
~
</expected>)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub StopAndEnd_3()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Public state As Integer = 0
Public Sub Main()
On Error GoTo handler
Throw New NullReferenceException()
Stop
Console.WriteLine("Done")
Return
handler:
Console.WriteLine(Microsoft.VisualBasic.Information.Err.GetException().GetType())
If state = 1 Then
Resume
End If
Resume Next
End Sub
End Module
Namespace System.Diagnostics
Public Class Debugger
Public Shared Sub Break()
Console.WriteLine("In Break")
Select Case Module1.state
Case 0, 1
Module1.state += 1
Case Else
Console.WriteLine("Test issue!!!")
Return
End Select
Throw New NotSupportedException()
End Sub
End Class
End Namespace
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
Dim compilationVerifier = CompileAndVerify(compilation, expectedOutput:=
<![CDATA[
System.NullReferenceException
In Break
System.NotSupportedException
In Break
System.NotSupportedException
Done
]]>)
End Sub
<WorkItem(660010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/660010")>
<Fact>
Public Sub Regress660010()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Class C
Inherits value
End C
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:=XmlReferences)
AssertTheseDiagnostics(compilation,
<expected>
BC30481: 'Class' statement must end with a matching 'End Class'.
Class C
~~~~~~~
BC30002: Type 'value' is not defined.
Inherits value
~~~~~
BC30678: 'End' statement not valid.
End C
~~~
</expected>)
End Sub
<WorkItem(718436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718436")>
<Fact>
Public Sub NotYetImplementedStatement()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Class C
Sub M()
Inherits A
Implements I
Imports X
Option Strict On
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source)
AssertTheseDiagnostics(compilation,
<expected>
BC30024: Statement is not valid inside a method.
Inherits A
~~~~~~~~~~
BC30024: Statement is not valid inside a method.
Implements I
~~~~~~~~~~~~
BC30024: Statement is not valid inside a method.
Imports X
~~~~~~~~~
BC30024: Statement is not valid inside a method.
Option Strict On
~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InaccessibleRemoveAccessor()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.field private class [mscorlib]System.Action TestEvent
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::add_Test
.method family specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
RemoveHandler e.Test, d
End Sub
End Module
Class E2
Inherits E1
Sub Main()
Dim d As System.Action = Nothing
AddHandler Test, d
RemoveHandler Test, d
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30390: 'E1.Protected RemoveHandler Event Test(obj As Action)' is not accessible in this context because it is 'Protected'.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InaccessibleAddAccessor()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.field private class [mscorlib]System.Action TestEvent
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method family specialname instance void
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
RemoveHandler e.Test, d
End Sub
End Module
Class E2
Inherits E1
Sub Main()
Dim d As System.Action = Nothing
AddHandler Test, d
RemoveHandler Test, d
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30390: 'E1.Protected AddHandler Event Test(obj As Action)' is not accessible in this context because it is 'Protected'.
AddHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub EventTypeIsNotADelegate()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class E1 obj) cil managed synchronized
{
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class E1 obj) cil managed synchronized
{
IL_0017: ret
} // end of method E1::remove_Test
.event E1 Test
{
.addon instance void E1::add_Test(class E1)
.removeon instance void E1::remove_Test(class E1)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC37223: 'Public Event Test As E1' is an unsupported event.
AddHandler e.Test, e
~~~~~~
BC37223: 'Public Event Test As E1' is an unsupported event.
RemoveHandler e.Test, e
~~~~~~
</expected>)
'CompileAndVerify(compilation)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidAddAccessor_01()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class E1 obj) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class E1)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30657: 'Public AddHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, d
~~~~~~
BC30657: 'Public AddHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="remove_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidAddAccessor_02()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test() cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test()
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30657: 'Public AddHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, d
~~~~~~
BC30657: 'Public AddHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="remove_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidAddAccessor_03()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj1, class E1 obj2) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action, class E1)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30657: 'Public AddHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, d
~~~~~~
BC30657: 'Public AddHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="remove_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidRemoveAccessor_01()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class E1 obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class E1)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, e
RemoveHandler e.Test, e
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="add_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidRemoveAccessor_02()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test() cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test()
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, e
RemoveHandler e.Test, e
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="add_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidRemoveAccessor_03()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj1) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj1, class E1 obj2) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action, class E1)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, e
RemoveHandler e.Test, e
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="add_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub NonVoidAccessors()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance int32
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0016: ldc.i4.0
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance int32
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0016: ldc.i4.0
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance int32 E1::add_Test(class [mscorlib]System.Action)
.removeon instance int32 E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation1, expectedOutput:="add_Test
remove_Test")
End Sub
''' <summary>
''' Tests that FULLWIDTH COLON (U+FF1A) is never parsed as part of XML name,
''' but is instead parsed as a statement separator when it immediately follows an XML name.
''' If the next token is an identifier or keyword, it should be parsed as a separate statement.
''' An XML name should never include more than one colon.
''' See also: http://fileformat.info/info/unicode/char/FF1A
''' </summary>
<Fact>
<WorkItem(529880, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529880")>
Public Sub FullWidthColonInXmlNames()
' FULLWIDTH COLON is represented by "~" below
Dim source = <![CDATA[
Imports System
Module M
Sub Main()
Test1()
Test2()
Test3()
Test4()
Test5()
Test6()
Test7()
Test8()
End Sub
Sub Test1()
Console.WriteLine(">1")
Dim x = <a/>.@xml:goo
Console.WriteLine("<1")
End Sub
Sub Test2()
Console.WriteLine(">2")
Dim x = <a/>.@xml:goo:goo
Console.WriteLine("<2")
End Sub
Sub Test3()
Console.WriteLine(">3")
Dim x = <a/>.@xml:return
Console.WriteLine("<3")
End Sub
Sub Test4()
Console.WriteLine(">4")
Dim x = <a/>.@xml:return:return
Console.WriteLine("<4")
End Sub
Sub Test5()
Console.WriteLine(">5")
Dim x = <a/>.@xml~goo
Console.WriteLine("<5")
End Sub
Sub Test6()
Console.WriteLine(">6")
Dim x = <a/>.@xml~return
Console.WriteLine("<6")
End Sub
Sub Test7()
Console.WriteLine(">7")
Dim x = <a/>.@xml~goo~return
Console.WriteLine("<7")
End Sub
Sub Test8()
Console.WriteLine(">8")
Dim x = <a/>.@xml~REM
Console.WriteLine("<8")
End Sub
Sub goo
Console.WriteLine("goo")
End Sub
Sub [return]
Console.WriteLine("return")
End Sub
Sub [REM]
Console.WriteLine("REM")
End Sub
End Module]]>.Value.Replace("~"c, SyntaxFacts.FULLWIDTH_COLON)
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="FullWidthColonInXmlNames">
<file name="M.vb"><%= source %></file>
</compilation>,
XmlReferences,
TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[
>1
<1
>2
goo
<2
>3
<3
>4
>5
goo
<5
>6
>7
goo
>8
<8]]>.Value.Replace(vbLf, Environment.NewLine))
End Sub
End Class
End Namespace
|
VSadov/roslyn
|
src/Compilers/VisualBasic/Test/Semantic/Binding/Binder_Statements_Tests.vb
|
Visual Basic
|
apache-2.0
| 132,240
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements
''' <summary>
''' Recommends the "Stop" statement.
''' </summary>
Friend Class StopKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Stop", VBFeaturesResources.Suspends_program_execution))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.IsSingleLineStatementContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
|
AmadeusW/roslyn
|
src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Statements/StopKeywordRecommender.vb
|
Visual Basic
|
apache-2.0
| 1,176
|
' 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.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CaseCorrection
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.Text
Namespace Microsoft.CodeAnalysis.VisualBasic.CaseCorrection
Partial Friend Class VisualBasicCaseCorrectionService
Inherits AbstractCaseCorrectionService
Private Const s_threshold As Integer = 50
Private Const s_attributeSuffix = "Attribute"
Private ReadOnly _syntaxFactsService As ISyntaxFactsService
Public Sub New(provider As HostLanguageServices)
_syntaxFactsService = provider.GetService(Of ISyntaxFactsService)()
End Sub
Protected Overrides Sub AddReplacements(semanticModel As SemanticModel,
root As SyntaxNode,
spans As IEnumerable(Of TextSpan),
workspace As Workspace,
replacements As ConcurrentDictionary(Of SyntaxToken, SyntaxToken),
cancellationToken As CancellationToken)
For Each span In spans
AddReplacementsWorker(semanticModel, root, span, replacements, cancellationToken)
Next
End Sub
Private Sub AddReplacementsWorker(semanticModel As SemanticModel,
root As SyntaxNode,
span As TextSpan,
replacements As ConcurrentDictionary(Of SyntaxToken, SyntaxToken),
cancellationToken As CancellationToken)
Dim candidates = root.DescendantTokens(span).Where(Function(tk As SyntaxToken) tk.Width > 0 OrElse tk.IsKind(SyntaxKind.EndOfFileToken))
If Not candidates.Any() Then
Return
End If
Dim rewriter = New Rewriter(_syntaxFactsService, TryCast(semanticModel, SemanticModel), cancellationToken)
If span.Length <= s_threshold Then
candidates.Do(Sub(t) Rewrite(t, rewriter, replacements))
Else
' checkIdentifier is expensive. make sure we run this in parallel.
Parallel.ForEach(candidates, Sub(t) Rewrite(t, rewriter, replacements))
End If
End Sub
Private Sub Rewrite(token As SyntaxToken, rewriter As Rewriter, replacements As ConcurrentDictionary(Of SyntaxToken, SyntaxToken))
Dim newToken = rewriter.VisitToken(token)
If newToken <> token Then
replacements(token) = newToken
End If
End Sub
End Class
End Namespace
|
cybernet14/roslyn
|
src/Workspaces/VisualBasic/Portable/CaseCorrection/VisualBasicCaseCorrectionService.vb
|
Visual Basic
|
apache-2.0
| 3,024
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class formMain
Inherits System.Windows.Forms.Form
'Form reemplaza a Dispose para limpiar la lista de componentes.
<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
'Requerido por el Diseñador de Windows Forms
Private components As System.ComponentModel.IContainer
'NOTA: el Diseñador de Windows Forms necesita el siguiente procedimiento
'Se puede modificar usando el Diseñador de Windows Forms.
'No lo modifique con el editor de código.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(formMain))
Me.splitContent = New System.Windows.Forms.SplitContainer()
Me.Label21 = New System.Windows.Forms.Label()
Me.Label20 = New System.Windows.Forms.Label()
Me.splitMain = New System.Windows.Forms.SplitContainer()
Me.Label9 = New System.Windows.Forms.Label()
Me.Label8 = New System.Windows.Forms.Label()
Me.Label7 = New System.Windows.Forms.Label()
Me.Label6 = New System.Windows.Forms.Label()
Me.Label5 = New System.Windows.Forms.Label()
Me.Label4 = New System.Windows.Forms.Label()
Me.Label3 = New System.Windows.Forms.Label()
Me.Label2 = New System.Windows.Forms.Label()
Me.Label1 = New System.Windows.Forms.Label()
Me.picSalir = New System.Windows.Forms.PictureBox()
Me.picStock = New System.Windows.Forms.PictureBox()
Me.picDevoluciones = New System.Windows.Forms.PictureBox()
Me.picVentas = New System.Windows.Forms.PictureBox()
Me.picReportados = New System.Windows.Forms.PictureBox()
Me.picListaPrecios = New System.Windows.Forms.PictureBox()
Me.picClientes = New System.Windows.Forms.PictureBox()
Me.picFormularios = New System.Windows.Forms.PictureBox()
Me.picInicio = New System.Windows.Forms.PictureBox()
Me.ErrorProvider = New System.Windows.Forms.ErrorProvider(Me.components)
CType(Me.splitContent, System.ComponentModel.ISupportInitialize).BeginInit()
Me.splitContent.Panel1.SuspendLayout()
Me.splitContent.Panel2.SuspendLayout()
Me.splitContent.SuspendLayout()
CType(Me.splitMain, System.ComponentModel.ISupportInitialize).BeginInit()
Me.splitMain.Panel1.SuspendLayout()
Me.splitMain.SuspendLayout()
CType(Me.picSalir, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.picStock, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.picDevoluciones, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.picVentas, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.picReportados, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.picListaPrecios, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.picClientes, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.picFormularios, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.picInicio, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.ErrorProvider, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'splitContent
'
Me.splitContent.Dock = System.Windows.Forms.DockStyle.Fill
Me.splitContent.IsSplitterFixed = True
Me.splitContent.Location = New System.Drawing.Point(0, 0)
Me.splitContent.Name = "splitContent"
Me.splitContent.Orientation = System.Windows.Forms.Orientation.Horizontal
'
'splitContent.Panel1
'
Me.splitContent.Panel1.BackColor = System.Drawing.Color.Black
Me.splitContent.Panel1.Controls.Add(Me.Label21)
Me.splitContent.Panel1.Controls.Add(Me.Label20)
'
'splitContent.Panel2
'
Me.splitContent.Panel2.Controls.Add(Me.splitMain)
Me.splitContent.Size = New System.Drawing.Size(819, 562)
Me.splitContent.SplitterDistance = 84
Me.splitContent.TabIndex = 0
'
'Label21
'
Me.Label21.AutoSize = True
Me.Label21.Font = New System.Drawing.Font("Monotype Corsiva", 12.0!, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label21.ForeColor = System.Drawing.Color.White
Me.Label21.Location = New System.Drawing.Point(307, 45)
Me.Label21.Name = "Label21"
Me.Label21.Size = New System.Drawing.Size(203, 18)
Me.Label21.TabIndex = 1
Me.Label21.Text = "Sistema de Gestión del Automotor"
'
'Label20
'
Me.Label20.AutoSize = True
Me.Label20.Font = New System.Drawing.Font("Bernard MT Condensed", 15.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label20.ForeColor = System.Drawing.Color.White
Me.Label20.Location = New System.Drawing.Point(338, 14)
Me.Label20.Name = "Label20"
Me.Label20.Size = New System.Drawing.Size(148, 24)
Me.Label20.TabIndex = 0
Me.Label20.Text = "SAAVEDRA SYSTEM"
'
'splitMain
'
Me.splitMain.Dock = System.Windows.Forms.DockStyle.Fill
Me.splitMain.IsSplitterFixed = True
Me.splitMain.Location = New System.Drawing.Point(0, 0)
Me.splitMain.Name = "splitMain"
Me.splitMain.Orientation = System.Windows.Forms.Orientation.Horizontal
'
'splitMain.Panel1
'
Me.splitMain.Panel1.Controls.Add(Me.Label9)
Me.splitMain.Panel1.Controls.Add(Me.Label8)
Me.splitMain.Panel1.Controls.Add(Me.Label7)
Me.splitMain.Panel1.Controls.Add(Me.Label6)
Me.splitMain.Panel1.Controls.Add(Me.Label5)
Me.splitMain.Panel1.Controls.Add(Me.Label4)
Me.splitMain.Panel1.Controls.Add(Me.Label3)
Me.splitMain.Panel1.Controls.Add(Me.Label2)
Me.splitMain.Panel1.Controls.Add(Me.Label1)
Me.splitMain.Panel1.Controls.Add(Me.picSalir)
Me.splitMain.Panel1.Controls.Add(Me.picStock)
Me.splitMain.Panel1.Controls.Add(Me.picDevoluciones)
Me.splitMain.Panel1.Controls.Add(Me.picVentas)
Me.splitMain.Panel1.Controls.Add(Me.picReportados)
Me.splitMain.Panel1.Controls.Add(Me.picListaPrecios)
Me.splitMain.Panel1.Controls.Add(Me.picClientes)
Me.splitMain.Panel1.Controls.Add(Me.picFormularios)
Me.splitMain.Panel1.Controls.Add(Me.picInicio)
Me.splitMain.Size = New System.Drawing.Size(819, 474)
Me.splitMain.SplitterDistance = 91
Me.splitMain.TabIndex = 0
'
'Label9
'
Me.Label9.AutoSize = True
Me.Label9.Font = New System.Drawing.Font("Georgia", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label9.Location = New System.Drawing.Point(757, 69)
Me.Label9.Name = "Label9"
Me.Label9.Size = New System.Drawing.Size(36, 16)
Me.Label9.TabIndex = 17
Me.Label9.Text = "Salir"
'
'Label8
'
Me.Label8.AutoSize = True
Me.Label8.Font = New System.Drawing.Font("Georgia", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label8.Location = New System.Drawing.Point(663, 69)
Me.Label8.Name = "Label8"
Me.Label8.Size = New System.Drawing.Size(42, 16)
Me.Label8.TabIndex = 16
Me.Label8.Text = "Stock"
'
'Label7
'
Me.Label7.AutoSize = True
Me.Label7.Font = New System.Drawing.Font("Georgia", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label7.Location = New System.Drawing.Point(549, 69)
Me.Label7.Name = "Label7"
Me.Label7.Size = New System.Drawing.Size(92, 16)
Me.Label7.TabIndex = 15
Me.Label7.Text = "Devoluciones"
'
'Label6
'
Me.Label6.AutoSize = True
Me.Label6.Font = New System.Drawing.Font("Georgia", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label6.Location = New System.Drawing.Point(476, 69)
Me.Label6.Name = "Label6"
Me.Label6.Size = New System.Drawing.Size(51, 16)
Me.Label6.TabIndex = 14
Me.Label6.Text = "Ventas"
'
'Label5
'
Me.Label5.AutoSize = True
Me.Label5.Font = New System.Drawing.Font("Georgia", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label5.Location = New System.Drawing.Point(373, 69)
Me.Label5.Name = "Label5"
Me.Label5.Size = New System.Drawing.Size(80, 16)
Me.Label5.TabIndex = 13
Me.Label5.Text = "Reportados"
'
'Label4
'
Me.Label4.AutoSize = True
Me.Label4.Font = New System.Drawing.Font("Georgia", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label4.Location = New System.Drawing.Point(278, 69)
Me.Label4.Name = "Label4"
Me.Label4.Size = New System.Drawing.Size(87, 16)
Me.Label4.TabIndex = 12
Me.Label4.Text = "Lista Precios"
'
'Label3
'
Me.Label3.AutoSize = True
Me.Label3.Font = New System.Drawing.Font("Georgia", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label3.Location = New System.Drawing.Point(200, 69)
Me.Label3.Name = "Label3"
Me.Label3.Size = New System.Drawing.Size(57, 16)
Me.Label3.TabIndex = 11
Me.Label3.Text = "Clientes"
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.Font = New System.Drawing.Font("Georgia", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label2.Location = New System.Drawing.Point(95, 69)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(85, 16)
Me.Label2.TabIndex = 10
Me.Label2.Text = "Formularios"
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Font = New System.Drawing.Font("Georgia", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label1.Location = New System.Drawing.Point(25, 69)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(45, 16)
Me.Label1.TabIndex = 9
Me.Label1.Text = "Inicio"
'
'picSalir
'
Me.picSalir.Enabled = False
Me.picSalir.Image = Global.Formularios_Saavedra.My.Resources.Resources.exitt
Me.picSalir.Location = New System.Drawing.Point(731, 3)
Me.picSalir.Name = "picSalir"
Me.picSalir.Size = New System.Drawing.Size(85, 71)
Me.picSalir.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage
Me.picSalir.TabIndex = 8
Me.picSalir.TabStop = False
'
'picStock
'
Me.picStock.Enabled = False
Me.picStock.Image = Global.Formularios_Saavedra.My.Resources.Resources.stock
Me.picStock.Location = New System.Drawing.Point(640, 3)
Me.picStock.Name = "picStock"
Me.picStock.Size = New System.Drawing.Size(85, 71)
Me.picStock.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage
Me.picStock.TabIndex = 7
Me.picStock.TabStop = False
'
'picDevoluciones
'
Me.picDevoluciones.Enabled = False
Me.picDevoluciones.Image = Global.Formularios_Saavedra.My.Resources.Resources.devoluciones
Me.picDevoluciones.Location = New System.Drawing.Point(549, 3)
Me.picDevoluciones.Name = "picDevoluciones"
Me.picDevoluciones.Size = New System.Drawing.Size(85, 71)
Me.picDevoluciones.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage
Me.picDevoluciones.TabIndex = 6
Me.picDevoluciones.TabStop = False
'
'picVentas
'
Me.picVentas.Enabled = False
Me.picVentas.Image = Global.Formularios_Saavedra.My.Resources.Resources.ventas
Me.picVentas.Location = New System.Drawing.Point(458, 3)
Me.picVentas.Name = "picVentas"
Me.picVentas.Size = New System.Drawing.Size(85, 71)
Me.picVentas.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage
Me.picVentas.TabIndex = 5
Me.picVentas.TabStop = False
'
'picReportados
'
Me.picReportados.Enabled = False
Me.picReportados.Image = Global.Formularios_Saavedra.My.Resources.Resources.pago
Me.picReportados.Location = New System.Drawing.Point(368, 3)
Me.picReportados.Name = "picReportados"
Me.picReportados.Size = New System.Drawing.Size(85, 71)
Me.picReportados.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage
Me.picReportados.TabIndex = 4
Me.picReportados.TabStop = False
'
'picListaPrecios
'
Me.picListaPrecios.Enabled = False
Me.picListaPrecios.Image = Global.Formularios_Saavedra.My.Resources.Resources.listas
Me.picListaPrecios.Location = New System.Drawing.Point(276, 3)
Me.picListaPrecios.Name = "picListaPrecios"
Me.picListaPrecios.Size = New System.Drawing.Size(85, 71)
Me.picListaPrecios.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage
Me.picListaPrecios.TabIndex = 3
Me.picListaPrecios.TabStop = False
'
'picClientes
'
Me.picClientes.Enabled = False
Me.picClientes.Image = Global.Formularios_Saavedra.My.Resources.Resources.clientes
Me.picClientes.Location = New System.Drawing.Point(185, 3)
Me.picClientes.Name = "picClientes"
Me.picClientes.Size = New System.Drawing.Size(85, 71)
Me.picClientes.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage
Me.picClientes.TabIndex = 2
Me.picClientes.TabStop = False
'
'picFormularios
'
Me.picFormularios.Enabled = False
Me.picFormularios.Image = Global.Formularios_Saavedra.My.Resources.Resources.formulario
Me.picFormularios.Location = New System.Drawing.Point(94, 3)
Me.picFormularios.Name = "picFormularios"
Me.picFormularios.Size = New System.Drawing.Size(85, 71)
Me.picFormularios.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage
Me.picFormularios.TabIndex = 1
Me.picFormularios.TabStop = False
'
'picInicio
'
Me.picInicio.Enabled = False
Me.picInicio.Image = Global.Formularios_Saavedra.My.Resources.Resources.home
Me.picInicio.Location = New System.Drawing.Point(3, 3)
Me.picInicio.Name = "picInicio"
Me.picInicio.Size = New System.Drawing.Size(85, 71)
Me.picInicio.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage
Me.picInicio.TabIndex = 0
Me.picInicio.TabStop = False
'
'ErrorProvider
'
Me.ErrorProvider.ContainerControl = Me
'
'formMain
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.ClientSize = New System.Drawing.Size(819, 562)
Me.Controls.Add(Me.splitContent)
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.MaximizeBox = False
Me.Name = "formMain"
Me.ShowIcon = False
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.splitContent.Panel1.ResumeLayout(False)
Me.splitContent.Panel1.PerformLayout()
Me.splitContent.Panel2.ResumeLayout(False)
CType(Me.splitContent, System.ComponentModel.ISupportInitialize).EndInit()
Me.splitContent.ResumeLayout(False)
Me.splitMain.Panel1.ResumeLayout(False)
Me.splitMain.Panel1.PerformLayout()
CType(Me.splitMain, System.ComponentModel.ISupportInitialize).EndInit()
Me.splitMain.ResumeLayout(False)
CType(Me.picSalir, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.picStock, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.picDevoluciones, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.picVentas, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.picReportados, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.picListaPrecios, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.picClientes, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.picFormularios, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.picInicio, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.ErrorProvider, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
End Sub
Friend WithEvents splitContent As SplitContainer
Friend WithEvents splitMain As SplitContainer
Friend WithEvents Label9 As Label
Friend WithEvents Label8 As Label
Friend WithEvents Label7 As Label
Friend WithEvents Label6 As Label
Friend WithEvents Label5 As Label
Friend WithEvents Label4 As Label
Friend WithEvents Label3 As Label
Friend WithEvents Label2 As Label
Friend WithEvents Label1 As Label
Friend WithEvents picSalir As PictureBox
Friend WithEvents picStock As PictureBox
Friend WithEvents picDevoluciones As PictureBox
Friend WithEvents picVentas As PictureBox
Friend WithEvents picReportados As PictureBox
Friend WithEvents picListaPrecios As PictureBox
Friend WithEvents picClientes As PictureBox
Friend WithEvents picFormularios As PictureBox
Friend WithEvents picInicio As PictureBox
Friend WithEvents Label21 As Label
Friend WithEvents Label20 As Label
Friend WithEvents ErrorProvider As ErrorProvider
End Class
|
MontiQt/SaavedraSystem
|
Formularios Saavedra/formMain.Designer.vb
|
Visual Basic
|
mit
| 18,779
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'<summary>
' A strongly-typed resource class, for looking up localized strings, etc.
'</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'<summary>
' Returns the cached ResourceManager instance used by this class.
'</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("_02.InternationalEmployees.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'<summary>
' Overrides the current thread's CurrentUICulture property for all
' resource lookups using this strongly typed resource class.
'</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set(ByVal value As Global.System.Globalization.CultureInfo)
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
VanyaD/CSS
|
CSSOverviewHomework/02. InternationalEmployees/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,715
|
'**********************************************************************************************
'* Pneumatic Valve for AdvancedHMI
'*
'* Archie Jacobs
'* Manufacturing Automation, LLC
'* support@advancedhmi.com
'*
'*
'* Copyright 2011 Archie Jacobs
'*
'*
'* Distributed under the GNU General Public License (www.gnu.org)
'*
'* This program is free software; you can redistribute it and/or
'* as published by the Free Software Foundation; either version 2
'* of the License, or (at your option) any later version.
'*
'* This program is distributed in the hope that it will be useful,
'* but WITHOUT ANY WARRANTY; without even the implied warranty of
'* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
'* GNU General Public License for more details.
'* You should have received a copy of the GNU General Public License
'* along with this program; if not, write to the Free Software
'* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
'*
'**********************************************************************************************
Public Class PneumaticBallValve
Inherits MfgControl.AdvancedHMI.Controls.PneumaticBallVave
#Region "PLC Related Properties"
'*****************************************************
'* Property - Component to communicate to PLC through
'*****************************************************
Private m_CommComponent As AdvancedHMIDrivers.IComComponent
<System.ComponentModel.Category("PLC Properties")> _
Public Property CommComponent() As AdvancedHMIDrivers.IComComponent
Get
Return m_CommComponent
End Get
Set(ByVal value As AdvancedHMIDrivers.IComComponent)
If m_CommComponent IsNot value Then
If SubScriptions IsNot Nothing Then
SubScriptions.UnsubscribeAll()
End If
m_CommComponent = value
SubscribeToCommDriver()
End If
End Set
End Property
'*****************************************
'* Property - Address in PLC to Link to
'*****************************************
Private m_PLCAddressText As String = ""
<System.ComponentModel.Category("PLC Properties")> _
Public Property PLCAddressText() As String
Get
Return m_PLCAddressText
End Get
Set(ByVal value As String)
If m_PLCAddressText <> value Then
m_PLCAddressText = value
'* When address is changed, re-subscribe to new address
SubscribeToCommDriver()
End If
End Set
End Property
'*****************************************
'* Property - Address in PLC to Link to
'*****************************************
Private InvertVisible As Boolean
Private m_PLCAddressVisible As String = ""
<System.ComponentModel.Category("PLC Properties")> _
Public Property PLCAddressVisible() As String
Get
Return m_PLCAddressVisible
End Get
Set(ByVal value As String)
If m_PLCAddressVisible <> value Then
m_PLCAddressVisible = value
'* When address is changed, re-subscribe to new address
SubscribeToCommDriver()
End If
End Set
End Property
'*****************************************
'* Property - Address in PLC to Link to
'*****************************************
Private m_PLCAddressValue As String = ""
<System.ComponentModel.Category("PLC Properties")> _
Public Property PLCAddressValue() As String
Get
Return m_PLCAddressValue
End Get
Set(ByVal value As String)
If m_PLCAddressValue <> value Then
m_PLCAddressValue = value
'* When address is changed, re-subscribe to new address
SubscribeToCommDriver()
End If
End Set
End Property
'*****************************************
'* Property - Address in PLC to Link to
'*****************************************
Private m_PLCAddressClick As String = ""
<System.ComponentModel.Category("PLC Properties")> _
Public Property PLCAddressClick() As String
Get
Return m_PLCAddressClick
End Get
Set(ByVal value As String)
If m_PLCAddressClick <> value Then
m_PLCAddressClick = value
End If
End Set
End Property
#End Region
#Region "Events"
Private WithEvents tmrError As New System.Windows.Forms.Timer
'****************************
'* Event - Mouse Down
'****************************
Private Sub MomentaryButton_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
If m_PLCAddressClick <> "" And Enabled AndAlso m_CommComponent IsNot Nothing Then
Try
Select Case OutputType
Case MfgControl.AdvancedHMI.Controls.OutputType.MomentarySet : m_CommComponent.Write(m_PLCAddressClick, 1)
Case MfgControl.AdvancedHMI.Controls.OutputType.MomentaryReset : m_CommComponent.Write(m_PLCAddressClick, 0)
Case MfgControl.AdvancedHMI.Controls.OutputType.SetTrue : m_CommComponent.Write(m_PLCAddressClick, 1)
Case MfgControl.AdvancedHMI.Controls.OutputType.SetFalse : m_CommComponent.Write(m_PLCAddressClick, 0)
Case MfgControl.AdvancedHMI.Controls.OutputType.Toggle
Dim CurrentValue As Boolean
CurrentValue = m_CommComponent.Read(m_PLCAddressClick, 1)(0)
If CurrentValue Then
m_CommComponent.Write(m_PLCAddressClick, 0)
Else
m_CommComponent.Write(m_PLCAddressClick, 1)
End If
Case Else
End Select
If tmrError.Enabled Then
tmrError.Enabled = False
End If
Catch ex As Exception
DisplayError("WRITE FAILED!" & ex.Message)
End Try
End If
Me.Invalidate()
End Sub
'****************************
'* Event - Mouse Up
'****************************
Private Sub MomentaryButton_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseUp
If m_PLCAddressClick <> "" And Enabled AndAlso m_CommComponent IsNot Nothing Then
Try
Select Case OutputType
Case MfgControl.AdvancedHMI.Controls.OutputType.MomentarySet : m_CommComponent.Write(m_PLCAddressClick, 0)
Case MfgControl.AdvancedHMI.Controls.OutputType.MomentaryReset : m_CommComponent.Write(m_PLCAddressClick, 1)
End Select
Catch ex As Exception
DisplayError("WRITE FAILED!" & ex.Message)
End Try
End If
Me.Invalidate()
End Sub
'********************************************************************
'* When an instance is added to the form, set the comm component
'* property. If a comm component does not exist, add one to the form
'********************************************************************
Protected Overrides Sub OnCreateControl()
MyBase.OnCreateControl()
If Me.DesignMode Then
'********************************************************
'* Search for AdvancedHMIDrivers.IComComponent component in parent form
'* If one exists, set the client of this component to it
'********************************************************
Dim i = 0
Dim j As Integer = Me.Parent.Site.Container.Components.Count
While m_CommComponent Is Nothing And i < j
If Me.Parent.Site.Container.Components(i).GetType.GetInterface("AdvancedHMIDrivers.IComComponent") IsNot Nothing Then m_CommComponent = CType(Me.Parent.Site.Container.Components(i), AdvancedHMIDrivers.IComComponent)
i += 1
End While
'************************************************
'* If no comm component was found, then add one and
'* point the CommComponent property to it
'*********************************************
If m_CommComponent Is Nothing Then
Me.Parent.Site.Container.Add(New AdvancedHMIDrivers.EthernetIPforPLCSLCMicroCom)
m_CommComponent = CType(Me.Parent.Site.Container.Components(Me.Parent.Site.Container.Components.Count - 1), AdvancedHMIDrivers.IComComponent)
End If
Else
SubscribeToCommDriver()
End If
End Sub
#End Region
#Region "Constructor/Destructor"
'****************************************************************
'* UserControl overrides dispose to clean up the component list.
'****************************************************************
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing Then
If SubScriptions IsNot Nothing Then
SubScriptions.dispose()
End If
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
#End Region
#Region "Subscribing and PLC data receiving"
Private SubScriptions As SubscriptionHandler
'**************************************************
'* Subscribe to addresses in the Comm(PLC) Driver
'**************************************************
Private Sub SubscribeToCommDriver()
If Not DesignMode And IsHandleCreated Then
'* Create a subscription handler object
If SubScriptions Is Nothing Then
SubScriptions = New SubscriptionHandler
SubScriptions.CommComponent = m_CommComponent
AddHandler SubScriptions.DisplayError, AddressOf DisplaySubscribeError
End If
'* Check through the properties looking for PLCAddress***, then see if the suffix matches an existing property
Dim p() As Reflection.PropertyInfo = Me.GetType().GetProperties
For i As Integer = 0 To p.Length - 1
'* Does this property start with "PLCAddress"?
If p(i).Name.IndexOf("PLCAddress", StringComparison.CurrentCultureIgnoreCase) = 0 Then
'* Get the property value
Dim PLCAddress As String = p(i).GetValue(Me, Nothing)
If PLCAddress <> "" Then
'* Get the text in the name after PLCAddress
Dim PropertyToWrite As String = p(i).Name.Substring(10)
Dim j As Integer = 0
'* See if there is a corresponding property with the extracted name
While j < p.Length AndAlso p(j).Name <> PropertyToWrite
j += 1
End While
'* If the proprty was found, then subscribe to the PLC Address
If j < p.Length Then
SubScriptions.SubscribeTo(PLCAddress, AddressOf PolledDataReturned, PropertyToWrite)
End If
End If
End If
Next
End If
End Sub
'***************************************
'* Call backs for returned data
'***************************************
Private OriginalText As String
Private Sub PolledDataReturned(ByVal sender As Object, ByVal e As SubscriptionHandlerEventArgs)
If e.PLCComEventArgs.ErrorId = 0 Then
Try
If e.PLCComEventArgs.Values IsNot Nothing AndAlso e.PLCComEventArgs.Values.Count > 0 Then
'* 13-NOV-14 Changed from Convert.ChangeType to CTypeDynamic because a 0/1 would not convert to boolean
'* Write the value to the property that came from the end of the PLCAddress... property name
Me.GetType().GetProperty(e.SubscriptionDetail.PropertyNameToSet). _
SetValue(Me, CTypeDynamic(e.PLCComEventArgs.Values(0), _
Me.GetType().GetProperty(e.SubscriptionDetail.PropertyNameToSet).PropertyType), Nothing)
End If
Catch ex As Exception
DisplayError("INVALID VALUE!" & ex.Message)
End Try
Else
DisplayError("Com Error " & e.PLCComEventArgs.ErrorId & "." & e.PLCComEventArgs.ErrorMessage)
End If
End Sub
Private Sub DisplaySubscribeError(ByVal sender As Object, ByVal e As MfgControl.AdvancedHMI.Drivers.Common.PlcComEventArgs)
DisplayError(e.ErrorMessage)
End Sub
#End Region
#Region "Error Display"
'********************************************************
'* Show an error via the text property for a short time
'********************************************************
Private WithEvents ErrorDisplayTime As System.Windows.Forms.Timer
Private Sub DisplayError(ByVal ErrorMessage As String)
If ErrorDisplayTime Is Nothing Then
ErrorDisplayTime = New System.Windows.Forms.Timer
AddHandler ErrorDisplayTime.Tick, AddressOf ErrorDisplay_Tick
ErrorDisplayTime.Interval = 5000
End If
'* Save the text to return to
If Not ErrorDisplayTime.Enabled Then
OriginalText = Me.Text
End If
ErrorDisplayTime.Enabled = True
Me.Text = ErrorMessage
End Sub
'**************************************************************************************
'* Return the text back to its original after displaying the error for a few seconds.
'**************************************************************************************
Private Sub ErrorDisplay_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ErrorDisplayTime.Tick
Text = OriginalText
If ErrorDisplayTime IsNot Nothing Then
ErrorDisplayTime.Enabled = False
ErrorDisplayTime.Dispose()
ErrorDisplayTime = Nothing
End If
End Sub
#End Region
End Class
|
bgreer5050/AdvancedHMI
|
AdvancedHMIControls/Controls/PneumaticBallValve.vb
|
Visual Basic
|
mit
| 14,398
|
Namespace Performance
Public Module _Shared
Private _FallbackPath As String = ""
Private _PerformanceLogPath As String = ""
Private _ThreadLevel As New Concurrent.ConcurrentDictionary(Of Integer, Integer)
Private _ThreadMessages As New Concurrent.ConcurrentDictionary(Of Integer, List(Of String))
Public Property ThreadLevel(threadID As Integer) As Integer
Get
Return _ThreadLevel.GetOrAdd(threadID, 0)
End Get
Set(value As Integer)
_ThreadLevel.AddOrUpdate(threadID, value, Function() value)
End Set
End Property
Private ReadOnly Property ThreadMessages(threadID As Integer) As List(Of String)
Get
Return _ThreadMessages.GetOrAdd(threadID, New List(Of String))
End Get
End Property
Public Function StartCounterDB([class] As String, method As String, other As String) As PerfCounter
Return StartCounter(False, "{0} -> {1}. {2}".FormatWith([class], method, other))
End Function
Public Function StartCounter([class] As String, method As String, other As String) As PerfCounter
Return StartCounter("{0} -> {1}. {2}".FormatWith([class], method, other))
End Function
Public Function StartCounter([class] As String, method As String) As PerfCounter
Return StartCounter("{0} -> {1}".FormatWith([class], method))
End Function
Public Function StartCounter(message As String) As PerfCounter
Return StartCounter(True, message)
End Function
Private Function StartCounter(incrementLevel As Boolean, message As String) As PerfCounter
If Not Settings.PerformanceCounters Then
Return Nothing
End If
Return New PerfCounter(incrementLevel, message)
End Function
Friend Function GetPerformanceLogPath() As String
If String.IsNullOrEmpty(_PerformanceLogPath) OrElse Not IO.Directory.Exists(_PerformanceLogPath) Then
If String.IsNullOrEmpty(Settings.PerformanceLogPath) Then
_PerformanceLogPath = GetFallbackPath()
Else
_PerformanceLogPath = Settings.PerformanceLogPath
End If
Dim LogDirectory As String = IO.Path.GetDirectoryName(_PerformanceLogPath)
If Not IO.Directory.Exists(LogDirectory) Then
IO.Directory.CreateDirectory(LogDirectory)
End If
End If
Return _PerformanceLogPath
End Function
Private Function GetFallbackPath() As String
If String.IsNullOrEmpty(_FallbackPath) Then
_FallbackPath = "{0}Performance.log".FormatWith(Settings.Directories.AppDataCompanyProductVersion)
End If
Return _FallbackPath
End Function
Friend Sub IncrementLevel(threadID As Integer)
ThreadLevel(threadID) += 1
End Sub
Friend Sub LogCounter(incrementLevel As Boolean, message As String, seconds As Double, threadID As Integer)
If incrementLevel Then
ThreadLevel(threadID) -= 1
End If
If ThreadLevel(threadID) = 0 Then
If ThreadMessages(threadID).Count <= 0 Then
WritePerfCounter("Thread ID: {0}{1}{2}{3:N3}s: {4}".FormatWith(threadID, vbNewLine, Settings.DefaultIndent, seconds, message))
Else
Dim Lines As String = "Thread ID: {0}".FormatWith(threadID)
For Each CurrentMessage As String In ThreadMessages(threadID).ToList
Lines = "{0}{1}{2}".FormatWith(Lines, vbNewLine, CurrentMessage)
Next
WritePerfCounter("{0}{1}{2:N3}s: {3}".FormatWith(Lines, vbNewLine, seconds, message))
End If
ThreadMessages(threadID).Clear()
Else
Dim Lines As String = "{0:N3}s: {1}".FormatWith(seconds, message)
For I As Integer = 0 To ThreadLevel(threadID)
Lines = "{0}{1}".FormatWith(Settings.DefaultIndent, Lines)
Next
ThreadMessages(threadID).Add(Lines)
End If
End Sub
Private Sub WritePerfCounter(message As String)
If Not Settings.PerformanceCounters Then
Return
End If
IORoutines.WriteToFile(True, True, GetPerformanceLogPath(), True, message)
frmPerformance.Instance.AddMessage("{0}{1}".FormatWith(message, vbNewLine))
End Sub
End Module
End Namespace
|
nublet/DMS
|
DMS.Base/Performance/Performance.vb
|
Visual Basic
|
mit
| 4,744
|
Option Strict Off
Option Explicit On
Imports System.Xml
Imports System.Collections
Imports System.Web.Configuration
Imports System.Data.SqlClient
Imports System.Web.HttpUtility
Imports VB = Microsoft.VisualBasic
Imports System.IO
Imports Protean.Tools.Xml
Imports Protean.Tools.Xml.XmlNodeState
Imports System
Imports System.Text
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Imports System.Collections.Generic
Partial Public Class Cms
Partial Public Class Cart
#Region "JSON Actions"
Public Class JSONActions
Inherits API.JsonActions
Public Event OnError(ByVal sender As Object, ByVal e As Protean.Tools.Errors.ErrorEventArgs)
Private Const mcModuleName As String = "Eonic.Cart.JSONActions"
Private Const cContactType As String = "Venue"
Private moLmsConfig As System.Collections.Specialized.NameValueCollection = WebConfigurationManager.GetWebApplicationSection("protean/lms")
Private myWeb As Protean.Cms
Private myCart As Protean.Cms.Cart
Public Sub New()
Dim ctest As String = "this constructor is being hit" 'for testing
myWeb = New Protean.Cms()
myWeb.InitializeVariables()
myWeb.Open()
myCart = New Protean.Cms.Cart(myWeb)
End Sub
Private Function updateCartforJSON(CartXml As XmlElement) As XmlElement
Dim newstring As String = CartXml.InnerXml.Replace("<Item ", "<CartItem ").Replace("</Item>", "</CartItem>")
CartXml.InnerXml = newstring
Dim cartItems As XmlElement = myWeb.moPageXml.CreateElement("CartItems")
Dim ItemCount As Int16 = 0
For Each oItem As XmlElement In CartXml.SelectNodes("Order/CartItem")
cartItems.AppendChild(oItem)
ItemCount = ItemCount + 1
Next
If ItemCount = 1 Then
Dim oItems As XmlElement = myWeb.moPageXml.CreateElement("CartItem")
oItems.SetAttribute("dummy", "true")
cartItems.AppendChild(oItems)
End If
CartXml.FirstChild.AppendChild(cartItems)
TidyHtmltoCData(CartXml)
Return CartXml
End Function
Public Function GetCart(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Try
Dim cProcessInfo As String = ""
Dim CartXml As XmlElement = myWeb.moCart.CreateCartElement(myWeb.moPageXml)
myCart.GetCart(CartXml.FirstChild)
CartXml = updateCartforJSON(CartXml)
Dim jsonString As String = Newtonsoft.Json.JsonConvert.SerializeXmlNode(CartXml, Newtonsoft.Json.Formatting.Indented)
jsonString = jsonString.Replace("""@", """_")
jsonString = jsonString.Replace("#cdata-section", "cDataValue")
Return jsonString
'persist cart
myCart.close()
Catch ex As Exception
RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "GetCart", ex, ""))
Return ex.Message
End Try
End Function
Public Function AddItems(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Try
Dim cProcessInfo As String = ""
'jsonObject("artId")
' myCart.AddItem()
'Output the new cart
Dim oDoc As New XmlDocument
Dim CartXml As XmlElement = myWeb.moCart.CreateCartElement(myWeb.moPageXml)
If myCart.mnCartId < 1 Then
myCart.CreateNewCart(CartXml, "Order")
If myCart.mcItemOrderType <> "" Then
myCart.mmcOrderType = myCart.mcItemOrderType
Else
myCart.mmcOrderType = ""
End If
myCart.mnProcessId = 1
End If
Dim item As Newtonsoft.Json.Linq.JObject
If (jObj("Item") IsNot Nothing) Then
For Each item In jObj("Item")
Dim bUnique As Boolean = False
Dim cProductPrice As Double = 0
Dim sProductName As String = ""
Dim bPackegingRequired As Boolean = False
Dim sOverideURL As String = ""
If item.ContainsKey("UniqueProduct") Then
bUnique = item("UniqueProduct")
End If
If item.ContainsKey("itemPrice") Then
cProductPrice = item("itemPrice")
End If
If item.ContainsKey("productName") Then
sProductName = item("productName")
End If
If item.ContainsKey("url") Then
sOverideURL = item("url")
End If
myCart.AddItem(item("contentId"), item("qty"), Nothing, sProductName, cProductPrice, "", bUnique, sOverideURL)
Next
End If
'Output the new cart
myCart.GetCart(CartXml.FirstChild)
CartXml = updateCartforJSON(CartXml)
'persist cart
myCart.close()
Dim jsonString As String = Newtonsoft.Json.JsonConvert.SerializeXmlNode(CartXml, Newtonsoft.Json.Formatting.None)
jsonString = jsonString.Replace("""@", """_")
jsonString = jsonString.Replace("#cdata-section", "cDataValue")
Return jsonString
Catch ex As Exception
RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "GetCart", ex, ""))
Return ex.Message
End Try
End Function
Public Function RemoveItems(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Try
Dim cProcessInfo As String = ""
Dim ItemCount As Long = 1
Dim item As Newtonsoft.Json.Linq.JObject
For Each item In jObj("Item")
If item("contentId") Is Nothing Then
ItemCount = myCart.RemoveItem(item("itemId"), 0)
Else
ItemCount = myCart.RemoveItem(0, item("contentId"))
End If
Next
If ItemCount = 0 Then
myCart.QuitCart()
myCart.EndSession()
End If
'Output the new cart
Dim CartXml As XmlElement = myWeb.moCart.CreateCartElement(myWeb.moPageXml)
myCart.GetCart(CartXml.FirstChild)
'persist cart
myCart.close()
CartXml = updateCartforJSON(CartXml)
Dim jsonString As String = Newtonsoft.Json.JsonConvert.SerializeXmlNode(CartXml, Newtonsoft.Json.Formatting.Indented)
jsonString = jsonString.Replace("""@", """_")
jsonString = jsonString.Replace("#cdata-section", "cDataValue")
Return jsonString
Catch ex As Exception
RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "GetCart", ex, ""))
Return ex.Message
End Try
End Function
Public Function UpdateItems(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Try
Dim cProcessInfo As String = ""
Dim ItemCount As Long = 1
Dim item As Newtonsoft.Json.Linq.JObject
Dim CartXml As XmlElement = myWeb.moCart.CreateCartElement(myWeb.moPageXml)
If myCart.mnCartId < 1 Then
myCart.CreateNewCart(CartXml)
If myCart.mcItemOrderType <> "" Then
myCart.mmcOrderType = myCart.mcItemOrderType
Else
myCart.mmcOrderType = ""
End If
myCart.mnProcessId = 1
End If
For Each item In jObj("Item")
If item("contentId") Is Nothing Then
If item("qty") = "0" Then
ItemCount = myCart.RemoveItem(item("itemId"), 0)
Else
ItemCount = myCart.UpdateItem(item("itemId"), 0, item("qty"), item("skipPackaging"))
End If
Else
If item("qty") = "0" Then
ItemCount = myCart.RemoveItem(0, item("contentId"))
Else
ItemCount = myCart.UpdateItem(0, item("contentId"), item("qty"))
End If
End If
Next
If ItemCount = 0 Then
myCart.QuitCart()
myCart.EndSession()
End If
'Output the new cart
myCart.GetCart(CartXml.FirstChild)
'persist cart
myCart.close()
CartXml = updateCartforJSON(CartXml)
Dim jsonString As String = Newtonsoft.Json.JsonConvert.SerializeXmlNode(CartXml, Newtonsoft.Json.Formatting.Indented)
jsonString = jsonString.Replace("""@", """_")
jsonString = jsonString.Replace("#cdata-section", "cDataValue")
Return jsonString
Catch ex As Exception
RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "GetCart", ex, ""))
Return ex.Message
End Try
End Function
Public Function GetShippingOptions(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Try
Dim cProcessInfo As String = ""
Dim dsShippingOption As DataSet
Dim cDestinationCountry As String = ""
' call it from cart
Dim nAmount As Long
Dim nQuantity As Long
Dim nWeight As Long
If (jObj IsNot Nothing) Then
If jObj("country") <> "" Then
cDestinationCountry = jObj("country")
Else
cDestinationCountry = myCart.moCartConfig("DefaultDeliveryCountry")
End If
If jObj("qty") = "0" Then
nQuantity = jObj("qty")
Else
nQuantity = 0
End If
If jObj("amount") = "0" Then
nAmount = jObj("amount")
Else
nAmount = 0
End If
If jObj("Weight") = "0" Then
nWeight = jObj("Weight")
Else
nWeight = 0
End If
End If
dsShippingOption = myCart.getValidShippingOptionsDS(cDestinationCountry, nAmount, nQuantity, nWeight)
Dim ShippingOptionXml As String = dsShippingOption.GetXml()
Dim xmlDoc As New XmlDocument
xmlDoc.LoadXml(ShippingOptionXml)
Dim jsonString As String = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xmlDoc.DocumentElement, Newtonsoft.Json.Formatting.Indented)
Return jsonString.Replace("""@", """_")
Catch ex As Exception
RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "GetShippingOptions", ex, ""))
Return ex.Message
End Try
End Function
Public Function UpdatedCartShippingOptions(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Try
Dim cProcessInfo As String = ""
Dim ShipOptKey As String
Dim json As Newtonsoft.Json.Linq.JObject = jObj
ShipOptKey = json.SelectToken("ShipOptKey")
myCart.updateGCgetValidShippingOptionsDS(ShipOptKey)
Dim CartXml As XmlElement = myWeb.moCart.CreateCartElement(myWeb.moPageXml)
myCart.GetCart(CartXml.FirstChild)
'persist cart
myCart.close()
CartXml = updateCartforJSON(CartXml)
Dim jsonString As String = Newtonsoft.Json.JsonConvert.SerializeXmlNode(CartXml, Newtonsoft.Json.Formatting.Indented)
jsonString = jsonString.Replace("""@", """_")
jsonString = jsonString.Replace("#cdata-section", "cDataValue")
Return jsonString
Catch ex As Exception
RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "UpdatedCartShippingOptions", ex, ""))
Return ex.Message
End Try
End Function
Public Function UpdateDeliveryOptionByCountry(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Dim country As String = jObj("country")
Dim CartXml As XmlElement = myWeb.moCart.CreateCartElement(myWeb.moPageXml)
'check config setting here so that it will take order option which is optional.
Dim cOrderofDeliveryOption As String = myCart.moCartConfig("ShippingTotalIsNotZero")
cOrderofDeliveryOption = myCart.updateDeliveryOptionByCountry(CartXml.FirstChild, country, cOrderofDeliveryOption)
If (myCart.CheckPromocodeAppliedForDelivery() <> "") Then
RemoveDiscountCode(myApi, jObj)
'this will remove discount section from address page in vuemain.js
cOrderofDeliveryOption = cOrderofDeliveryOption & "#1"
Else
cOrderofDeliveryOption = cOrderofDeliveryOption & "#0"
End If
Return cOrderofDeliveryOption
End Function
Public Function GetContacts(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Try
Dim JsonResult As String = ""
Dim dirId As String = jObj("dirId")
'Dim offerId As String = jObj("offerId")
Dim userContacts = myWeb.moDbHelper.GetUserContactsXml(dirId)
JsonResult = JsonConvert.SerializeObject(userContacts)
Return JsonResult
Catch ex As Exception
RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "GetLocations", ex, ""))
Return ex.Message
End Try
End Function
Public Function GetContactForm(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Dim nId As Integer
Try
Dim JsonResult As String = ""
Dim oDdoc = New XmlDocument()
Dim contactId As Integer = jObj("contactId")
Dim cAddressType As String = jObj("addressType")
Dim oForm As xForm = myCart.contactXform(cAddressType, "", "")
Dim oFormXml As String = oForm.Instance.SelectSingleNode("tblCartContact").OuterXml
oDdoc.LoadXml(oFormXml)
JsonResult = JsonConvert.SerializeXmlNode(oDdoc)
Return JsonResult
Catch ex As Exception
RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "GetLocations", ex, ""))
Return ex.Message
End Try
Return JsonConvert.ToString(nId)
End Function
Public Function SetContact(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Dim nId As Integer
Try
Dim supplierId As Integer = jObj("supplierId")
Dim contact As Contact = jObj("venue").ToObject(Of Contact)()
contact.cContactType = cContactType
contact.cContactForeignRef = String.Format("SUP-{0}", supplierId)
nId = myWeb.moDbHelper.SetContact(contact)
Catch ex As Exception
RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "AddContact", ex, ""))
Return ex.Message
End Try
Return JsonConvert.ToString(nId)
End Function
Public Function DeleteContact(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Dim isSuccess As Boolean
Try
Dim cContactKey As String = jObj("nContactKey")
isSuccess = myWeb.moDbHelper.DeleteContact(cContactKey)
Catch ex As Exception
RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "DeleteContact", ex, ""))
Return ex.Message
End Try
Return JsonConvert.ToString(isSuccess)
End Function
Public Function AddProductOption(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Try
Dim CartXml As XmlElement = myWeb.moCart.CreateCartElement(myWeb.moPageXml)
'myCart.GetCart(CartXml.FirstChild)
'add product option
myCart.AddProductOption(jObj)
'myCart.UpdatePackagingANdDeliveryType()
myCart.GetCart(CartXml.FirstChild)
'persist cart
myCart.close()
CartXml = updateCartforJSON(CartXml)
Dim jsonString As String = Newtonsoft.Json.JsonConvert.SerializeXmlNode(CartXml, Newtonsoft.Json.Formatting.Indented)
jsonString = jsonString.Replace("""@", """_")
jsonString = jsonString.Replace("#cdata-section", "cDataValue")
Return jsonString
Catch ex As Exception
End Try
End Function
Public Function AddDiscountCode(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Try
Dim CartXml As XmlElement = myWeb.moCart.CreateCartElement(myWeb.moPageXml)
Dim strMessage As String = String.Empty
Dim jsonString As String = String.Empty
If Not (jObj("Code") Is Nothing) Then
strMessage = myCart.moDiscount.AddDiscountCode(jObj("Code"))
If (strMessage = jObj("Code")) Then
myCart.GetCart(CartXml.FirstChild)
'persist cart
myCart.close()
CartXml = updateCartforJSON(CartXml)
'jsonString = Newtonsoft.Json.JsonConvert.SerializeXmlNode(CartXml, Newtonsoft.Json.Formatting.Indented)
'jsonString = jsonString.Replace("""@", """_")
'jsonString = jsonString.Replace("#cdata-section", "cDataValue")
End If
If (strMessage <> String.Empty) Then
Return strMessage
End If
End If
Return strMessage
Catch ex As Exception
End Try
End Function
Public Function RemoveDiscountCode(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Try
Dim CartXml As XmlElement = myWeb.moCart.CreateCartElement(myWeb.moPageXml)
myCart.moDiscount.RemoveDiscountCode()
myCart.GetCart(CartXml.FirstChild)
'persist cart
myCart.close()
CartXml = updateCartforJSON(CartXml)
Dim jsonString As String = Newtonsoft.Json.JsonConvert.SerializeXmlNode(CartXml, Newtonsoft.Json.Formatting.Indented)
jsonString = jsonString.Replace("""@", """_")
jsonString = jsonString.Replace("#cdata-section", "cDataValue")
Return jsonString
Catch ex As Exception
End Try
End Function
Public Function UpdateCartProductPrice(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Try
Dim cProcessInfo As String = ""
Dim cProductPrice As Double = CDbl(jObj("itemPrice"))
Dim cartItemId As Long = CLng(jObj("itemId"))
If myWeb.moDbHelper.checkUserRole(myCart.moCartConfig("AllowPriceUpdateRole"), "Role", CLng("0" & myWeb.moSession("nUserId"))) Then
myCart.UpdateItemPrice(cartItemId, cProductPrice)
End If
Dim CartXml As XmlElement = myWeb.moCart.CreateCartElement(myWeb.moPageXml)
myCart.GetCart(CartXml.FirstChild)
'persist cart
myCart.close()
CartXml = updateCartforJSON(CartXml)
Dim jsonString As String = Newtonsoft.Json.JsonConvert.SerializeXmlNode(CartXml, Newtonsoft.Json.Formatting.Indented)
jsonString = jsonString.Replace("""@", """_")
jsonString = jsonString.Replace("#cdata-section", "cDataValue")
Return jsonString
Catch ex As Exception
Return ex.Message
End Try
End Function
Public Function AddCartAddress(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject, ByVal contactType As String, ByVal cartId As Int32, Optional ByVal emailAddress As String = "", Optional ByVal telphone As String = "") As Int32
Try
Dim contact As New Contact()
Dim nId As Int32
If (jObj IsNot Nothing) Then
contact.cContactEmail = emailAddress
contact.cContactTel = telphone
contact.cContactType = contactType
contact.nContactCartId = cartId
If (jObj("Forename") IsNot Nothing) Then
contact.cContactFirstName = jObj("Forename")
End If
If (jObj("Surname") IsNot Nothing) Then
contact.cContactLastName = jObj("Surname")
End If
If (jObj("Title") IsNot Nothing) Then
contact.cContactTitle = jObj("Title")
End If
If (jObj("cContactCompany") IsNot Nothing) Then
contact.cContactCompany = jObj("cContactCompany")
End If
If (jObj("CartId") IsNot Nothing) Then
contact.nContactCartId = cartId
End If
If (jObj("Address1") IsNot Nothing) Then
contact.cContactAddress = jObj("Address1")
End If
If (jObj("Address2") IsNot Nothing) Then
contact.cContactAddress = contact.cContactAddress + " " + jObj("Address2").ToString()
End If
If (jObj("City") IsNot Nothing) Then
contact.cContactCity = jObj("City")
End If
If (jObj("State") IsNot Nothing) Then
contact.cContactState = jObj("State")
End If
If (jObj("Country") IsNot Nothing) Then
contact.cContactCountry = jObj("Country")
End If
If (jObj("Postcode") IsNot Nothing) Then
contact.cContactZip = jObj("Postcode")
End If
If (jObj("Fax") IsNot Nothing) Then
contact.cContactFax = jObj("Fax")
End If
contact.cContactName = contact.cContactTitle + " " + contact.cContactFirstName + " " + contact.cContactLastName
End If
nId = myWeb.moDbHelper.SetContact(contact)
Return nId
Catch ex As Exception
Return ex.Message
End Try
End Function
Public Function SubmitAddressForm(ByRef myApi As Protean.API, ByRef jObj As Dictionary(Of String, String)) As String
Try
'Submit the address form as per Cart > Apply > Billing
myCart.mcCartCmd = "Billing"
myCart.apply()
'myCart.addressSubProcess(oElmt, "Billing Address")
'' then set processID = 5 if we have shipping set otherwise processID = 4
''confirm myCart.moCartXml.SelectSingleNode("Order/Shipping") node in xml
'assigning gateway
If (myApi.moRequest("ewSubmitClone_cartBillAddress") IsNot Nothing) Then
myCart.mcPaymentMethod = myApi.moRequest("ewSubmitClone_cartBillAddress")
Else
Return "Gateway not provided"
End If
If myCart.mcPaymentMethod <> "" And Not myCart.moCartXml.SelectSingleNode("Order/Contact[@type='Shipping Address']") Is Nothing Then
myCart.mnProcessId = 4
ElseIf myCart.mcPaymentMethod <> "" And Not myCart.moCartXml.SelectSingleNode("Order/Contact[@type='Billing Address']") Is Nothing Then
myCart.mnProcessId = 5
End If
'paymentform
Dim moPageXml As XmlDocument
moPageXml = myWeb.moPageXml
Dim oCartXML As XmlDocument = moPageXml
Dim oElmt As XmlElement
Dim oContentElmt As XmlElement
oContentElmt = myCart.CreateCartElement(oCartXML)
oElmt = oContentElmt.FirstChild
myCart.GetCart(oElmt)
Dim oPayProv As New Providers.Payment.BaseProvider(myWeb, myCart.mcPaymentMethod)
Dim ccPaymentXform As Protean.xForm = New Protean.xForm(myWeb.msException)
ccPaymentXform = oPayProv.Activities.GetPaymentForm(myWeb, myCart, oElmt)
moPageXml.SelectSingleNode("/Page/Contents").AppendChild(ccPaymentXform.moXformElmt)
' moPageXml.CreateElement("/Page/Contents").AppendChild(ccPaymentXform.moXformElmt)
Return "true"
Catch ex As Exception
Return ex.Message
End Try
End Function
Public Function CompleteOrder(ByVal sProviderName As String, ByVal nCartId As Integer, ByVal sAuthNo As String, ByVal dAmount As Double, ByVal ShippingType As String) As String
Try
Dim oXml As XmlDocument = New XmlDocument
Dim cShippingType As String = String.Empty
Dim oDetailXml As XmlElement = oXml.CreateElement("Response")
Dim CartXml As XmlElement = myWeb.moCart.CreateCartElement(myWeb.moPageXml)
addNewTextNode("AuthCode", oDetailXml, sAuthNo)
If (ShippingType = String.Empty) Then
myCart.updateGCgetValidShippingOptionsDS(65)
Else
Dim shippingXml As XmlElement = myCart.makeShippingOptionsXML()
' Dim nShipOptKey As Integer = Convert.ToInt32(shippingXml.SelectSingleNode("Method[cShipOptName='" + ShippingType + "']").SelectSingleNode("nShipOptKey").InnerText)
myCart.updateGCgetValidShippingOptionsDS(ShippingType)
End If
myWeb.moDbHelper.savePayment(nCartId, 0, sProviderName, sAuthNo, sProviderName, oDetailXml, DateTime.Now, False, dAmount)
myWeb.moDbHelper.SaveCartStatus(nCartId, cartProcess.Complete)
myCart.GetCart(CartXml.FirstChild)
myCart.purchaseActions(CartXml)
'persist cart
myCart.close()
CartXml = updateCartforJSON(CartXml)
Dim jsonString As String = Newtonsoft.Json.JsonConvert.SerializeXmlNode(CartXml, Newtonsoft.Json.Formatting.Indented)
jsonString = jsonString.Replace("""@", """_")
jsonString = jsonString.Replace("#cdata-section", "cDataValue")
Return jsonString
Catch ex As Exception
Return ex.Message
End Try
End Function
''' <summary>
''' Refund order
''' </summary>
''' <param name="myApi"></param>
''' <param name="jObj"></param>
''' <returns></returns>
Public Function RefundOrder(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Try
Dim bIsAuthorized As Boolean = False
Dim validGroup = IIf(jObj("validGroup") IsNot Nothing, CStr(jObj("validGroup")), "")
bIsAuthorized = ValidateAPICall(myWeb, validGroup)
If bIsAuthorized = False Then Return "Error -Authorization Failed"
Dim oCart As New Cart(myWeb)
oCart.moPageXml = myWeb.moPageXml
Dim nProviderReference = IIf(jObj("nProviderReference") IsNot Nothing, CType(jObj("nProviderReference"), Long), 0)
Dim nAmount = IIf(jObj("nAmount") IsNot Nothing, CDec(jObj("nAmount")), "0")
Dim cProviderName = IIf(jObj("sProviderName") IsNot Nothing, CStr(jObj("sProviderName")), "")
Dim cRefundPaymentReceipt = ""
If cProviderName <> "" Then
Dim oPayProv As New Providers.Payment.BaseProvider(myWeb, cProviderName)
cRefundPaymentReceipt = oPayProv.Activities.RefundPayment(nProviderReference, nAmount)
Dim xmlDoc As New XmlDocument
Dim xmlResponse As XmlElement = xmlDoc.CreateElement("Response")
xmlResponse.InnerXml = "<RefundPaymentReceiptId>" & cRefundPaymentReceipt & "</RefundPaymentReceiptId>"
xmlDoc.LoadXml(xmlResponse.InnerXml.ToString())
Dim josResult As String = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xmlDoc.DocumentElement, Newtonsoft.Json.Formatting.Indented)
josResult = josResult.Replace("""@", """_")
josResult = josResult.Replace("#cdata-section", "cDataValue")
Return josResult
End If
Catch ex As Exception
RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "RefundOrder", ex, ""))
Return "Error " + ex.Message
End Try
End Function
''' <summary>
''' Process New payment
''' </summary>
''' <param name="myApi"></param>
''' <param name="jObj"></param>
''' <returns></returns>
Public Function ProcessNewPayment(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Try
Dim bIsAuthorized As Boolean = False
Dim cValidGroup = IIf(jObj("validGroup") IsNot Nothing, CStr(jObj("validGroup")), "")
bIsAuthorized = ValidateAPICall(myWeb, cValidGroup)
If bIsAuthorized = False Then Return "Error -Authorization Failed"
Dim oCart As New Cart(myWeb)
oCart.moPageXml = myWeb.moPageXml
Dim cProviderName = IIf(jObj("sProviderName") IsNot Nothing, CStr(jObj("sProviderName")), "")
Dim nOrderId = IIf(jObj("orderId") IsNot Nothing, CStr(jObj("orderId")), "0")
Dim nAmount = IIf(jObj("amount") IsNot Nothing, CDec(jObj("amount")), "0")
Dim cCardNumber = IIf(jObj("cardNumber") IsNot Nothing, CStr(jObj("cardNumber")), "")
Dim cCV2 = IIf(jObj("cV2") IsNot Nothing, CStr(jObj("cV2")), "")
Dim dExpiryDate = IIf(jObj("expiryDate") IsNot Nothing, CStr(jObj("expiryDate")), "")
Dim dStartDate = IIf(jObj("startDate") IsNot Nothing, CStr(jObj("startDate")), "")
Dim cCardHolderName = IIf(jObj("cardHolderName") IsNot Nothing, CStr(jObj("cardHolderName")), "")
Dim cAddress1 = IIf(jObj("address1") IsNot Nothing, CStr(jObj("address1")), "")
Dim cAddress2 = IIf(jObj("address2") IsNot Nothing, CStr(jObj("address2")), "")
Dim cTown = IIf(jObj("town") IsNot Nothing, CStr(jObj("town")), "")
Dim cPostCode = IIf(jObj("postCode") IsNot Nothing, CStr(jObj("postCode")), "")
Dim cPaymentReceipt = ""
Dim josResult As String = ""
If cProviderName <> "" Then
Dim oPayProv As New Providers.Payment.BaseProvider(myWeb, cProviderName)
cPaymentReceipt = oPayProv.Activities.ProcessNewPayment(nOrderId, nAmount, cCardNumber, cCV2, dExpiryDate, dStartDate, cCardHolderName, cAddress1, cAddress2, cTown, cPostCode, cValidGroup)
Dim xmlDoc As New XmlDocument
Dim xmlResponse As XmlElement = xmlDoc.CreateElement("Response")
xmlResponse.InnerXml = "<PaymentReceiptId>" & cPaymentReceipt & "</PaymentReceiptId>"
xmlDoc.LoadXml(xmlResponse.InnerXml.ToString())
josResult = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xmlDoc.DocumentElement, Newtonsoft.Json.Formatting.Indented)
josResult = josResult.Replace("""@", """_")
josResult = josResult.Replace("#cdata-section", "cDataValue")
End If
Return josResult
Catch ex As Exception
RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "ProcessNewPayment", ex, ""))
Return "Error" 'ex.Message
End Try
End Function
Public Function CreatePaypalOrder(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Try
Dim cProcessInfo As String = ""
Dim josResult As String = "SUCCESS"
'input params
' Dim cProductPrice As Double = CDbl(jObj("orderId"))
Try
'if we receive any response from judopay pass it from PaymentReceipt
'response should contain payment related all references like result, status, cardtoken, receiptId etc
'validate if weather success or declined in Judopay.cs and redirect accordingly
Dim myWeb As Protean.Cms = New Protean.Cms()
Dim oPayProv As New Providers.Payment.BaseProvider(myWeb, "PayPalCommerce")
oPayProv.Activities.CreateOrder(True).Wait()
Catch ex As Exception
josResult = "ERROR"
End Try
Return josResult
Catch ex As Exception
Return ex.Message
End Try
End Function
Public Function GetPaypalOrder(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Try
Dim cProcessInfo As String = ""
Dim josResult As String = "SUCCESS"
'input params
Dim cOrderId As Double = CDbl(jObj("orderId"))
Try
Dim myWeb As Protean.Cms = New Protean.Cms()
Dim oPayProv As New Providers.Payment.BaseProvider(myWeb, "PayPalCommerce")
oPayProv.Activities.GetOrder(cOrderId).Wait()
oPayProv.Activities.CaptureOrder(cOrderId, True).Wait()
oPayProv.Activities.AuthorizeOrder(cOrderId, True).Wait()
Catch ex As Exception
josResult = "ERROR"
End Try
Return josResult
Catch ex As Exception
Return ex.Message
End Try
End Function
Public Function CapturePaypalOrder(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As String
Try
Dim cProcessInfo As String = ""
Dim josResult As String = "SUCCESS"
'input params
Dim cOrderId As Double = CDbl(jObj("orderId"))
Try
Dim myWeb As Protean.Cms = New Protean.Cms()
Dim oPayProv As New Providers.Payment.BaseProvider(myWeb, "PayPalCommerce")
oPayProv.Activities.CaptureOrder(cOrderId, True).Wait()
Catch ex As Exception
josResult = "ERROR"
End Try
Return josResult
Catch ex As Exception
Return ex.Message
End Try
End Function
Public Function SaveToSellerNotes(ByRef myApi As Protean.API, ByRef jObj As Newtonsoft.Json.Linq.JObject) As Boolean
Try
Dim cProcessInfo As String = ""
Dim cResponse As String = jObj.ToString()
Dim sSql As String
Dim myWeb As Protean.Cms = New Protean.Cms()
Dim oCart As Protean.Cms.Cart = New Cart(myWeb)
Dim message As String = cResponse.Replace("{", "")
Dim errorMessage As String = message.Replace("}", "")
'Update Seller Notes:
sSql = "select * from tblCartOrder where nCartOrderKey = " & oCart.mnCartId
Dim oDs As DataSet
Dim oRow As DataRow
oDs = myWeb.moDbHelper.getDataSetForUpdate(sSql, "Order", "Cart")
For Each oRow In oDs.Tables("Order").Rows
oRow("cSellerNotes") = oRow("cSellerNotes") & vbLf & Today & " " & TimeOfDay & ": changed to: (Payment Failed) " & vbLf & "comment: " & " Declined " & vbLf & "Full Response:' " & errorMessage & "'"
Next
myWeb.moDbHelper.updateDataset(oDs, "Order")
Return True
Catch ex As Exception
RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "SaveToSellerNotes", ex, ""))
Return ex.Message
End Try
End Function
End Class
#End Region
End Class
End Class
|
Eonic/EonicWeb5
|
Assemblies/ProteanCMS/CMS/Cart/Cart.JSONActions.vb
|
Visual Basic
|
apache-2.0
| 41,493
|
Imports BVSoftware.Bvc5.Core
Imports System.Collections.ObjectModel
Imports System.Linq
Imports System.Collections.Generic
Partial Class BVModules_CategoryTemplates_Scopelist_Grid_With_Subs_Grid_Product_Category
Inherits BaseStoreCategoryPage
Private _AllCats As Collection(Of Catalog.Category) = Nothing
Dim pricingWorkflow As BusinessRules.Workflow = Nothing
Protected Sub Page_PreInit1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
Me.MasterPageFile = PersonalizationServices.GetSafeMasterPage("Category.master")
Me.BlockId = "D2D63F6A-2480-42a1-A593-FCFA83A2C8B8"
End Sub
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
If LocalCategory.PreContentColumnId <> String.Empty Then
Me.PreContentColumn.ColumnID = LocalCategory.PreContentColumnId
Me.PreContentColumn.LoadColumn()
End If
If LocalCategory.PostContentColumnId <> String.Empty Then
Me.PostContentColumn.ColumnID = LocalCategory.PostContentColumnId
Me.PostContentColumn.LoadColumn()
End If
End Sub
Protected Sub PageLoad(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If LocalCategory IsNot Nothing Then
Dim itemsPerPage As Integer = Me.SettingsManager.GetIntegerSetting("ItemsPerPage")
If itemsPerPage = 0 Then
itemsPerPage = 6
End If
Pager1.ItemsPerPage = itemsPerPage
Pager2.ItemsPerPage = itemsPerPage
PopulateCategoryInfo()
Dim rowCount As Integer = 0
pricingWorkflow = BusinessRules.Workflow.FindByName("Product Pricing")
Dim allDisplayProducts As Collection(Of Catalog.Product) = Nothing
Dim displayProducts As List(Of Catalog.Product) = Nothing
If Me.ProductSearchCriteria IsNot Nothing Then
allDisplayProducts = LocalCategory.FindAllProductsByCriteria(Me.ProductSearchCriteria, Me.SortOrder, WebAppSettings.DisableInventory, False, 0, 100, rowCount)
Else
allDisplayProducts = LocalCategory.FindAllProducts(Me.SortOrder, WebAppSettings.DisableInventory, False, 0, 100, rowCount)
End If
Select Case LocalCategory.DisplaySortOrder
Case 1
displayProducts = allDisplayProducts.OrderByDescending(Function(p) p.IsInStock).ThenByDescending(Function(p) p.CreationDate).Skip(Pager1.CurrentRow).Take(Pager1.ItemsPerPage).ToList()
Case Else
displayProducts = allDisplayProducts.Skip(Pager1.CurrentRow).Take(Pager1.ItemsPerPage).ToList()
End Select
If displayProducts.Count > 0 Then
categorygridtemplate.Visible = True
Else
categorygridtemplate.Visible = False
End If
Select Case LocalCategory.DisplaySortOrder
Case 1
Me.DataList1.DataSource = displayProducts
Case Else
Me.DataList1.DataSource = displayProducts
End Select
Me.DataList1.DataBind()
Pager1.RowCount = rowCount
Pager2.RowCount = rowCount
End If
End Sub
Public Sub PopulateCategoryInfo()
' Page Title
If LocalCategory.MetaTitle.Trim.Length > 0 Then
Me.PageTitle = LocalCategory.MetaTitle
Else
Me.PageTitle = LocalCategory.Name
End If
' Meta Keywords
If LocalCategory.MetaKeywords.Trim.Length > 0 Then
CType(Page, BaseStorePage).MetaKeywords = LocalCategory.MetaKeywords
Else
CType(Page, BaseStorePage).MetaKeywords = LocalCategory.Name
End If
' Meta Description
'If LocalCategory.MetaDescription.Trim.Length > 0 Then
' CType(Page, BaseStorePage).MetaDescription = LocalCategory.MetaDescription
' If (Pager1.CurrentPage > 1) Then
' CType(Page, BaseStorePage).MetaDescription += " Page " & Pager1.CurrentPage.ToString()
' Me.PageTitle += " Page " & Pager1.CurrentPage.ToString()
' End If
'End If
' Meta Description
If LocalCategory.MetaDescription.Trim.Length > 0 Then
CType(Page, BaseStorePage).MetaDescription = LocalCategory.MetaDescription
End If
' Title
If LocalCategory.ShowTitle = False Then
Me.lblTitle.Visible = False
Me.lblTitle3.Visible = False
Else
Me.lblTitle.Visible = True
Me.lblTitle.Text = LocalCategory.Name
startH1.Visible = True
endH1.Visible = True
Me.lblTitle3.Visible = True
Me.lblTitle3.Text = "Best Selling " & LocalCategory.Name
End If
If LocalCategory.BannerImageUrl.Trim.Length > 0 Then
Me.BannerImage.Visible = True
Me.BannerImage.ImageUrl = Page.ResolveUrl(Utilities.ImageHelper.GetValidImage(LocalCategory.BannerImageUrl, True))
Me.BannerImage.AlternateText = LocalCategory.Name
Else
Me.BannerImage.Visible = False
End If
'Description
If LocalCategory.Description.Trim.Length > 0 Then
Dim s As StringBuilder = New StringBuilder()
s.Append(LocalCategory.Description)
s.Replace("<a", "<a class='RightBlockHeading'")
s.Replace("<ul>", "<ul class='desc'>")
Dim str As String = s.ToString()
If (str.Length > 600) Then
Dim indexOfFullStop As Integer = str.IndexOf(". ", 600)
If indexOfFullStop <> -1 Then
Me.DescriptionLiteral.Text = str.Substring(0, indexOfFullStop + 2)
Me.DescriptionLiteralHidden.Text = str.Substring(indexOfFullStop + 2, str.Length - (indexOfFullStop + 2))
Else
Me.DescriptionLiteral.Text = str
Me.ShowHideButton.Style("display") = "none"
End If
Else
Me.DescriptionLiteral.Text = str
Me.ShowHideButton.Style("display") = "none"
End If
Else
Me.ShowHideButton.Style("display") = "none"
Me.DescriptionLiteral.Text = String.Empty
End If
End Sub
Protected Sub DataList1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles DataList1.ItemDataBound
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
Dim p As Catalog.Product = CType(e.Item.DataItem, Catalog.Product)
If p IsNot Nothing Then
Dim destinationLink As String = Utilities.UrlRewriter.BuildUrlForProduct(p, Me.Page.Request)
Dim imageUrl As String
imageUrl = Page.ResolveUrl(Utilities.ImageHelper.GetValidImage(p.ImageFileSmall, True))
Dim anchor As HtmlAnchor = DirectCast(e.Item.FindControl("recordimageanchor"), HtmlAnchor)
anchor.HRef = destinationLink
anchor.Title = p.ProductName
anchor.InnerHtml = "<img src=""" & ResolveUrl(imageUrl) & """ width=""181"" height=""106"" />" & p.ProductName
'Dim ProductImage As HtmlImage = DirectCast(e.Item.FindControl("ProductImage"), HtmlImage)
'ProductImage.Src = imageUrl
'ProductImage.Alt = p.ProductName & " " & p.Sku
' Force Image Size
'ViewUtilities.ForceImageSize(ProductImage, p.ImageFileSmall, ViewUtilities.Sizes.Small, Me.Page)
If p.ProductTypeId <> String.Empty AndAlso p.ManufacturerId <> String.Empty Then
Dim t As Catalog.ProductType = Catalog.ProductType.FindByBvin(p.ProductTypeId)
Dim m As Contacts.Manufacturer = Contacts.Manufacturer.FindByBvin(p.ManufacturerId)
If t IsNot Nothing And m IsNot Nothing Then
Dim litReview As Web.UI.WebControls.Literal = DirectCast(e.Item.FindControl("reviewtitlefield"), Literal)
If litReview IsNot Nothing Then
litReview.Text = m.DisplayName & " " & t.ProductTypeName & " Review"
End If
End If
End If
'to display stock status to client
Dim lblStockStatusGrid As Label = DirectCast(e.Item.FindControl("lblStockStatusGrid"), Label)
If p.IsInStock Then
lblStockStatusGrid.Text = "In Stock"
Else
lblStockStatusGrid.Text = "Back Order"
End If
Dim ltlPrice As Literal
ltlPrice = DirectCast(e.Item.FindControl("ltlPrice"), Literal)
ltlPrice.Text = p.GetSitePriceForDisplay(0D, pricingWorkflow)
Else
Dim NameAnchor As HtmlAnchor = DirectCast(e.Item.FindControl("NameAnchor"), HtmlAnchor)
NameAnchor.InnerHtml = "Product Could Not Be Located."
End If
End If
End Sub
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
If Pager1.Visible Then
Select Case DirectCast(Me.SettingsManager.GetIntegerSetting("PagerMode"), Controls.PagerModes)
Case BVSoftware.Bvc5.Core.Controls.PagerModes.Top
Pager1.Visible = True
Pager2.Visible = False
Case BVSoftware.Bvc5.Core.Controls.PagerModes.Bottom
Pager1.Visible = False
Pager2.Visible = True
Case BVSoftware.Bvc5.Core.Controls.PagerModes.Both
Pager1.Visible = True
Pager2.Visible = True
End Select
End If
End Sub
End Class
|
ajaydex/Scopelist_2015
|
BVModules/CategoryTemplates/Scopelist Grid With Subs Grid Product/Category.aspx.vb
|
Visual Basic
|
apache-2.0
| 10,057
|
'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.
Public Class GenerateReport
Inherits ESRI.ArcGIS.Desktop.AddIns.Button
Public Sub New()
End Sub
Protected Overrides Sub OnClick()
My.ArcMap.Application.CurrentTool = Nothing
Dim exportReport As ExportReport = New ExportReport()
exportReport.Show()
End Sub
Protected Overrides Sub OnUpdate()
Enabled = My.ArcMap.Application IsNot Nothing
End Sub
End Class
|
Esri/arcobjects-sdk-community-samples
|
Net/Map/AddInReportManager/VBNET/GenerateReport.vb
|
Visual Basic
|
apache-2.0
| 957
|
' 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.Completion
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Completion.SuggestionMode
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Tags
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion
<ExportLanguageServiceFactory(GetType(CompletionService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicCompletionServiceFactory
Implements ILanguageServiceFactory
Public Function CreateLanguageService(languageServices As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService
Return New VisualBasicCompletionService(languageServices.WorkspaceServices.Workspace)
End Function
End Class
Partial Friend Class VisualBasicCompletionService
Inherits CommonCompletionService
Private ReadOnly _completionProviders As ImmutableArray(Of CompletionProvider) = ImmutableArray.Create(Of CompletionProvider)(
New KeywordCompletionProvider(),
New SymbolCompletionProvider(),
New ObjectInitializerCompletionProvider(),
New ObjectCreationCompletionProvider(),
New EnumCompletionProvider(),
New NamedParameterCompletionProvider(),
New VisualBasicSuggestionModeCompletionProvider(),
New ImplementsClauseCompletionProvider(),
New HandlesClauseCompletionProvider(),
New PartialTypeCompletionProvider(),
New CrefCompletionProvider(),
New CompletionListTagCompletionProvider(),
New OverrideCompletionProvider(),
New XmlDocCommentCompletionProvider(),
New InternalsVisibleToCompletionProvider()
)
Private ReadOnly _workspace As Workspace
Public Sub New(workspace As Workspace,
Optional exclusiveProviders As ImmutableArray(Of CompletionProvider)? = Nothing)
MyBase.New(workspace, exclusiveProviders)
_workspace = workspace
End Sub
Public Overrides ReadOnly Property Language As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
Private _latestRules As CompletionRules = CompletionRules.Create(
dismissIfEmpty:=True,
dismissIfLastCharacterDeleted:=True,
defaultCommitCharacters:=CompletionRules.Default.DefaultCommitCharacters,
defaultEnterKeyRule:=EnterKeyRule.Always)
Public Overrides Function GetRules() As CompletionRules
Dim options = _workspace.Options
' Although EnterKeyBehavior is a per-language setting, the meaning of an unset setting (Default) differs between C# And VB
' In VB the default means Always to maintain previous behavior
Dim enterRule = options.GetOption(CompletionOptions.EnterKeyBehavior, LanguageNames.VisualBasic)
Dim snippetsRule = options.GetOption(CompletionOptions.SnippetsBehavior, LanguageNames.VisualBasic)
If enterRule = EnterKeyRule.Default Then
enterRule = EnterKeyRule.Always
End If
If snippetsRule = SnippetsRule.Default Then
snippetsRule = SnippetsRule.IncludeAfterTypingIdentifierQuestionTab
End If
Dim newRules = _latestRules.WithDefaultEnterKeyRule(enterRule).
WithSnippetsRule(snippetsRule)
Interlocked.Exchange(_latestRules, newRules)
Return newRules
End Function
Protected Overrides Function GetBuiltInProviders() As ImmutableArray(Of CompletionProvider)
Return _completionProviders
End Function
Protected Overrides Function GetBetterItem(item As CompletionItem, existingItem As CompletionItem) As CompletionItem
' If one Is a keyword, And the other Is some other item that inserts the same text as the keyword,
' keep the keyword (VB only), unless the other item is preselected
If IsKeywordItem(existingItem) AndAlso existingItem.Rules.MatchPriority >= item.Rules.MatchPriority Then
Return existingItem
End If
Return MyBase.GetBetterItem(item, existingItem)
End Function
Protected Overrides Function ItemsMatch(item As CompletionItem, existingItem As CompletionItem) As Boolean
If Not MyBase.ItemsMatch(item, existingItem) Then
Return False
End If
' DevDiv 957450 Normally, we want to show items with the same display text And
' different glyphs. That way, the we won't hide user - defined symbols that happen
' to match a keyword (Like Select). However, we want to avoid showing the keyword
' for an intrinsic right next to the item for the corresponding symbol.
' Therefore, if a keyword claims to represent an "intrinsic" item, we'll ignore
' the glyph when matching.
Dim keywordCompletionItem = If(IsKeywordItem(existingItem), existingItem, If(IsKeywordItem(item), item, Nothing))
If keywordCompletionItem IsNot Nothing AndAlso keywordCompletionItem.Tags.Contains(WellKnownTags.Intrinsic) Then
Dim otherItem = If(keywordCompletionItem Is item, existingItem, item)
Dim changeText = GetChangeText(otherItem)
If changeText = keywordCompletionItem.DisplayText Then
Return True
Else
Return False
End If
End If
Return item.Tags = existingItem.Tags OrElse Enumerable.SequenceEqual(item.Tags, existingItem.Tags)
End Function
Private Function GetChangeText(item As CompletionItem) As String
Dim provider = TryCast(GetProvider(item), CommonCompletionProvider)
If provider IsNot Nothing Then
' TODO: Document Is Not available in this code path.. what about providers that need to reconstruct information before producing text?
Dim result = provider.GetTextChangeAsync(Nothing, item, Nothing, CancellationToken.None).Result
If result IsNot Nothing Then
Return result.Value.NewText
End If
End If
Return item.DisplayText
End Function
Public Overrides Function GetDefaultCompletionListSpan(text As SourceText, caretPosition As Integer) As TextSpan
Return CompletionUtilities.GetCompletionItemSpan(text, caretPosition)
End Function
Friend Overrides Function SupportsTriggerOnDeletion(options As OptionSet) As Boolean
' If the option is null (i.e. default) or 'true', then we want to trigger completion.
' Only if the option is false do we not want to trigger.
Dim opt = options.GetOption(CompletionOptions.TriggerOnDeletion, Me.Language)
Return If(opt = False, False, True)
End Function
End Class
End Namespace
|
DustinCampbell/roslyn
|
src/Features/VisualBasic/Portable/Completion/VisualBasicCompletionService.vb
|
Visual Basic
|
apache-2.0
| 7,528
|
' Copyright 2013, Google Inc. All Rights Reserved.
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
' Author: api.anash@gmail.com (Anash P. Oommen)
Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201306
Imports System
Imports System.Collections.Generic
Imports System.IO
Namespace Google.Api.Ads.AdWords.Examples.VB.v201306
''' <summary>
''' This code example gets all videos and images. To upload video, see
''' http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454.
''' To upload image, run UploadImage.vb.
'''
''' Tags: MediaService.get
''' </summary>
Public Class GetAllVideosAndImages
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 GetAllVideosAndImages
Console.WriteLine(codeExample.Description)
Try
codeExample.Run(New AdWordsUser)
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 gets all videos and images. To upload video, see " & _
"http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. To " & _
"upload image, run UploadImage.vb."
End Get
End Property
''' <summary>
''' Runs the code example.
''' </summary>
''' <param name="user">The AdWords user.</param>
Public Sub Run(ByVal user As AdWordsUser)
' Get the MediaService.
Dim mediaService As MediaService = user.GetService(AdWordsService.v201306.MediaService)
' Create the video selector.
Dim selector As New Selector
selector.fields = New String() {"MediaId", "Width", "Height", "MimeType"}
' Set the filter.
Dim predicate As New Predicate
predicate.operator = PredicateOperator.IN
predicate.field = "Type"
predicate.values = New String() {MediaMediaType.VIDEO.ToString(), _
MediaMediaType.IMAGE.ToString()}
selector.predicates = New Predicate() {predicate}
' Select selector paging.
selector.paging = New Paging
Dim offset As Integer = 0
Dim pageSize As Integer = 500
Dim page As New MediaPage
Try
Do
selector.paging.startIndex = offset
selector.paging.numberResults = pageSize
page = mediaService.get(selector)
If ((Not page Is Nothing) AndAlso (Not page.entries Is Nothing)) Then
Dim i As Integer = offset
For Each media As Media In page.entries
If TypeOf media Is Video Then
Dim video As Video = media
Console.WriteLine("{0}) Video with id '{1}' and name '{2}' was found.", _
i, video.mediaId, video.name)
ElseIf TypeOf media Is Image Then
Dim image As Image = media
Dim dimensions As Dictionary(Of MediaSize, Dimensions) = _
CreateMediaDimensionMap(image.dimensions)
Console.WriteLine("{0}) Image with id '{1}', dimensions '{2}x{3}', and MIME " & _
"type '{4}' was found.", i, image.mediaId, dimensions(MediaSize.FULL).width, _
dimensions(MediaSize.FULL).height, image.mimeType)
End If
i = i + 1
Next
End If
offset = offset + pageSize
Loop While (offset < page.totalNumEntries)
Console.WriteLine("Number of images and videos found: {0}", page.totalNumEntries)
Catch ex As Exception
Throw New System.ApplicationException("Failed to get images and videos.", ex)
End Try
End Sub
''' <summary>
''' Converts an array of Media_Size_DimensionsMapEntry into a dictionary.
''' </summary>
''' <param name="dimensions">The array of Media_Size_DimensionsMapEntry to be
''' converted into a dictionary.</param>
''' <returns>A dictionary with key as MediaSize, and value as Dimensions.
''' </returns>
Private Function CreateMediaDimensionMap(ByVal dimensions As Media_Size_DimensionsMapEntry()) _
As Dictionary(Of MediaSize, Dimensions)
Dim mediaMap As New Dictionary(Of MediaSize, Dimensions)
For Each dimension As Media_Size_DimensionsMapEntry In dimensions
mediaMap.Add(dimension.key, dimension.value)
Next
Return mediaMap
End Function
End Class
End Namespace
|
akilb/googleads-adwords-dotnet-lib
|
examples/adxbuyer/VB/v201306/Miscellaneous/GetAllVideosAndImages.vb
|
Visual Basic
|
apache-2.0
| 5,312
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.ConvertToInterpolatedString
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertToInterpolatedString
Public Class ConvertConcatenationToInterpolatedStringTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New VisualBasicConvertConcatenationToInterpolatedStringRefactoringProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestMissingOnSimpleString() As Task
Await TestMissingInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = [||]""string""
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithStringOnLeft() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = [||]""string"" & 1
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""string{1}""
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestRightSideOfString() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = ""string""[||] & 1
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""string{1}""
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithStringOnRight() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = 1 & [||]""string""
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""{1}string""
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithComplexExpressionOnLeft() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = 1 + 2 & [||]""string""
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""{1 + 2}string""
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithTrivia1() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = 1 + 2 & [||]""string"" ' trailing trivia
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""{1 + 2}string"" ' trailing trivia
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithComplexExpressions() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = 1 + 2 & [||]""string"" & 3 & 4
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""{1 + 2}string{3}{4}""
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithEscapes1() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = ""\r"" & 2 & [||]""string"" & 3 & ""\n""
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""\r{2}string{3}\n""
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithEscapes2() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = ""\\r"" & 2 & [||]""string"" & 3 & ""\\n""
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""\\r{2}string{3}\\n""
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithOverloadedOperator() As Task
Await TestInRegularAndScriptAsync(
"
public class D
public shared operator&(D d, string s) as boolean
end operator
public shared operator&(string s, D d) as boolean
end operator
end class
Public Class C
Sub M()
dim d as D = nothing
dim v = 1 & [||]""string"" & d
End Sub
End Class",
"
public class D
public shared operator&(D d, string s) as boolean
end operator
public shared operator&(string s, D d) as boolean
end operator
end class
Public Class C
Sub M()
dim d as D = nothing
dim v = $""{1}string"" & d
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithOverloadedOperator2() As Task
Await TestMissingInRegularAndScriptAsync(
"
public class D
public shared operator&(D d, string s) as boolean
end operator
public shared operator&(string s, D d) as boolean
end operator
end class
Public Class C
Sub M()
dim d as D = nothing
dim v = d & [||]""string"" & 1
End Sub
End Class")
End Function
<WorkItem(16820, "https://github.com/dotnet/roslyn/issues/16820")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithMultipleStringConcatinations() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = ""A"" & 1 & [||]""B"" & ""C""
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""A{1}BC""
End Sub
End Class")
End Function
<WorkItem(16820, "https://github.com/dotnet/roslyn/issues/16820")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithMultipleStringConcatinations2() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = ""A"" & [||]""B"" & ""C"" & 1
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""ABC{1}""
End Sub
End Class")
End Function
<WorkItem(16820, "https://github.com/dotnet/roslyn/issues/16820")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithMultipleStringConcatinations3() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = ""A"" & 1 & [||]""B"" & ""C"" & 2 & ""D"" & ""E"" & ""F"" & 3
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""A{1}BC{2}DEF{3}""
End Sub
End Class")
End Function
<WorkItem(23536, "https://github.com/dotnet/roslyn/issues/23536")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithStringLiteralWithBraces() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = 1 & [||]""{string}""
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""{1}{{string}}""
End Sub
End Class")
End Function
<WorkItem(23536, "https://github.com/dotnet/roslyn/issues/23536")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithStringLiteralWithDoubleBraces() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = 1 & [||]""{{string}}""
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""{1}{{{{string}}}}""
End Sub
End Class")
End Function
<WorkItem(23536, "https://github.com/dotnet/roslyn/issues/23536")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithMultipleStringLiteralsWithBraces() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = ""{"" & 1 & [||]""}""
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""{{{1}}}""
End Sub
End Class")
End Function
<WorkItem(16981, "https://github.com/dotnet/roslyn/issues/16981")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestMissingWithSelectionOnEntireToBeInterpolatedString() As Task
Await TestMissingInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = [|""string"" & 1|]
End Sub
End Class")
End Function
<WorkItem(16981, "https://github.com/dotnet/roslyn/issues/16981")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestMissingWithSelectionOnPartOfToBeInterpolatedString() As Task
Await TestMissingInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = [|""string"" & 1|] & ""string""
End Sub
End Class")
End Function
<WorkItem(16981, "https://github.com/dotnet/roslyn/issues/16981")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestMissingWithSelectionExceedingToBeInterpolatedString() As Task
Await TestMissingInRegularAndScriptAsync(
"
Public Class C
Sub M()
[|dim v = ""string"" & 1|]
End Sub
End Class")
End Function
<WorkItem(16981, "https://github.com/dotnet/roslyn/issues/16981")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithCaretBeforeNonStringToken() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = [||]3 & ""string"" & 1 & ""string""
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""{3}string{1}string""
End Sub
End Class")
End Function
<WorkItem(16981, "https://github.com/dotnet/roslyn/issues/16981")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithCaretAfterNonStringToken() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = 3[||] & ""string"" & 1 & ""string""
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""{3}string{1}string""
End Sub
End Class")
End Function
<WorkItem(16981, "https://github.com/dotnet/roslyn/issues/16981")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithCaretBeforeAmpersandToken() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = 3 [||]& ""string"" & 1 & ""string""
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""{3}string{1}string""
End Sub
End Class")
End Function
<WorkItem(16981, "https://github.com/dotnet/roslyn/issues/16981")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithCaretAfterAmpersandToken() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = 3 &[||] ""string"" & 1 & ""string""
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""{3}string{1}string""
End Sub
End Class")
End Function
<WorkItem(16981, "https://github.com/dotnet/roslyn/issues/16981")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithCaretBeforeLastAmpersandToken() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = 3 & ""string"" & 1 [||]& ""string""
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""{3}string{1}string""
End Sub
End Class")
End Function
<WorkItem(16981, "https://github.com/dotnet/roslyn/issues/16981")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithCaretAfterLastAmpersandToken() As Task
Await TestInRegularAndScriptAsync(
"
Public Class C
Sub M()
dim v = 3 & ""string"" & 1 &[||] ""string""
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""{3}string{1}string""
End Sub
End Class")
End Function
End Class
End Namespace
|
MichalStrehovsky/roslyn
|
src/EditorFeatures/VisualBasicTest/ConvertToInterpolatedString/ConvertConcatenationToInterpolatedStringTests.vb
|
Visual Basic
|
apache-2.0
| 13,195
|
' 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.Xml.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.Commands
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Operations
Imports Moq
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.LineCommit
Public Class CommitOnEnterTests
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub CommitAfterEnterOnSimpleStatement()
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>[|
imports System$$|]
</Document>
</Project>
</Workspace>
AssertCommitsStatement(test, expectCommit:=True)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub NoCommitAfterEnterAfterQuery()
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()
Dim x = From x In { 1, 2, 3 }$$
End Sub
End Class
</Document>
</Project>
</Workspace>
AssertCommitsStatement(test, expectCommit:=False)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
<WorkItem(531421)>
Public Sub NoCommitAfterExplicitLineContinuation()
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()
M() _$$
End Sub
End Class
</Document>
</Project>
</Workspace>
AssertCommitsStatement(test, expectCommit:=False)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
<WorkItem(531421)>
Public Sub CommitAfterBlankLineFollowingExplicitLineContinuation()
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()[|
M() _
|]$$
End Sub
End Class
</Document>
</Project>
</Workspace>
AssertCommitsStatement(test, expectCommit:=True)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub CommitAfterDeclaration()
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>[|
Class C$$
Sub M()
m() _
End Sub
End Class|]
</Document>
</Project>
</Workspace>
AssertCommitsStatement(test, expectCommit:=True)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub CommitAfterEndConstruct()
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>[|
Class C
Sub M()
m() _
End Sub
End Class$$|]
</Document>
</Project>
</Workspace>
AssertCommitsStatement(test, expectCommit:=True, usedSemantics:=False)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub CommitAfterBlankLineAfterQuery()
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()[|
Dim x = From x In { 1, 2, 3 }
$$|]
End Sub
End Class
</Document>
</Project>
</Workspace>
AssertCommitsStatement(test, expectCommit:=True)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub NoCommitAfterEnterAfterPartialExpression()
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()
Dim x = 1 + $$
End Sub
End Class
</Document>
</Project>
</Workspace>
AssertCommitsStatement(test, expectCommit:=False)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub CommitAfterEnterAfterPartialExpression()
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()
Dim x = 1 + [|
$$|]
End Sub
End Class
</Document>
</Project>
</Workspace>
AssertCommitsStatement(test, expectCommit:=True)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub CommitAfterEnterOnBlankLine()
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()[|
$$|]
End Sub
End Class
</Document>
</Project>
</Workspace>
AssertCommitsStatement(test, expectCommit:=True)
End Sub
<WpfFact>
<WorkItem(539451)>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub CommitAfterColon()
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()[|
Call M() : $$|]
End Sub
End Class
</Document>
</Project>
</Workspace>
AssertCommitsStatement(test, expectCommit:=True)
End Sub
<WpfFact>
<WorkItem(539408)>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub CommitAfterConstDirective()
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>[|
#const foo = 42$$|]
</Document>
</Project>
</Workspace>
AssertCommitsStatement(test, expectCommit:=True)
End Sub
<WpfFact>
<WorkItem(539408)>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub CommitAfterComment()
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>[|
rem Hello World$$|]
</Document>
</Project>
</Workspace>
AssertCommitsStatement(test, expectCommit:=True)
End Sub
<WpfFact>
<WorkItem(544372)>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub UndoAfterCommitOnBlankLine()
Using testData = New CommitTestData(<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>$$
</Document>
</Project>
</Workspace>)
testData.CommandHandler.ExecuteCommand(New ReturnKeyCommandArgs(testData.View, testData.Buffer), Sub() testData.EditorOperations.InsertNewLine())
testData.UndoHistory.Undo(count:=1)
Assert.Equal(0, testData.View.Caret.Position.BufferPosition.GetContainingLine().LineNumber)
End Using
End Sub
<WpfFact>
<WorkItem(540210)>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub CommitAfterThenTouchingThen()
' Note that the source we are starting this test with is *not* syntactically correct,
' but by having the extra "End If" we guarantee the ending code will be as if End
' Construct generation happened.
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()[|
If True Then$$ q = Sub()
End Sub|]
End If
End Sub
End Class
</Document>
</Project>
</Workspace>
AssertCommitsStatement(test, expectCommit:=True)
End Sub
<WpfFact>
<WorkItem(540210)>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub CommitAfterThenTouchingStatement()
' Note that the source we are starting this test with is *not* syntactically correct,
' but by having the extra "End If" we guarantee the ending code will be as if End
' Construct generation happened.
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub M()[|
If True Then $$q = Sub()
End Sub|]
End If
End Sub
End Class
</Document>
</Project>
</Workspace>
AssertCommitsStatement(test, expectCommit:=True)
End Sub
<WpfFact>
<WorkItem(530463)>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub CommitAfterPropertyStatement()
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class A
Property P1[|
Property P2$$|]
Property P3
End Class
Class E
Property P1
End Class
</Document>
</Project>
</Workspace>
AssertCommitsStatement(test, expectCommit:=True)
End Sub
<WpfFact>
<WorkItem(986168)>
<Trait(Traits.Feature, Traits.Features.LineCommit)>
Public Sub DontCommitInsideStringLiteral()
Dim test = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module M
Sub M()
Dim s = "$$
Console.WriteLine("The method or operation is not implemented.")
End Sub
End Module
</Document>
</Project>
</Workspace>
AssertCommitsStatement(test, expectCommit:=False)
End Sub
Private Sub AssertCommitsStatement(test As XElement, expectCommit As Boolean, Optional usedSemantics As Boolean = True)
Using testData = New CommitTestData(test)
Dim lineNumber = testData.View.Caret.Position.BufferPosition.GetContainingLine().LineNumber
testData.CommandHandler.ExecuteCommand(New ReturnKeyCommandArgs(testData.View, testData.Buffer), Sub() testData.EditorOperations.InsertNewLine())
testData.AssertHadCommit(expectCommit)
If expectCommit Then
testData.AssertUsedSemantics(usedSemantics)
End If
Assert.Equal(lineNumber + 1, testData.View.Caret.Position.BufferPosition.GetContainingLine().LineNumber)
End Using
End Sub
End Class
End Namespace
|
oocx/roslyn
|
src/EditorFeatures/VisualBasicTest/LineCommit/CommitOnEnterTests.vb
|
Visual Basic
|
apache-2.0
| 12,815
|
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports System.Collections.Immutable
Namespace Performance
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Public Class StringBuilderInLoopAnalyzer
Inherits DiagnosticAnalyzer
Public Shared ReadOnly Id As String = DiagnosticId.StringBuilderInLoop.ToDiagnosticId()
Public Const Title As String = "Don't concatenate strings in loops"
Public Const MessageFormat As String = "Don't concatenate '{0}' in a loop."
Public Const Category As String = SupportedCategories.Performance
Public Const Description As String = "Do not concatenate a string in a loop. It will allocate a lot of memory. Use a StringBuilder instead. It will require less allocation, less garbage collection work, less CPU cycles, and less overall time."
Protected Shared Rule As DiagnosticDescriptor = New DiagnosticDescriptor(
Id,
Title,
MessageFormat,
Category,
DiagnosticSeverity.Warning,
isEnabledByDefault:=True,
description:=Description,
helpLinkUri:=HelpLink.ForDiagnostic(DiagnosticId.StringBuilderInLoop))
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) = ImmutableArray.Create(Rule)
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf Analyze, SyntaxKind.AddAssignmentStatement, SyntaxKind.ConcatenateAssignmentStatement, SyntaxKind.SimpleAssignmentStatement)
End Sub
Private Sub Analyze(context As SyntaxNodeAnalysisContext)
If (context.IsGenerated()) Then Return
Dim assignmentExpression = DirectCast(context.Node, AssignmentStatementSyntax)
Dim loopStatment = assignmentExpression.FirstAncestorOfType(
GetType(WhileBlockSyntax),
GetType(ForBlockSyntax),
GetType(ForEachBlockSyntax),
GetType(DoLoopBlockSyntax))
If loopStatment Is Nothing Then Exit Sub
Dim semanticModel = context.SemanticModel
Dim symbolForAssignment = semanticModel.GetSymbolInfo(assignmentExpression.Left).Symbol
If symbolForAssignment Is Nothing Then Exit Sub
If TypeOf symbolForAssignment Is IPropertySymbol AndAlso DirectCast(symbolForAssignment, IPropertySymbol).Type.Name <> "String" Then Exit Sub
If TypeOf symbolForAssignment Is IFieldSymbol AndAlso DirectCast(symbolForAssignment, IFieldSymbol).Type.Name <> "String" Then Exit Sub
If TypeOf symbolForAssignment Is IParameterSymbol AndAlso DirectCast(symbolForAssignment, IParameterSymbol).Type.Name <> "String" Then Exit Sub
If TypeOf symbolForAssignment Is ILocalSymbol Then
Dim localSymbol = DirectCast(symbolForAssignment, ILocalSymbol)
If localSymbol.Type.SpecialType <> SpecialType.System_String Then Exit Sub
' Don't analyze string declared within the loop.
If loopStatment.DescendantTokens(localSymbol.DeclaringSyntaxReferences(0).Span).Any() Then Exit Sub
End If
If assignmentExpression.IsKind(SyntaxKind.SimpleAssignmentStatement) Then
If (Not If(assignmentExpression.Right?.IsKind(SyntaxKind.AddExpression), False)) Then Exit Sub
Dim identifierOnConcatExpression = TryCast(DirectCast(assignmentExpression.Right, BinaryExpressionSyntax).Left, IdentifierNameSyntax)
If identifierOnConcatExpression Is Nothing Then Exit Sub
Dim symbolOnIdentifierOnConcatExpression = semanticModel.GetSymbolInfo(identifierOnConcatExpression).Symbol
If Not symbolForAssignment.Equals(symbolOnIdentifierOnConcatExpression) Then Exit Sub
ElseIf Not assignmentExpression.IsKind(SyntaxKind.AddAssignmentStatement) AndAlso
Not assignmentExpression.IsKind(SyntaxKind.ConcatenateAssignmentStatement) Then
Exit Sub
End If
Dim assignmentExpressionLeft = assignmentExpression.Left.ToString()
Dim props = New Dictionary(Of String, String) From {{NameOf(assignmentExpressionLeft), assignmentExpressionLeft}}.ToImmutableDictionary()
Dim diag = Diagnostic.Create(Rule, assignmentExpression.GetLocation(), props, assignmentExpression.Left.ToString())
context.ReportDiagnostic(diag)
End Sub
End Class
End Namespace
|
adraut/code-cracker
|
src/VisualBasic/CodeCracker/Performance/StringBuilderInLoopAnalyzer.vb
|
Visual Basic
|
apache-2.0
| 4,642
|
' 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.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports System.Runtime.InteropServices
Imports System.Threading
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Binder used for interiors of documentation comment for binding 'cref' attribute value
''' </summary>
Partial Friend NotInheritable Class DocumentationCommentCrefBinder
Inherits DocumentationCommentBinder
Public Sub New(containingBinder As Binder, commentedSymbol As Symbol)
MyBase.New(containingBinder, commentedSymbol)
End Sub
Private _typeParameterBinder As TypeParametersBinder
Private Function GetOrCreateTypeParametersAwareBinder(typeParameters As Dictionary(Of String, CrefTypeParameterSymbol)) As Binder
If Me._typeParameterBinder Is Nothing Then
Interlocked.CompareExchange(Me._typeParameterBinder, New TypeParametersBinder(Me, typeParameters), Nothing)
End If
#If DEBUG Then
' Make sure the type parameter symbols are the same
Debug.Assert(typeParameters.Count = Me._typeParameterBinder._typeParameters.Count)
For Each kvp In typeParameters
Debug.Assert(kvp.Value.Equals(Me._typeParameterBinder._typeParameters(kvp.Key)))
Next
#End If
Return Me._typeParameterBinder
End Function
Private Function HasTrailingSkippedTokensAndShouldReportError(reference As CrefReferenceSyntax) As Boolean
Dim triviaList As SyntaxTriviaList = reference.GetTrailingTrivia()
For Each trivia In triviaList
If trivia.Kind = SyntaxKind.SkippedTokensTrivia Then
' ignore those, represending VB intrinsic types
Dim name As TypeSyntax = reference.Name
If name.Kind = SyntaxKind.IdentifierName Then
Dim identifier As SyntaxToken = DirectCast(name, IdentifierNameSyntax).Identifier
If Not identifier.IsBracketed AndAlso IsIntrinsicTypeForDocumentationComment(SyntaxFacts.GetKeywordKind(identifier.ValueText)) Then
' special case to be ignored, also see description
' in ParseXml.vb::TryParseXmlCrefAttributeValue(...)
Continue For
End If
ElseIf name.Kind = SyntaxKind.PredefinedType Then
Continue For
End If
' Otherwise report an error
Return True
End If
Next
Return False
End Function
Friend Overrides Function BindInsideCrefAttributeValue(reference As CrefReferenceSyntax, preserveAliases As Boolean, diagnosticBag As DiagnosticBag, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ImmutableArray(Of Symbol)
' If the node has trailing syntax nodes, it should report error, unless the name
' is a VB intrinsic type (which ensures compatibility with Dev11)
If HasTrailingSkippedTokensAndShouldReportError(reference) Then
Return ImmutableArray(Of Symbol).Empty
End If
If reference.Signature Is Nothing Then
Return BindNameInsideCrefReferenceInLegacyMode(reference.Name, preserveAliases, useSiteDiagnostics)
End If
' Extended 'cref' attribute syntax should not contain complex generic arguments
' such as in [cref="List(Of Action(Of A))"], because these generic arguments actually
' define type parameters to be used in signature part and return value
If NameSyntaxHasComplexGenericArguments(reference.Name) Then
Return ImmutableArray(Of Symbol).Empty
End If
Dim symbols = ArrayBuilder(Of Symbol).GetInstance
' Bind the name part and collect type parameters
Dim typeParameters As New Dictionary(Of String, CrefTypeParameterSymbol)(CaseInsensitiveComparison.Comparer)
CollectCrefNameSymbolsStrict(reference.Name, reference.Signature.ArgumentTypes.Count, typeParameters, symbols, preserveAliases, useSiteDiagnostics)
If symbols.Count = 0 Then
symbols.Free()
Return ImmutableArray(Of Symbol).Empty
End If
RemoveOverridenMethodsAndProperties(symbols)
' Bind signature and return type if present
Dim signatureTypes As ArrayBuilder(Of SignatureElement) = Nothing
Dim returnType As TypeSymbol = Nothing
BindSignatureAndReturnValue(reference, typeParameters, signatureTypes, returnType, diagnosticBag)
' Create only if needed
Debug.Assert(signatureTypes Is Nothing OrElse signatureTypes.Count > 0)
Dim signatureParameterCount As Integer = If(signatureTypes Is Nothing, 0, signatureTypes.Count)
' Choose between symbols those with matching signatures
Dim candidatePointer As Integer = 0
Dim goodPointer As Integer = 0
While candidatePointer < symbols.Count
Dim candidateSymbol As Symbol = symbols(candidatePointer)
' NOTE: we do a very simple signature check and
' avoid using signature comparer
Select Case candidateSymbol.Kind
Case SymbolKind.Method
Dim candidateMethod = DirectCast(candidateSymbol, MethodSymbol)
If candidateMethod.ParameterCount <> signatureParameterCount Then
' Signature does not match
Exit Select
End If
Dim parameters As ImmutableArray(Of ParameterSymbol) = candidateMethod.Parameters
For i = 0 To signatureParameterCount - 1
Dim parameter As ParameterSymbol = parameters(i)
If parameter.IsByRef <> signatureTypes(i).IsByRef OrElse
Not parameter.Type.IsSameTypeIgnoringCustomModifiers(signatureTypes(i).Type) Then
' Signature does not match
Exit Select
End If
Next
If returnType IsNot Nothing Then
If candidateMethod.IsSub OrElse Not candidateMethod.ReturnType.IsSameTypeIgnoringCustomModifiers(returnType) Then
' Return type does not match
Exit Select
End If
End If
' Good candidate
symbols(goodPointer) = candidateSymbol
goodPointer += 1
candidatePointer += 1
Continue While
Case SymbolKind.Property
Dim candidateProperty = DirectCast(candidateSymbol, PropertySymbol)
Dim parameters As ImmutableArray(Of ParameterSymbol) = candidateProperty.Parameters
If parameters.Length <> signatureParameterCount Then
' Signature does not match
Exit Select
End If
For i = 0 To signatureParameterCount - 1
Dim parameter As ParameterSymbol = parameters(i)
If parameter.IsByRef <> signatureTypes(i).IsByRef OrElse
Not parameter.Type.IsSameTypeIgnoringCustomModifiers(signatureTypes(i).Type) Then
' Signature does not match
Exit Select
End If
Next
Debug.Assert(returnType Is Nothing,
"Return type is only allowed for Operator CType, why we found a property here?")
' Good candidate
symbols(goodPointer) = candidateSymbol
goodPointer += 1
candidatePointer += 1
Continue While
Case Else
' All other symbols are ignored
End Select
' Ignore symbol
candidatePointer += 1
End While
If signatureTypes IsNot Nothing Then
signatureTypes.Free()
End If
If goodPointer < candidatePointer Then
symbols.Clip(goodPointer)
End If
Return symbols.ToImmutableAndFree()
End Function
Friend Overrides Function BindInsideCrefAttributeValue(name As TypeSyntax, preserveAliases As Boolean, diagnosticBag As DiagnosticBag, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ImmutableArray(Of Symbol)
Dim isPartOfSignatureOrReturnType As Boolean = False
Dim crefReference As CrefReferenceSyntax = GetEnclosingCrefReference(name, isPartOfSignatureOrReturnType)
If crefReference Is Nothing Then
Debug.Assert(False, "Speculative binding??")
Return ImmutableArray(Of Symbol).Empty
End If
If crefReference.Signature Is Nothing Then
Debug.Assert(Not isPartOfSignatureOrReturnType)
Return BindNameInsideCrefReferenceInLegacyMode(name, preserveAliases, useSiteDiagnostics)
End If
If isPartOfSignatureOrReturnType Then
Return BindInsideCrefSignatureOrReturnType(crefReference, name, preserveAliases, diagnosticBag)
Else
Return BindInsideCrefReferenceName(name, crefReference.Signature.ArgumentTypes.Count, preserveAliases, useSiteDiagnostics)
End If
End Function
Private Function BindInsideCrefSignatureOrReturnType(crefReference As CrefReferenceSyntax, name As TypeSyntax, preserveAliases As Boolean, diagnosticBag As DiagnosticBag) As ImmutableArray(Of Symbol)
Dim typeParameterAwareBinder As Binder = Me.GetOrCreateTypeParametersAwareBinder(crefReference)
Dim result As Symbol
If (diagnosticBag Is Nothing) Then
Dim diagnostics = DiagnosticBag.GetInstance
result = typeParameterAwareBinder.BindNamespaceOrTypeOrAliasSyntax(name, diagnostics)
diagnostics.Free()
Else
result = typeParameterAwareBinder.BindNamespaceOrTypeOrAliasSyntax(name, diagnosticBag)
End If
If result IsNot Nothing AndAlso result.Kind = SymbolKind.Alias AndAlso Not preserveAliases Then
result = DirectCast(result, AliasSymbol).Target
End If
Return If(result Is Nothing,
ImmutableArray(Of Symbol).Empty,
ImmutableArray.Create(Of Symbol)(result))
End Function
Private Function GetOrCreateTypeParametersAwareBinder(crefReference As CrefReferenceSyntax) As Binder
' To create type-param-aware binder we need to have type parameters,
' but we don't want to do so if the binder is already created
If Me._typeParameterBinder IsNot Nothing Then
Return Me._typeParameterBinder
End If
Dim typeParameters As New Dictionary(Of String, CrefTypeParameterSymbol)(IdentifierComparison.Comparer)
Dim crefName As TypeSyntax = crefReference.Name
Dim genericName As GenericNameSyntax = Nothing
While crefName IsNot Nothing
Select Case crefName.Kind
Case SyntaxKind.GenericName
genericName = DirectCast(crefName, GenericNameSyntax)
crefName = Nothing
Case SyntaxKind.QualifiedName
Dim qName = DirectCast(crefName, QualifiedNameSyntax)
crefName = qName.Left
If qName.Right.Kind = SyntaxKind.GenericName Then
genericName = DirectCast(qName.Right, GenericNameSyntax)
End If
Case SyntaxKind.IdentifierName,
SyntaxKind.CrefOperatorReference,
SyntaxKind.GlobalName,
SyntaxKind.PredefinedType
Exit While
Case SyntaxKind.QualifiedCrefOperatorReference
crefName = DirectCast(crefName, QualifiedCrefOperatorReferenceSyntax).Left
Case Else
Throw ExceptionUtilities.UnexpectedValue(crefName.Kind)
End Select
' Fall back to the next name part, if we need to collect type
' parameters genericName is supposed to be not Nothing
If genericName IsNot Nothing Then
Dim arguments As SeparatedSyntaxList(Of TypeSyntax) = genericName.TypeArgumentList.Arguments
For i = 0 To arguments.Count - 1
Dim typeSyntax As TypeSyntax = arguments(i)
Select Case typeSyntax.Kind
Case SyntaxKind.IdentifierName
Dim identifier = DirectCast(typeSyntax, IdentifierNameSyntax)
Dim typeParameterName As String = identifier.Identifier.ValueText
' As we go 'left-to-right' don't override right-most parameters with the same name
If Not typeParameters.ContainsKey(typeParameterName) Then
typeParameters(typeParameterName) = New CrefTypeParameterSymbol(i, typeParameterName, identifier)
End If
Case Else
' An error case
End Select
Next
End If
End While
Return GetOrCreateTypeParametersAwareBinder(typeParameters)
End Function
Private Function BindInsideCrefReferenceName(name As TypeSyntax, argCount As Integer, preserveAliases As Boolean, <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo)) As ImmutableArray(Of Symbol)
' NOTE: in code here and below 'parent' may be Nothing in
' case of speculative binding (which is NYI)
Dim parent As VisualBasicSyntaxNode = name.Parent
' Type parameter
If parent IsNot Nothing AndAlso parent.Kind = SyntaxKind.TypeArgumentList Then
Dim ordinal As Integer = DirectCast(parent, TypeArgumentListSyntax).Arguments.IndexOf(name)
If name.Kind = SyntaxKind.IdentifierName Then
Dim identifier = DirectCast(name, IdentifierNameSyntax)
Return ImmutableArray.Create(Of Symbol)(New CrefTypeParameterSymbol(ordinal, identifier.Identifier.ValueText, identifier))
End If
' An error case
Return ImmutableArray.Create(Of Symbol)(New CrefTypeParameterSymbol(ordinal, StringConstants.NamedSymbolErrorName, name))
End If
' Names considered to be checked for color-color case are Identifier or Generic names which
' are the left part of the qualified name parent
Dim checkForColorColor As Boolean = False
Dim nameText As String = Nothing
Dim arity As Integer = -1
lAgain:
Select Case name.Kind
Case SyntaxKind.IdentifierName,
SyntaxKind.GenericName
If parent IsNot Nothing AndAlso parent.Kind = SyntaxKind.QualifiedName Then
Dim qualified = DirectCast(parent, QualifiedNameSyntax)
If qualified.Right Is name Then
name = qualified
parent = name.Parent
GoTo lAgain
End If
End If
' color-color info
checkForColorColor = True
If name.Kind = SyntaxKind.IdentifierName Then
nameText = DirectCast(name, IdentifierNameSyntax).Identifier.ValueText
arity = 0
Else
Dim generic = DirectCast(name, GenericNameSyntax)
nameText = generic.Identifier.ValueText
arity = generic.TypeArgumentList.Arguments.Count
End If
' Fall through
Case SyntaxKind.CrefOperatorReference
If parent IsNot Nothing AndAlso parent.Kind = SyntaxKind.QualifiedCrefOperatorReference Then
name = DirectCast(parent, QualifiedCrefOperatorReferenceSyntax)
parent = name.Parent
GoTo lAgain
End If
' Fall through
Case SyntaxKind.QualifiedName,
SyntaxKind.QualifiedCrefOperatorReference
' Fall through
Case SyntaxKind.GlobalName
Return ImmutableArray.Create(Of Symbol)(Me.Compilation.GlobalNamespace)
Case Else
Throw ExceptionUtilities.UnexpectedValue(name.Kind)
End Select
Dim symbols = ArrayBuilder(Of Symbol).GetInstance
CollectCrefNameSymbolsStrict(name, argCount, New Dictionary(Of String, CrefTypeParameterSymbol)(IdentifierComparison.Comparer), symbols, preserveAliases, useSiteDiagnostics)
RemoveOverridenMethodsAndProperties(symbols)
If symbols.Count = 1 AndAlso checkForColorColor Then
Dim symbol As Symbol = symbols(0)
Dim type As TypeSymbol = Nothing
Select Case symbol.Kind
Case SymbolKind.Field
type = DirectCast(symbol, FieldSymbol).Type
Case SymbolKind.Method
type = DirectCast(symbol, MethodSymbol).ReturnType
Case SymbolKind.Property
type = DirectCast(symbol, PropertySymbol).Type
End Select
Dim replaceWithType As Boolean = False
If type IsNot Nothing Then
If IdentifierComparison.Equals(type.Name, nameText) Then
Dim namedType = TryCast(type, NamedTypeSymbol)
If namedType IsNot Nothing Then
replaceWithType = namedType.Arity = arity
Else
replaceWithType = arity = 0
End If
End If
End If
If replaceWithType Then
symbols(0) = type
End If
End If
Return symbols.ToImmutableAndFree()
End Function
Private Function GetEnclosingCrefReference(nameFromCref As TypeSyntax, <Out> ByRef partOfSignatureOrReturnType As Boolean) As CrefReferenceSyntax
partOfSignatureOrReturnType = False
Dim node As VisualBasicSyntaxNode = nameFromCref
While node IsNot Nothing
Select Case node.Kind
Case SyntaxKind.CrefReference
Exit While
Case SyntaxKind.SimpleAsClause
partOfSignatureOrReturnType = True
Case SyntaxKind.CrefSignature
partOfSignatureOrReturnType = True
End Select
node = node.Parent
End While
Return DirectCast(node, CrefReferenceSyntax)
End Function
Private Structure SignatureElement
Public ReadOnly Type As TypeSymbol
Public ReadOnly IsByRef As Boolean
Public Sub New(type As TypeSymbol, isByRef As Boolean)
Me.Type = type
Me.IsByRef = isByRef
End Sub
End Structure
Private Sub BindSignatureAndReturnValue(reference As CrefReferenceSyntax,
typeParameters As Dictionary(Of String, CrefTypeParameterSymbol),
<Out> ByRef signatureTypes As ArrayBuilder(Of SignatureElement),
<Out> ByRef returnType As TypeSymbol,
diagnosticBag As DiagnosticBag)
signatureTypes = Nothing
returnType = Nothing
Dim typeParameterAwareBinder As Binder = Me.GetOrCreateTypeParametersAwareBinder(typeParameters)
Dim diagnostic = If(diagnosticBag, DiagnosticBag.GetInstance())
Dim signature As CrefSignatureSyntax = reference.Signature
Debug.Assert(signature IsNot Nothing)
If signature.ArgumentTypes.Count > 0 Then
signatureTypes = ArrayBuilder(Of SignatureElement).GetInstance
For Each part In signature.ArgumentTypes
signatureTypes.Add(
New SignatureElement(
typeParameterAwareBinder.BindTypeSyntax(part.Type, diagnostic),
part.Modifier.Kind = SyntaxKind.ByRefKeyword))
Next
End If
If reference.AsClause IsNot Nothing Then
returnType = typeParameterAwareBinder.BindTypeSyntax(reference.AsClause.Type, diagnostic)
End If
If diagnosticBag Is Nothing Then diagnostic.Free()
End Sub
Private Sub CollectCrefNameSymbolsStrict(nameFromCref As TypeSyntax,
argsCount As Integer,
typeParameters As Dictionary(Of String, CrefTypeParameterSymbol),
symbols As ArrayBuilder(Of Symbol),
preserveAlias As Boolean,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo))
' This binding mode is used for extended cref-reference syntax with mandatory
' signature specified, we enforce more strict rules in this case
Select Case nameFromCref.Kind
Case SyntaxKind.QualifiedCrefOperatorReference
' 'A.B.Operator+' or 'C(Of T).Operator CType'
CollectQualifiedOperatorReferenceSymbolsStrict(
DirectCast(nameFromCref, QualifiedCrefOperatorReferenceSyntax), argsCount, typeParameters, symbols, useSiteDiagnostics)
Case SyntaxKind.CrefOperatorReference
' 'Operator+' or 'Operator CType'
CollectTopLevelOperatorReferenceStrict(
DirectCast(nameFromCref, CrefOperatorReferenceSyntax), argsCount, symbols, useSiteDiagnostics)
Case SyntaxKind.IdentifierName,
SyntaxKind.GenericName
' 'New', 'A', or 'B(Of T)'
CollectSimpleNameSymbolsStrict(
DirectCast(nameFromCref, SimpleNameSyntax), typeParameters, symbols, preserveAlias, useSiteDiagnostics, False)
Case SyntaxKind.QualifiedName
' 'A(Of T).B.M(Of E)'
CollectQualifiedNameSymbolsStrict(
DirectCast(nameFromCref, QualifiedNameSyntax), typeParameters, symbols, preserveAlias, useSiteDiagnostics)
Case Else
Throw ExceptionUtilities.UnexpectedValue(nameFromCref.Kind)
End Select
End Sub
Private Sub CollectTopLevelOperatorReferenceStrict(reference As CrefOperatorReferenceSyntax, argCount As Integer, symbols As ArrayBuilder(Of Symbol), <[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo))
CollectOperatorsAndConversionsInType(reference, argCount, Me.ContainingType, symbols, useSiteDiagnostics)
End Sub
Private Sub CollectSimpleNameSymbolsStrict(node As SimpleNameSyntax,
typeParameters As Dictionary(Of String, CrefTypeParameterSymbol),
symbols As ArrayBuilder(Of Symbol),
preserveAlias As Boolean,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo),
typeOrNamespaceOnly As Boolean)
' Name syntax of Cref should not have diagnostics
If node.ContainsDiagnostics Then
Return
End If
If node.Kind = SyntaxKind.GenericName Then
' Generic name
Dim genericName = DirectCast(node, GenericNameSyntax)
' Search exact arity only
CollectSimpleNameSymbolsStrict(genericName.Identifier.ValueText,
genericName.TypeArgumentList.Arguments.Count,
symbols,
preserveAlias,
useSiteDiagnostics,
typeOrNamespaceOnly)
CreateTypeParameterSymbolsAndConstructSymbols(genericName, symbols, typeParameters)
Else
' Simple identifier name
Debug.Assert(node.Kind = SyntaxKind.IdentifierName)
Dim identifier = DirectCast(node, IdentifierNameSyntax)
Dim token As SyntaxToken = identifier.Identifier
If IdentifierComparison.Equals(identifier.Identifier.ValueText, SyntaxFacts.GetText(SyntaxKind.NewKeyword)) AndAlso Not token.IsBracketed Then
CollectConstructorsSymbolsStrict(symbols)
Else
' Search 0-arity only
CollectSimpleNameSymbolsStrict(identifier.Identifier.ValueText, 0, symbols, preserveAlias, useSiteDiagnostics, typeOrNamespaceOnly)
End If
End If
End Sub
Private Sub CollectQualifiedNameSymbolsStrict(node As QualifiedNameSyntax,
typeParameters As Dictionary(Of String, CrefTypeParameterSymbol),
symbols As ArrayBuilder(Of Symbol),
preserveAlias As Boolean,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo))
' Name syntax of Cref should not have diagnostics
If node.ContainsDiagnostics Then
Return
End If
Dim allowColorColor As Boolean = True
Dim left As NameSyntax = node.Left
Select Case left.Kind
Case SyntaxKind.IdentifierName
CollectSimpleNameSymbolsStrict(DirectCast(left, SimpleNameSyntax), typeParameters, symbols, preserveAlias:=False, useSiteDiagnostics:=useSiteDiagnostics, typeOrNamespaceOnly:=True)
Case SyntaxKind.GenericName
CollectSimpleNameSymbolsStrict(DirectCast(left, SimpleNameSyntax), typeParameters, symbols, preserveAlias:=False, useSiteDiagnostics:=useSiteDiagnostics, typeOrNamespaceOnly:=True)
Case SyntaxKind.QualifiedName
CollectQualifiedNameSymbolsStrict(DirectCast(left, QualifiedNameSyntax), typeParameters, symbols, preserveAlias:=False, useSiteDiagnostics:=useSiteDiagnostics)
allowColorColor = False
Case SyntaxKind.GlobalName
symbols.Add(Me.Compilation.GlobalNamespace)
Case Else
Throw ExceptionUtilities.UnexpectedValue(left.Kind)
End Select
If symbols.Count <> 1 Then
' Stop resolving
typeParameters.Clear()
symbols.Clear()
Return
End If
Dim singleSymbol As Symbol = symbols(0)
symbols.Clear()
' We found one single symbol, we need to search for the 'right'
' name in the context of this symbol
Dim right As SimpleNameSyntax = node.Right
If right.Kind = SyntaxKind.GenericName Then
' Generic name
Dim genericName = DirectCast(right, GenericNameSyntax)
' Search exact arity only
CollectSimpleNameSymbolsStrict(singleSymbol,
allowColorColor,
genericName.Identifier.ValueText,
genericName.TypeArgumentList.Arguments.Count,
symbols,
preserveAlias,
useSiteDiagnostics)
CreateTypeParameterSymbolsAndConstructSymbols(genericName, symbols, typeParameters)
Else
' Simple identifier name
Debug.Assert(right.Kind = SyntaxKind.IdentifierName)
Dim identifier = DirectCast(right, IdentifierNameSyntax)
Dim token As SyntaxToken = identifier.Identifier
If IdentifierComparison.Equals(identifier.Identifier.ValueText, SyntaxFacts.GetText(SyntaxKind.NewKeyword)) AndAlso Not token.IsBracketed Then
CollectConstructorsSymbolsStrict(singleSymbol, symbols)
Else
' Search 0-arity only
CollectSimpleNameSymbolsStrict(singleSymbol, allowColorColor, identifier.Identifier.ValueText, 0, symbols, preserveAlias, useSiteDiagnostics)
End If
End If
End Sub
Private Sub CollectQualifiedOperatorReferenceSymbolsStrict(node As QualifiedCrefOperatorReferenceSyntax,
argCount As Integer,
typeParameters As Dictionary(Of String, CrefTypeParameterSymbol),
symbols As ArrayBuilder(Of Symbol),
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo))
' Name syntax of Cref should not have diagnostics
If node.ContainsDiagnostics Then
Return
End If
Dim allowColorColor As Boolean = True
Dim left As NameSyntax = node.Left
Select Case left.Kind
Case SyntaxKind.IdentifierName
CollectSimpleNameSymbolsStrict(DirectCast(left, SimpleNameSyntax), typeParameters, symbols, preserveAlias:=False, useSiteDiagnostics:=useSiteDiagnostics, typeOrNamespaceOnly:=True)
Case SyntaxKind.GenericName
CollectSimpleNameSymbolsStrict(DirectCast(left, SimpleNameSyntax), typeParameters, symbols, preserveAlias:=False, useSiteDiagnostics:=useSiteDiagnostics, typeOrNamespaceOnly:=True)
Case SyntaxKind.QualifiedName
CollectQualifiedNameSymbolsStrict(DirectCast(left, QualifiedNameSyntax), typeParameters, symbols, preserveAlias:=False, useSiteDiagnostics:=useSiteDiagnostics)
allowColorColor = False
Case Else
Throw ExceptionUtilities.UnexpectedValue(left.Kind)
End Select
If symbols.Count <> 1 Then
' Stop resolving
typeParameters.Clear()
symbols.Clear()
Return
End If
Dim singleSymbol As Symbol = symbols(0)
symbols.Clear()
If singleSymbol.Kind = SymbolKind.Alias Then
singleSymbol = DirectCast(singleSymbol, AliasSymbol).Target
End If
CollectOperatorsAndConversionsInType(node.Right, argCount, TryCast(singleSymbol, TypeSymbol), symbols, useSiteDiagnostics)
End Sub
Private Sub CollectConstructorsSymbolsStrict(symbols As ArrayBuilder(Of Symbol))
Dim containingSymbol As Symbol = Me.ContainingMember
If containingSymbol Is Nothing Then
Return
End If
If containingSymbol.Kind <> SymbolKind.NamedType Then
containingSymbol = containingSymbol.ContainingType
End If
Dim type = DirectCast(containingSymbol, NamedTypeSymbol)
If type IsNot Nothing Then
symbols.AddRange(type.InstanceConstructors)
End If
Return
End Sub
Private Sub CollectConstructorsSymbolsStrict(containingSymbol As Symbol, symbols As ArrayBuilder(Of Symbol))
Debug.Assert(symbols.Count = 0)
If containingSymbol.Kind = SymbolKind.NamedType Then
symbols.AddRange(DirectCast(containingSymbol, NamedTypeSymbol).InstanceConstructors)
End If
End Sub
Private Sub CollectSimpleNameSymbolsStrict(name As String,
arity As Integer,
symbols As ArrayBuilder(Of Symbol),
preserveAlias As Boolean,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo),
typeOrNamespaceOnly As Boolean)
Debug.Assert(Not String.IsNullOrEmpty(name))
Debug.Assert(arity >= 0)
Const options As LookupOptions =
LookupOptions.UseBaseReferenceAccessibility Or
LookupOptions.MustNotBeReturnValueVariable Or
LookupOptions.IgnoreExtensionMethods Or
LookupOptions.MustNotBeLocalOrParameter Or
LookupOptions.NoSystemObjectLookupForInterfaces
Dim result As LookupResult = LookupResult.GetInstance()
Me.Lookup(result, name, arity, If(typeOrNamespaceOnly, options Or LookupOptions.NamespacesOrTypesOnly, options), useSiteDiagnostics)
If Not result.IsGoodOrAmbiguous OrElse Not result.HasSymbol Then
result.Free()
Return
End If
CollectGoodOrAmbiguousFromLookupResult(result, symbols, preserveAlias)
result.Free()
End Sub
Private Sub CollectSimpleNameSymbolsStrict(containingSymbol As Symbol,
allowColorColor As Boolean,
name As String,
arity As Integer,
symbols As ArrayBuilder(Of Symbol),
preserveAlias As Boolean,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo))
Debug.Assert(Not String.IsNullOrEmpty(name))
Debug.Assert(arity >= 0)
Dim lookupResult As LookupResult = lookupResult.GetInstance()
Dim options As LookupOptions = LookupOptions.UseBaseReferenceAccessibility Or
LookupOptions.MustNotBeReturnValueVariable Or
LookupOptions.IgnoreExtensionMethods Or
LookupOptions.MustNotBeLocalOrParameter Or
LookupOptions.NoSystemObjectLookupForInterfaces
lAgain:
Select Case containingSymbol.Kind
Case SymbolKind.Namespace
LookupMember(lookupResult, DirectCast(containingSymbol, NamespaceSymbol), name, arity, options, useSiteDiagnostics)
Case SymbolKind.Alias
containingSymbol = DirectCast(containingSymbol, AliasSymbol).Target
GoTo lAgain
Case SymbolKind.NamedType, SymbolKind.ArrayType
LookupMember(lookupResult, DirectCast(containingSymbol, TypeSymbol), name, arity, options, useSiteDiagnostics)
Case SymbolKind.Property
If allowColorColor Then
' Check for Color Color case
Dim [property] = DirectCast(containingSymbol, PropertySymbol)
Dim propertyType As TypeSymbol = [property].Type
If IdentifierComparison.Equals([property].Name, propertyType.Name) Then
containingSymbol = propertyType
GoTo lAgain
End If
End If
Case SymbolKind.Field
If allowColorColor Then
' Check for Color Color case
Dim field = DirectCast(containingSymbol, FieldSymbol)
Dim fieldType As TypeSymbol = field.Type
If IdentifierComparison.Equals(field.Name, fieldType.Name) Then
containingSymbol = fieldType
GoTo lAgain
End If
End If
Case SymbolKind.Method
' Check for Color Color case
If allowColorColor Then
Dim method = DirectCast(containingSymbol, MethodSymbol)
If Not method.IsSub Then
Dim returnType As TypeSymbol = method.ReturnType
If IdentifierComparison.Equals(method.Name, returnType.Name) Then
containingSymbol = returnType
GoTo lAgain
End If
End If
End If
Case Else
' Nothing can be found in context of these symbols
End Select
If Not lookupResult.IsGoodOrAmbiguous OrElse Not lookupResult.HasSymbol Then
lookupResult.Free()
Return
End If
CollectGoodOrAmbiguousFromLookupResult(lookupResult, symbols, preserveAlias)
lookupResult.Free()
End Sub
Private Sub CreateTypeParameterSymbolsAndConstructSymbols(genericName As GenericNameSyntax,
symbols As ArrayBuilder(Of Symbol),
typeParameters As Dictionary(Of String, CrefTypeParameterSymbol))
Dim arguments As SeparatedSyntaxList(Of TypeSyntax) = genericName.TypeArgumentList.Arguments
Dim typeParameterSymbols(arguments.Count - 1) As TypeSymbol
For i = 0 To arguments.Count - 1
Dim typeSyntax As TypeSyntax = arguments(i)
Dim created As CrefTypeParameterSymbol = Nothing
Select Case typeSyntax.Kind
Case SyntaxKind.IdentifierName
Dim identifier = DirectCast(typeSyntax, IdentifierNameSyntax)
created = New CrefTypeParameterSymbol(i, identifier.Identifier.ValueText, identifier)
typeParameterSymbols(i) = created
Case Else
' An error case
created = New CrefTypeParameterSymbol(i, StringConstants.NamedSymbolErrorName, typeSyntax)
typeParameterSymbols(i) = created
End Select
typeParameters(created.Name) = created
Next
For i = 0 To symbols.Count - 1
Dim symbol As Symbol = symbols(i)
lAgain:
Select Case symbol.Kind
Case SymbolKind.Method
Dim method = DirectCast(symbol, MethodSymbol)
Debug.Assert(method.Arity = genericName.TypeArgumentList.Arguments.Count)
symbols(i) = method.Construct(typeParameterSymbols.AsImmutableOrNull.As(Of TypeSymbol))
Case SymbolKind.NamedType, SymbolKind.ErrorType
Dim type = DirectCast(symbol, NamedTypeSymbol)
Debug.Assert(type.Arity = genericName.TypeArgumentList.Arguments.Count)
symbols(i) = type.Construct(typeParameterSymbols.AsImmutableOrNull.As(Of TypeSymbol))
Case SymbolKind.Alias
symbol = DirectCast(symbol, AliasSymbol).Target
GoTo lAgain
End Select
Next
End Sub
Private Sub CollectGoodOrAmbiguousFromLookupResult(lookupResult As LookupResult, symbols As ArrayBuilder(Of Symbol), preserveAlias As Boolean)
Dim di As DiagnosticInfo = lookupResult.Diagnostic
If TypeOf di Is AmbiguousSymbolDiagnostic Then
' Several ambiguous symbols wrapped in 'AmbiguousSymbolDiagnostic', return
' unwrapped symbols in 'ambiguousSymbols' and return Nothing as a rresult
Debug.Assert(lookupResult.Kind = LookupResultKind.Ambiguous)
Dim ambiguousSymbols As ImmutableArray(Of Symbol) = DirectCast(di, AmbiguousSymbolDiagnostic).AmbiguousSymbols
Debug.Assert(ambiguousSymbols.Length > 1)
For Each sym In ambiguousSymbols
symbols.Add(If(preserveAlias, sym, UnwrapAlias(sym)))
Next
Else
' Return result as a single good symbol
For Each sym In lookupResult.Symbols
symbols.Add(If(preserveAlias, sym, UnwrapAlias(sym)))
Next
End If
End Sub
Private Sub CollectOperatorsAndConversionsInType(crefOperator As CrefOperatorReferenceSyntax, argCount As Integer, type As TypeSymbol, symbols As ArrayBuilder(Of Symbol),
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo))
If type Is Nothing Then
Return
End If
If argCount > 2 OrElse argCount < 1 Then
Return
End If
Select Case crefOperator.OperatorToken.Kind
Case SyntaxKind.IsTrueKeyword
If argCount = 1 Then
Dim opInfo As New OverloadResolution.OperatorInfo(UnaryOperatorKind.IsTrue)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.TrueOperatorName, opInfo, useSiteDiagnostics)
End If
Case SyntaxKind.IsFalseKeyword
If argCount = 1 Then
Dim opInfo As New OverloadResolution.OperatorInfo(UnaryOperatorKind.IsFalse)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.FalseOperatorName, opInfo, useSiteDiagnostics)
End If
Case SyntaxKind.NotKeyword
If argCount = 1 Then
Dim opInfo As New OverloadResolution.OperatorInfo(UnaryOperatorKind.Not)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator,
WellKnownMemberNames.OnesComplementOperatorName, opInfo,
useSiteDiagnostics,
WellKnownMemberNames.LogicalNotOperatorName, opInfo)
End If
Case SyntaxKind.PlusToken
If argCount = 1 Then
Dim opInfo As New OverloadResolution.OperatorInfo(UnaryOperatorKind.Plus)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.UnaryPlusOperatorName, opInfo, useSiteDiagnostics)
Else
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.Add)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.AdditionOperatorName, opInfo, useSiteDiagnostics)
End If
Case SyntaxKind.MinusToken
If argCount = 1 Then
Dim opInfo As New OverloadResolution.OperatorInfo(UnaryOperatorKind.Minus)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.UnaryNegationOperatorName, opInfo, useSiteDiagnostics)
Else
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.Subtract)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.SubtractionOperatorName, opInfo, useSiteDiagnostics)
End If
Case SyntaxKind.AsteriskToken
If argCount = 2 Then
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.Multiply)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.MultiplyOperatorName, opInfo, useSiteDiagnostics)
End If
Case SyntaxKind.SlashToken
If argCount = 2 Then
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.Divide)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.DivisionOperatorName, opInfo, useSiteDiagnostics)
End If
Case SyntaxKind.BackslashToken
If argCount = 2 Then
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.IntegerDivide)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.IntegerDivisionOperatorName, opInfo, useSiteDiagnostics)
End If
Case SyntaxKind.ModKeyword
If argCount = 2 Then
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.Modulo)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.ModulusOperatorName, opInfo, useSiteDiagnostics)
End If
Case SyntaxKind.CaretToken
If argCount = 2 Then
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.Power)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.ExponentOperatorName, opInfo, useSiteDiagnostics)
End If
Case SyntaxKind.EqualsToken
If argCount = 2 Then
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.Equals)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.EqualityOperatorName, opInfo, useSiteDiagnostics)
End If
Case SyntaxKind.LessThanGreaterThanToken
If argCount = 2 Then
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.NotEquals)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.InequalityOperatorName, opInfo, useSiteDiagnostics)
End If
Case SyntaxKind.LessThanToken
If argCount = 2 Then
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.LessThan)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.LessThanOperatorName, opInfo, useSiteDiagnostics)
End If
Case SyntaxKind.GreaterThanToken
If argCount = 2 Then
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.GreaterThan)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.GreaterThanOperatorName, opInfo, useSiteDiagnostics)
End If
Case SyntaxKind.LessThanEqualsToken
If argCount = 2 Then
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.LessThanOrEqual)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.LessThanOrEqualOperatorName, opInfo, useSiteDiagnostics)
End If
Case SyntaxKind.GreaterThanEqualsToken
If argCount = 2 Then
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.GreaterThanOrEqual)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.GreaterThanOrEqualOperatorName, opInfo, useSiteDiagnostics)
End If
Case SyntaxKind.LikeKeyword
If argCount = 2 Then
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.Like)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.LikeOperatorName, opInfo, useSiteDiagnostics)
End If
Case SyntaxKind.AmpersandToken
If argCount = 2 Then
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.Concatenate)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.ConcatenateOperatorName, opInfo, useSiteDiagnostics)
End If
Case SyntaxKind.AndKeyword
If argCount = 2 Then
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.And)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator,
WellKnownMemberNames.BitwiseAndOperatorName, opInfo,
useSiteDiagnostics,
WellKnownMemberNames.LogicalAndOperatorName, opInfo)
End If
Case SyntaxKind.OrKeyword
If argCount = 2 Then
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.Or)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator,
WellKnownMemberNames.BitwiseOrOperatorName, opInfo,
useSiteDiagnostics,
WellKnownMemberNames.LogicalOrOperatorName, opInfo)
End If
Case SyntaxKind.XorKeyword
If argCount = 2 Then
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.Xor)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator, WellKnownMemberNames.ExclusiveOrOperatorName, opInfo, useSiteDiagnostics)
End If
Case SyntaxKind.LessThanLessThanToken
If argCount = 2 Then
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.LeftShift)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator,
WellKnownMemberNames.LeftShiftOperatorName, opInfo,
useSiteDiagnostics,
WellKnownMemberNames.UnsignedLeftShiftOperatorName, opInfo)
End If
Case SyntaxKind.GreaterThanGreaterThanToken
If argCount = 2 Then
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.RightShift)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.UserDefinedOperator,
WellKnownMemberNames.RightShiftOperatorName, opInfo,
useSiteDiagnostics,
WellKnownMemberNames.UnsignedRightShiftOperatorName, opInfo)
End If
Case SyntaxKind.CTypeKeyword
If argCount = 1 Then
Dim opInfo As New OverloadResolution.OperatorInfo(BinaryOperatorKind.RightShift)
CollectOperatorsAndConversionsInType(type, symbols, MethodKind.Conversion,
WellKnownMemberNames.ImplicitConversionName, New OverloadResolution.OperatorInfo(UnaryOperatorKind.Implicit),
useSiteDiagnostics,
WellKnownMemberNames.ExplicitConversionName, New OverloadResolution.OperatorInfo(UnaryOperatorKind.Explicit))
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(crefOperator.OperatorToken.Kind)
End Select
End Sub
Private Sub CollectOperatorsAndConversionsInType(type As TypeSymbol,
symbols As ArrayBuilder(Of Symbol),
kind As MethodKind,
name1 As String,
info1 As OverloadResolution.OperatorInfo,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo),
Optional name2 As String = Nothing,
Optional info2 As OverloadResolution.OperatorInfo = Nothing)
Dim methods = ArrayBuilder(Of MethodSymbol).GetInstance()
OverloadResolution.CollectUserDefinedOperators(type, Nothing, kind, name1, info1, name2, info2, methods, useSiteDiagnostics)
symbols.AddRange(methods)
methods.Free()
End Sub
Private Shared Function NameSyntaxHasComplexGenericArguments(name As TypeSyntax) As Boolean
Select Case name.Kind
Case SyntaxKind.IdentifierName,
SyntaxKind.CrefOperatorReference,
SyntaxKind.GlobalName,
SyntaxKind.PredefinedType
Return False
Case SyntaxKind.QualifiedCrefOperatorReference
Return NameSyntaxHasComplexGenericArguments(DirectCast(name, QualifiedCrefOperatorReferenceSyntax).Left)
Case SyntaxKind.QualifiedName
Dim qualified = DirectCast(name, QualifiedNameSyntax)
Return NameSyntaxHasComplexGenericArguments(qualified.Left) OrElse
NameSyntaxHasComplexGenericArguments(qualified.Right)
Case SyntaxKind.GenericName
Dim genericArguments = DirectCast(name, GenericNameSyntax).TypeArgumentList.Arguments
For i = 0 To genericArguments.Count - 1
If genericArguments(i).Kind <> SyntaxKind.IdentifierName Then
Return True
End If
Next
Return False
Case Else
Throw ExceptionUtilities.UnexpectedValue(name.Kind)
End Select
End Function
End Class
End Namespace
|
mono/roslyn
|
src/Compilers/VisualBasic/Portable/Binding/DocumentationCommentCrefBinder.vb
|
Visual Basic
|
apache-2.0
| 58,063
|
' 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.UnitTests.SignatureHelp
Imports Microsoft.CodeAnalysis.VisualBasic.SignatureHelp
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SignatureHelp
Public Class InvocationExpressionSignatureHelpProviderTests
Inherits AbstractVisualBasicSignatureHelpProviderTests
Friend Overrides Function GetSignatureHelpProviderType() As Type
Return GetType(InvocationExpressionSignatureHelpProvider)
End Function
#Region "Regular tests"
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationWithoutParameters() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo()
[|Goo($$|])
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo()", String.Empty, Nothing, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")>
Public Async Function PickCorrectOverload_PickString() As Task
Dim markup = <Text><![CDATA[
Public Class C
Sub M()
[|M(i:="Hello"$$|])
End Sub
Public Sub M(i As String)
End Sub
Public Sub M(i As Integer)
End Sub
Public Sub M(filtered As Byte)
End Sub
End Class
]]></Text>.Value
Dim expectedOrderedItems = {
New SignatureHelpTestItem("C.M(i As Integer)", String.Empty, Nothing, currentParameterIndex:=0),
New SignatureHelpTestItem("C.M(i As String)", String.Empty, Nothing, currentParameterIndex:=0, isSelected:=True)
}
Await TestAsync(markup, expectedOrderedItems)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")>
Public Async Function PickCorrectOverload_PickInteger() As Task
Dim markup = <Text><![CDATA[
Public Class C
Sub M()
[|M(i:=1$$|])
End Sub
Public Sub M(i As String)
End Sub
Public Sub M(i As Integer)
End Sub
Public Sub M(filtered As Byte)
End Sub
End Class
]]></Text>.Value
Dim expectedOrderedItems = {
New SignatureHelpTestItem("C.M(i As Integer)", String.Empty, Nothing, currentParameterIndex:=0, isSelected:=True),
New SignatureHelpTestItem("C.M(i As String)", String.Empty, Nothing, currentParameterIndex:=0)
}
Await TestAsync(markup, expectedOrderedItems)
End Function
<WorkItem(958593, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958593")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationInsideStringLiteral() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo()
[|Goo("$$"|])
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo()", currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationWithoutParametersMethodXmlComments() As Task
Dim markup = <a><![CDATA[
Class C
''' <summary>
''' Summary for Goo
''' </summary>
Sub Goo()
[|Goo($$|])
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo()", "Summary for Goo", Nothing, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationWithParametersOn1() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo(a As Integer, b As Integer)
[|Goo($$a, b|])
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationWithParametersXmlCommentsOn1() As Task
Dim markup = <a><![CDATA[
Class C
''' <summary>
''' Summary for Goo
''' </summary>
''' <param name="a">Param a</param>
''' <param name="b">Param b</param>
Sub Goo(a As Integer, b As Integer)
[|Goo($$a, b|])
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(a As Integer, b As Integer)", "Summary for Goo", "Param a", currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationWithParametersOn2() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo(a As Integer, b As Integer)
[|Goo(a, $$b|])
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=1))
Await TestAsync(markup, expectedOrderedItems)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationWithParametersXmlCommentsOn2() As Task
Dim markup = <a><![CDATA[
Class C
''' <summary>
''' Summary for Goo
''' </summary>
''' <param name="a">Param a</param>
''' <param name="b">Param b</param>
Sub Goo(a As Integer, b As Integer)
[|Goo(a, $$b|])
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(a As Integer, b As Integer)", "Summary for Goo", "Param b", currentParameterIndex:=1))
Await TestAsync(markup, expectedOrderedItems)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationWithoutClosingParen() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo()
[|Goo($$
|]End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo()", String.Empty, Nothing, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationWithoutClosingParenWithParametersOn1() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo(a As Integer, b As Integer)
[|Goo($$a, b
|]End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationWithoutClosingParenWithParametersOn2() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo(a As Integer, b As Integer)
[|Goo(a, $$b
|]End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=1))
Await TestAsync(markup, expectedOrderedItems)
End Function
<WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationOnBaseExpression_ProtectedAccessibility() As Task
Dim markup = <a><![CDATA[
Imports System
Public Class Base
Protected Overridable Sub Goo(x As Integer)
End Sub
End Class
Public Class Derived
Inherits Base
Private Sub Test()
[|MyBase.Goo($$
|]End Sub
Protected Overrides Sub Goo(x As Integer)
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("Base.Goo(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationOnBaseExpression_AbstractBase() As Task
Dim markup = <a><![CDATA[
Imports System
Public MustInherit Class Base
Protected MustOverride Sub Goo(x As Integer)
End Sub
End Class
Public Class Derived
Inherits Base
Private Sub Test()
[|MyBase.Goo($$
|]End Sub
Protected Overrides Sub Goo(x As Integer)
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("Base.Goo(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationOnThisExpression_ProtectedAccessibility() As Task
Dim markup = <a><![CDATA[
Imports System
Public Class Base
Protected Overridable Sub Goo(x As Integer)
End Sub
End Class
Public Class Derived
Inherits Base
Private Sub Test()
[|Me.Goo($$
|]End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("Base.Goo(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationOnThisExpression_ProtectedAccessibility_Overridden() As Task
Dim markup = <a><![CDATA[
Imports System
Public Class Base
Protected Overridable Sub Goo(x As Integer)
End Sub
End Class
Public Class Derived
Inherits Base
Private Sub Test()
[|Me.Goo($$
|]End Sub
Protected Overrides Sub Goo(x As Integer)
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("Derived.Goo(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase() As Task
Dim markup = <a><![CDATA[
Imports System
Public MustInherit Class Base
Protected MustOverride Sub Goo(x As Integer)
End Sub
End Class
Public Class Derived
Inherits Base
Private Sub Test()
[|Me.Goo($$
|]End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("Base.Goo(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase_Overridden() As Task
Dim markup = <a><![CDATA[
Imports System
Public MustInherit Class Base
Protected MustOverride Sub Goo(x As Integer)
End Sub
End Class
Public Class Derived
Inherits Base
Private Sub Test()
[|Me.Goo($$
|]End Sub
Protected Overrides Sub Goo(x As Integer)
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("Derived.Goo(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationOnBaseExpression_ProtectedFriendAccessibility() As Task
Dim markup = <a><![CDATA[
Imports System
Public Class Base
Protected Friend Sub Goo(x As Integer)
End Sub
End Class
Public Class Derived
Inherits Base
Private Sub Test()
[|MyBase.Goo($$
|]End Sub
Protected Overrides Sub Goo(x As Integer)
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("Base.Goo(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationOnBaseMember_ProtectedAccessibility_ThroughType() As Task
Dim markup = <a><![CDATA[
Imports System
Public Class Base
Protected Sub Goo(x As Integer)
End Sub
End Class
Public Class Derived
Inherits Base
Private Sub Test()
Dim x as New Base()
[|x.Goo($$
|]End Sub
Protected Overrides Sub Goo(x As Integer)
End Sub
End Class
]]></a>.Value
Await TestAsync(markup, Nothing)
End Function
<WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationOnBaseExpression_PrivateAccessibility() As Task
Dim markup = <a><![CDATA[
Imports System
Public Class Base
Private Sub Goo(x As Integer)
End Sub
End Class
Public Class Derived
Inherits Base
Private Sub Test()
Dim x as New Base()
[|x.Goo($$
|]End Sub
Protected Overrides Sub Goo(x As Integer)
End Sub
End Class
]]></a>.Value
Await TestAsync(markup, Nothing)
End Function
<WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationOnBaseExpression_Constructor() As Task
Dim markup = <a><![CDATA[
Imports System
Public MustInherit Class Base
Protected Sub New(x As Integer)
End Sub
End Class
Public Class Derived
Inherits Base
Public Sub New()
[|MyBase.New($$
|]End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("Base.New(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188"), WorkItem(544989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544989")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationOnBaseExpression_Finalizer() As Task
Dim markup = <a><![CDATA[
Class C
Protected Overrides Sub Finalize()
[|MyBase.Finalize($$
|]End Sub
End Class]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("Object.Finalize()"))
Await TestAsync(markup, expectedOrderedItems)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationOnSubLambda() As Task
Dim markup = <a><![CDATA[
Imports System
Class C
Sub Goo(a As Integer, b As Integer)
Dim bar As Action(Of Integer) = Sub(i) Console.WriteLine(i)
[|bar($$
|]End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("Action(Of Integer)(obj As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationOnFunctionLambda() As Task
Dim markup = <a><![CDATA[
Imports System
Class C
Sub Goo(a As Integer, b As Integer)
Dim bar As Func(Of Integer, String) = Function(i) i.ToString()
[|bar($$
|]End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("Func(Of Integer, String)(arg As Integer) As String", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationOnLambdaInsideAnonType() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo()
Dim lambda = Function() 0
Dim bar = New With {.Value = [|lambda($$}
|]End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("Invoke() As Integer", String.Empty, Nothing, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationOnMemberAccessExpression() As Task
Dim markup = <a><![CDATA[
Class C
Shared Sub Bar(a As Integer)
End Sub
Sub Goo()
[|C.Bar($$
|]End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C.Bar(a As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestExtensionMethod1() As Task
Dim markup = <a><![CDATA[
Imports System.Runtime.CompilerServices
Class C
Sub Method()
Dim s As String = "test"
[|s.ExtensionMethod($$
|]End Sub
End Class
Public Module MyExtension
<Extension()>
Public Function ExtensionMethod(s As String, x As Integer) As Integer
Return s.Length
End Function
End Module
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem($"<{VBFeaturesResources.Extension}> MyExtension.ExtensionMethod(x As Integer) As Integer", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestProperty() As Task
Dim markup = <a><![CDATA[
Class C
Property goo As Integer
Sub bar()
[|goo($$
|]End Sub
End Class]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C.goo() As Integer", String.Empty, Nothing, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<WorkItem(544068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544068")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestExtension() As Task
Dim markup = <a><![CDATA[
Imports System.Runtime.CompilerServices
Public Class Goo
Sub bar()
Me.ExtensionMethod($$
End Sub
End Class
Module SomeModule
<Extension()>
Public Sub ExtensionMethod(ByRef f As Goo)
End Sub
End Module
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() From {
New SignatureHelpTestItem($"<{VBFeaturesResources.Extension}> SomeModule.ExtensionMethod()", String.Empty, Nothing, currentParameterIndex:=0)
}
Await TestAsync(markup, expectedOrderedItems)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationOnAnonymousType() As Task
Dim markup = <a><![CDATA[
Imports System.Collections.Generic
Module Program
Sub Main(args As String())
Dim x = New With {.A = 0, .B = 1}
M(x).Add($$
End Sub
Function M(Of T)(goo As T) As List(Of T)
End Function
End Module]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem(
$"List(Of 'a).Add(item As 'a)
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} New With {{ .A As Integer, .B As Integer }}",
String.Empty,
String.Empty,
currentParameterIndex:=0,
description:=$"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} New With {{ .A As Integer, .B As Integer }}"))
Await TestAsync(markup, expectedOrderedItems)
End Function
<WorkItem(545118, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545118")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestStatic1() As Task
Dim markup = <a><![CDATA[
Class C
Shared Sub Goo()
Bar($$
End Sub
Shared Sub Bar()
End Sub
Sub Bar(i As Integer)
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() From {
New SignatureHelpTestItem("C.Bar()", currentParameterIndex:=0)
}
Await TestAsync(markup, expectedOrderedItems)
End Function
<WorkItem(545118, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545118")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestStatic2() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo()
Bar($$
End Sub
Shared Sub Bar()
End Sub
Sub Bar(i As Integer)
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() From {
New SignatureHelpTestItem("C.Bar()", currentParameterIndex:=0),
New SignatureHelpTestItem("C.Bar(i As Integer)", currentParameterIndex:=0)
}
Await TestAsync(markup, expectedOrderedItems)
End Function
<WorkItem(539111, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539111")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestFilteringInOverloadedGenericMethods() As Task
Dim markup = <a><![CDATA[
Class C
Sub M()
GenericMethod(Of String, Integer)(Nothing, 42$$)
End Sub
''' <summary>
''' Hello Generic World!
''' </summary>
''' <typeparam name="T1">Type Param 1</typeparam>
''' <param name="i">Param 1 of type T1</param>
''' <returns>Null</returns>
Function GenericMethod(Of T1)(i As T1) As C
Return Nothing
End Function
''' <summary>
''' Hello Generic World 2.0!
''' </summary>
''' <typeparam name="T1">Type Param 1</typeparam>
''' <typeparam name="T2">Type Param 2</typeparam>
''' <param name="i">Param 1 of type T1</param>
''' <param name="i2">Param 2 of type T2</param>
''' <returns>Null</returns>
Function GenericMethod(Of T1, T2)(i As T1, i2 As T2) As C
Return Nothing
End Function
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(
New SignatureHelpTestItem(signature:="C.GenericMethod(Of String, Integer)(i As String, i2 As Integer) As C",
methodDocumentation:="Hello Generic World 2.0!",
parameterDocumentation:="Param 2 of type T2",
currentParameterIndex:=1))
Await TestAsync(markup, expectedOrderedItems)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestAwaitableItem() As Task
Dim markup = <a><![CDATA[
Imports System.Threading.Tasks
Class C
''' <summary>
''' Doc Comment!
''' </summary>
Async Function Goo() As Task
Me.Goo($$
End Function
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() From {
New SignatureHelpTestItem("C.Goo() As Task", currentParameterIndex:=0, methodDocumentation:=String.Empty)
}
Await TestSignatureHelpWithMscorlib45Async(markup, expectedOrderedItems, LanguageNames.VisualBasic)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestAwaitableItem2() As Task
Dim markup = <a><![CDATA[
Imports System.Threading.Tasks
Class C
''' <summary>
''' Doc Comment!
''' </summary>
Async Function Goo() As Task(Of Integer)
Me.Goo($$
End Function
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() From {
New SignatureHelpTestItem("C.Goo() As Task(Of Integer)", currentParameterIndex:=0, methodDocumentation:=String.Empty)
}
Await TestSignatureHelpWithMscorlib45Async(markup, expectedOrderedItems, LanguageNames.VisualBasic)
End Function
#End Region
#Region "Default Properties"
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestDefaultProperty() As Task
Dim markup = <a><![CDATA[
Class C
Default Public Property item(index As Integer) As String
Get
Return "goo"
End Get
Set(ByVal value As String)
End Set
End Property
End Class
Class D
Sub Goo
Dim obj As New C
[|obj($$
|]End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C(index As Integer) As String", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
#End Region
#Region "Current Parameter Name"
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestCurrentParameterName() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo(someParameter As Integer, something As Boolean)
Goo(something:=false, someParameter:=$$)
End Sub
End Class
]]></a>.Value
Await VerifyCurrentParameterNameAsync(markup, "someParameter")
End Function
#End Region
#Region "Trigger tests"
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationOnTriggerParens() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo()
[|Goo($$
|]End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo()", String.Empty, Nothing, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationOnTriggerComma() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo(a As Integer, b As Integer)
[|Goo(a,$$
|]End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=1))
Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestNoInvocationOnSpace() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo(a As Integer, b As Integer)
[|Goo(a, $$|]
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestConditionalIndexing() As Task
Dim markup = <a><![CDATA[
Class C
Dim x as String = Nothing
Sub Goo()
x?($$)
End Sub
End Class
]]></a>.Value
Dim expected = New SignatureHelpTestItem("String(index As Integer) As Char", currentParameterIndex:=0)
Await TestAsync(markup, {expected}, experimental:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestConditionalMethodCall() As Task
Dim markup = <a><![CDATA[
Class C
Dim x as String = Nothing
Sub Goo()
x?.ToString($$)
End Sub
End Class
]]></a>.Value
Dim expected = {New SignatureHelpTestItem("String.ToString() As String", currentParameterIndex:=0),
New SignatureHelpTestItem("String.ToString(provider As System.IFormatProvider) As String", currentParameterIndex:=0)}
Await TestAsync(markup, expected, experimental:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestConditionalDelegateInvocation() As Task
Dim markup = <a><![CDATA[
Imports System
Class C
Sub Goo()
Dim x As Func(Of Integer, Integer)
x?($$
End Sub
End Class
]]></a>.Value
Dim expected = {New SignatureHelpTestItem("Func(Of Integer, Integer)(arg As Integer) As Integer", currentParameterIndex:=0)}
Await TestAsync(markup, expected, experimental:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestNonIdentifierConditionalIndexer() As Task
Dim expected = {New SignatureHelpTestItem("String(index As Integer) As Char")}
' inline with a string literal
Await TestAsync("
Class C
Sub M()
Dim c = """"?($$
End Sub
End Class
", expected)
' parenthesized expression
Await TestAsync("
Class C
Sub M()
Dim c = ("""")?($$
End Sub
End Class
", expected)
' new object expression
Await TestAsync("
Class C
Sub M()
Dim c = (New System.String("" ""c, 1))?($$
End Sub
End Class
", expected)
' more complicated parenthesized expression
Await TestAsync("
Class C
Sub M()
Dim c = (CType(Nothing, System.Collections.Generic.List(Of Integer)))?($$
End Sub
End Class
", {New SignatureHelpTestItem("System.Collections.Generic.List(Of Integer)(index As Integer) As Integer")})
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestTriggerCharacterInComment01() As Task
Dim markup = "
Class C
Sub M(p As String)
M(',$$
End Sub
End Class
"
Await TestAsync(markup, Enumerable.Empty(Of SignatureHelpTestItem)(), usePreviousCharAsTrigger:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestTriggerCharacterInString01() As Task
Dim markup = "
Class C
Sub M(p As String)
M("",$$""
End Sub
End Class
"
Await TestAsync(markup, Enumerable.Empty(Of SignatureHelpTestItem)(), usePreviousCharAsTrigger:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Sub TestTriggerCharacters()
Dim expectedTriggerCharacters() As Char = {","c, "("c}
Dim unexpectedTriggerCharacters() As Char = {" "c, "["c, "<"c}
VerifyTriggerCharacters(expectedTriggerCharacters, unexpectedTriggerCharacters)
End Sub
#End Region
#Region "EditorBrowsable tests"
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_Method_BrowsableStateAlways() As Task
Dim markup = <Text><![CDATA[
Class Program
Sub M()
Goo.Bar($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
Public Class Goo
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)>
Public Shared Sub Bar()
End Sub
End Class
]]></Text>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("Goo.Bar()", String.Empty, Nothing, currentParameterIndex:=0))
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=expectedOrderedItems,
expectedOrderedItemsSameSolution:=expectedOrderedItems,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_Method_BrowsableStateNever() As Task
Dim markup = <Text><![CDATA[
Class Program
Sub M()
Goo.Bar($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
Public Class Goo
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)>
Public Shared Sub Bar()
End Sub
End Class
]]></Text>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("Goo.Bar()", String.Empty, Nothing, currentParameterIndex:=0))
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem),
expectedOrderedItemsSameSolution:=expectedOrderedItems,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_Method_BrowsableStateAdvanced() As Task
Dim markup = <Text><![CDATA[
Class Program
Sub M()
Dim f As Goo
f.Bar($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
Public Class Goo
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)>
Public Sub Bar()
End Sub
End Class
]]></Text>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("Goo.Bar()", String.Empty, Nothing, currentParameterIndex:=0))
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem),
expectedOrderedItemsSameSolution:=expectedOrderedItems,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic,
hideAdvancedMembers:=True)
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=expectedOrderedItems,
expectedOrderedItemsSameSolution:=expectedOrderedItems,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic,
hideAdvancedMembers:=False)
End Function
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_Method_Overloads_OneBrowsableAlways_OneBrowsableNever() As Task
Dim markup = <Text><![CDATA[
Class Program
Sub M()
Dim f As Goo
f.Bar($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
Public Class Goo
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)>
Public Sub Bar()
End Sub
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)>
Public Sub Bar(x As Integer)
End Sub
End Class
]]></Text>.Value
Dim expectedOrderedItemsMetadataReference = New List(Of SignatureHelpTestItem)()
expectedOrderedItemsMetadataReference.Add(New SignatureHelpTestItem("Goo.Bar()", String.Empty, Nothing, currentParameterIndex:=0))
Dim expectedOrderedItemsSameSolution = New List(Of SignatureHelpTestItem)()
expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("Goo.Bar()", String.Empty, Nothing, currentParameterIndex:=0))
expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("Goo.Bar(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution:=expectedOrderedItemsSameSolution,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_Method_Overloads_BothBrowsableNever() As Task
Dim markup = <Text><![CDATA[
Class Program
Sub M()
New Goo().Bar($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
Public Class Goo
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)>
Public Sub Bar()
End Sub
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)>
Public Sub Bar(x As Integer)
End Sub
End Class
]]></Text>.Value
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem),
expectedOrderedItemsSameSolution:=New List(Of SignatureHelpTestItem),
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestOverriddenSymbolsFilteredFromSigHelp() As Task
Dim markup = <Text><![CDATA[
Class Program
Sub M()
Dim dd as D
dd.Goo($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
Public Class B
Public Overridable Sub Goo(original As Integer)
End Sub
End Class
Public Class D
Inherits B
Public Overrides Sub Goo(derived As Integer)
End Sub
End Class
]]></Text>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("D.Goo(derived As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=expectedOrderedItems,
expectedOrderedItemsSameSolution:=expectedOrderedItems,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverClass() As Task
Dim markup = <Text><![CDATA[
Class Program
Sub M()
Dim x As C
x.Goo($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)>
Public Class C
Public Sub Goo()
End Sub
End Class
]]></Text>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo()", String.Empty, Nothing, currentParameterIndex:=0))
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=expectedOrderedItems,
expectedOrderedItemsSameSolution:=expectedOrderedItems,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverBaseClass() As Task
Dim markup = <Text><![CDATA[
Class Program
Sub M()
Dim x As D
x.Goo($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)>
Public Class B
Public Sub Goo()
End Sub
End Class
Public Class D
Inherits B
Public Overloads Sub Goo(x As Integer)
End Sub
End Class
]]></Text>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem) From {
New SignatureHelpTestItem("B.Goo()", String.Empty, Nothing, currentParameterIndex:=0),
New SignatureHelpTestItem("D.Goo(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)
}
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=expectedOrderedItems,
expectedOrderedItemsSameSolution:=expectedOrderedItems,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_HidingWithDifferentParameterList() As Task
Dim markup = <Text><![CDATA[
Class Program
Sub M()
Dim x As D
x.Goo($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
Public Class B
Public Sub Goo()
End Sub
End Class
Public Class D
Inherits B
Public Sub Goo(x As Integer)
End Sub
End Class
]]></Text>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("D.Goo(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=expectedOrderedItems,
expectedOrderedItemsSameSolution:=expectedOrderedItems,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_BrowsableStateNeverMethodsInBaseClass() As Task
Dim markup = <Text><![CDATA[
Class Program
Inherits B
Sub M()
Goo($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
Public Class B
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)>
Public Sub Goo()
End Sub
End Class
]]></Text>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("B.Goo()", String.Empty, Nothing, currentParameterIndex:=0))
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem),
expectedOrderedItemsSameSolution:=expectedOrderedItems,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableAlways() As Task
Dim markup = <Text><![CDATA[
Class Program
Sub M()
Dim ci = New C(Of Integer)()
ci.Goo($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
Public Class C(Of T)
Public Sub Goo(t As T)
End Sub
Public Sub Goo(i As Integer)
End Sub
End Class
]]></Text>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of Integer).Goo(t As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of Integer).Goo(i As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=expectedOrderedItems,
expectedOrderedItemsSameSolution:=expectedOrderedItems,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed1() As Task
Dim markup = <Text><![CDATA[
Class Program
Sub M()
Dim ci = New C(Of Integer)()
ci.Goo($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
Public Class C(Of T)
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)>
Public Sub Goo(t As T)
End Sub
Public Sub Goo(i As Integer)
End Sub
End Class
]]></Text>.Value
Dim expectedOrderedItemsMetadataReference = New List(Of SignatureHelpTestItem)()
expectedOrderedItemsMetadataReference.Add(New SignatureHelpTestItem("C(Of Integer).Goo(i As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Dim expectedOrderedItemsSameSolution = New List(Of SignatureHelpTestItem)()
expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C(Of Integer).Goo(t As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C(Of Integer).Goo(i As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution:=expectedOrderedItemsSameSolution,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed2() As Task
Dim markup = <Text><![CDATA[
Class Program
Sub M()
Dim ci = New C(Of Integer)()
ci.Goo($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
Public Class C(Of T)
Public Sub Goo(t As T)
End Sub
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)>
Public Sub Goo(i As Integer)
End Sub
End Class
]]></Text>.Value
Dim expectedOrderedItemsMetadataReference = New List(Of SignatureHelpTestItem)()
expectedOrderedItemsMetadataReference.Add(New SignatureHelpTestItem("C(Of Integer).Goo(t As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Dim expectedOrderedItemsSameSolution = New List(Of SignatureHelpTestItem)()
expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C(Of Integer).Goo(t As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C(Of Integer).Goo(i As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution:=expectedOrderedItemsSameSolution,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableNever() As Task
Dim markup = <Text><![CDATA[
Class Program
Sub M()
Dim ci = New C(Of Integer)()
ci.Goo($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
Public Class C(Of T)
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)>
Public Sub Goo(t As T)
End Sub
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)>
Public Sub Goo(i As Integer)
End Sub
End Class
]]></Text>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of Integer).Goo(t As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of Integer).Goo(i As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem),
expectedOrderedItemsSameSolution:=expectedOrderedItems,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableAlways() As Task
Dim markup = <Text><![CDATA[
Class Program
Sub M()
Dim cii As C(Of Integer, Integer)
cii.Goo($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
Public Class C(Of T, U)
Public Sub Goo(t As T)
End Sub
Public Sub Goo(u As U)
End Sub
End Class
]]></Text>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of Integer, Integer).Goo(t As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of Integer, Integer).Goo(u As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=expectedOrderedItems,
expectedOrderedItemsSameSolution:=expectedOrderedItems,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_GenericType2CausingMethodSignatureEquality_BrowsableMixed() As Task
Dim markup = <Text><![CDATA[
Class Program
Sub M()
Dim cii As C(Of Integer, Integer)
cii.Goo($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
Public Class C(Of T, U)
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)>
Public Sub Goo(t As T)
End Sub
Public Sub Goo(u As U)
End Sub
End Class
]]></Text>.Value
Dim expectedOrderedItemsMetadataReference = New List(Of SignatureHelpTestItem)()
expectedOrderedItemsMetadataReference.Add(New SignatureHelpTestItem("C(Of Integer, Integer).Goo(u As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Dim expectedOrderedItemsSameSolution = New List(Of SignatureHelpTestItem)()
expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C(Of Integer, Integer).Goo(t As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C(Of Integer, Integer).Goo(u As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution:=expectedOrderedItemsSameSolution,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableNever() As Task
Dim markup = <Text><![CDATA[
Class Program
Sub M()
Dim cii as C(Of Integer, Integer)
cii.Goo($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
Public Class C(Of T, U)
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)>
Public Sub Goo(t As T)
End Sub
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)>
Public Sub Goo(u As U)
End Sub
End Class
]]></Text>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of Integer, Integer).Goo(t As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of Integer, Integer).Goo(u As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem),
expectedOrderedItemsSameSolution:=expectedOrderedItems,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_DefaultProperty_BrowsableStateAlways() As Task
Dim markup = <Text><![CDATA[
Class Program
Sub M()
Dim cc As C
cc($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
Public Class C
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)>
Default Public Property Prop1(x As Integer) As String
Get
Return "Hi"
End Get
Set(value As String)
End Set
End Property
End Class
]]></Text>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C(x As Integer) As String", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=expectedOrderedItems,
expectedOrderedItemsSameSolution:=expectedOrderedItems,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_DefaultProperty_BrowsableStateNever() As Task
Dim markup = <Text><![CDATA[
Class Program
Sub M()
Dim cc As C
cc($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
Public Class C
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
Default Public Property Prop1(x As Integer) As String
Get
Return "Hi"
End Get
Set(value As String)
End Set
End Property
End Class
]]></Text>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C(x As Integer) As String", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem)(),
expectedOrderedItemsSameSolution:=expectedOrderedItems,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<WorkItem(7336, "DevDiv_Projects/Roslyn")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_DefaultProperty_BrowsableStateAdvanced() As Task
Dim markup = <Text><![CDATA[
Class Program
Sub M()
Dim cc As C
cc($$
End Sub
End Class
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
Public Class C
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)>
Default Public Property Prop1(x As Integer) As String
Get
Return "Hi"
End Get
Set(value As String)
End Set
End Property
End Class
]]></Text>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("C(x As Integer) As String", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem)(),
expectedOrderedItemsSameSolution:=expectedOrderedItems,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic,
hideAdvancedMembers:=True)
Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup,
referencedCode:=referencedCode,
expectedOrderedItemsMetadataReference:=expectedOrderedItems,
expectedOrderedItemsSameSolution:=expectedOrderedItems,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic,
hideAdvancedMembers:=False)
End Function
#End Region
<WorkItem(543038, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543038")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestSignatureHelpWhenALambdaExpressionDeclaredAndInvokedAtTheSameTime() As Task
Dim markup = <text>
Class C
Private ReadOnly field As Integer
Sub New
field = Function(ByVal arg As Integer)
Return 2
End Function($$
End Sub
End Class
</text>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("Invoke(arg As Integer) As Integer", currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestMethodUnavailableInOneLinkedFile() As Task
Dim markup = <text><![CDATA[<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="Proj1" PreprocessorSymbols="GOO=true">
<Document FilePath="SourceDocument">
class C
#if GOO
sub bar()
end sub
#endif
sub goo()
bar($$
end sub
end class
</Document>
</Project>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="Proj1" LinkFilePath="SourceDocument"/>
</Project>
</Workspace>]]></text>.Value.NormalizeLineEndings()
Dim expectedDescription = New SignatureHelpTestItem("C.bar()" + vbCrLf + vbCrLf + String.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available) + vbCrLf + String.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available) + vbCrLf + vbCrLf + FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts, currentParameterIndex:=0)
Await VerifyItemWithReferenceWorkerAsync(markup, {expectedDescription}, False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestExcludeLinkedFilesWithInactiveRegions() As Task
Dim markup = <text><![CDATA[<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="Proj1" PreprocessorSymbols="GOO=true,BAR=true">
<Document FilePath="SourceDocument">
class C
#if GOO
sub bar()
end sub
#endif
#if BAR
sub goo()
bar($$
end sub
#endif
</Document>
</Project>
<Project Language = "Visual Basic" CommonReferences="true" AssemblyName="Proj2">
<Document IsLinkFile = "true" LinkAssemblyName="Proj1" LinkFilePath="SourceDocument"/>
</Project>
<Project Language = "Visual Basic" CommonReferences="true" AssemblyName="Proj3" PreprocessorSymbols="BAR=true">
<Document IsLinkFile = "true" LinkAssemblyName="Proj1" LinkFilePath="SourceDocument"/>
</Project>
</Workspace>]]></text>.Value.NormalizeLineEndings()
Dim expectedDescription = New SignatureHelpTestItem("C.bar()" + $"\r\n\r\n{String.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{String.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}".Replace("\r\n", vbCrLf), currentParameterIndex:=0)
Await VerifyItemWithReferenceWorkerAsync(markup, {expectedDescription}, False)
End Function
<WorkItem(699, "https://github.com/dotnet/roslyn/issues/699")>
<WorkItem(1068424, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068424")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestGenericParameters1() As Task
Dim markup = <a><![CDATA[
Class C
Sub M()
Goo(""$$)
End Sub
Sub Goo(Of T)(a As T)
End Sub
Sub Goo(Of T, U)(a As T, b As U)
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem) From
{
New SignatureHelpTestItem("C.Goo(Of String)(a As String)", String.Empty, String.Empty, currentParameterIndex:=0),
New SignatureHelpTestItem("C.Goo(Of T, U)(a As T, b As U)", String.Empty)
}
Await TestAsync(markup, expectedOrderedItems)
End Function
<WorkItem(699, "https://github.com/dotnet/roslyn/issues/699")>
<WorkItem(1068424, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068424")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestGenericParameters2() As Task
Dim markup = <a><![CDATA[
Class C
Sub M()
Goo("", $$)
End Sub
Sub Goo(Of T)(a As T)
End Sub
Sub Goo(Of T, U)(a As T, b As U)
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem) From
{
New SignatureHelpTestItem("C.Goo(Of T)(a As T)", String.Empty),
New SignatureHelpTestItem("C.Goo(Of T, U)(a As T, b As U)", String.Empty, String.Empty, currentParameterIndex:=1)
}
Await TestAsync(markup, expectedOrderedItems)
End Function
<WorkItem(3537, "https://github.com/dotnet/roslyn/issues/3537")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestEscapedIdentifiers() As Task
Dim markup = "
Class C
Sub [Next]()
Dim x As New C
x.Next($$)
End Sub
End Class
"
Await TestAsync(markup, SpecializedCollections.SingletonEnumerable(New SignatureHelpTestItem("C.Next()", String.Empty)))
End Function
<WorkItem(4144, "https://github.com/dotnet/roslyn/issues/4144")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestSigHelpIsVisibleOnInaccessibleItem() As Task
Dim markup = "
Imports System.Collections.Generic
Class A
Dim args As List(Of Integer)
End Class
Class B
Inherits A
Sub M()
args.Add($$
End Sub
End Class
"
Await TestAsync(markup, {New SignatureHelpTestItem("List(Of Integer).Add(item As Integer)")})
End Function
<WorkItem(2579, "https://github.com/dotnet/roslyn/issues/2579")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationOnMeExpression_Constructor() As Task
Dim markup = <a><![CDATA[
Imports System
Public Class A
Public Sub New()
[|Me.New($$
|]End Sub
Public Sub New(x As Integer)
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem("A.New(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
<WorkItem(40451, "https://github.com/dotnet/roslyn/issues/40451")>
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestSigHelpIsVisibleWithDuplicateMethodNames() As Task
Dim markup = "
Class C
Shared Sub Test()
M(1, 2$$)
End Sub
Sub M(y As Integer)
End Sub
Shared Sub M(x As Integer, y As Integer)
End Sub
End Class
"
Await TestAsync(markup, {New SignatureHelpTestItem("C.M(x As Integer, y As Integer)")})
End Function
End Class
End Namespace
|
shyamnamboodiripad/roslyn
|
src/EditorFeatures/VisualBasicTest/SignatureHelp/InvocationExpressionSignatureHelpProviderTests.vb
|
Visual Basic
|
apache-2.0
| 76,430
|
' 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.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Queries
''' <summary>
''' Recommends the From keyword to introduce a LINQ query or do a cross-join.
''' </summary>
Friend Class FromKeywordRecommender
Inherits AbstractKeywordRecommender
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As IEnumerable(Of RecommendedKeyword)
If context.IsAnyExpressionContext OrElse context.IsQueryOperatorContext Then
Return SpecializedCollections.SingletonEnumerable(
New RecommendedKeyword("From", VBFeaturesResources.Specifies_a_collection_and_a_range_variable_to_use_in_a_query))
End If
Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)()
End Function
End Class
End Namespace
|
jmarolf/roslyn
|
src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Queries/FromKeywordRecommender.vb
|
Visual Basic
|
mit
| 1,250
|
' 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 Roslyn.Test.Utilities
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB
Public Class PDBConstLocalTests
Inherits BasicTestBase
<Fact()>
Public Sub TestSimpleLocalConstants()
Dim source =
<compilation>
<file>
Imports System
Public Class C
Public Sub M()
const x as integer = 1
const y as integer = 2
Console.WriteLine(x + y)
end sub
end class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(
source,
TestOptions.DebugDll)
compilation.VerifyDiagnostics()
compilation.VerifyPdb("C.M",
<symbols>
<files>
<file id="1" name="" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" />
</files>
<methods>
<method containingType="C" name="M">
<sequencePoints>
<entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="19" document="1"/>
<entry offset="0x1" startLine="6" startColumn="9" endLine="6" endColumn="33" document="1"/>
<entry offset="0x8" startLine="7" startColumn="5" endLine="7" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x9">
<namespace name="System" importlevel="file"/>
<currentnamespace name=""/>
<constant name="x" value="1" type="Int32"/>
<constant name="y" value="2" type="Int32"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<Fact()>
Public Sub TestLambdaLocalConstants()
Dim source =
<compilation>
<file>
Imports System
Public Class C
Public Sub M(a as action)
const x as integer = 1
M(
Sub()
const y as integer = 2
const z as integer = 3
Console.WriteLine(x + y + z)
end Sub
)
end sub
end class
</file>
</compilation>
Dim c = CompileAndVerify(source, options:=TestOptions.DebugDll)
c.VerifyPdb(
<symbols>
<files>
<file id="1" name="" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" />
</files>
<methods>
<method containingType="C" name="M" parameterNames="a">
<customDebugInfo>
<encLambdaMap>
<methodOrdinal>1</methodOrdinal>
<lambda offset="48"/>
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="30" document="1"/>
<entry offset="0x1" startLine="5" startColumn="9" endLine="11" endColumn="11" document="1"/>
<entry offset="0x2c" startLine="12" startColumn="5" endLine="12" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x2d">
<namespace name="System" importlevel="file"/>
<currentnamespace name=""/>
<constant name="x" value="1" type="Int32"/>
</scope>
</method>
<method containingType="C+_Closure$__" name="_Lambda$__1-0">
<sequencePoints>
<entry offset="0x0" startLine="6" startColumn="13" endLine="6" endColumn="18" document="1"/>
<entry offset="0x1" startLine="9" startColumn="17" endLine="9" endColumn="45" document="1"/>
<entry offset="0x8" startLine="10" startColumn="13" endLine="10" endColumn="20" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x9">
<importsforward declaringType="C" methodName="M" parameterNames="a"/>
<constant name="y" value="2" type="Int32"/>
<constant name="z" value="3" type="Int32"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
#If False Then
<WorkItem(11017)>
<Fact()>
Public Sub TestIteratorLocalConstants()
Dim text = <text>
using System.Collections.Generic;
class C
{
IEnumerable<int> M()
{
const int x = 1;
for (int i = 0; i < 10; i++)
{
const int y = 2;
yield return x + y + i;
}
}
}
</text>.Value
AssertXmlEqual(expected, actual)
End Sub
#End If
<WorkItem(529101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529101")>
<Fact()>
Public Sub TestLocalConstantsTypes()
Dim source = <compilation>
<file>
Imports System
Public Class C
Sub M()
const o as object = nothing
const s as string = "hello"
const f as single = single.MinValue
const d as double = double.MaxValue
const dec as decimal = 1.5D
const dt as datetime = #2/29/2012#
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(
source,
TestOptions.DebugDll)
compilation.VerifyPdb("C.M",
<symbols>
<files>
<file id="1" name="" language="3a12d0b8-c26c-11d0-b442-00a0244a1dd2" languageVendor="994b45c4-e6e9-11d2-903f-00c04fa302a1" documentType="5a869d0b-6611-11d3-bd2a-0000f80849bd" />
</files>
<methods>
<method containingType="C" name="M">
<sequencePoints>
<entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="12" document="1"/>
<entry offset="0x1" startLine="10" startColumn="5" endLine="10" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x2">
<namespace name="System" importlevel="file"/>
<currentnamespace name=""/>
<constant name="o" value="null" type="Object"/>
<constant name="s" value="hello" type="String"/>
<constant name="f" value="-3.402823E+38" type="Single"/>
<constant name="d" value="1.79769313486232E+308" type="Double"/>
<constant name="dec" value="1.5" type="Decimal"/>
<constant name="dt" value="02/29/2012 00:00:00" type="DateTime"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
End Class
End Namespace
|
pdelvo/roslyn
|
src/Compilers/VisualBasic/Test/Emit/PDB/PDBConstLocalTests.vb
|
Visual Basic
|
apache-2.0
| 7,061
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Roslyn.Test.Utilities
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB
Public Class PDBConstLocalTests
Inherits BasicTestBase
<Fact()>
Public Sub TestSimpleLocalConstants()
Dim source =
<compilation>
<file>
Imports System
Public Class C
Public Sub M()
const x as integer = 1
const y as integer = 2
Console.WriteLine(x + y)
end sub
end class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(
source,
TestOptions.DebugDll)
compilation.VerifyDiagnostics()
compilation.VerifyPdb("C.M",
<symbols>
<methods>
<method containingType="C" name="M">
<sequencePoints>
<entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="19" document="0"/>
<entry offset="0x1" startLine="6" startColumn="9" endLine="6" endColumn="33" document="0"/>
<entry offset="0x8" startLine="7" startColumn="5" endLine="7" endColumn="12" document="0"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x9">
<namespace name="System" importlevel="file"/>
<currentnamespace name=""/>
<constant name="x" value="1" type="Int32"/>
<constant name="y" value="2" type="Int32"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<Fact()>
Public Sub TestLambdaLocalConstants()
Dim source =
<compilation>
<file>
Imports System
Public Class C
Public Sub M(a as action)
const x as integer = 1
M(
Sub()
const y as integer = 2
const z as integer = 3
Console.WriteLine(x + y + z)
end Sub
)
end sub
end class
</file>
</compilation>
Dim c = CompileAndVerify(source, options:=TestOptions.DebugDll)
c.VerifyPdb(
<symbols>
<methods>
<method containingType="C" name="M" parameterNames="a">
<customDebugInfo>
<encLambdaMap>
<methodOrdinal>1</methodOrdinal>
<lambda offset="48"/>
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="30" document="0"/>
<entry offset="0x1" startLine="5" startColumn="9" endLine="11" endColumn="11" document="0"/>
<entry offset="0x2c" startLine="12" startColumn="5" endLine="12" endColumn="12" document="0"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x2d">
<namespace name="System" importlevel="file"/>
<currentnamespace name=""/>
<constant name="x" value="1" type="Int32"/>
</scope>
</method>
<method containingType="C+_Closure$__" name="_Lambda$__1-0">
<sequencePoints>
<entry offset="0x0" startLine="6" startColumn="13" endLine="6" endColumn="18" document="0"/>
<entry offset="0x1" startLine="9" startColumn="17" endLine="9" endColumn="45" document="0"/>
<entry offset="0x8" startLine="10" startColumn="13" endLine="10" endColumn="20" document="0"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x9">
<importsforward declaringType="C" methodName="M" parameterNames="a"/>
<constant name="y" value="2" type="Int32"/>
<constant name="z" value="3" type="Int32"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
#If False Then
<WorkItem(11017)>
<Fact()>
Public Sub TestIteratorLocalConstants()
Dim text = <text>
using System.Collections.Generic;
class C
{
IEnumerable<int> M()
{
const int x = 1;
for (int i = 0; i < 10; i++)
{
const int y = 2;
yield return x + y + i;
}
}
}
</text>.Value
AssertXmlEqual(expected, actual)
End Sub
#End If
<WorkItem(529101, "DevDiv")>
<Fact()>
Public Sub TestLocalConstantsTypes()
Dim source = <compilation>
<file>
Imports System
Public Class C
Sub M()
const o as object = nothing
const s as string = "hello"
const f as single = single.MinValue
const d as double = double.MaxValue
const dec as decimal = 1.5D
const dt as datetime = #2/29/2012#
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(
source,
TestOptions.DebugDll)
compilation.VerifyPdb("C.M",
<symbols>
<methods>
<method containingType="C" name="M">
<sequencePoints>
<entry offset="0x0" startLine="3" startColumn="5" endLine="3" endColumn="12" document="0"/>
<entry offset="0x1" startLine="10" startColumn="5" endLine="10" endColumn="12" document="0"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x2">
<namespace name="System" importlevel="file"/>
<currentnamespace name=""/>
<constant name="o" value="null" type="Object"/>
<constant name="s" value="hello" type="String"/>
<constant name="f" value="-3.402823E+38" type="Single"/>
<constant name="d" value="1.79769313486232E+308" type="Double"/>
<constant name="dec" value="1.5" type="Decimal"/>
<constant name="dt" value="02/29/2012 00:00:00" type="DateTime"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
End Class
End Namespace
|
droyad/roslyn
|
src/Compilers/VisualBasic/Test/Emit/PDB/PDBConstLocalTests.vb
|
Visual Basic
|
apache-2.0
| 6,377
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' This class represent a compiler generated method of a delegate type that is based upon source delegate or event delegate declaration.
''' </summary>
Friend Class SourceDelegateMethodSymbol
Inherits SourceMethodSymbol
' Parameters.
Private _parameters As ImmutableArray(Of ParameterSymbol)
' Return type. Void for a Sub.
Private ReadOnly _returnType As TypeSymbol
Protected Sub New(delegateType As NamedTypeSymbol,
syntax As VisualBasicSyntaxNode,
binder As Binder,
flags As SourceMemberFlags,
returnType As TypeSymbol)
MyBase.New(delegateType, flags, binder.GetSyntaxReference(syntax), delegateType.Locations)
Debug.Assert(TypeOf syntax Is DelegateStatementSyntax OrElse
TypeOf syntax Is EventStatementSyntax)
Debug.Assert(returnType IsNot Nothing)
_returnType = returnType
End Sub
Protected Sub InitializeParameters(parameters As ImmutableArray(Of ParameterSymbol))
Debug.Assert(_parameters.IsDefault)
Debug.Assert(Not parameters.IsDefault)
_parameters = parameters
End Sub
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return _returnType
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return _parameters
End Get
End Property
Friend Overrides ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of MethodSymbol)
Get
Return OverriddenMembersResult(Of MethodSymbol).Empty
End Get
End Property
Friend Shared Sub MakeDelegateMembers(delegateType As NamedTypeSymbol,
syntax As VisualBasicSyntaxNode,
parameterListOpt As ParameterListSyntax,
binder As Binder,
<Out> ByRef constructor As MethodSymbol,
<Out> ByRef beginInvoke As MethodSymbol,
<Out> ByRef endInvoke As MethodSymbol,
<Out> ByRef invoke As MethodSymbol,
diagnostics As DiagnosticBag)
Debug.Assert(TypeOf syntax Is DelegateStatementSyntax OrElse
TypeOf syntax Is EventStatementSyntax)
Dim returnType As TypeSymbol = BindReturnType(syntax, binder, diagnostics)
' reuse types to avoid reporting duplicate errors if missing:
Dim voidType = binder.GetSpecialType(SpecialType.System_Void, syntax, diagnostics)
Dim iAsyncResultType = binder.GetSpecialType(SpecialType.System_IAsyncResult, syntax, diagnostics)
Dim objectType = binder.GetSpecialType(SpecialType.System_Object, syntax, diagnostics)
Dim intPtrType = binder.GetSpecialType(SpecialType.System_IntPtr, syntax, diagnostics)
Dim asyncCallbackType = binder.GetSpecialType(SpecialType.System_AsyncCallback, syntax, diagnostics)
' A delegate has the following members: (see CLI spec 13.6)
' (1) a method named Invoke with the specified signature
Dim invokeMethod = New InvokeMethod(delegateType, returnType, syntax, binder, parameterListOpt, diagnostics)
invoke = invokeMethod
' (2) a constructor with argument types (object, System.IntPtr)
constructor = New Constructor(delegateType, voidType, objectType, intPtrType, syntax, binder)
' If this is a winmd compilation we don't want to add the begin/endInvoke members to the symbol
If delegateType.IsCompilationOutputWinMdObj() Then
beginInvoke = Nothing
endInvoke = Nothing
Else
' (3) BeginInvoke
beginInvoke = New BeginInvokeMethod(invokeMethod, iAsyncResultType, objectType, asyncCallbackType, syntax, binder)
' and (4) EndInvoke methods
endInvoke = New EndInvokeMethod(invokeMethod, iAsyncResultType, syntax, binder)
End If
End Sub
Private Shared Function BindReturnType(syntax As VisualBasicSyntaxNode, binder As Binder, diagnostics As DiagnosticBag) As TypeSymbol
If syntax.Kind = SyntaxKind.DelegateFunctionStatement Then
Dim delegateSyntax = DirectCast(syntax, DelegateStatementSyntax)
Dim getErrorInfo As Func(Of DiagnosticInfo) = Nothing
If binder.OptionStrict = OptionStrict.On Then
getErrorInfo = ErrorFactory.GetErrorInfo_ERR_StrictDisallowsImplicitProc
ElseIf binder.OptionStrict = OptionStrict.Custom Then
getErrorInfo = ErrorFactory.GetErrorInfo_WRN_ObjectAssumed1_WRN_MissingAsClauseinFunction
End If
Dim asClause = DirectCast(delegateSyntax.AsClause, SimpleAsClauseSyntax)
Return binder.DecodeIdentifierType(delegateSyntax.Identifier, asClause, getErrorInfo, diagnostics)
Else
Return binder.GetSpecialType(SpecialType.System_Void, syntax, diagnostics)
End If
End Function
''' <summary>
''' Returns true if this method is an extension method.
''' </summary>
Public NotOverridable Overrides ReadOnly Property IsExtensionMethod As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property MayBeReducibleExtensionMethod As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Gets a value indicating whether this instance is external method.
''' </summary>
''' <value>
''' <c>true</c> if this instance is external method; otherwise, <c>false</c>.
''' </value>
Public NotOverridable Overrides ReadOnly Property IsExternalMethod As Boolean
Get
Return True
End Get
End Property
Public NotOverridable Overrides Function GetDllImportData() As DllImportData
Return Nothing
End Function
Friend NotOverridable Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes
Get
Return Reflection.MethodImplAttributes.Runtime
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray(Of SyntaxReference).Empty
End Get
End Property
''' <summary>
''' Get the type parameters on this method. If the method has not generic,
''' returns an empty list.
''' </summary>
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return ImmutableArray(Of TypeParameterSymbol).Empty
End Get
End Property
''' <summary>
''' Gets a value indicating whether the symbol was generated by the compiler
''' rather than declared explicitly.
''' </summary>
Public NotOverridable Overrides ReadOnly Property IsImplicitlyDeclared As Boolean
Get
Return True
End Get
End Property
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
Return False
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return Me.MethodKind = MethodKind.Constructor
End Get
End Property
Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String)
Return ImmutableArray(Of String).Empty
End Function
Protected NotOverridable Overrides Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))
' delegate methods don't inherit attributes from the delegate type, only parameters and return types do
Return Nothing
End Function
Private NotInheritable Class Constructor
Inherits SourceDelegateMethodSymbol
Public Sub New(delegateType As NamedTypeSymbol,
voidType As TypeSymbol,
objectType As TypeSymbol,
intPtrType As TypeSymbol,
syntax As VisualBasicSyntaxNode,
binder As Binder)
MyBase.New(delegateType,
syntax,
binder,
flags:=SourceMemberFlags.MethodKindConstructor Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.MethodIsSub,
returnType:=voidType)
InitializeParameters(ImmutableArray.Create(Of ParameterSymbol)(
New SynthesizedParameterSymbol(Me, objectType, 0, False, StringConstants.DelegateConstructorInstanceParameterName),
New SynthesizedParameterSymbol(Me, intPtrType, 1, False, StringConstants.DelegateConstructorMethodParameterName)))
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return WellKnownMemberNames.InstanceConstructorName
End Get
End Property
Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))
' Constructor doesn't have return type attributes
Return Nothing
End Function
End Class
Private NotInheritable Class InvokeMethod
Inherits SourceDelegateMethodSymbol
Public Sub New(delegateType As NamedTypeSymbol,
returnType As TypeSymbol,
syntax As VisualBasicSyntaxNode,
binder As Binder,
parameterListOpt As ParameterListSyntax,
diagnostics As DiagnosticBag)
MyBase.New(delegateType,
syntax,
binder,
flags:=SourceMemberFlags.MethodKindDelegateInvoke Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.Overridable Or
If(returnType.SpecialType = SpecialType.System_Void, SourceMemberFlags.MethodIsSub, Nothing),
returnType:=returnType)
InitializeParameters(binder.DecodeParameterListOfDelegateDeclaration(Me, parameterListOpt, diagnostics))
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return WellKnownMemberNames.DelegateInvokeName
End Get
End Property
End Class
Private NotInheritable Class BeginInvokeMethod
Inherits SourceDelegateMethodSymbol
Public Sub New(invoke As InvokeMethod,
iAsyncResultType As TypeSymbol,
objectType As TypeSymbol,
asyncCallbackType As TypeSymbol,
syntax As VisualBasicSyntaxNode,
binder As Binder)
MyBase.New(invoke.ContainingType,
syntax,
binder,
flags:=SourceMemberFlags.MethodKindOrdinary Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.Overridable,
returnType:=iAsyncResultType)
Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance()
Dim ordinal As Integer = 0
For Each parameter In invoke.Parameters
parameters.Add(New SourceClonedParameterSymbol(DirectCast(parameter, SourceParameterSymbol), Me, ordinal))
ordinal += 1
Next
parameters.Add(New SynthesizedParameterSymbol(Me, asyncCallbackType, ordinal, False, StringConstants.DelegateMethodCallbackParameterName))
ordinal += 1
parameters.Add(New SynthesizedParameterSymbol(Me, objectType, ordinal, False, StringConstants.DelegateMethodInstanceParameterName))
InitializeParameters(parameters.ToImmutableAndFree())
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return WellKnownMemberNames.DelegateBeginInvokeName
End Get
End Property
Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))
' BeginInvoke doesn't have return type attributes
Return Nothing
End Function
End Class
Private NotInheritable Class EndInvokeMethod
Inherits SourceDelegateMethodSymbol
Public Sub New(invoke As InvokeMethod,
iAsyncResultType As TypeSymbol,
syntax As VisualBasicSyntaxNode,
binder As Binder)
MyBase.New(invoke.ContainingType,
syntax,
binder,
flags:=SourceMemberFlags.MethodKindOrdinary Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.Overridable Or
If(invoke.ReturnType.SpecialType = SpecialType.System_Void, SourceMemberFlags.MethodIsSub, Nothing),
returnType:=invoke.ReturnType)
Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance()
Dim ordinal = 0
For Each parameter In invoke.Parameters
If parameter.IsByRef Then
parameters.Add(New SourceClonedParameterSymbol(DirectCast(parameter, SourceParameterSymbol), Me, ordinal))
ordinal += 1
End If
Next
parameters.Add(New SynthesizedParameterSymbol(Me, iAsyncResultType, parameters.Count, False, StringConstants.DelegateMethodResultParameterName))
InitializeParameters(parameters.ToImmutableAndFree())
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return WellKnownMemberNames.DelegateEndInvokeName
End Get
End Property
Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))
' EndInvoke doesn't have return type attributes
Return Nothing
End Function
End Class
End Class
End Namespace
|
bbarry/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/Source/SourceDelegateMethodSymbol.vb
|
Visual Basic
|
apache-2.0
| 15,822
|
Imports SistFoncreagro.BussinesLogic
Imports SistFoncreagro.BussinessEntities
Imports System.Data
Imports Telerik.Web.UI
Imports System.Web.Services
Imports System.Data.SqlClient
Imports System.Collections.Generic
Imports System.Collections
Imports System.Configuration
Imports System
Public Class VentanaAutorizacion
Inherits System.Web.UI.Page
Dim Nombre As String
Dim IdPersonal As String
Dim IdPermisoUsuario As String
Dim PermisoUsuario As PermisoUsuario
Dim _PermisoUsuario As New PermisoUsuario
Dim PermisoUsuarioBL As New PermisoUsuarioBL
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Nombre = Request.QueryString("Nombre")
IdPersonal = Request.QueryString("IdPersonal")
IdPermisoUsuario = Request.QueryString("IdPermisoUsuario")
Me.Label1.Text = Nombre
If Page.IsPostBack = False Then
'para recuperar datos
PermisoUsuario = PermisoUsuarioBL.GetPERMISOUSUARIOByIdPersonal(IdPersonal)
If PermisoUsuario.FechaPermiso.HasValue Then
Me.RadDatePicker1.SelectedDate = PermisoUsuario.FechaPermiso
Else
Me.RadDatePicker1.SelectedDate = Date.Now
End If
If PermisoUsuario.Estado = True Then
Me.DropDownList1.SelectedValue = 1
Else
Me.DropDownList1.SelectedValue = 0
End If
Me.TextBox12.Text = PermisoUsuario.HoraInicio
Me.TextBox1.Text = PermisoUsuario.HoraFin
End If
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
_PermisoUsuario.Estado = Me.DropDownList1.SelectedValue
_PermisoUsuario.FechaPermiso = Me.RadDatePicker1.SelectedDate
_PermisoUsuario.HoraFin = Me.TextBox1.Text
_PermisoUsuario.HoraInicio = Me.TextBox12.Text
_PermisoUsuario.IdPersonal = IdPersonal
_PermisoUsuario.IdPersonalAutoriza = Session("IdUser")
_PermisoUsuario.IdPermisoUsuario = IdPermisoUsuario
PermisoUsuarioBL.SavePERMISOUSUARIO(_PermisoUsuario)
End Sub
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.WebSite/Logistica/VentanaAutorizacion.aspx.vb
|
Visual Basic
|
mit
| 2,181
|
Imports SistFoncreagro.BussinesLogic
Imports SistFoncreagro.BussinessEntities
Imports Telerik.Web.UI
Public Class FrmAprobarRendicion
Inherits System.Web.UI.Page
Dim ReciboRendicionBL As New RecibosRendicionBL
Dim _ReciboRendicion As New RecibosRendicion
Dim RendicionBL As New RendicionBL
Dim _Rendicion As New Rendicion
Dim Rendicion As Rendicion
Dim IdRendicion As String
Dim _DocumentoRendido As New DocumentoRendido
Dim DocumentoRendidoBL As New DocumentoRendidoBL
Dim ReciboBL As New ReciboBL
Dim TransaccionBl As New TransaccionBL
Dim EjercicioBL As New EjercicioBL
Dim estadoMes As String = ""
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
estadoMes = EjercicioBL.GetEstadoMes(Session("Anio"), Session("Mes"))
If estadoMes = "C" Then
Me.ImageButton6.Visible = False
Me.ImageButton7.Visible = False
End If
Me.ImageButton6.Attributes.Add("onClick", "radconfirm('¿Esta acción APROBARÁ la Rendición?', confirmCallBackFn, 330, 100, null,'Mensaje de Confirmación'); return false;")
'If Me.RadTextBox3.Text.Length > 0 Then
' Me.ImageButton7.Attributes.Add("onClick", "radconfirm('¿Esta acción REGRESARÁ la Rendicion para su corrección?', confirmCallBackFn1, 330, 100, null, 'Mensaje de Confirmación'); return false;")
'End If
IdRendicion = Request.QueryString("IdRendicion")
Me.RadTextBox2.Text = IdRendicion
If Page.IsPostBack = False Then
If Me.RadTextBox2.Text > 0 Then
'para recuperar datos de rendicion
Rendicion = RendicionBL.GetRENDICIONByIdRendicion(IdRendicion)
Me.RadTextBox2.Text = Rendicion.IdRendicion
Me.RadComboBox5.SelectedValue = Rendicion.IdOpFinanciera
Me.RadComboBox4.SelectedValue = Rendicion.IdSubDiario
Me.RadTextBox1.Text = Rendicion.Codigo
Me.RadComboBox3.SelectedValue = Rendicion.IdProyecto
Me.txtDate.Text = Rendicion.Fecha
Me.RadTextBox3.Text = Rendicion.Observacion
Me.RadNumericTextBox1.Text = RendicionBL.GetTotalRendicion(Me.RadTextBox2.Text)
End If
End If
End Sub
Protected Sub RadAjaxManager1_AjaxRequest(ByVal sender As Object, ByVal e As Telerik.Web.UI.AjaxRequestEventArgs) Handles RadAjaxManager1.AjaxRequest
If e.Argument.StartsWith("Enviar") Then
Dim j() As String
Dim valor As String
j = Split(e.Argument, "|")
valor = j(1)
If valor = "true" Then
Dim IdTransaccion As Int32
Dim codigo As String
IdTransaccion = TransaccionBl.GenerarTRANSACCIONByIdRendicion(IdRendicion, Session("IdUser"))
RendicionBL.UpdateEstadoRENDICION(IdRendicion, "3")
codigo = TransaccionBl.GetTransaccionByIdTransaccion(IdTransaccion).IdSubDiario.ToString + "-" + TransaccionBl.GetTransaccionByIdTransaccion(IdTransaccion).Codigo
Dim cadena_java As String = _
"<script language='javascript'>function f(){radalert('<b>Se ha generado el Comprobante: " + codigo.ToString + "</b> ', 330, 100,'Mensaje de Información',alertCallBackFn); Sys.Application.remove_load(f);}; Sys.Application.add_load(f);</script>"
ScriptManager.RegisterStartupScript(Page, GetType(Page), "AlertaX", cadena_java.ToString, False)
End If
ElseIf e.Argument.StartsWith("Observar") Then
Dim j() As String
Dim valor As String
j = Split(e.Argument, "|")
valor = j(1)
If valor = "true" Then
RendicionBL.UpdateObservacionRENDICION(IdRendicion, Me.RadTextBox3.Text)
RendicionBL.UpdateEstadoRENDICION(IdRendicion, "4")
Response.Redirect("ListaRendicionesPorAprobar.aspx")
End If
ElseIf e.Argument.StartsWith("Redireccionar") Then
Response.Redirect("ListaRendicionesPorAprobar.aspx")
End If
End Sub
Protected Sub ImageButton7_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton7.Click
If Me.RadTextBox3.Text.Length > 0 Then
Dim radconfirmscript As String = "<script language='javascript'>function f(){radconfirm('¿Esta acción REGRESARÁ la Rendicion para su corrección?', confirmCallBackFn1, 330, 100, null, 'Mensaje de Confirmación'); Sys.Application.remove_load(f);}; Sys.Application.add_load(f); ;</script>"
Page.ClientScript.RegisterStartupScript(Me.[GetType](), "radconfirm", radconfirmscript)
End If
End Sub
Protected Sub ImageButton9_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton9.Click
Dim cadena_java As String
cadena_java = "<script type='text/javascript'> " & _
" window.open('ReporteContabilizacionFondoFijo.aspx?IdRendicion=" + Me.RadTextBox2.Text + "'); " & _
Chr(60) & "/script>"
ScriptManager.RegisterStartupScript(Page, GetType(Page), "Cerrar", cadena_java.ToString, False)
End Sub
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.WebSite/Contabilidad/Formularios/FrmAprobarRendicion.aspx.vb
|
Visual Basic
|
mit
| 5,381
|
#Region "License"
' The MIT License (MIT)
'
' Copyright (c) 2018 Richard L King (TradeWright Software Systems)
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.
#End Region
Imports System.Threading.Tasks
Friend NotInheritable Class MarketDepthParser
Inherits ParserBase
Implements IParser
Private Const ModuleName As String = NameOf(MarketDepthParser)
Friend Overrides Async Function ParseAsync(pVersion As Integer, timestamp As Date) As Task(Of Boolean)
Dim id = Await _Reader.GetIntAsync("Id")
Dim lPosition = Await _Reader.GetIntAsync("Position")
Dim lOperation = DirectCast(Await _Reader.GetIntAsync("Operation"), DOMOperation)
Dim lSide = DirectCast(Await _Reader.GetIntAsync("Side"), DOMSide)
Dim lPrice = Await _Reader.GetDoubleAsync("Price")
Dim lSize = Await _Reader.GetIntAsync("Size")
LogSocketInputMessage(ModuleName,"ParseAsync")
Try
_EventConsumers.MarketDepthConsumer?.NotifyMarketDepth(New MarketDepthUpdateEventArgs(timestamp, IdManager.GetCallerId(id, IdType.MarketDepth), lPosition, lOperation, lSide, lPrice, lSize, ""))
Return True
Catch e As Exception
Throw New ApiApplicationException("NotifyMarketDepth", e)
End Try
End Function
Friend Overrides ReadOnly Property MessageType As ApiSocketInMsgType
Get
Return ApiSocketInMsgType.MarketDepth
End Get
End Property
End Class
|
tradewright/tradewright-twsapi
|
src/IBApi/Parsers/MarketDepthParser.vb
|
Visual Basic
|
mit
| 2,494
|
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 order As New List(Of PropertyOrder)()
order.Add(New PropertyOrder(MessagePropertyPath.ReceivedTime, SortDirection.Descending))
Dim view As New IndexedPageView()
view.MaxEntriesReturned = 10
Dim response As FindItemResponse = service.FindItem(StandardFolder.Inbox, MessagePropertyPath.AllPropertyPaths, order, view)
For i As Integer = 0 To response.Items.Count - 1
If TypeOf response.Items(i) Is Message Then
Dim message As Message = DirectCast(response.Items(i), Message)
Console.WriteLine("Subject = " & message.Subject)
Console.WriteLine("ReceivedTime = " & message.ReceivedTime)
If message.From IsNot Nothing Then
Console.WriteLine("From = " & message.From.Name)
End If
Console.WriteLine("Body Preview = " & message.BodyPlainText)
Console.WriteLine("----------------------------------------------------------------")
End If
Next
Console.Read()
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/VBFindTopTenMessages/Module1.vb
|
Visual Basic
|
mit
| 1,948
|
Imports System.Collections.ObjectModel
Imports System.ComponentModel
Imports System.Data
Imports System.Text.RegularExpressions
Imports Business.Business
Imports Entities.Entities
Imports MaterialDesignThemes.Wpf
Public Class ucPhieuKham
Dim listChiTietPhieuKham As ObservableCollection(Of ROWChiTietPhieuKhamDTO)
Dim firstTime As Boolean = True
''' <summary>
''' Làm cho textbox chỉ nhập đc số
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub NumberValidationTextBox(ByVal sender As Object, ByVal e As TextCompositionEventArgs)
Dim regex As Regex = New Regex("[^0-9]+")
e.Handled = regex.IsMatch(e.Text)
End Sub
Private Sub NewButton_Click(sender As Object, e As RoutedEventArgs)
'Kiểm tra danh sách chi tiết phiếu khám có rỗng không
If Not listChiTietPhieuKham.Count = 0 Then
'Kiểm tra người dùng đã cập nhật chi tiết phiếu khám mới thêm vào trước đó hay chưa
If Not listChiTietPhieuKham.Last.MaChiTietPhieuKham = ChiTietPhieuKhamBUS.GetMaChiTietPhieuKham() Then
'Thêm chi tiết phiếu khám mới rỗng vào danh sách
Dim ChiTietPhieuKham As New ROWChiTietPhieuKhamDTO() With {.MaChiTietPhieuKham = ChiTietPhieuKhamBUS.GetMaChiTietPhieuKham(),
.MaKhamBenh = cbMaKhamBenh.SelectedValue}
listChiTietPhieuKham.Add(ChiTietPhieuKham)
dgChiTietPhieuKham.SelectedIndex = dgChiTietPhieuKham.Items.Count - 1
Else
Domain.Dialog.Show("Bạn chưa cập nhật bệnh nhân bạn mới thêm vào trước đó")
Exit Sub
End If
Else
'Thêm chi tiết phiếu khám mới rỗng vào danh sách
Dim ChiTietPhieuKham As New ROWChiTietPhieuKhamDTO() With {.MaChiTietPhieuKham = ChiTietPhieuKhamBUS.GetMaChiTietPhieuKham(),
.MaKhamBenh = cbMaKhamBenh.SelectedValue}
listChiTietPhieuKham.Add(ChiTietPhieuKham)
dgChiTietPhieuKham.SelectedIndex = dgChiTietPhieuKham.Items.Count - 1
End If
End Sub
Private Sub UpdateButton_Click(sender As Object, e As RoutedEventArgs)
'Kiểm tra người dùng đã chọn chi tiết phiếu khám trong danh sách hay chưa
If dgChiTietPhieuKham.SelectedIndex = -1 Then
Domain.Dialog.Show("Chưa có đối tượng được chọn")
Exit Sub
End If
'Lấy thông tin từ người dùng và kiểm tra
Dim chiTietPhieuKham As New ChiTietPhieuKhamDTO
chiTietPhieuKham.MaChiTietPhieuKham = tbMaChiTietPhieuKham.Text
chiTietPhieuKham.MaKhamBenh = cbMaKhamBenh.Text
chiTietPhieuKham.TrieuChung = tbTrieuChung.Text
chiTietPhieuKham.LoiDan = tbLoiDan.Text
chiTietPhieuKham.MaLoaiBenh = cbLoaiBenh.SelectedValue
chiTietPhieuKham.MaThuoc = cbThuoc.SelectedValue
chiTietPhieuKham.MaDonVi = cbDonVi.SelectedValue
If Not ChiTietPhieuKhamBUS.IsVaildSoLuong(tbSoLuong.Text, chiTietPhieuKham.SoLuong) Then
Domain.Dialog.Show("Số lượng không hợp lệ")
Exit Sub
End If
chiTietPhieuKham.MaCachDung = cbCachDung.SelectedValue
If Not ChiTietPhieuKhamBUS.IsVaildChiTietPhieuKham(chiTietPhieuKham) Then
Domain.Dialog.Show("Thông tin không hợp lệ")
Exit Sub
End If
'Tiến hành cập nhật
Dim result As Boolean = ChiTietPhieuKhamBUS.InsertOrUpdateChiTietPhieuKham(chiTietPhieuKham)
If (result = True) Then
Domain.Dialog.Show("Cập nhật thành công")
Else
Domain.Dialog.Show("Cập nhật thất bại")
End If
ReloadData()
End Sub
Private Async Sub DeleteButton_Click(sender As Object, e As RoutedEventArgs)
'Kiểm tra người dùng có muốn xóa hay không
Dim dialog As New Domain.YesNoDialog
dialog.Message.Text = "Bạn chắc chắn xóa " + dgChiTietPhieuKham.SelectedItems.Count.ToString() + " thuốc được chọn"
Await DialogHost.Show(dialog)
If (dialog.DialogResult = MessageBoxResult.No) Then
Exit Sub
End If
'Tiến hành xóa
Dim result As Boolean
For Each ChiTietPhieuKham As ChiTietPhieuKhamDTO In dgChiTietPhieuKham.SelectedItems
result = DeleteChiTietPhieuKhamByMa(ChiTietPhieuKham.MaChiTietPhieuKham)
Next
If (result = True) Then
Domain.Dialog.Show("Xóa thành công")
Else
Domain.Dialog.Show("Xóa thất bại")
End If
ReloadData()
End Sub
Private Sub CancelButton_Click(sender As Object, e As RoutedEventArgs)
dgChiTietPhieuKham.SelectedIndex = -1
End Sub
Private Sub ExportButton_Click(sender As Object, e As RoutedEventArgs)
'Kiểm tra danh sách chi tiết phiếu khám có rỗng không
If Not listChiTietPhieuKham.Count = 0 Then
'Kiểm tra người dùng đã cập nhật chi tiết phiếu khám mới thêm vào trước đó hay chưa
If Not listChiTietPhieuKham.Last.MaChiTietPhieuKham = ChiTietPhieuKhamBUS.GetMaChiTietPhieuKham() Then
'Thêm chi tiết phiếu khám mới rỗng vào danh sách
PhieuKhamBUS.ExportInvoice(cbMaKhamBenh.SelectedValue)
Else
Domain.Dialog.Show("Bạn chưa cập nhật bệnh nhân bạn mới thêm vào trước đó")
Exit Sub
End If
Else
'Thêm chi tiết phiếu khám mới rỗng vào danh sách
PhieuKhamBUS.ExportInvoice(cbMaKhamBenh.SelectedValue)
End If
End Sub
''' <summary>
''' Tải lại dữ liệu khi người dùng chọn bệnh nhân khác
''' </summary>
Private Sub ReloadData()
If dgChiTietPhieuKham IsNot Nothing And cbMaKhamBenh.SelectedValue IsNot Nothing Then
listChiTietPhieuKham = ROWChiTietPhieuKhamBUS.GetChiTietPhieuKhamByMaKhamBenh(cbMaKhamBenh.SelectedValue.ToString())
dgChiTietPhieuKham.DataContext = listChiTietPhieuKham
End If
End Sub
''' <summary>
''' Khởi tạo nguồn dữ liệu cho combobox khi người dùng vào màn hình
''' </summary>
Private Sub LoadComboBoxData()
If Me.IsVisible = True Then
If firstTime Then
dpNgayKhamBenh.SelectedDate = Date.Now
firstTime = False
End If
cbLoaiBenh.ItemsSource = LoaiBenhBUS.GetAllLoaiBenh()
If cbMaKhamBenh.SelectedItem IsNot Nothing Then
cbLoaiBenh.SelectedValue = CType(cbMaKhamBenh.SelectedItem, KhamBenhDTO).MaLoaiBenh
End If
cbDonVi.ItemsSource = LoaiDonViBUS.GetAllLoaiDonVi()
cbCachDung.ItemsSource = LoaiCachDungBUS.GetAllLoaiCachDung()
cbThuoc.ItemsSource = LoaiThuocBUS.GetAllLoaiThuoc()
ReloadData()
End If
End Sub
Private Sub cbMaKhamBenh_SelectionChanged(sender As Object, e As SelectionChangedEventArgs)
'Cập nhật lại danh sách chi tiết phiếu khám khi người dùng chọn bệnh nhân khác
If cbMaKhamBenh IsNot Nothing Then
ReloadData()
End If
End Sub
Private Sub dpNgayKhamBenh_SelectedDateChanged(sender As Object, e As SelectionChangedEventArgs)
'Cập nhật lại danh sách bệnh nhân khi ngày người dùng chọn thay đổi
If dpNgayKhamBenh IsNot Nothing And dpNgayKhamBenh.SelectedDate IsNot Nothing Then
cbMaKhamBenh.ItemsSource = KhamBenhBUS.GetKhamBenhByNgayKham(dpNgayKhamBenh.SelectedDate)
End If
End Sub
Private Sub cbMaKhamBenh_MouseDown(sender As Object, e As MouseButtonEventArgs)
If dpNgayKhamBenh.SelectedDate Is Nothing Then
Domain.Dialog.Show("Ngày khám chưa được chọn")
End If
End Sub
''' <summary>
''' Kiếm tra xem ngày hợp lệ hay không
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub DatePickerDateValidationError(sender As Object, e As DatePickerDateValidationErrorEventArgs)
Dim dp As DatePicker = sender
e.ThrowException = False
Domain.Dialog.Show("Ngày không hợp lệ")
dp.SelectedDate = Date.Now()
End Sub
End Class
|
trumpsilver/ScrapTest
|
Presentation/ucPhieuKham.xaml.vb
|
Visual Basic
|
mit
| 8,649
|
Option Infer On
Imports System
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim partDocument As SolidEdgePart.PartDocument = Nothing
Dim models As SolidEdgePart.Models = Nothing
Dim model As SolidEdgePart.Model = Nothing
Dim body As SolidEdgeGeometry.Body = Nothing
Dim shells As SolidEdgeGeometry.Shells = Nothing
Dim shell As SolidEdgeGeometry.Shell = Nothing
Dim faces As SolidEdgeGeometry.Faces = Nothing
Dim face As SolidEdgeGeometry.Face = Nothing
Dim torus As SolidEdgeGeometry.Torus = Nothing
Try
' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register()
' Attempt to connect to a running instance of Solid Edge.
application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application)
partDocument = TryCast(application.ActiveDocument, SolidEdgePart.PartDocument)
If partDocument IsNot Nothing Then
models = partDocument.Models
model = models.Item(1)
body = CType(model.Body, SolidEdgeGeometry.Body)
shells = CType(body.Shells, SolidEdgeGeometry.Shells)
shell = CType(shells.Item(1), SolidEdgeGeometry.Shell)
faces = CType(shell.Faces, SolidEdgeGeometry.Faces)
For i As Integer = 1 To faces.Count
face = CType(faces.Item(i), SolidEdgeGeometry.Face)
torus = TryCast(face.Geometry, SolidEdgeGeometry.Torus)
If torus IsNot Nothing Then
Dim majorRadius = torus.MajorRadius
End If
Next i
End If
Catch ex As System.Exception
Console.WriteLine(ex)
Finally
OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgeGeometry.Torus.MajorRadius.vb
|
Visual Basic
|
mit
| 2,302
|
'03:43:56
'03.10.2013
'Autor: LargoWinch
Friend Class RequestServerLogin
Inherits L_ReceiveBasePacket
Public Sub New(ByVal Client As L_LoginClient, ByVal data() As Byte)
MyBase.makeme(Client, data)
End Sub
Private login1, login2 As Integer
Private serverId As Byte
Public Overrides Sub read()
login1 = readD()
login2 = readD()
serverId = readC()
End Sub
Public Overrides Sub run()
If getClient().login1 <> login1 AndAlso getClient().login2 <> login2 Then
getClient().sendPacket(New SM_LOGIN_FAIL(getClient(), SM_LOGIN_FAIL.LoginFailReason.SYSTEM_ERROR))
Return
End If
Dim server As L_L2Server = ServerThreadPool.getInstance().get(serverId)
If server Is Nothing Then
getClient().sendPacket(New SM_LOGIN_FAIL(getClient(), SM_LOGIN_FAIL.LoginFailReason.SYSTEM_ERROR))
Return
End If
If server.connected = 0 Then
getClient().sendPacket(New SM_LOGIN_FAIL(getClient(), SM_LOGIN_FAIL.LoginFailReason.SERVER_MAINTENANCE))
Else
If server.gmonly AndAlso getClient().activeAccount.Builder = 0 Then
getClient().sendPacket(New SM_LOGIN_FAIL(getClient(), SM_LOGIN_FAIL.LoginFailReason.NO_ACCESS_COUPON))
Return
End If
ServerThreadPool.getInstance().SendPlayer(serverId, getClient(), Date.Now.ToLocalTime().ToString())
Dim sqb As New Sql_Block("accounts")
sqb.param("serverId", serverId)
sqb.param("lastlogin", Date.Now.ToLocalTime())
sqb.param("lastAddress", getClient()._address)
sqb.where("account", getClient().activeAccount.Name)
sqb.sql_update()
getClient().sendPacket(New PlayOk(getClient()))
End If
End Sub
End Class
|
LargoWinch/LegacyEmu
|
LoginServer/Login_Server/LoginServer/network/clientpackets/RequestServerLogin.vb
|
Visual Basic
|
apache-2.0
| 1,867
|
' 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.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Namespace Microsoft.CodeAnalysis.VisualBasic
<ExportLanguageServiceFactory(GetType(ISyntaxFactsService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicSyntaxFactsServiceFactory
Implements ILanguageServiceFactory
Public Function CreateLanguageService(languageServices As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService
Return VisualBasicSyntaxFactsService.Instance
End Function
End Class
Friend Class VisualBasicSyntaxFactsService
Inherits AbstractSyntaxFactsService
Implements ISyntaxFactsService
Public Shared ReadOnly Property Instance As New VisualBasicSyntaxFactsService
Private Sub New()
End Sub
Public ReadOnly Property IsCaseSensitive As Boolean Implements ISyntaxFactsService.IsCaseSensitive
Get
Return False
End Get
End Property
Public ReadOnly Property StringComparer As StringComparer Implements ISyntaxFactsService.StringComparer
Get
Return CaseInsensitiveComparison.Comparer
End Get
End Property
Public ReadOnly Property ElasticMarker As SyntaxTrivia Implements ISyntaxFactsService.ElasticMarker
Get
Return SyntaxFactory.ElasticMarker
End Get
End Property
Public ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia Implements ISyntaxFactsService.ElasticCarriageReturnLineFeed
Get
Return SyntaxFactory.ElasticCarriageReturnLineFeed
End Get
End Property
Protected Overrides ReadOnly Property DocumentationCommentService As IDocumentationCommentService
Get
Return VisualBasicDocumentationCommentService.Instance
End Get
End Property
Public Function SupportsIndexingInitializer(options As ParseOptions) As Boolean Implements ISyntaxFactsService.SupportsIndexingInitializer
Return False
End Function
Public Function SupportsThrowExpression(options As ParseOptions) As Boolean Implements ISyntaxFactsService.SupportsThrowExpression
Return False
End Function
Public Function ParseToken(text As String) As SyntaxToken Implements ISyntaxFactsService.ParseToken
Return SyntaxFactory.ParseToken(text, startStatement:=True)
End Function
Public Function IsAwaitKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsAwaitKeyword
Return token.Kind = SyntaxKind.AwaitKeyword
End Function
Public Function IsIdentifier(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsIdentifier
Return token.Kind = SyntaxKind.IdentifierToken
End Function
Public Function IsGlobalNamespaceKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsGlobalNamespaceKeyword
Return token.Kind = SyntaxKind.GlobalKeyword
End Function
Public Function IsVerbatimIdentifier(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsVerbatimIdentifier
Return False
End Function
Public Function IsOperator(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsOperator
Return (IsUnaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is UnaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) OrElse
(IsBinaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is BinaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax))
End Function
Public Function IsContextualKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsContextualKeyword
Return token.IsContextualKeyword()
End Function
Public Function IsKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsKeyword
Return token.IsKeyword()
End Function
Public Function IsPreprocessorKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsPreprocessorKeyword
Return token.IsPreprocessorKeyword()
End Function
Public Function IsHashToken(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsHashToken
Return token.Kind = SyntaxKind.HashToken
End Function
Public Function TryGetCorrespondingOpenBrace(token As SyntaxToken, ByRef openBrace As SyntaxToken) As Boolean Implements ISyntaxFactsService.TryGetCorrespondingOpenBrace
If token.Kind = SyntaxKind.CloseBraceToken Then
Dim tuples = token.Parent.GetBraces()
openBrace = tuples.Item1
Return openBrace.Kind = SyntaxKind.OpenBraceToken
End If
Return False
End Function
Public Function IsInInactiveRegion(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFactsService.IsInInactiveRegion
If syntaxTree Is Nothing Then
Return False
End If
Return syntaxTree.IsInInactiveRegion(position, cancellationToken)
End Function
Public Function IsInNonUserCode(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFactsService.IsInNonUserCode
If syntaxTree Is Nothing Then
Return False
End If
Return syntaxTree.IsInNonUserCode(position, cancellationToken)
End Function
Public Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFactsService.IsEntirelyWithinStringOrCharOrNumericLiteral
If syntaxTree Is Nothing Then
Return False
End If
Return syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken)
End Function
Public Function IsDirective(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsDirective
Return TypeOf node Is DirectiveTriviaSyntax
End Function
Public Function TryGetExternalSourceInfo(node As SyntaxNode, ByRef info As ExternalSourceInfo) As Boolean Implements ISyntaxFactsService.TryGetExternalSourceInfo
Select Case node.Kind
Case SyntaxKind.ExternalSourceDirectiveTrivia
info = New ExternalSourceInfo(CInt(DirectCast(node, ExternalSourceDirectiveTriviaSyntax).LineStart.Value), False)
Return True
Case SyntaxKind.EndExternalSourceDirectiveTrivia
info = New ExternalSourceInfo(Nothing, True)
Return True
End Select
Return False
End Function
Public Function IsObjectCreationExpressionType(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsObjectCreationExpressionType
Return node.IsParentKind(SyntaxKind.ObjectCreationExpression) AndAlso
DirectCast(node.Parent, ObjectCreationExpressionSyntax).Type Is node
End Function
Public Function IsAttributeName(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsAttributeName
Return node.IsParentKind(SyntaxKind.Attribute) AndAlso
DirectCast(node.Parent, AttributeSyntax).Name Is node
End Function
Public Function IsRightSideOfQualifiedName(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsRightSideOfQualifiedName
Dim vbNode = TryCast(node, SimpleNameSyntax)
Return vbNode IsNot Nothing AndAlso vbNode.IsRightSideOfQualifiedName()
End Function
Public Function IsNameOfMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsNameOfMemberAccessExpression
Dim vbNode = TryCast(node, SimpleNameSyntax)
Return vbNode IsNot Nothing AndAlso vbNode.IsMemberAccessExpressionName()
End Function
Public Function IsConditionalMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsConditionalMemberAccessExpression
Return TypeOf node Is ConditionalAccessExpressionSyntax
End Function
Public Function IsInvocationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsInvocationExpression
Return TypeOf node Is InvocationExpressionSyntax
End Function
Public Function IsAnonymousFunction(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsAnonymousFunction
Return TypeOf node Is LambdaExpressionSyntax
End Function
Public Function IsGenericName(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsGenericName
Return TypeOf node Is GenericNameSyntax
End Function
Public Function IsNamedParameter(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsNamedParameter
Return node.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is node)
End Function
Public Function GetDefaultOfParameter(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetDefaultOfParameter
Return TryCast(node, ParameterSyntax)?.Default
End Function
Public Function GetParameterList(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetParameterList
Return VisualBasicSyntaxGenerator.GetParameterList(node)
End Function
Public Function IsSkippedTokensTrivia(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsSkippedTokensTrivia
Return TypeOf node Is SkippedTokensTriviaSyntax
End Function
Public Function HasIncompleteParentMember(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.HasIncompleteParentMember
Return node.IsParentKind(SyntaxKind.IncompleteMember)
End Function
Public Function GetIdentifierOfGenericName(genericName As SyntaxNode) As SyntaxToken Implements ISyntaxFactsService.GetIdentifierOfGenericName
Dim vbGenericName = TryCast(genericName, GenericNameSyntax)
Return If(vbGenericName IsNot Nothing, vbGenericName.Identifier, Nothing)
End Function
Public Function IsUsingDirectiveName(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsUsingDirectiveName
Return node.IsParentKind(SyntaxKind.SimpleImportsClause) AndAlso
DirectCast(node.Parent, SimpleImportsClauseSyntax).Name Is node
End Function
Public Function IsForEachStatement(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsForEachStatement
Return TypeOf node Is ForEachStatementSyntax
End Function
Public Function IsDeconstructionAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsDeconstructionAssignment
Return False
End Function
Public Function IsDeconstructionForEachStatement(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsDeconstructionForEachStatement
Return False
End Function
Public Function IsLockStatement(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsLockStatement
Return TypeOf node Is SyncLockStatementSyntax
End Function
Public Function IsUsingStatement(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsUsingStatement
Return node.Kind() = SyntaxKind.UsingStatement
End Function
Public Function IsReturnStatement(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsReturnStatement
Return node.Kind() = SyntaxKind.ReturnStatement
End Function
Public Function IsStatement(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsStatement
Return TypeOf node Is StatementSyntax
End Function
Public Function IsParameter(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsParameter
Return TypeOf node Is ParameterSyntax
End Function
Public Function IsVariableDeclarator(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsVariableDeclarator
Return TypeOf node Is VariableDeclaratorSyntax
End Function
Public Function IsMethodBody(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsMethodBody
Return TypeOf node Is MethodBlockBaseSyntax
End Function
Public Function GetExpressionOfReturnStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetExpressionOfReturnStatement
Return TryCast(node, ReturnStatementSyntax)?.Expression
End Function
Public Function IsThisConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsThisConstructorInitializer
If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then
Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax)
Return memberAccess.IsThisConstructorInitializer()
End If
Return False
End Function
Public Function IsBaseConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsBaseConstructorInitializer
If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then
Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax)
Return memberAccess.IsBaseConstructorInitializer()
End If
Return False
End Function
Public Function IsQueryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsQueryExpression
Return node.Kind() = SyntaxKind.QueryExpression
End Function
Public Function IsQueryKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsQueryKeyword
Select Case token.Kind()
Case SyntaxKind.GroupKeyword,
SyntaxKind.JoinKeyword,
SyntaxKind.IntoKeyword,
SyntaxKind.AggregateKeyword,
SyntaxKind.DistinctKeyword,
SyntaxKind.SkipKeyword,
SyntaxKind.TakeKeyword,
SyntaxKind.LetKeyword,
SyntaxKind.ByKeyword,
SyntaxKind.OrderKeyword,
SyntaxKind.EqualsKeyword,
SyntaxKind.AscendingKeyword,
SyntaxKind.DescendingKeyword,
SyntaxKind.WhereKeyword
Return True
Case SyntaxKind.InKeyword
Select Case token.Parent.Kind()
Case SyntaxKind.FromClause,
SyntaxKind.SimpleJoinClause,
SyntaxKind.GroupJoinClause
Return True
Case Else
Return False ' e.g. ForEach ... in
End Select
Case SyntaxKind.OnKeyword
Select Case token.Parent.Kind()
Case SyntaxKind.SimpleJoinClause,
SyntaxKind.GroupJoinClause
Return True
Case Else
Return False ' e.g. On Error Goto
End Select
Case SyntaxKind.FromKeyword
Return token.Parent.Kind() = SyntaxKind.FromClause ' False for e.g. Object collection initializer
Case SyntaxKind.WhileKeyword
Select Case token.Parent.Kind()
Case SyntaxKind.SkipWhileClause,
SyntaxKind.TakeWhileClause
Return True
Case Else
Return False ' e.g. Exit While
End Select
Case SyntaxKind.SelectKeyword
Return token.Parent.Kind() = SyntaxKind.SelectClause ' False for e.g. Select Case
Case Else
Return False
End Select
End Function
Public Function IsThrowExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsThrowExpression
' VB does not support throw expressions currently.
Return False
End Function
Public Function IsPredefinedType(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsPredefinedType
Dim actualType As PredefinedType = PredefinedType.None
Return TryGetPredefinedType(token, actualType) AndAlso actualType <> PredefinedType.None
End Function
Public Function IsPredefinedType(token As SyntaxToken, type As PredefinedType) As Boolean Implements ISyntaxFactsService.IsPredefinedType
Dim actualType As PredefinedType = PredefinedType.None
Return TryGetPredefinedType(token, actualType) AndAlso actualType = type
End Function
Public Function TryGetPredefinedType(token As SyntaxToken, ByRef type As PredefinedType) As Boolean Implements ISyntaxFactsService.TryGetPredefinedType
type = GetPredefinedType(token)
Return type <> PredefinedType.None
End Function
Private Function GetPredefinedType(token As SyntaxToken) As PredefinedType
Select Case token.Kind
Case SyntaxKind.BooleanKeyword
Return PredefinedType.Boolean
Case SyntaxKind.ByteKeyword
Return PredefinedType.Byte
Case SyntaxKind.SByteKeyword
Return PredefinedType.SByte
Case SyntaxKind.IntegerKeyword
Return PredefinedType.Int32
Case SyntaxKind.UIntegerKeyword
Return PredefinedType.UInt32
Case SyntaxKind.ShortKeyword
Return PredefinedType.Int16
Case SyntaxKind.UShortKeyword
Return PredefinedType.UInt16
Case SyntaxKind.LongKeyword
Return PredefinedType.Int64
Case SyntaxKind.ULongKeyword
Return PredefinedType.UInt64
Case SyntaxKind.SingleKeyword
Return PredefinedType.Single
Case SyntaxKind.DoubleKeyword
Return PredefinedType.Double
Case SyntaxKind.DecimalKeyword
Return PredefinedType.Decimal
Case SyntaxKind.StringKeyword
Return PredefinedType.String
Case SyntaxKind.CharKeyword
Return PredefinedType.Char
Case SyntaxKind.ObjectKeyword
Return PredefinedType.Object
Case SyntaxKind.DateKeyword
Return PredefinedType.DateTime
Case Else
Return PredefinedType.None
End Select
End Function
Public Function IsPredefinedOperator(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsPredefinedOperator
Dim actualOp As PredefinedOperator = PredefinedOperator.None
Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp <> PredefinedOperator.None
End Function
Public Function IsPredefinedOperator(token As SyntaxToken, op As PredefinedOperator) As Boolean Implements ISyntaxFactsService.IsPredefinedOperator
Dim actualOp As PredefinedOperator = PredefinedOperator.None
Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp = op
End Function
Public Function TryGetPredefinedOperator(token As SyntaxToken, ByRef op As PredefinedOperator) As Boolean Implements ISyntaxFactsService.TryGetPredefinedOperator
op = GetPredefinedOperator(token)
Return op <> PredefinedOperator.None
End Function
Private Function GetPredefinedOperator(token As SyntaxToken) As PredefinedOperator
Select Case token.Kind
Case SyntaxKind.PlusToken, SyntaxKind.PlusEqualsToken
Return PredefinedOperator.Addition
Case SyntaxKind.MinusToken, SyntaxKind.MinusEqualsToken
Return PredefinedOperator.Subtraction
Case SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword
Return PredefinedOperator.BitwiseAnd
Case SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword
Return PredefinedOperator.BitwiseOr
Case SyntaxKind.AmpersandToken, SyntaxKind.AmpersandEqualsToken
Return PredefinedOperator.Concatenate
Case SyntaxKind.SlashToken, SyntaxKind.SlashEqualsToken
Return PredefinedOperator.Division
Case SyntaxKind.EqualsToken
Return PredefinedOperator.Equality
Case SyntaxKind.XorKeyword
Return PredefinedOperator.ExclusiveOr
Case SyntaxKind.CaretToken, SyntaxKind.CaretEqualsToken
Return PredefinedOperator.Exponent
Case SyntaxKind.GreaterThanToken
Return PredefinedOperator.GreaterThan
Case SyntaxKind.GreaterThanEqualsToken
Return PredefinedOperator.GreaterThanOrEqual
Case SyntaxKind.LessThanGreaterThanToken
Return PredefinedOperator.Inequality
Case SyntaxKind.BackslashToken, SyntaxKind.BackslashEqualsToken
Return PredefinedOperator.IntegerDivision
Case SyntaxKind.LessThanLessThanToken, SyntaxKind.LessThanLessThanEqualsToken
Return PredefinedOperator.LeftShift
Case SyntaxKind.LessThanToken
Return PredefinedOperator.LessThan
Case SyntaxKind.LessThanEqualsToken
Return PredefinedOperator.LessThanOrEqual
Case SyntaxKind.LikeKeyword
Return PredefinedOperator.Like
Case SyntaxKind.NotKeyword
Return PredefinedOperator.Complement
Case SyntaxKind.ModKeyword
Return PredefinedOperator.Modulus
Case SyntaxKind.AsteriskToken, SyntaxKind.AsteriskEqualsToken
Return PredefinedOperator.Multiplication
Case SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.GreaterThanGreaterThanEqualsToken
Return PredefinedOperator.RightShift
Case Else
Return PredefinedOperator.None
End Select
End Function
Public Function GetText(kind As Integer) As String Implements ISyntaxFactsService.GetText
Return SyntaxFacts.GetText(CType(kind, SyntaxKind))
End Function
Public Function IsIdentifierPartCharacter(c As Char) As Boolean Implements ISyntaxFactsService.IsIdentifierPartCharacter
Return SyntaxFacts.IsIdentifierPartCharacter(c)
End Function
Public Function IsIdentifierStartCharacter(c As Char) As Boolean Implements ISyntaxFactsService.IsIdentifierStartCharacter
Return SyntaxFacts.IsIdentifierStartCharacter(c)
End Function
Public Function IsIdentifierEscapeCharacter(c As Char) As Boolean Implements ISyntaxFactsService.IsIdentifierEscapeCharacter
Return c = "["c OrElse c = "]"c
End Function
Public Function IsValidIdentifier(identifier As String) As Boolean Implements ISyntaxFactsService.IsValidIdentifier
Dim token = SyntaxFactory.ParseToken(identifier)
' TODO: There is no way to get the diagnostics to see if any are actually errors?
Return IsIdentifier(token) AndAlso Not token.ContainsDiagnostics AndAlso token.ToString().Length = identifier.Length
End Function
Public Function IsVerbatimIdentifier(identifier As String) As Boolean Implements ISyntaxFactsService.IsVerbatimIdentifier
Return IsValidIdentifier(identifier) AndAlso MakeHalfWidthIdentifier(identifier.First()) = "[" AndAlso MakeHalfWidthIdentifier(identifier.Last()) = "]"
End Function
Public Function IsTypeCharacter(c As Char) As Boolean Implements ISyntaxFactsService.IsTypeCharacter
Return c = "%"c OrElse
c = "&"c OrElse
c = "@"c OrElse
c = "!"c OrElse
c = "#"c OrElse
c = "$"c
End Function
Public Function IsStartOfUnicodeEscapeSequence(c As Char) As Boolean Implements ISyntaxFactsService.IsStartOfUnicodeEscapeSequence
Return False ' VB does not support identifiers with escaped unicode characters
End Function
Public Function IsLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsLiteral
Select Case token.Kind()
Case _
SyntaxKind.IntegerLiteralToken,
SyntaxKind.CharacterLiteralToken,
SyntaxKind.DecimalLiteralToken,
SyntaxKind.FloatingLiteralToken,
SyntaxKind.DateLiteralToken,
SyntaxKind.StringLiteralToken,
SyntaxKind.DollarSignDoubleQuoteToken,
SyntaxKind.DoubleQuoteToken,
SyntaxKind.InterpolatedStringTextToken,
SyntaxKind.TrueKeyword,
SyntaxKind.FalseKeyword,
SyntaxKind.NothingKeyword
Return True
End Select
Return False
End Function
Public Function IsStringLiteralOrInterpolatedStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsStringLiteralOrInterpolatedStringLiteral
Return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken)
End Function
Public Function IsNumericLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsNumericLiteralExpression
Return If(node Is Nothing, False, node.IsKind(SyntaxKind.NumericLiteralExpression))
End Function
Public Function IsBindableToken(token As Microsoft.CodeAnalysis.SyntaxToken) As Boolean Implements ISyntaxFactsService.IsBindableToken
Return Me.IsWord(token) OrElse
Me.IsLiteral(token) OrElse
Me.IsOperator(token)
End Function
Public Function IsSimpleMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsSimpleMemberAccessExpression
Return TypeOf node Is MemberAccessExpressionSyntax AndAlso
DirectCast(node, MemberAccessExpressionSyntax).Kind = SyntaxKind.SimpleMemberAccessExpression
End Function
Public Function IsPointerMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsPointerMemberAccessExpression
Return False
End Function
Public Sub GetNameAndArityOfSimpleName(node As SyntaxNode, ByRef name As String, ByRef arity As Integer) Implements ISyntaxFactsService.GetNameAndArityOfSimpleName
Dim simpleName = TryCast(node, SimpleNameSyntax)
If simpleName IsNot Nothing Then
name = simpleName.Identifier.ValueText
arity = simpleName.Arity
End If
End Sub
Public Function LooksGeneric(name As SyntaxNode) As Boolean Implements ISyntaxFactsService.LooksGeneric
Return name.IsKind(SyntaxKind.GenericName)
End Function
Public Function GetExpressionOfMemberAccessExpression(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFactsService.GetExpressionOfMemberAccessExpression
Return TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget)
End Function
Public Function GetTargetOfMemberBinding(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetTargetOfMemberBinding
' Member bindings are a C# concept.
Return Nothing
End Function
Public Function GetExpressionOfConditionalAccessExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetExpressionOfConditionalAccessExpression
Return TryCast(node, ConditionalAccessExpressionSyntax)?.Expression
End Function
Public Function GetExpressionOfElementAccessExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetExpressionOfElementAccessExpression
Return TryCast(node, InvocationExpressionSyntax)?.Expression
End Function
Public Function GetArgumentListOfElementAccessExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetArgumentListOfElementAccessExpression
Return TryCast(node, InvocationExpressionSyntax)?.ArgumentList
End Function
Public Function GetExpressionOfInterpolation(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetExpressionOfInterpolation
Return TryCast(node, InterpolationSyntax)?.Expression
End Function
Public Function IsInNamespaceOrTypeContext(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsInNamespaceOrTypeContext
Return SyntaxFacts.IsInNamespaceOrTypeContext(node)
End Function
Public Function IsInStaticContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFactsService.IsInStaticContext
Return node.IsInStaticContext()
End Function
Public Function GetExpressionOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFactsService.GetExpressionOfArgument
Return TryCast(node, ArgumentSyntax).GetArgumentExpression()
End Function
Public Function GetRefKindOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.RefKind Implements ISyntaxFactsService.GetRefKindOfArgument
' TODO(cyrusn): Consider the method this argument is passed to, to determine this.
Return RefKind.None
End Function
Public Function IsArgument(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsArgument
Return TypeOf node Is ArgumentSyntax
End Function
Public Function IsSimpleArgument(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsSimpleArgument
Dim argument = TryCast(node, ArgumentSyntax)
Return argument IsNot Nothing AndAlso Not argument.IsNamed AndAlso Not argument.IsOmitted
End Function
Public Function IsInConstantContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFactsService.IsInConstantContext
Return node.IsInConstantContext()
End Function
Public Function IsInConstructor(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFactsService.IsInConstructor
Return node.GetAncestors(Of StatementSyntax).Any(Function(s) s.Kind = SyntaxKind.ConstructorBlock)
End Function
Public Function IsUnsafeContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFactsService.IsUnsafeContext
Return False
End Function
Public Function GetNameOfAttribute(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFactsService.GetNameOfAttribute
Return DirectCast(node, AttributeSyntax).Name
End Function
Public Function IsParenthesizedExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsParenthesizedExpression
Return node.Kind() = SyntaxKind.ParenthesizedExpression
End Function
Public Function GetExpressionOfParenthesizedExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetExpressionOfParenthesizedExpression
Return DirectCast(node, ParenthesizedExpressionSyntax).Expression
End Function
Public Function IsIfStatement(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsIfStatement
Return (node.Kind() = SyntaxKind.IfStatement)
End Function
Public Function IsAttribute(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFactsService.IsAttribute
Return TypeOf node Is AttributeSyntax
End Function
Public Function IsAttributeNamedArgumentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsAttributeNamedArgumentIdentifier
Dim identifierName = TryCast(node, IdentifierNameSyntax)
Return identifierName.IsParentKind(SyntaxKind.NameColonEquals) AndAlso
identifierName.Parent.IsParentKind(SyntaxKind.SimpleArgument) AndAlso
identifierName.Parent.Parent.IsParentKind(SyntaxKind.ArgumentList) AndAlso
identifierName.Parent.Parent.Parent.IsParentKind(SyntaxKind.Attribute)
End Function
Public Function GetContainingTypeDeclaration(root As SyntaxNode, position As Integer) As SyntaxNode Implements ISyntaxFactsService.GetContainingTypeDeclaration
If root Is Nothing Then
Throw New ArgumentNullException(NameOf(root))
End If
If position < 0 OrElse position > root.Span.End Then
Throw New ArgumentOutOfRangeException(NameOf(position))
End If
Return root.
FindToken(position).
GetAncestors(Of SyntaxNode)().
FirstOrDefault(Function(n) TypeOf n Is TypeBlockSyntax OrElse TypeOf n Is DelegateStatementSyntax)
End Function
Public Function GetContainingVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetContainingVariableDeclaratorOfFieldDeclaration
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
Dim parent = node.Parent
While node IsNot Nothing
If node.Kind = SyntaxKind.VariableDeclarator AndAlso node.IsParentKind(SyntaxKind.FieldDeclaration) Then
Return node
End If
node = node.Parent
End While
Return Nothing
End Function
Public Function FindTokenOnLeftOfPosition(node As SyntaxNode,
position As Integer,
Optional includeSkipped As Boolean = True,
Optional includeDirectives As Boolean = False,
Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFactsService.FindTokenOnLeftOfPosition
Return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments)
End Function
Public Function FindTokenOnRightOfPosition(node As SyntaxNode,
position As Integer,
Optional includeSkipped As Boolean = True,
Optional includeDirectives As Boolean = False,
Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFactsService.FindTokenOnRightOfPosition
Return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments)
End Function
Public Function IsObjectCreationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsObjectCreationExpression
Return TypeOf node Is ObjectCreationExpressionSyntax
End Function
Public Function IsObjectInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsObjectInitializerNamedAssignmentIdentifier
Dim unused As SyntaxNode = Nothing
Return IsObjectInitializerNamedAssignmentIdentifier(node, unused)
End Function
Public Function IsObjectInitializerNamedAssignmentIdentifier(
node As SyntaxNode,
ByRef initializedInstance As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsObjectInitializerNamedAssignmentIdentifier
Dim identifier = TryCast(node, IdentifierNameSyntax)
If identifier?.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then
' .parent is the NamedField.
' .parent.parent is the ObjectInitializer.
' .parent.parent.parent will be the ObjectCreationExpression.
initializedInstance = identifier.Parent.Parent.Parent
Return True
End If
Return False
End Function
Public Function IsElementAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsElementAccessExpression
' VB doesn't have a specialized node for element access. Instead, it just uses an
' invocation expression or dictionary access expression.
Return node.Kind = SyntaxKind.InvocationExpression OrElse node.Kind = SyntaxKind.DictionaryAccessExpression
End Function
Public Function ToIdentifierToken(name As String) As SyntaxToken Implements ISyntaxFactsService.ToIdentifierToken
Return name.ToIdentifierToken()
End Function
Public Sub GetPartsOfParenthesizedExpression(
node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef expression As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFactsService.GetPartsOfParenthesizedExpression
Dim parenthesizedExpression = DirectCast(node, ParenthesizedExpressionSyntax)
openParen = parenthesizedExpression.OpenParenToken
expression = parenthesizedExpression.Expression
closeParen = parenthesizedExpression.CloseParenToken
End Sub
Public Function Parenthesize(expression As SyntaxNode, Optional includeElasticTrivia As Boolean = True, Optional addSimplifierAnnotation As Boolean = True) As SyntaxNode Implements ISyntaxFactsService.Parenthesize
Return DirectCast(expression, ExpressionSyntax).Parenthesize(addSimplifierAnnotation)
End Function
Public Function IsTypeNamedVarInVariableOrFieldDeclaration(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsTypeNamedVarInVariableOrFieldDeclaration
Return False
End Function
Public Function IsTypeNamedDynamic(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsTypeNamedDynamic
Return False
End Function
Public Function IsIndexerMemberCRef(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsIndexerMemberCRef
Return False
End Function
Public Function GetContainingMemberDeclaration(root As SyntaxNode, position As Integer, Optional useFullSpan As Boolean = True) As SyntaxNode Implements ISyntaxFactsService.GetContainingMemberDeclaration
Contract.ThrowIfNull(root, NameOf(root))
Contract.ThrowIfTrue(position < 0 OrElse position > root.FullSpan.End, NameOf(position))
Dim [end] = root.FullSpan.End
If [end] = 0 Then
' empty file
Return Nothing
End If
' make sure position doesn't touch end of root
position = Math.Min(position, [end] - 1)
Dim node = root.FindToken(position).Parent
While node IsNot Nothing
If useFullSpan OrElse node.Span.Contains(position) Then
If TypeOf node Is MethodBlockBaseSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return node
End If
If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return node
End If
If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then
Return node
End If
If TypeOf node Is PropertyBlockSyntax OrElse
TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is EnumBlockSyntax OrElse
TypeOf node Is NamespaceBlockSyntax OrElse
TypeOf node Is EventBlockSyntax OrElse
TypeOf node Is FieldDeclarationSyntax Then
Return node
End If
End If
node = node.Parent
End While
Return Nothing
End Function
Public Function IsMethodLevelMember(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsMethodLevelMember
' Note: Derived types of MethodBaseSyntax are expanded explicitly, since PropertyStatementSyntax and
' EventStatementSyntax will NOT be parented by MethodBlockBaseSyntax. Additionally, there are things
' like AccessorStatementSyntax and DelegateStatementSyntax that we never want to tread as method level
' members.
If TypeOf node Is MethodStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is SubNewStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is OperatorStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return True
End If
If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then
Return True
End If
If TypeOf node Is DeclareStatementSyntax Then
Return True
End If
Return TypeOf node Is ConstructorBlockSyntax OrElse
TypeOf node Is MethodBlockSyntax OrElse
TypeOf node Is OperatorBlockSyntax OrElse
TypeOf node Is EventBlockSyntax OrElse
TypeOf node Is PropertyBlockSyntax OrElse
TypeOf node Is EnumMemberDeclarationSyntax OrElse
TypeOf node Is FieldDeclarationSyntax
End Function
Public Function GetMemberBodySpanForSpeculativeBinding(node As SyntaxNode) As TextSpan Implements ISyntaxFactsService.GetMemberBodySpanForSpeculativeBinding
Dim member = GetContainingMemberDeclaration(node, node.SpanStart)
If member Is Nothing Then
Return Nothing
End If
' TODO: currently we only support method for now
Dim method = TryCast(member, MethodBlockBaseSyntax)
If method IsNot Nothing Then
If method.BlockStatement Is Nothing OrElse method.EndBlockStatement Is Nothing Then
Return Nothing
End If
' We don't want to include the BlockStatement or any trailing trivia up to and including its statement
' terminator in the span. Instead, we use the start of the first statement's leading trivia (if any) up
' to the start of the EndBlockStatement. If there aren't any statements in the block, we use the start
' of the EndBlockStatements leading trivia.
Dim firstStatement = method.Statements.FirstOrDefault()
Dim spanStart = If(firstStatement IsNot Nothing,
firstStatement.FullSpan.Start,
method.EndBlockStatement.FullSpan.Start)
Return TextSpan.FromBounds(spanStart, method.EndBlockStatement.SpanStart)
End If
Return Nothing
End Function
Public Function ContainsInMemberBody(node As SyntaxNode, span As TextSpan) As Boolean Implements ISyntaxFactsService.ContainsInMemberBody
Dim method = TryCast(node, MethodBlockBaseSyntax)
If method IsNot Nothing Then
Return method.Statements.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan(method.Statements), span)
End If
Dim [event] = TryCast(node, EventBlockSyntax)
If [event] IsNot Nothing Then
Return [event].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([event].Accessors), span)
End If
Dim [property] = TryCast(node, PropertyBlockSyntax)
If [property] IsNot Nothing Then
Return [property].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([property].Accessors), span)
End If
Dim field = TryCast(node, FieldDeclarationSyntax)
If field IsNot Nothing Then
Return field.Declarators.Count > 0 AndAlso ContainsExclusively(GetSeparatedSyntaxListSpan(field.Declarators), span)
End If
Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax)
If [enum] IsNot Nothing Then
Return [enum].Initializer IsNot Nothing AndAlso ContainsExclusively([enum].Initializer.Span, span)
End If
Dim propStatement = TryCast(node, PropertyStatementSyntax)
If propStatement IsNot Nothing Then
Return propStatement.Initializer IsNot Nothing AndAlso ContainsExclusively(propStatement.Initializer.Span, span)
End If
Return False
End Function
Private Function ContainsExclusively(outerSpan As TextSpan, innerSpan As TextSpan) As Boolean
If innerSpan.IsEmpty Then
Return outerSpan.Contains(innerSpan.Start)
End If
Return outerSpan.Contains(innerSpan)
End Function
Private Function GetSyntaxListSpan(Of T As SyntaxNode)(list As SyntaxList(Of T)) As TextSpan
Contract.Requires(list.Count > 0)
Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End)
End Function
Private Function GetSeparatedSyntaxListSpan(Of T As SyntaxNode)(list As SeparatedSyntaxList(Of T)) As TextSpan
Contract.Requires(list.Count > 0)
Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End)
End Function
Public Function GetMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFactsService.GetMethodLevelMembers
Dim list = New List(Of SyntaxNode)()
AppendMethodLevelMembers(root, list)
Return list
End Function
Public Function GetMembersOfTypeDeclaration(typeDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFactsService.GetMembersOfTypeDeclaration
Return DirectCast(typeDeclaration, TypeBlockSyntax).Members
End Function
Public Function IsTopLevelNodeWithMembers(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsTopLevelNodeWithMembers
Return TypeOf node Is NamespaceBlockSyntax OrElse
TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is EnumBlockSyntax
End Function
Private Const s_dotToken As String = "."
Public Function GetDisplayName(node As SyntaxNode, options As DisplayNameOptions, Optional rootNamespace As String = Nothing) As String Implements ISyntaxFactsService.GetDisplayName
If node Is Nothing Then
Return String.Empty
End If
Dim pooled = PooledStringBuilder.GetInstance()
Dim builder = pooled.Builder
' member keyword (if any)
Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax)
If (options And DisplayNameOptions.IncludeMemberKeyword) <> 0 Then
Dim keywordToken = memberDeclaration.GetMemberKeywordToken()
If keywordToken <> Nothing AndAlso Not keywordToken.IsMissing Then
builder.Append(keywordToken.Text)
builder.Append(" "c)
End If
End If
Dim names = ArrayBuilder(Of String).GetInstance()
' containing type(s)
Dim parent = node.Parent
While TypeOf parent Is TypeBlockSyntax
names.Push(GetName(parent, options, containsGlobalKeyword:=False))
parent = parent.Parent
End While
If (options And DisplayNameOptions.IncludeNamespaces) <> 0 Then
' containing namespace(s) in source (if any)
Dim containsGlobalKeyword As Boolean = False
While parent IsNot Nothing AndAlso parent.Kind() = SyntaxKind.NamespaceBlock
names.Push(GetName(parent, options, containsGlobalKeyword))
parent = parent.Parent
End While
' root namespace (if any)
If Not containsGlobalKeyword AndAlso Not String.IsNullOrEmpty(rootNamespace) Then
builder.Append(rootNamespace)
builder.Append(s_dotToken)
End If
End If
While Not names.IsEmpty()
Dim name = names.Pop()
If name IsNot Nothing Then
builder.Append(name)
builder.Append(s_dotToken)
End If
End While
names.Free()
' name (include generic type parameters)
builder.Append(GetName(node, options, containsGlobalKeyword:=False))
' parameter list (if any)
If (options And DisplayNameOptions.IncludeParameters) <> 0 Then
builder.Append(memberDeclaration.GetParameterList())
End If
' As clause (if any)
If (options And DisplayNameOptions.IncludeType) <> 0 Then
Dim asClause = memberDeclaration.GetAsClause()
If asClause IsNot Nothing Then
builder.Append(" "c)
builder.Append(asClause)
End If
End If
Return pooled.ToStringAndFree()
End Function
Private Shared Function GetName(node As SyntaxNode, options As DisplayNameOptions, ByRef containsGlobalKeyword As Boolean) As String
Const missingTokenPlaceholder As String = "?"
Select Case node.Kind()
Case SyntaxKind.CompilationUnit
Return Nothing
Case SyntaxKind.IdentifierName
Dim identifier = DirectCast(node, IdentifierNameSyntax).Identifier
Return If(identifier.IsMissing, missingTokenPlaceholder, identifier.Text)
Case SyntaxKind.IncompleteMember
Return missingTokenPlaceholder
Case SyntaxKind.NamespaceBlock
Dim nameSyntax = CType(node, NamespaceBlockSyntax).NamespaceStatement.Name
If nameSyntax.Kind() = SyntaxKind.GlobalName Then
containsGlobalKeyword = True
Return Nothing
Else
Return GetName(nameSyntax, options, containsGlobalKeyword)
End If
Case SyntaxKind.QualifiedName
Dim qualified = CType(node, QualifiedNameSyntax)
If qualified.Left.Kind() = SyntaxKind.GlobalName Then
containsGlobalKeyword = True
Return GetName(qualified.Right, options, containsGlobalKeyword) ' don't use the Global prefix if specified
Else
Return GetName(qualified.Left, options, containsGlobalKeyword) + s_dotToken + GetName(qualified.Right, options, containsGlobalKeyword)
End If
End Select
Dim name As String = Nothing
Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax)
If memberDeclaration IsNot Nothing Then
Dim nameToken = memberDeclaration.GetNameToken()
If nameToken <> Nothing Then
name = If(nameToken.IsMissing, missingTokenPlaceholder, nameToken.Text)
If (options And DisplayNameOptions.IncludeTypeParameters) <> 0 Then
Dim pooled = PooledStringBuilder.GetInstance()
Dim builder = pooled.Builder
builder.Append(name)
AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList())
name = pooled.ToStringAndFree()
End If
End If
End If
Debug.Assert(name IsNot Nothing, "Unexpected node type " + node.Kind().ToString())
Return name
End Function
Private Shared Sub AppendTypeParameterList(builder As StringBuilder, typeParameterList As TypeParameterListSyntax)
If typeParameterList IsNot Nothing AndAlso typeParameterList.Parameters.Count > 0 Then
builder.Append("(Of ")
builder.Append(typeParameterList.Parameters(0).Identifier.Text)
For i = 1 To typeParameterList.Parameters.Count - 1
builder.Append(", ")
builder.Append(typeParameterList.Parameters(i).Identifier.Text)
Next
builder.Append(")"c)
End If
End Sub
Private Sub AppendMethodLevelMembers(node As SyntaxNode, list As List(Of SyntaxNode))
For Each member In node.GetMembers()
If IsTopLevelNodeWithMembers(member) Then
AppendMethodLevelMembers(member, list)
Continue For
End If
If IsMethodLevelMember(member) Then
list.Add(member)
End If
Next
End Sub
Public Function GetMethodLevelMemberId(root As SyntaxNode, node As SyntaxNode) As Integer Implements ISyntaxFactsService.GetMethodLevelMemberId
Contract.Requires(root.SyntaxTree Is node.SyntaxTree)
Dim currentId As Integer = Nothing
Dim currentNode As SyntaxNode = Nothing
Contract.ThrowIfFalse(TryGetMethodLevelMember(root, Function(n, i) n Is node, currentId, currentNode))
Contract.ThrowIfFalse(currentId >= 0)
CheckMemberId(root, node, currentId)
Return currentId
End Function
Public Function GetMethodLevelMember(root As SyntaxNode, memberId As Integer) As SyntaxNode Implements ISyntaxFactsService.GetMethodLevelMember
Dim currentId As Integer = Nothing
Dim currentNode As SyntaxNode = Nothing
If Not TryGetMethodLevelMember(root, Function(n, i) i = memberId, currentId, currentNode) Then
Return Nothing
End If
Contract.ThrowIfNull(currentNode)
CheckMemberId(root, currentNode, memberId)
Return currentNode
End Function
Private Function TryGetMethodLevelMember(node As SyntaxNode, predicate As Func(Of SyntaxNode, Integer, Boolean), ByRef currentId As Integer, ByRef currentNode As SyntaxNode) As Boolean
For Each member In node.GetMembers()
If TypeOf member Is NamespaceBlockSyntax OrElse
TypeOf member Is TypeBlockSyntax OrElse
TypeOf member Is EnumBlockSyntax Then
If TryGetMethodLevelMember(member, predicate, currentId, currentNode) Then
Return True
End If
Continue For
End If
If IsMethodLevelMember(member) Then
If predicate(member, currentId) Then
currentNode = member
Return True
End If
currentId = currentId + 1
End If
Next
currentNode = Nothing
Return False
End Function
<Conditional("DEBUG")>
Private Sub CheckMemberId(root As SyntaxNode, node As SyntaxNode, memberId As Integer)
Dim list = GetMethodLevelMembers(root)
Dim index = list.IndexOf(node)
Contract.ThrowIfFalse(index = memberId)
End Sub
Public Function GetBindableParent(token As SyntaxToken) As SyntaxNode Implements ISyntaxFactsService.GetBindableParent
Dim node = token.Parent
While node IsNot Nothing
Dim parent = node.Parent
' If this node is on the left side of a member access expression, don't ascend
' further or we'll end up binding to something else.
Dim memberAccess = TryCast(parent, MemberAccessExpressionSyntax)
If memberAccess IsNot Nothing Then
If memberAccess.Expression Is node Then
Exit While
End If
End If
' If this node is on the left side of a qualified name, don't ascend
' further or we'll end up binding to something else.
Dim qualifiedName = TryCast(parent, QualifiedNameSyntax)
If qualifiedName IsNot Nothing Then
If qualifiedName.Left Is node Then
Exit While
End If
End If
' If this node is the type of an object creation expression, return the
' object creation expression.
Dim objectCreation = TryCast(parent, ObjectCreationExpressionSyntax)
If objectCreation IsNot Nothing Then
If objectCreation.Type Is node Then
node = parent
Exit While
End If
End If
' The inside of an interpolated string is treated as its own token so we
' need to force navigation to the parent expression syntax.
If TypeOf node Is InterpolatedStringTextSyntax AndAlso TypeOf parent Is InterpolatedStringExpressionSyntax Then
node = parent
Exit While
End If
' If this node is not parented by a name, we're done.
Dim name = TryCast(parent, NameSyntax)
If name Is Nothing Then
Exit While
End If
node = parent
End While
Return node
End Function
Public Function GetConstructors(root As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode) Implements ISyntaxFactsService.GetConstructors
Dim compilationUnit = TryCast(root, CompilationUnitSyntax)
If compilationUnit Is Nothing Then
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End If
Dim constructors = New List(Of SyntaxNode)()
AppendConstructors(compilationUnit.Members, constructors, cancellationToken)
Return constructors
End Function
Private Sub AppendConstructors(members As SyntaxList(Of StatementSyntax), constructors As List(Of SyntaxNode), cancellationToken As CancellationToken)
For Each member As StatementSyntax In members
cancellationToken.ThrowIfCancellationRequested()
Dim constructor = TryCast(member, ConstructorBlockSyntax)
If constructor IsNot Nothing Then
constructors.Add(constructor)
Continue For
End If
Dim [namespace] = TryCast(member, NamespaceBlockSyntax)
If [namespace] IsNot Nothing Then
AppendConstructors([namespace].Members, constructors, cancellationToken)
End If
Dim [class] = TryCast(member, ClassBlockSyntax)
If [class] IsNot Nothing Then
AppendConstructors([class].Members, constructors, cancellationToken)
End If
Dim [struct] = TryCast(member, StructureBlockSyntax)
If [struct] IsNot Nothing Then
AppendConstructors([struct].Members, constructors, cancellationToken)
End If
Next
End Sub
Public Function GetInactiveRegionSpanAroundPosition(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As TextSpan Implements ISyntaxFactsService.GetInactiveRegionSpanAroundPosition
Dim trivia = tree.FindTriviaToLeft(position, cancellationToken)
If trivia.Kind = SyntaxKind.DisabledTextTrivia Then
Return trivia.FullSpan
End If
Return Nothing
End Function
Public Function GetNameForArgument(argument As SyntaxNode) As String Implements ISyntaxFactsService.GetNameForArgument
If TryCast(argument, ArgumentSyntax)?.IsNamed Then
Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText
End If
Return String.Empty
End Function
Public Function IsLeftSideOfDot(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsLeftSideOfDot
Return TryCast(node, ExpressionSyntax).IsLeftSideOfDot()
End Function
Public Function GetRightSideOfDot(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetRightSideOfDot
Return If(TryCast(node, QualifiedNameSyntax)?.Right,
TryCast(node, MemberAccessExpressionSyntax)?.Name)
End Function
Public Function IsLeftSideOfAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsLeftSideOfAssignment
Return TryCast(node, ExpressionSyntax).IsLeftSideOfAnyAssignStatement
End Function
Public Function IsLeftSideOfAnyAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsLeftSideOfAnyAssignment
Return TryCast(node, ExpressionSyntax).IsLeftSideOfAnyAssignStatement
End Function
Public Function GetRightHandSideOfAssignment(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetRightHandSideOfAssignment
Return TryCast(node, AssignmentStatementSyntax)?.Right
End Function
Public Function IsInferredAnonymousObjectMemberDeclarator(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsInferredAnonymousObjectMemberDeclarator
Return node.IsKind(SyntaxKind.InferredFieldInitializer)
End Function
Public Function IsOperandOfIncrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsOperandOfIncrementExpression
Return False
End Function
Public Function IsOperandOfIncrementOrDecrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsOperandOfIncrementOrDecrementExpression
Return False
End Function
Public Function GetContentsOfInterpolatedString(interpolatedString As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFactsService.GetContentsOfInterpolatedString
Return (TryCast(interpolatedString, InterpolatedStringExpressionSyntax)?.Contents).Value
End Function
Public Function IsNumericLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsNumericLiteral
Return token.Kind = SyntaxKind.DecimalLiteralToken OrElse
token.Kind = SyntaxKind.FloatingLiteralToken OrElse
token.Kind = SyntaxKind.IntegerLiteralToken
End Function
Public Function IsCharacterLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsCharacterLiteral
Return token.Kind() = SyntaxKind.CharacterLiteralToken
End Function
Public Overrides Function IsStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsStringLiteral
Return token.IsKind(SyntaxKind.StringLiteralToken)
End Function
Public Overrides Function IsInterpolatedStringTextToken(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsInterpolatedStringTextToken
Return token.IsKind(SyntaxKind.InterpolatedStringTextToken)
End Function
Public Function IsStringLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsStringLiteralExpression
Return node.Kind() = SyntaxKind.StringLiteralExpression
End Function
Public Function IsVerbatimStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFactsService.IsVerbatimStringLiteral
' VB does not have verbatim strings
Return False
End Function
Public Function GetArgumentsOfInvocationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFactsService.GetArgumentsOfInvocationExpression
Return GetArgumentsOfArgumentList(TryCast(node, InvocationExpressionSyntax)?.ArgumentList)
End Function
Public Function GetArgumentsOfObjectCreationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFactsService.GetArgumentsOfObjectCreationExpression
Return GetArgumentsOfArgumentList(TryCast(node, ObjectCreationExpressionSyntax)?.ArgumentList)
End Function
Public Function GetArgumentsOfArgumentList(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFactsService.GetArgumentsOfArgumentList
Dim arguments = TryCast(node, ArgumentListSyntax)?.Arguments
Return If(arguments.HasValue, arguments.Value, Nothing)
End Function
Public Function ConvertToSingleLine(node As SyntaxNode, Optional useElasticTrivia As Boolean = False) As SyntaxNode Implements ISyntaxFactsService.ConvertToSingleLine
Return node.ConvertToSingleLine(useElasticTrivia)
End Function
Public Function IsDocumentationComment(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsDocumentationComment
Return node.IsKind(SyntaxKind.DocumentationCommentTrivia)
End Function
Public Function IsUsingOrExternOrImport(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsUsingOrExternOrImport
Return node.IsKind(SyntaxKind.ImportsStatement)
End Function
Public Function IsGlobalAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsGlobalAttribute
If node.IsKind(SyntaxKind.Attribute) Then
Dim attributeNode = CType(node, AttributeSyntax)
If attributeNode.Target IsNot Nothing Then
Return attributeNode.Target.AttributeModifier.IsKind(SyntaxKind.AssemblyKeyword)
End If
End If
Return False
End Function
Public Function IsDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsDeclaration
' From the Visual Basic language spec:
' NamespaceMemberDeclaration :=
' NamespaceDeclaration |
' TypeDeclaration
' TypeDeclaration ::=
' ModuleDeclaration |
' NonModuleDeclaration
' NonModuleDeclaration ::=
' EnumDeclaration |
' StructureDeclaration |
' InterfaceDeclaration |
' ClassDeclaration |
' DelegateDeclaration
' ClassMemberDeclaration ::=
' NonModuleDeclaration |
' EventMemberDeclaration |
' VariableMemberDeclaration |
' ConstantMemberDeclaration |
' MethodMemberDeclaration |
' PropertyMemberDeclaration |
' ConstructorMemberDeclaration |
' OperatorDeclaration
Select Case node.Kind()
' Because fields declarations can define multiple symbols "Public a, b As Integer"
' We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name.
Case SyntaxKind.VariableDeclarator
If (node.Parent.IsKind(SyntaxKind.FieldDeclaration)) Then
Return True
End If
Return False
Case SyntaxKind.NamespaceStatement,
SyntaxKind.NamespaceBlock,
SyntaxKind.ModuleStatement,
SyntaxKind.ModuleBlock,
SyntaxKind.EnumStatement,
SyntaxKind.EnumBlock,
SyntaxKind.StructureStatement,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceStatement,
SyntaxKind.InterfaceBlock,
SyntaxKind.ClassStatement,
SyntaxKind.ClassBlock,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.EventStatement,
SyntaxKind.EventBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.FieldDeclaration,
SyntaxKind.SubStatement,
SyntaxKind.SubBlock,
SyntaxKind.FunctionStatement,
SyntaxKind.FunctionBlock,
SyntaxKind.PropertyStatement,
SyntaxKind.PropertyBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.SubNewStatement,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorStatement,
SyntaxKind.OperatorBlock
Return True
End Select
Return False
End Function
Public Sub AddFirstMissingCloseBrace(root As SyntaxNode, contextNode As SyntaxNode, ByRef newRoot As SyntaxNode, ByRef newContextNode As SyntaxNode) Implements ISyntaxFactsService.AddFirstMissingCloseBrace
' Nothing to be done. VB doesn't have close braces
newRoot = root
newContextNode = contextNode
End Sub
Public Function GetObjectCreationInitializer(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetObjectCreationInitializer
Return DirectCast(node, ObjectCreationExpressionSyntax).Initializer
End Function
Public Function GetObjectCreationType(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetObjectCreationType
Return DirectCast(node, ObjectCreationExpressionSyntax).Type
End Function
Public Function IsSimpleAssignmentStatement(statement As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsSimpleAssignmentStatement
Return statement.IsKind(SyntaxKind.SimpleAssignmentStatement)
End Function
Public Sub GetPartsOfAssignmentStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFactsService.GetPartsOfAssignmentStatement
Dim assignment = DirectCast(statement, AssignmentStatementSyntax)
left = assignment.Left
operatorToken = assignment.OperatorToken
right = assignment.Right
End Sub
Public Function GetNameOfMemberAccessExpression(memberAccessExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetNameOfMemberAccessExpression
Return DirectCast(memberAccessExpression, MemberAccessExpressionSyntax).Name
End Function
Public Function GetOperatorTokenOfMemberAccessExpression(memberAccessExpression As SyntaxNode) As SyntaxToken Implements ISyntaxFactsService.GetOperatorTokenOfMemberAccessExpression
Return DirectCast(memberAccessExpression, MemberAccessExpressionSyntax).OperatorToken
End Function
Public Function GetIdentifierOfSimpleName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFactsService.GetIdentifierOfSimpleName
Return DirectCast(node, SimpleNameSyntax).Identifier
End Function
Public Function GetIdentifierOfVariableDeclarator(node As SyntaxNode) As SyntaxToken Implements ISyntaxFactsService.GetIdentifierOfVariableDeclarator
Return DirectCast(node, VariableDeclaratorSyntax).Names.Last().Identifier
End Function
Public Function IsIdentifierName(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsIdentifierName
Return node.IsKind(SyntaxKind.IdentifierName)
End Function
Public Function IsLocalDeclarationStatement(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsLocalDeclarationStatement
Return node.IsKind(SyntaxKind.LocalDeclarationStatement)
End Function
Public Function IsLocalFunctionStatement(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsLocalFunctionStatement
' VB does not have local funtions
Return False
End Function
Public Function IsDeclaratorOfLocalDeclarationStatement(declarator As SyntaxNode, localDeclarationStatement As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsDeclaratorOfLocalDeclarationStatement
Return DirectCast(localDeclarationStatement, LocalDeclarationStatementSyntax).Declarators.
Contains(DirectCast(declarator, VariableDeclaratorSyntax))
End Function
Public Function AreEquivalent(token1 As SyntaxToken, token2 As SyntaxToken) As Boolean Implements ISyntaxFactsService.AreEquivalent
Return SyntaxFactory.AreEquivalent(token1, token2)
End Function
Public Function AreEquivalent(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean Implements ISyntaxFactsService.AreEquivalent
Return SyntaxFactory.AreEquivalent(node1, node2)
End Function
Public Function IsExpressionOfInvocationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsExpressionOfInvocationExpression
Return node IsNot Nothing AndAlso TryCast(node.Parent, InvocationExpressionSyntax)?.Expression Is node
End Function
Public Function IsAwaitExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsAwaitExpression
Return node.IsKind(SyntaxKind.AwaitExpression)
End Function
Public Function IsExpressionOfAwaitExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsExpressionOfAwaitExpression
Return node IsNot Nothing AndAlso TryCast(node.Parent, AwaitExpressionSyntax)?.Expression Is node
End Function
Public Function IsExpressionOfMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsExpressionOfMemberAccessExpression
Return node IsNot Nothing AndAlso TryCast(node.Parent, MemberAccessExpressionSyntax)?.Expression Is node
End Function
Public Function GetExpressionOfInvocationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetExpressionOfInvocationExpression
Return DirectCast(node, InvocationExpressionSyntax).Expression
End Function
Public Function GetExpressionOfAwaitExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetExpressionOfAwaitExpression
Return DirectCast(node, AwaitExpressionSyntax).Expression
End Function
Public Function IsPossibleTupleContext(
syntaxTree As SyntaxTree,
position As Integer,
cancellationToken As CancellationToken) As Boolean Implements ISyntaxFactsService.IsPossibleTupleContext
Dim token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken)
Return syntaxTree.IsPossibleTupleContext(token, position)
End Function
Public Function GetExpressionOfExpressionStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetExpressionOfExpressionStatement
Return DirectCast(node, ExpressionStatementSyntax).Expression
End Function
Public Function IsNullLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsNullLiteralExpression
Return node.Kind() = SyntaxKind.NothingLiteralExpression
End Function
Public Function IsDefaultLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsDefaultLiteralExpression
Return IsNullLiteralExpression(node)
End Function
Public Function IsBinaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsBinaryExpression
Return TypeOf node Is BinaryExpressionSyntax
End Function
Public Sub GetPartsOfBinaryExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFactsService.GetPartsOfBinaryExpression
Dim binaryExpression = DirectCast(node, BinaryExpressionSyntax)
left = binaryExpression.Left
operatorToken = binaryExpression.OperatorToken
right = binaryExpression.Right
End Sub
Public Sub GetPartsOfConditionalExpression(node As SyntaxNode, ByRef condition As SyntaxNode, ByRef whenTrue As SyntaxNode, ByRef whenFalse As SyntaxNode) Implements ISyntaxFactsService.GetPartsOfConditionalExpression
Dim conditionalExpression = DirectCast(node, TernaryConditionalExpressionSyntax)
condition = conditionalExpression.Condition
whenTrue = conditionalExpression.WhenTrue
whenFalse = conditionalExpression.WhenFalse
End Sub
Public Function WalkDownParentheses(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.WalkDownParentheses
Return If(TryCast(node, ExpressionSyntax)?.WalkDownParentheses(), node)
End Function
Public Function IsLogicalAndExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsLogicalAndExpression
Return node.IsKind(SyntaxKind.AndAlsoExpression)
End Function
Public Function IsLogicalOrExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsLogicalOrExpression
Return node.IsKind(SyntaxKind.OrElseExpression)
End Function
Public Function IsLogicalNotExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsLogicalNotExpression
Return node.IsKind(SyntaxKind.NotExpression)
End Function
Public Function IsConditionalAnd(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsConditionalAnd
Return node.Kind() = SyntaxKind.AndAlsoExpression
End Function
Public Function IsConditionalOr(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsConditionalOr
Return node.Kind() = SyntaxKind.OrElseExpression
End Function
Public Function GetOperandOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetOperandOfPrefixUnaryExpression
Return DirectCast(node, UnaryExpressionSyntax).Operand
End Function
Public Function GetOperatorTokenOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxToken Implements ISyntaxFactsService.GetOperatorTokenOfPrefixUnaryExpression
Return DirectCast(node, UnaryExpressionSyntax).OperatorToken
End Function
Public Sub GetPartsOfMemberAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef name As SyntaxNode) Implements ISyntaxFactsService.GetPartsOfMemberAccessExpression
Dim memberAccess = DirectCast(node, MemberAccessExpressionSyntax)
expression = memberAccess.Expression
name = memberAccess.Name
End Sub
Public Function GetNextExecutableStatement(statement As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetNextExecutableStatement
Return DirectCast(statement, StatementSyntax).GetNextStatement()?.FirstAncestorOrSelf(Of ExecutableStatementSyntax)
End Function
Public Overrides Function IsWhitespaceTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFactsService.IsWhitespaceTrivia
Return trivia.IsWhitespace()
End Function
Public Overrides Function IsEndOfLineTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFactsService.IsEndOfLineTrivia
Return trivia.IsEndOfLine()
End Function
Public Overrides Function IsSingleLineCommentTrivia(trivia As SyntaxTrivia) As Boolean
Return trivia.Kind = SyntaxKind.CommentTrivia
End Function
Public Overrides Function IsMultiLineCommentTrivia(trivia As SyntaxTrivia) As Boolean
' VB does not have multi-line comments.
Return False
End Function
Public Overrides Function IsShebangDirectiveTrivia(trivia As SyntaxTrivia) As Boolean
' VB does not have shebang directives.
Return False
End Function
Public Overrides Function IsPreprocessorDirective(trivia As SyntaxTrivia) As Boolean
Return SyntaxFacts.IsPreprocessorDirective(trivia.Kind())
End Function
Public Function IsRegularComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFactsService.IsRegularComment
Return trivia.Kind = SyntaxKind.CommentTrivia
End Function
Public Function IsDocumentationComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFactsService.IsDocumentationComment
Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia
End Function
Public Function IsElastic(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFactsService.IsElastic
Return trivia.IsElastic()
End Function
Public Function IsOnTypeHeader(root As SyntaxNode, position As Integer) As Boolean Implements ISyntaxFactsService.IsOnTypeHeader
Dim statement = root.FindToken(position).GetAncestor(Of TypeStatementSyntax)
If statement Is Nothing Then
Return Nothing
End If
Dim start = If(statement.AttributeLists.LastOrDefault()?.GetLastToken().GetNextToken().SpanStart,
statement.SpanStart)
Dim _end = If(statement.TypeParameterList?.GetLastToken().FullSpan.End,
statement.Identifier.FullSpan.End)
Return position >= start AndAlso position <= _end
End Function
Public Function IsBetweenTypeMembers(sourceText As SourceText, root As SyntaxNode, position As Integer) As Boolean Implements ISyntaxFactsService.IsBetweenTypeMembers
Dim token = root.FindToken(position)
Dim typeDecl = token.GetAncestor(Of TypeBlockSyntax)
If typeDecl IsNot Nothing Then
Dim start = If(typeDecl.Implements.LastOrDefault()?.Span.End,
If(typeDecl.Inherits.LastOrDefault()?.Span.End,
typeDecl.BlockStatement.Span.End))
If position >= start AndAlso
position <= typeDecl.EndBlockStatement.Span.Start Then
Dim line = sourceText.Lines.GetLineFromPosition(position)
If Not line.IsEmptyOrWhitespace() Then
Return False
End If
Dim member = typeDecl.Members.FirstOrDefault(Function(d) d.FullSpan.Contains(position))
If member Is Nothing Then
' There are no members, Or we're after the last member.
Return True
Else
' We're within a member. Make sure we're in the leading whitespace of
' the member.
If position < member.SpanStart Then
For Each trivia In member.GetLeadingTrivia()
If Not trivia.IsWhitespaceOrEndOfLine() Then
Return False
End If
If trivia.FullSpan.Contains(position) Then
Return True
End If
Next
End If
End If
End If
End If
Return False
End Function
Public Function GetSelectedMembers(root As SyntaxNode, textSpan As TextSpan) As ImmutableArray(Of SyntaxNode) Implements ISyntaxFactsService.GetSelectedMembers
Return ImmutableArray(Of SyntaxNode).CastUp(root.GetMembersInSpan(textSpan))
End Function
Private Function ISyntaxFactsService_GetFileBanner(root As SyntaxNode) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFactsService.GetFileBanner
Return GetFileBanner(root)
End Function
Private Function ISyntaxFactsService_GetFileBanner(firstToken As SyntaxToken) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFactsService.GetFileBanner
Return GetFileBanner(firstToken)
End Function
Protected Overrides Function ContainsInterleavedDirective(span As TextSpan, token As SyntaxToken, cancellationToken As CancellationToken) As Boolean
Return token.ContainsInterleavedDirective(span, cancellationToken)
End Function
Private Function ISyntaxFactsService_ContainsInterleavedDirective(node As SyntaxNode, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFactsService.ContainsInterleavedDirective
Return ContainsInterleavedDirective(node, cancellationToken)
End Function
Private Function ISyntaxFactsService_ContainsInterleavedDirective1(nodes As ImmutableArray(Of SyntaxNode), cancellationToken As CancellationToken) As Boolean Implements ISyntaxFactsService.ContainsInterleavedDirective
Return ContainsInterleavedDirective(nodes, cancellationToken)
End Function
Public Function IsDocumentationCommentExteriorTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFactsService.IsDocumentationCommentExteriorTrivia
Return trivia.Kind() = SyntaxKind.DocumentationCommentExteriorTrivia
End Function
Private Function ISyntaxFactsService_GetBannerText(documentationCommentTriviaSyntax As SyntaxNode, maxBannerLength As Integer, cancellationToken As CancellationToken) As String Implements ISyntaxFactsService.GetBannerText
Return GetBannerText(documentationCommentTriviaSyntax, maxBannerLength, cancellationToken)
End Function
Public Function GetModifiers(node As SyntaxNode) As SyntaxTokenList Implements ISyntaxFactsService.GetModifiers
Return node.GetModifiers()
End Function
Public Function WithModifiers(node As SyntaxNode, modifiers As SyntaxTokenList) As SyntaxNode Implements ISyntaxFactsService.WithModifiers
Return node.WithModifiers(modifiers)
End Function
Public Function IsLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsLiteralExpression
Return TypeOf node Is LiteralExpressionSyntax
End Function
Public Function IsFalseLiteralExpression(expression As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsFalseLiteralExpression
Return expression.IsKind(SyntaxKind.FalseLiteralExpression)
End Function
Public Function IsTrueLiteralExpression(expression As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsTrueLiteralExpression
Return expression.IsKind(SyntaxKind.TrueLiteralExpression)
End Function
Public Function GetVariablesOfLocalDeclarationStatement(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFactsService.GetVariablesOfLocalDeclarationStatement
Return DirectCast(node, LocalDeclarationStatementSyntax).Declarators
End Function
Public Function GetInitializerOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetInitializerOfVariableDeclarator
Return DirectCast(node, VariableDeclaratorSyntax).Initializer
End Function
Public Function GetTypeOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetTypeOfVariableDeclarator
Dim declarator = DirectCast(node, VariableDeclaratorSyntax)
Return TryCast(declarator.AsClause, SimpleAsClauseSyntax)?.Type
End Function
Public Function GetValueOfEqualsValueClause(node As SyntaxNode) As SyntaxNode Implements ISyntaxFactsService.GetValueOfEqualsValueClause
Return DirectCast(node, EqualsValueSyntax).Value
End Function
Public Function IsExecutableBlock(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsExecutableBlock
Return node.IsExecutableBlock()
End Function
Public Function GetExecutableBlockStatements(node As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFactsService.GetExecutableBlockStatements
Return node.GetExecutableBlockStatements()
End Function
Public Function FindInnermostCommonExecutableBlock(nodes As IEnumerable(Of SyntaxNode)) As SyntaxNode Implements ISyntaxFactsService.FindInnermostCommonExecutableBlock
Return nodes.FindInnermostCommonExecutableBlock()
End Function
Private Function ISyntaxFactsService_GetLeadingBlankLines(node As SyntaxNode) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFactsService.GetLeadingBlankLines
Return MyBase.GetLeadingBlankLines(node)
End Function
Private Function ISyntaxFactsService_GetNodeWithoutLeadingBlankLines(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode) As TSyntaxNode Implements ISyntaxFactsService.GetNodeWithoutLeadingBlankLines
Return MyBase.GetNodeWithoutLeadingBlankLines(node)
End Function
Public Function IsCastExpression(node As SyntaxNode) As Boolean Implements ISyntaxFactsService.IsCastExpression
Return node.Kind = SyntaxKind.DirectCastExpression
End Function
Public Sub GetPartsOfCastExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef expression As SyntaxNode) Implements ISyntaxFactsService.GetPartsOfCastExpression
Dim cast = DirectCast(node, DirectCastExpressionSyntax)
type = cast.Type
expression = cast.Expression
End Sub
Public Function GetDeconstructionReferenceLocation(node As SyntaxNode) As Location Implements ISyntaxFactsService.GetDeconstructionReferenceLocation
Throw New NotImplementedException()
End Function
Public Function GetDeclarationIdentifierIfOverride(token As SyntaxToken) As SyntaxToken? Implements ISyntaxFactsService.GetDeclarationIdentifierIfOverride
If token.Kind() = SyntaxKind.OverridesKeyword Then
Dim parent = token.Parent
Select Case parent.Kind()
Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement
Dim method = DirectCast(parent, MethodStatementSyntax)
Return method.Identifier
Case SyntaxKind.PropertyStatement
Dim [property] = DirectCast(parent, PropertyStatementSyntax)
Return [property].Identifier
End Select
End If
Return Nothing
End Function
Public Function SpansPreprocessorDirective(nodes As IEnumerable(Of SyntaxNode)) As Boolean Implements ISyntaxFactsService.SpansPreprocessorDirective
Return nodes.SpansPreprocessorDirective()
End Function
End Class
End Namespace
|
OmarTawfik/roslyn
|
src/Workspaces/VisualBasic/Portable/LanguageServices/VisualBasicSyntaxFactsService.vb
|
Visual Basic
|
apache-2.0
| 95,008
|
Imports CodeCracker.VisualBasic.Performance
Imports Xunit
Namespace Performance
Public Class StringBuilderInLoopTests
Inherits CodeFixVerifier(Of StringBuilderInLoopAnalyzer, StringBuilderInLoopCodeFixProvider)
<Fact>
Public Async Function WhileWithoutAddAssignmentExpressionDoesNotCreateDiagnostic() As Task
Const source = "
Namespace ConsoleApplication1
Class TypeName
Public Sub Foo()
While (DateTime.Now.Second Mod 2 = 0)
Method()
End While
End Sub
Public Sub Method()
End Sub
End Class
End Namespace"
Await VerifyBasicHasNoDiagnosticsAsync(source)
End Function
<Fact>
Public Async Function WhileWithoutStringConcatDoesNotCreateDiagnostic() As Task
Dim source = "
Dim a = 0
While A < 10
a += 1
End While".WrapInVBMethod()
Await VerifyBasicHasNoDiagnosticsAsync(source)
End Function
<Fact>
Public Async Function WhileWithoutStringConcatWithMethoParameterDoesNotCreateDiagnostic() As Task
Dim source = "
Public Class TypeName
Public Sub Looper(ByRef a As Integer)
While a < 10
a += 1
End While
End Sub
End Class"
Await VerifyBasicHasNoDiagnosticsAsync(source)
End Function
<Fact>
Public Async Function WhileWithStringConcatOnLocalVariableCreateDiagnostic() As Task
Dim source = "
Dim a = """"
While DateTime.Now.Second mod 2 = 10
a += """"
End While".WrapInVBMethod()
Dim expected = GetExpected()
Await VerifyBasicDiagnosticAsync(source, expected)
End Function
<Fact>
Public Async Function WhileWithStringConcatOnFieldVariableCreatesDiagnostic() As Task
Const source = "
Namespace ConsoleApplication1
Class TypeName
Private a As String = """"
Public Sub Foo()
While (DateTime.Now.Second Mod 2 = 0)
a += """"
End While
End Sub
End Class
End Namespace"
Dim expected As DiagnosticResult = GetExpected()
expected.Locations(0).Line = 7
expected.Locations(0).Column = 17
Await VerifyBasicDiagnosticAsync(source, expected)
End Function
Private Shared Function GetExpected() As DiagnosticResult
Return New DiagnosticResult With {
.Id = StringBuilderInLoopAnalyzer.Id,
.Message = String.Format(StringBuilderInLoopAnalyzer.MessageFormat, "a"),
.Severity = Microsoft.CodeAnalysis.DiagnosticSeverity.Warning,
.Locations = {New DiagnosticResultLocation("Test0.vb", 9, 17)}
}
End Function
<Fact>
Public Async Function WhileWithStringConcatOnLocalVariableCreatesDiagnostic() As Task
Dim source = "
Dim a = """"
While DateTime.Now.Second mod 2 = 0
a += """"
End While
".WrapInVBMethod()
Await VerifyBasicDiagnosticAsync(source, GetExpected())
End Function
<Fact>
Public Async Function WhileWithStringConcatOnPropertyVariableCreatesDiagnostic() As Task
Const source = "
Namespace ConsoleApplication1
Class TypeName
Private Property a As String = """"
Public Sub Foo()
While (DateTime.Now.Second Mod 2 = 0)
a += """"
End While
End Sub
End Class
End Namespace"
Dim expected As DiagnosticResult = GetExpected()
expected.Locations(0).Line = 7
expected.Locations(0).Column = 17
Await VerifyBasicDiagnosticAsync(source, expected)
End Function
<Fact>
Public Async Function WhileWithStringConcatWithSeveralConcatsOnDifferentVarsCreatesSeveralDiagnostics() As Task
Dim source = "
Dim a = """"
Dim myString2 = """"
While DateTime.Now.Second mod 2 = 0
a += """"
myString2 += """"
End While
Console.WriteLine(myString2)
".WrapInVBMethod()
Dim expected1 As New DiagnosticResult With {
.Id = StringBuilderInLoopAnalyzer.Id,
.Message = String.Format(StringBuilderInLoopAnalyzer.MessageFormat, "a"),
.Severity = Microsoft.CodeAnalysis.DiagnosticSeverity.Warning,
.Locations = {New DiagnosticResultLocation("Test0.vb", 10, 17)}
}
Dim expected2 As New DiagnosticResult With {
.Id = StringBuilderInLoopAnalyzer.Id,
.Message = String.Format(StringBuilderInLoopAnalyzer.MessageFormat, "myString2"),
.Severity = Microsoft.CodeAnalysis.DiagnosticSeverity.Warning,
.Locations = {New DiagnosticResultLocation("Test0.vb", 11, 17)}
}
Await VerifyBasicDiagnosticAsync(source, expected1, expected2)
End Function
<Fact>
Public Async Function WhileWithStringConcatWithSimpleAssignmentCreatesDiagnostic() As Task
Dim source = "
Dim a = """"
While DateTime.Now.Second mod 2 = 0
a = a + """"
End While
".WrapInVBMethod()
Await VerifyBasicDiagnosticAsync(source, GetExpected())
End Function
<Fact>
Public Async Function WhileWithStringConcatWithSimpleAssignmentOnDifferentDimDoesNotCreateDiagnostic() As Task
Dim source = "Dim a = """"
Dim otherString = """"
While DateTime.Now.Second Mod 2 = 0
a = otherString + """"
End While
".WrapInVBMethod
Await VerifyBasicHasNoDiagnosticsAsync(source)
End Function
<Fact>
Public Async Function FixesAddAssignmentInWhile() As Task
Dim source = "Dim a = """"
While DateTime.Now.Second Mod 2 = 0
a += ""a""
End While
".WrapInVBMethod
Dim fix = "Dim a = """"
Dim builder As New Text.StringBuilder()
builder.Append(a)
While DateTime.Now.Second Mod 2 = 0
builder.Append(""a"")
End While
a = builder.ToString()
".WrapInVBMethod()
Await VerifyBasicFixAsync(source, fix)
End Function
<Fact>
Public Async Function FixesAddAssignmentInWhileWithSystemTextInContext() As Task
Const source = "
Imports System
Imports System.Text
Namespace ConsoleApplication1
Class TypeName
Public Sub Test()
Dim a = """"
While (DateTime.Now.Second Mod 2 = 0)
a += ""a""
End While
End Sub
End Class
End Namespace"
Const fix = "
Imports System
Imports System.Text
Namespace ConsoleApplication1
Class TypeName
Public Sub Test()
Dim a = """"
Dim builder As New StringBuilder()
builder.Append(a)
While (DateTime.Now.Second Mod 2 = 0)
builder.Append(""a"")
End While
a = builder.ToString()
End Sub
End Class
End Namespace"
Await VerifyBasicFixAsync(source, fix)
End Function
<Fact>
Public Async Function FixesSimpleAssignmentInWhile() As Task
Dim source = "Dim a = """"
' comment 3
While (DateTime.Now.Second Mod 2 = 0)
' comment 1
a += ""a"" 'comment 2
End While 'comment 4
".WrapInVBMethod
Dim fix = "Dim a = """"
Dim builder As New Text.StringBuilder()
builder.Append(a)
' comment 3
While (DateTime.Now.Second Mod 2 = 0)
' comment 1
builder.Append(""a"") 'comment 2
End While 'comment 4
a = builder.ToString()
".WrapInVBMethod
Await VerifyBasicFixAsync(source, fix)
End Function
<Fact>
Public Async Function FixesAddAssignmentWhenThereAre2WhilesOnBlock() As Task
Dim source = "Dim a = """"
While (DateTime.Now.Second Mod 2 = 0)
Dim a = 1
End While
While (DateTime.Now.Second Mod 2 = 0)
a += ""a""
End While
".WrapInVBMethod()
Dim fix = "Dim a = """"
While (DateTime.Now.Second Mod 2 = 0)
Dim a = 1
End While
Dim builder As New Text.StringBuilder()
builder.Append(a)
While (DateTime.Now.Second Mod 2 = 0)
builder.Append(""a"")
End While
a = builder.ToString()
".WrapInVBMethod()
Await VerifyBasicFixAsync(source, fix)
End Function
<Fact>
Public Async Function FixesAddAssignmentWithoutClashingTheBuilderName() As Task
Dim source = "Dim builder = 1
Dim a = """"
While (DateTime.Now.Second Mod 2 = 0)
a += ""a""
End While
".WrapInVBMethod()
Dim fix = "Dim builder = 1
Dim a = """"
Dim builder1 As New Text.StringBuilder()
builder1.Append(a)
While (DateTime.Now.Second Mod 2 = 0)
builder1.Append(""a"")
End While
a = builder1.ToString()
".WrapInVBMethod()
Await VerifyBasicFixAsync(source, fix)
End Function
<Fact>
Public Async Function FixesAddAssignmentWithoutClashingTheBuilderNameOnAField() As Task
Const source = "
Namespace ConsoleApplication1
Class TypeName
Private builder As Integer
Public Sub Foo()
Dim builder = 1
Dim a = """"
While (DateTime.Now.Second Mod 2 = 0)
a += ""a""
End While
End Sub
End Class
End Namespace"
Const fix = "
Namespace ConsoleApplication1
Class TypeName
Private builder As Integer
Public Sub Foo()
Dim builder = 1
Dim a = """"
Dim builder1 As New System.Text.StringBuilder()
builder1.Append(a)
While (DateTime.Now.Second Mod 2 = 0)
builder1.Append(""a"")
End While
a = builder1.ToString()
End Sub
End Class
End Namespace"
Await VerifyBasicFixAsync(source, fix)
End Function
<Fact>
Public Async Function ForWithStringConcatOnLocalVariableCreatesDiagnostic() As Task
Dim source = "Dim a = """"
For i As Integer = 1 To 10
a += ""a""
Next".WrapInVBMethod
Dim fix = "Dim a = """"
Dim builder As New Text.StringBuilder()
builder.Append(a)
For i As Integer = 1 To 10
builder.Append(""a"")
Next
a = builder.ToString()".WrapInVBMethod
Await VerifyBasicFixAsync(source, fix)
End Function
<Fact>
Public Async Function FixesAddAssignmentInFor() As Task
Dim source = "Dim a = """"
For i As Integer = 1 To 10
a += ""b""
Exit For
Next".WrapInVBMethod
Dim builder As New System.Text.StringBuilder()
builder.Append("a")
Dim fix = "Dim a = """"
Dim builder As New Text.StringBuilder()
builder.Append(a)
For i As Integer = 1 To 10
builder.Append(""b"")
Exit For
Next
a = builder.ToString()".WrapInVBMethod
Await VerifyBasicFixAsync(source, fix)
End Function
<Fact>
Public Async Function ForeachWithStringConcatOnLocalVariableCreatesDiagnostic() As Task
Dim source = "
Dim a = """"
For Each i In {1, 2, 3}
a += """"
Next".WrapInVBMethod
Dim expected As New DiagnosticResult With
{
.Id = StringBuilderInLoopAnalyzer.Id,
.Message = String.Format(StringBuilderInLoopAnalyzer.MessageFormat, "a"),
.Severity = Microsoft.CodeAnalysis.DiagnosticSeverity.Warning,
.Locations = {New DiagnosticResultLocation("Test0.vb", 9, 17)}
}
Await VerifyBasicDiagnosticAsync(source, expected)
End Function
<Fact>
Public Async Function FixesAddAssignmentInForEach() As Task
Dim source = "Dim a = """"
For Each i In {1, 2, 3}
a += ""a""
Next".WrapInVBMethod
Dim fix = "Dim a = """"
Dim builder As New Text.StringBuilder()
builder.Append(a)
For Each i In {1, 2, 3}
builder.Append(""a"")
Next
a = builder.ToString()".WrapInVBMethod
Await VerifyBasicFixAsync(source, fix)
End Function
<Fact>
Public Async Function DoWithStringConcatOnLocalVariableCreatesDiagnostic() As Task
Dim source = "
Dim a = """"
Do
a += """"
Loop Until DateTime.Now.Second Mod 2 = 0
".WrapInVBMethod
Dim expected As New DiagnosticResult With
{
.Id = StringBuilderInLoopAnalyzer.Id,
.Message = String.Format(StringBuilderInLoopAnalyzer.MessageFormat, "a"),
.Severity = Microsoft.CodeAnalysis.DiagnosticSeverity.Warning,
.Locations = {New DiagnosticResultLocation("Test0.vb", 9, 17)}
}
Await VerifyBasicDiagnosticAsync(source, expected)
End Function
<Fact>
Public Async Function FixesAddAssignmentInForDo() As Task
Dim source = "Dim a = """"
Do
a += ""a""
Loop Until DateTime.Now.Second Mod 2 = 0
".WrapInVBMethod
Dim b As New System.Text.StringBuilder()
Dim fix = "Dim a = """"
Dim builder As New Text.StringBuilder()
builder.Append(a)
Do
builder.Append(""a"")
Loop Until DateTime.Now.Second Mod 2 = 0
a = builder.ToString()
".WrapInVBMethod
Await VerifyBasicFixAsync(source, fix)
End Function
<Fact>
Public Async Function ForLoopInMethodWithoutStringShouldNotCreateDiagnostic() As Task
Dim source = "
Public Class Test
Private Sub AdjustSample(ByRef readIndex As Integer, writeBuffer() As Single, ByRef writeIndex As Integer)
For i = 0 To 2
writeBuffer(writeIndex) = 0
readIndex += 1
writeIndex += 1
Next
End Sub
End Class"
Await VerifyBasicHasNoDiagnosticsAsync(source)
End Function
<Fact>
Public Async Function ForLoopStringDeclaredAndConcatenatedWithinShouldNotCreateDiagnostic() As Task
Dim source = "
For i = 0 To 10
Dim someString As String = i.ToString()
someString &= "" ""
Console.WriteLine(someString)
Next".WrapInVBMethod()
Await VerifyBasicHasNoDiagnosticsAsync(source)
End Function
End Class
End Namespace
|
baks/code-cracker
|
test/VisualBasic/CodeCracker.Test/Performance/StringBuilderInLoopTests.vb
|
Visual Basic
|
apache-2.0
| 15,691
|
' 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.ApiDesignGuidelines.Analyzers
''' <summary>
''' CA1065: Do not raise exceptions in unexpected locations
''' </summary>
<ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]>
Public NotInheritable Class BasicDoNotRaiseExceptionsInUnexpectedLocationsFixer
Inherits DoNotRaiseExceptionsInUnexpectedLocationsFixer
End Class
End Namespace
|
mattwar/roslyn-analyzers
|
src/Microsoft.ApiDesignGuidelines.Analyzers/VisualBasic/BasicDoNotRaiseExceptionsInUnexpectedLocations.Fixer.vb
|
Visual Basic
|
apache-2.0
| 773
|
Imports System.IO
Imports System.Net
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Security.Permissions
Imports System.ComponentModel
<PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
<System.Runtime.InteropServices.ComVisibleAttribute(True)> _
Public Class frmBrowser
Public WithEvents oDoc As HtmlDocument
Private oElement As HtmlElement
Private TempPopAllowed As Boolean = False
Private popURL As String
Private LastDomain As String
'Public PageImage As New PictureBox
Public NumFeeds As Integer = 0
#Region " Form "
Private Sub frmBrowser_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
oDoc = Nothing
My.Settings.Save()
wb.Dispose()
End Sub
Private Sub frmBrowser_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AppManager.CurrentBrowser = Me.wb
wb.ObjectForScripting = Me
Me.wb.IsWebBrowserContextMenuEnabled = True
End Sub
#End Region
#Region " Handleing Document Script Calls "
'Since we are using the browser control, we have to handle javascript and other events raised by
'the html document that target window.external such as add to favorites, organize favorites etc.
'We could implement this in the extended control itself,
'but for purposes of this demo, we will handle a couple common ones
'in this region.
'// Security note on Javascript handleing, you will probably want to check to make
'//sure that the event was raised by a user click or show dialogs, not allow automatic running of
'//these routines by using dialogs or other methods.
'//Make sure your signatures match the common calls from the page.
Public Sub AddFavorite(ByVal strURL As String, ByVal strTitle As String)
wb.AddToFavorites(Trim(strURL), Trim(strTitle))
End Sub
Public Sub OrganizeFavorites()
wb.ShowOrganizeFavorites()
End Sub
Public Sub ShowCalc()
Process.Start("Calc.exe")
End Sub
Public Sub ShowSettings()
Dim ofrm As New frmSettings
ofrm.ShowDialog(AppManager.MainForm)
End Sub
#End Region
#Region " Browser Control / Document "
Private Sub wb_CanGoBackChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles wb.CanGoBackChanged
AppManager.MainForm.btnBack.Enabled = wb.CanGoBack
End Sub
Private Sub wb_CanGoForwardChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles wb.CanGoForwardChanged
AppManager.MainForm.btnForward.Enabled = wb.CanGoForward
End Sub
Private Sub wb_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles wb.DocumentCompleted
FastWebsiteLoading()
End Sub
Private Sub FastWebsiteLoading()
oDoc = wb.Document
Dim s As String
Dim strDomain() As String
For Each s In My.Settings.BlockedSites
strDomain = Split(s, "http://")
If strDomain(1) = wb.Document.Domain Then
wb.DocumentText = My.Resources.Blocked
AppManager.MainForm.pBar.Visible = False
Exit Sub
End If
Me.wb.ObjectForScripting = True
wb.ScriptErrorsSuppressed = True
Next
Me.Text = wb.DocumentTitle
'Here you may want to prefetch the icon, or implement a form of caching icons.
AppManager.MainForm.pBar.Visible = False
If LastDomain = oDoc.Domain Then
'We want to leave the popup settings alone.
Else
'different domain, reset the popup blocker.
Me.TempPopAllowed = False
InfoBar1.PictureBox1.Image = My.Resources.popBlocked
InfoBar1.Text = " Pop up blocked."
LastDomain = oDoc.Domain
End If
If My.Settings.UsePhishingFilter = True Then
RunPhishingFilter()
End If
End Sub
Private Sub oDoc_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.HtmlElementEventArgs) Handles oDoc.MouseDown
'Here is it's an input element? if yes we want to show the normal windows options....
If My.Settings.UseInternalMenu = True Then
If e.MouseButtonsPressed = Windows.Forms.MouseButtons.Right And oElement.TagName = "INPUT" Then
wb.IsWebBrowserContextMenuEnabled = True
Else
wb.IsWebBrowserContextMenuEnabled = False
End If
End If
Dim MPoint As New Point(e.MousePosition.X, e.MousePosition.Y)
oElement = oDoc.GetElementFromPoint(MPoint)
If MouseButtons = Windows.Forms.MouseButtons.Middle Then
Dim ofrm As New frmBrowser
AppManager.AddTab(ofrm, oElement.GetAttribute("HREF"))
End If
End Sub
Private Sub oDoc_MouseMove(ByVal sender As Object, _
ByVal e As System.Windows.Forms.HtmlElementEventArgs) Handles oDoc.MouseMove
On Error Resume Next
Dim MPoint As New Point(e.MousePosition.X, e.MousePosition.Y)
If My.Settings.ShowTags = True Then
AppManager.MainForm.lblElement.Text = "<" & oElement.TagName & ">"
Else
AppManager.MainForm.lblElement.Text = String.Empty
End If
oElement = oDoc.GetElementFromPoint(MPoint)
End Sub
Private Sub wb_EncryptionLevelChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles wb.EncryptionLevelChanged
With AppManager.MainForm.lblSec
Select Case wb.EncryptionLevel
Case WebBrowserEncryptionLevel.Bit128
.Image = My.Resources.Lock
Case WebBrowserEncryptionLevel.Bit40
.Image = My.Resources.Lock
Case WebBrowserEncryptionLevel.Bit56
.Image = My.Resources.Lock
Case WebBrowserEncryptionLevel.Fortezza
.Image = My.Resources.Lock
Case WebBrowserEncryptionLevel.Insecure
.Image = My.Resources.LockOpen
Case WebBrowserEncryptionLevel.Mixed
.Image = My.Resources.LockOpen
Case WebBrowserEncryptionLevel.Unknown
.Image = My.Resources.LockOpen
Case Else
.Image = My.Resources.LockOpen
End Select
.ToolTipText = wb.EncryptionLevel.ToString
End With
End Sub
Private Sub wb_NavigatingExtended(ByVal sender As Object, ByVal e As exBrowser.WebBrowserNavigatingExtendedEventArgs) Handles wb.NavigatingExtended
Dim s As String
For Each s In My.Settings.BlockedSites
If s = e.Url.ToString Or s & "/" = e.Url.ToString Then
e.Cancel = True
wb.DocumentText = My.Resources.Blocked
AppManager.MainForm.pBar.Visible = False
Else
AppManager.MainForm.pBar.Visible = True
End If
Next
End Sub
Private Sub wb_NewWindow(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles wb.NewWindow
e.Cancel = True
End Sub
Private Sub wb_NewWindowExtended(ByVal sender As Object, _
ByVal e As exBrowser.WebBrowserNewWindowExtendedEventArgs) Handles wb.NewWindowExtended
'//////////// End DL checking ///////////////////////
'Here we implement something simular to IE 7
'You might want to allow shit + click or some other override, that's up to you.
'1st check if site is in allowed list
Dim s As String
For Each s In My.Settings.AllowedPopSites
If s = wb.Document.Domain Then
'Site is allowed... Show pop in new tab and exit...
e.Cancel = True
Dim ofrm As New frmBrowser
AppManager.AddTab(ofrm, e.Url.ToString)
Exit Sub
End If
Next
If My.Settings.PopUpBlockerEnabled = True Then
If Me.TempPopAllowed = True Then
'Site temporarily allowed... open in new tab, then exit...
e.Cancel = True
Dim ofrm As New frmBrowser
AppManager.AddTab(ofrm, e.Url.ToString)
Exit Sub
Else
'Blocker is enabled and not temp allowed...
e.Cancel = True
If My.Settings.PopSound = True Then
My.Computer.Audio.Play(My.Resources.Windows_Pop_up_Blocked, AudioPlayMode.Background)
End If
If My.Settings.PopInfoBar = True Then
Me.InfoBar1.Visible = True
End If
popURL = e.Url.ToString
End If
Else
'Blocker is not enabled... open in new tab.
e.Cancel = True
Dim ofrm As New frmBrowser
AppManager.AddTab(ofrm, e.Url.ToString)
End If
End Sub
Private Sub wb_StatusTextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles wb.StatusTextChanged
If AppManager.CurrentBrowser Is Me.wb Then
AppManager.MainForm.lblStatus.Text = wb.StatusText
End If
End Sub
Private Function FixURL(ByVal sURL As String) As String
sURL = sURL.Trim
If Not sURL.ToLower().StartsWith("http://") _
Then sURL = "http://" & sURL
Return sURL
End Function
Private Sub wb_DocumentTitleChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles wb.DocumentTitleChanged
Me.Text = wb.DocumentTitle
AppManager.MainForm.Text = wb.DocumentTitle & " - " & My.Resources.AppName
End Sub
Private Sub wb_Navigated(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserNavigatedEventArgs) Handles wb.Navigated
AppManager.MainForm.Text = wb.DocumentTitle & " - " & My.Resources.AppName
AppManager.MainForm.pBar.Visible = False
Me.Icon = AppManager.GetFavIcon(wb.Document.Domain & "/favicon.ico")
AppManager.MainForm.tc1.TabPages(Me).Icon = Me.Icon
AppManager.MainForm.cboURL.Text = wb.Url.ToString
wb.ScriptErrorsSuppressed = True
If My.Settings.RSScheck = True Then
DetectFeeds()
Else
frmMain.CheckFeedsToolStripMenuItem.Enabled = False
frmMain.RssFeedToolStripMenuItem1.Enabled = False
End If
End Sub
Private Sub RunPhishingFilter()
'///////////////////////////////////////////////////////////
'Here you could parse the page for bad links, images etc from
'a known list of sites...
'Here we will just use the blocked sites list
'as an example of what to do
'///////////////////////////////////////////////////////////
Dim BadLink As Boolean = False
Dim oEl As HtmlElement
Dim s As String
Dim li As ListItem
Dim ofrm As New frmPhising
For Each oEl In oDoc.Links
For Each s In My.Settings.PhishingSites
If InStr(oEl.GetAttribute("HREF"), s) Then
li = New ListItem
li.Text = oEl.GetAttribute("HREF")
ofrm.lbPhishing.Items.Add(li)
BadLink = True
End If
Next
Next
If BadLink = True Then
ofrm.ShowDialog()
Else
ofrm.Dispose()
End If
End Sub
Private Sub DetectFeeds()
Try
Dim oEl As HtmlElement
For Each oEl In wb.Document.All
If oEl.GetAttribute("Type") = "application/rss+xml" Then
NumFeeds = NumFeeds + 1
End If
Next
If NumFeeds = 0 Then
AppManager.MainForm.mnuFeeds.Enabled = False
Else
AppManager.MainForm.mnuFeeds.Enabled = True
End If
Catch ex As Exception
NumFeeds = 0
AppManager.MainForm.mnuFeeds.Enabled = False
End Try
End Sub
#End Region
#Region " Context Menu "
Private Sub mnuImageSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuImageSave.Click
Dim opb As New PictureBox
Dim sfd As New SaveFileDialog
Try
Dim odir As String = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)
sfd.InitialDirectory = odir.ToString
Dim ofile() As String = Split(oElement.GetAttribute("src"), "/")
sfd.Title = "Save web image"
sfd.FileName = ofile(UBound(ofile)).ToString
If sfd.ShowDialog() = Windows.Forms.DialogResult.OK Then
If sfd.FileName = String.Empty Then
Exit Sub
Else
AppManager.LoadWebImageToPictureBox(opb, oElement.GetAttribute("src"))
opb.Image.Save(sfd.FileName, Imaging.ImageFormat.Jpeg)
End If
If AppManager.LoadWebImageToPictureBox(opb, oElement.GetAttribute("src")) Then
opb.Image.Save(sfd.FileName, Imaging.ImageFormat.Gif)
End If
If AppManager.LoadWebImageToPictureBox(opb, oElement.GetAttribute("src")) Then
opb.Image.Save(sfd.FileName, Imaging.ImageFormat.Png)
If AppManager.LoadWebImageToPictureBox(opb, oElement.GetAttribute("src")) Then
opb.Image.Save(sfd.FileName, Imaging.ImageFormat.Bmp)
End If
If AppManager.LoadWebImageToPictureBox(opb, oElement.GetAttribute("src")) Then
opb.Image.Save(sfd.FileName, Imaging.ImageFormat.Emf)
End If
If AppManager.LoadWebImageToPictureBox(opb, oElement.GetAttribute("src")) Then
opb.Image.Save(sfd.FileName, Imaging.ImageFormat.Icon)
End If
If AppManager.LoadWebImageToPictureBox(opb, oElement.GetAttribute("src")) Then
opb.Image.Save(sfd.FileName, Imaging.ImageFormat.Tiff)
End If
If AppManager.LoadWebImageToPictureBox(opb, oElement.GetAttribute("src")) Then
opb.Image.Save(sfd.FileName, Imaging.ImageFormat.Wmf)
End If
End If
End If
Catch ex As Exception
Dim ofrm As New frmError
ofrm.err = ex
ofrm.ShowDialog()
Finally
opb.Dispose()
sfd.Dispose()
End Try
End Sub
Private Sub ContextMenuStrip1_Opening(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles ContextMenuStrip1.Opening
If Not IsNothing(oElement) Then
If oElement.TagName = "IMG" Then
mnuImage.Enabled = True
Else
mnuImage.Enabled = False
End If
If oElement.TagName = "A" Or oElement.TagName = "AREA" Or oElement.TagName = "p" Then
OpenInNewTabToolStripMenuItem.Enabled = True
Else
OpenInNewTabToolStripMenuItem.Enabled = False
End If
End If
mnuBack.Enabled = AppManager.CurrentBrowser.CanGoBack
mnuForward.Enabled = AppManager.CurrentBrowser.CanGoForward
End Sub
Private Sub ElemToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ElemToolStripMenuItem.Click
ShowProps()
End Sub
Private Sub mnuImageProperties_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuImageProperties.Click
ShowProps()
End Sub
Private Sub ShowProps()
Dim ofrm As New frmProperties
ofrm.obj = oElement
ofrm.Show()
End Sub
Private Sub PropertiesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PropertiesToolStripMenuItem.Click
AppManager.CurrentBrowser.ShowPropertiesDialog()
End Sub
Private Sub mnuPageSaveAs_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuPageSaveAs.Click
AppManager.CurrentBrowser.ShowSaveAsDialog()
End Sub
Private Sub mnuPagePrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuPagePrint.Click
AppManager.CurrentBrowser.ShowPrintDialog()
End Sub
Private Sub mnuCopy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuCopy.Click
AppManager.CurrentBrowser.Document.ExecCommand("Copy", False, System.DBNull.Value)
End Sub
Private Sub mnuPaste_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuPaste.Click
AppManager.CurrentBrowser.Document.ExecCommand("Paste", False, System.DBNull.Value)
End Sub
Private Sub mnuViewImageNewTab_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuViewImageNewTab.Click
Dim ofrm As New frmBrowser
AppManager.AddTab(ofrm, oElement.GetAttribute("src"))
End Sub
Private Sub mnuFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFind.Click
AppManager.CurrentBrowser.ShowFindDialog()
End Sub
Private Sub wb_ProgressChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserProgressChangedEventArgs) Handles wb.ProgressChanged
If AppManager.CurrentBrowser Is Me.wb Then
AppManager.MainForm.lblStatus.Text = wb.StatusText
AppManager.MainForm.pBar.Value = ((e.CurrentProgress / e.MaximumProgress) * 100)
End If
End Sub
Private Sub mnuImageCopy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuImageCopy.Click
Dim opb As New PictureBox
AppManager.LoadWebImageToPictureBox(opb, oElement.GetAttribute("src"))
Clipboard.SetImage(opb.Image)
opb.Dispose()
End Sub
Private Sub mnuPopTempAllow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuPopTempAllow.Click
Me.TempPopAllowed = True
InfoBar1.Text = "Popups Temporarily allowed."
InfoBar1.PictureBox1.Image = My.Resources.popallowed
If Me.popURL = "" Then
'Nothing to do
Else
Dim oFrm As New frmBrowser
AppManager.AddTab(oFrm, popURL)
InfoBar1.Visible = False
End If
End Sub
Private Sub mnuPopAllowthissite_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuPopAllowthissite.Click
My.Settings.AllowedPopSites.Add(wb.Document.Domain)
End Sub
Private Sub mnuPopBlockEnabled_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuPopBlockEnabled.Click
My.Settings.PopUpBlockerEnabled = mnuPopBlockEnabled.Checked
End Sub
Private Sub mnuPopShowInfoBar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuPopShowInfoBar.Click
My.Settings.PopInfoBar = mnuPopShowInfoBar.Checked
End Sub
Private Sub mnuPopMoreSettings_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuPopMoreSettings.Click
Dim ofrm As New frmSettings
ofrm.TabControl1.SelectedIndex = 0
ofrm.ShowDialog(AppManager.MainForm)
End Sub
Private Sub cmiInfoBar_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles cmiInfoBar.Opening
Select Case My.Settings.PopUpBlockerEnabled
Case True
mnuPopBlockEnabled.Text = "Pop up Blocker Enabled."
Case False
mnuPopBlockEnabled.Text = "Pop up Blocker Disabled."
End Select
mnuPopBlockEnabled.Checked = My.Settings.PopUpBlockerEnabled
mnuPopShowInfoBar.Checked = My.Settings.PopInfoBar
End Sub
Private Sub mnuSaveAllImages_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuSaveAllImages.Click
Dim ofrm As New frmScrapeImages
ofrm.ShowDialog(AppManager.MainForm)
End Sub
#End Region
Private Sub OpenInNewTabToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenInNewTabToolStripMenuItem.Click
Dim ofrm As New frmBrowser
AppManager.AddTab(ofrm, oElement.GetAttribute("HREF"))
End Sub
End Class
|
sheikhimran01/xtravo
|
Xtravo/Forms/frmBrowser.vb
|
Visual Basic
|
mit
| 20,585
|
Imports System.Collections
Namespace SecuritySwitch.Configuration
''' <summary>
''' Indicates the type of security for a ItemSetting.
''' </summary>
Public Enum SecurityType
''' <summary>
''' The item should be secure.
''' </summary>
Secure
''' <summary>
''' The item should be insecure.
''' </summary>
Insecure
''' <summary>
''' The item should be ignored.
''' </summary>
Ignore
End Enum
''' <summary>
''' The ItemSettingComparer class implements the IComparer interface to compare.
''' </summary>
Public Class ItemSettingComparer
Implements IComparer
''' <summary>
''' Compares the two objects as string and ItemSetting or both ItemSetting
''' by the Path property.
''' </summary>
''' <param name="x">First object to compare.</param>
''' <param name="y">Second object to compare.</param>
''' <returns></returns>
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compare
' Check the type of the parameters
If Not TypeOf x Is ItemSetting AndAlso Not TypeOf x Is String Then
' Throw an exception for the first argument
Throw New ArgumentException("Parameter must be a ItemSetting or a String.", "x")
ElseIf Not TypeOf y Is ItemSetting AndAlso Not TypeOf y Is String Then
' Throw an exception for the second argument
Throw New ArgumentException("Parameter must be a ItemSetting or a String.", "y")
End If
' Initialize the path variables
Dim xPath As String = String.Empty
Dim yPath As String = String.Empty
' Get the path for x
If TypeOf x Is ItemSetting Then
xPath = CType(x, ItemSetting).Path
Else
xPath = CType(x, String)
End If
' Get the path for y
If TypeOf y Is ItemSetting Then
yPath = CType(y, ItemSetting).Path
Else
yPath = CType(y, String)
End If
' Compare the paths, ignoring case
Return String.Compare(xPath, yPath, True)
End Function
End Class
''' <summary>
''' The ItemSetting class is the base class that represents entries in the <securitySwitch>
''' configuration section.
''' </summary>
Public Class ItemSetting
' Fields
Private _secure As SecurityType = SecurityType.Secure
Private _path As String = String.Empty
''' <summary>
''' Gets or sets the type of security for this directory or file.
''' </summary>
Public Property Secure() As SecurityType
Get
Return _secure
End Get
Set(ByVal Value As SecurityType)
_secure = Value
End Set
End Property
''' <summary>
''' Gets or sets the path of this directory or file.
''' </summary>
Public Property Path() As String
Get
Return _path
End Get
Set(ByVal Value As String)
_path = Value
End Set
End Property
''' <summary>
''' Creates an instance of this class.
''' </summary>
Public Sub New()
MyBase.New()
End Sub
''' <summary>
''' Creates an instance with initial values.
''' </summary>
''' <param name="path">The relative path to the directory or file.</param>
''' <param name="ignore">A flag to ignore security for the directory or file.</param>
Public Sub New(ByVal path As String, ByVal secure As SecurityType)
' Initialize the path and secure properties
Me._path = path
Me._secure = secure
End Sub
''' <summary>
''' Creates an instance with an initial path value.
''' </summary>
''' <param name="path">The relative path to the directory or file.</param>
Public Sub New(ByVal path As String)
Me.New(path, SecurityType.Secure)
End Sub
End Class
''' <summary>
''' The ItemSettingCollection class houses a collection of ItemSetting instances.
''' </summary>
Public Class ItemSettingCollection
Inherits CollectionBase
''' <summary>
''' Initialize an instance of this collection.
''' </summary>
Public Sub New()
MyBase.New()
End Sub
''' <summary>
''' Returns the index of a specified item in the collection.
''' </summary>
''' <param name="Item">The item to find.</param>
''' <returns>Returns the index of the item.</returns>
Public Function IndexOf(ByVal item As ItemSetting) As Integer
Return List.IndexOf(item)
End Function
''' <summary>
''' Returns the index of an item with the specified path in the collection.
''' </summary>
''' <param name="path">The path of the item to find.</param>
''' <returns>Returns the index of the item with the path.</returns>
Public Function IndexOf(ByVal path As String) As Integer
' Create a comparer for sorting and searching
Dim Comparer As New ItemSettingComparer
InnerList.Sort(Comparer)
Return InnerList.BinarySearch(path, Comparer)
End Function
End Class
End Namespace
|
ayseff/securityswitch.version-2
|
VB/Configuration/ItemSetting.vb
|
Visual Basic
|
bsd-3-clause
| 4,838
|
' 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.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend Partial Class DataFlowPass
''' <summary>
''' Collection of 0, 1 or more slots. Allows returning of several slots by some
''' DataFlowPass methods to handle cases where implicit receiver represents
''' several variables, like in:
''' Dim a, b, c As New C(...) With {...}
'''
''' Because such constructions are very rare in real user code, the collection only
''' allocates an array builder for storing several values if there are indeed more
''' than one slot to be stored. Because the collection may optionally create an
''' array builder, collection's Free() method must be called when appropriate.
'''
''' Note that the collection is mutable, so one can add or modify the values.
''' If some collection elements get replaced with 'SlotKind.NotTracked' collection
''' does NOT "shrink", i.e. once allocated the array builder is not freed even if
''' all the elements are set to 'SlotKind.NotTracked'.
'''
''' Collection cannot store 'SlotKind.Unreachable' (0) which has a special meaning.
''' </summary>
Protected Structure SlotCollection
Private _singleValue As Integer
Private _builder As ArrayBuilder(Of Integer)
Public ReadOnly Property Count As Integer
Get
If Me._builder IsNot Nothing Then
Return Me._builder.Count
End If
Return If(Me._singleValue = SlotKind.Unreachable, 0, 1)
End Get
End Property
Default Public Property Item(index As Integer) As Integer
Get
Debug.Assert(index >= 0 AndAlso index < Me.Count)
If Me._builder IsNot Nothing Then
Return Me._builder(index)
End If
Return Me._singleValue
End Get
Set(value As Integer)
Debug.Assert(index >= 0 AndAlso index < Me.Count)
Debug.Assert(value <> SlotKind.Unreachable)
If Me._builder IsNot Nothing Then
Me._builder(index) = value
End If
Me._singleValue = value
End Set
End Property
Public Sub Append(slot As Integer)
Debug.Assert(slot <> SlotKind.Unreachable)
If Me._builder IsNot Nothing Then
Me._builder.Add(slot)
ElseIf Me._singleValue = 0 Then
Me._singleValue = slot
Else
Me._builder = ArrayBuilder(Of Integer).GetInstance()
Me._builder.Add(Me._singleValue)
Me._builder.Add(slot)
End If
End Sub
Public Sub Free()
If Me._builder IsNot Nothing Then
Me._builder.Free()
Me._builder = Nothing
End If
Me._singleValue = 0
End Sub
End Structure
End Class
End Namespace
|
abock/roslyn
|
src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/DataFlowPass.SlotCollection.vb
|
Visual Basic
|
mit
| 3,653
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Globalization
Imports System.Text
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Syntax
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class TestSyntaxNodes
Inherits BasicTestBase
Private _spaceTrivia As SyntaxTrivia = SyntaxFactory.WhitespaceTrivia(" ")
Private _newlineTrivia As SyntaxTriviaList = SyntaxTriviaListBuilder.Create.Add(SyntaxFactory.WhitespaceTrivia(Environment.NewLine)).ToList
Private Function CreateIntegerLiteral(value As ULong) As LiteralExpressionSyntax
Return SyntaxFactory.NumericLiteralExpression(SyntaxFactory.IntegerLiteralToken(value.ToString(), LiteralBase.Decimal, TypeCharacter.None, value))
End Function
' Creates "1- X( 3, 4+ 8, 9)"
Private Function CreateSimpleTree() As BinaryExpressionSyntax
Dim operandsx() As ArgumentSyntax = {SyntaxFactory.SimpleArgument(CreateIntegerLiteral(3)),
SyntaxFactory.SimpleArgument(SyntaxFactory.AddExpression(CreateIntegerLiteral(4), SyntaxFactory.Token(SyntaxKind.PlusToken, trailing:=_spaceTrivia), CreateIntegerLiteral(8))),
SyntaxFactory.SimpleArgument(CreateIntegerLiteral(9))}
'Dim operands = New SeparatedSyntaxListBuilder(Of ArgumentSyntax)(8)
'operands.Add(Syntax.SimpleArgument(CreateIntegerLiteral(3)))
'operands.AddSeparator(Syntax.Token(SyntaxKind.CommaToken,spaceTrivia))
'operands.Add(Syntax.SimpleArgument(Syntax.AddExpression(CreateIntegerLiteral(4),
'Syntax.Token(SyntaxKind.PlusToken,spaceTrivia), CreateIntegerLiteral(8))))
'operands.AddSeparator(Syntax.Token(SyntaxKind.CommaToken,spaceTrivia))
'operands.Add(Syntax.SimpleArgument(CreateIntegerLiteral(9)))
' Use Syntax.SeparatedList factory method instead of builder
Dim operands = SyntaxFactory.SeparatedList(Of ArgumentSyntax)({SyntaxFactory.SimpleArgument(CreateIntegerLiteral(3)),
SyntaxFactory.SimpleArgument(SyntaxFactory.AddExpression(CreateIntegerLiteral(4), SyntaxFactory.Token(SyntaxKind.PlusToken, trailing:=_spaceTrivia), CreateIntegerLiteral(8))),
SyntaxFactory.SimpleArgument(CreateIntegerLiteral(9))},
{SyntaxFactory.Token(SyntaxKind.CommaToken, trailing:=_spaceTrivia),
SyntaxFactory.Token(SyntaxKind.CommaToken, trailing:=_spaceTrivia)
})
Return SyntaxFactory.SubtractExpression(CreateIntegerLiteral(1), SyntaxFactory.Token(SyntaxKind.MinusToken, trailing:=_spaceTrivia),
SyntaxFactory.InvocationExpression(SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("X")),
SyntaxFactory.ArgumentList(SyntaxFactory.Token(SyntaxKind.OpenParenToken, trailing:=_spaceTrivia),
operands,
SyntaxFactory.Token(SyntaxKind.CloseParenToken, trailing:=_spaceTrivia))))
End Function
<Fact>
Public Sub TestParents()
Dim simpleTree = CreateSimpleTree()
Assert.Null(simpleTree.Parent)
Assert.Equal(simpleTree, CType(simpleTree, BinaryExpressionSyntax).Left.Parent)
Assert.Equal(simpleTree, CType(simpleTree, BinaryExpressionSyntax).Right.Parent)
Dim x As InvocationExpressionSyntax = CType(CType(simpleTree, BinaryExpressionSyntax).Right, InvocationExpressionSyntax)
Dim argList As ArgumentListSyntax = x.ArgumentList
Assert.Equal(argList, argList.Arguments(0).Parent)
Assert.Equal(argList, argList.Arguments(1).Parent)
Assert.Equal(argList, argList.Arguments.GetWithSeparators(1).Parent)
Assert.Equal(argList, argList.Arguments.GetWithSeparators(3).Parent)
End Sub
<Fact>
Public Sub TestChildren()
Dim simpleTree = CreateSimpleTree()
Dim invocation As InvocationExpressionSyntax = CType(CType(simpleTree, BinaryExpressionSyntax).Right, InvocationExpressionSyntax)
Dim argList As ArgumentListSyntax = invocation.ArgumentList
Dim children = argList.ChildNodesAndTokens()
Assert.Equal(7, children.Count)
Assert.Equal(children(0), argList.OpenParenToken)
Assert.Equal(children(1), argList.Arguments(0))
Assert.Equal(children(2), argList.Arguments.GetWithSeparators(1))
Assert.Equal(children(3), argList.Arguments(1))
Assert.Equal(children(4), argList.Arguments.GetWithSeparators(3))
Assert.Equal(children(5), argList.Arguments(2))
Assert.Equal(children(6), argList.CloseParenToken)
children = simpleTree.ChildNodesAndTokens()
Dim binop = DirectCast(simpleTree, BinaryExpressionSyntax)
Assert.Equal(3, children.Count)
Assert.Equal(children(0), binop.Left)
Assert.Equal(children(1), binop.OperatorToken)
Assert.Equal(children(2), binop.Right)
Dim ItemList As New List(Of String)
Dim ItemListRev As New List(Of String)
Dim VB1 = children.GetEnumerator
Do While VB1.MoveNext
ItemList.Add(VB1.Current.ToString)
Loop
Dim i As SyntaxNodeOrToken
For Each i In children.Reverse
ItemListRev.Add(i.ToString)
Next
Assert.Equal(ItemList.Count, ItemListRev.Count)
If (ItemList.Count > 0) Then
Dim L0 As Integer = (ItemList.Count - 1)
Dim I0 As Integer = 0
Do While (I0 <= L0)
Assert.Equal(ItemList.Item(I0), ItemListRev.Item(((ItemList.Count - 1) - I0)))
I0 += 1
Loop
End If
Dim b1 As Integer = 0
Dim enumerator = children.GetEnumerator
enumerator.Reset()
Do While enumerator.MoveNext
Dim item1 As SyntaxNodeOrToken = enumerator.Current
b1 += 1
Loop
Dim b2 As Integer = 0
Dim enumeratorr = children.Reverse.GetEnumerator
enumeratorr.Reset()
Do While enumeratorr.MoveNext
Dim item1 As SyntaxNodeOrToken = enumeratorr.Current
b2 += 1
Loop
Assert.Equal(b1, b2)
Assert.Throws(Of ArgumentOutOfRangeException)((Sub()
Dim i1 As SyntaxNodeOrToken = children.Item(-1)
End Sub
))
Assert.Equal(ItemList.Item((ItemList.Count - 1)), children.Last.ToString)
Assert.Equal(ItemList.Item(0), Enumerable.First(Of SyntaxNodeOrToken)(DirectCast(children, IEnumerable(Of SyntaxNodeOrToken))).ToString)
'Comparison operators = and <>
Dim xc As ChildSyntaxList = children
Assert.Equal(xc, children)
Assert.NotEqual(xc, New ChildSyntaxList)
'Explicitly calling the <> operator as a double negative
Assert.False(xc <> children, "Verifying <> operator for ChildSyntaxList items - This should return false as xc was assigned from Children")
End Sub
<Fact>
<WorkItem(21812, "https://github.com/dotnet/roslyn/issues/21812")>
Public Sub TestTupleTypeInSyntaxFactory()
Dim int = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntegerKeyword))
Dim tuple = SyntaxFactory.TupleType(SyntaxFactory.TypedTupleElement(int), SyntaxFactory.TypedTupleElement(int))
' Array
Dim intArraySyntax = Parse("
Class C
Dim x As (Integer, Integer)()
End Class")
intArraySyntax.AssertTheseDiagnostics(<errors></errors>)
SyntaxFactory.ArrayType(tuple) ' no exception
' Object creation
Dim objectCreationSyntax = Parse("
Class C
Dim x = New (Integer, Integer)(1)
End Class")
objectCreationSyntax.AssertTheseDiagnostics(<errors></errors>)
SyntaxFactory.ObjectCreationExpression(tuple) ' no exception
' Array creation
Dim arrayCreationSyntax = Parse("
Class C
Dim x = New (Integer, Integer)(1) { }
End Class")
arrayCreationSyntax.AssertTheseDiagnostics(<errors></errors>)
SyntaxFactory.ArrayCreationExpression(tuple, SyntaxFactory.CollectionInitializer()) ' no exception
' Nullable
Dim nullableSyntax = Parse("
Class C
Dim x As (Integer, Integer)?
End Class")
nullableSyntax.AssertTheseDiagnostics(<errors></errors>)
SyntaxFactory.NullableType(tuple) ' no exception
' Attribute (cannot parse)
Dim attributeSyntax = Parse("
<(Integer, Integer)>
")
attributeSyntax.AssertTheseDiagnostics(<errors><![CDATA[
BC30203: Identifier expected.
<(Integer, Integer)>
~
]]></errors>)
Assert.Throws(Of ArgumentException)(Sub() SyntaxFactory.Attribute(tuple))
' Inherits
Dim inheritsSyntax = Parse("
Class C
Inherits (Integer, Integer)
End Class
")
inheritsSyntax.AssertTheseDiagnostics(<errors></errors>)
SyntaxFactory.InheritsStatement(tuple)
' Implements
Dim implementsSyntax = Parse("
Class C
Implements (Integer, Integer)
End Class
")
implementsSyntax.AssertTheseDiagnostics(<errors></errors>)
SyntaxFactory.ImplementsStatement(tuple)
End Sub
' Verify spans within a list of consecutive nodes are all consistent.
Private Sub VerifyListSpans(Of T As VisualBasicSyntaxNode)(list As SyntaxList(Of T), expectedFullSpan As TextSpan)
If list.Count > 0 Then
' List should fill up the full span.
Assert.Equal(expectedFullSpan.Start, list(0).FullSpan.Start)
Assert.Equal(expectedFullSpan.End, list(list.Count - 1).FullSpan.End)
For i = 0 To list.Count - 1
' Make sure children's full spans are adjacent
If i > 0 Then
Assert.Equal(list(i - 1).FullSpan.End, list(i).FullSpan.Start)
End If
If i < list.Count - 1 Then
Assert.Equal(list(i).FullSpan.End, list(i + 1).FullSpan.Start)
End If
' Recursively verify
VerifyAllSpans(list(i))
Next
End If
End Sub
' Verify spans within a list of consecutive nodes are all consistent.
Private Sub VerifyListSpans(list As ChildSyntaxList, expectedFullSpan As TextSpan)
If list.Count > 0 Then
' List should fill up the full span.
Assert.Equal(expectedFullSpan.Start, list(0).FullSpan.Start)
Assert.Equal(expectedFullSpan.End, list(list.Count - 1).FullSpan.End)
For i = 0 To list.Count - 2
' Make sure children's full spans are adjacent
Assert.Equal(list(i).FullSpan.End, list(i + 1).FullSpan.Start)
' Recursively verify
Dim node = list(i)
If node.IsNode Then
VerifyAllSpans(node.AsNode)
End If
Next
End If
End Sub
' Verify spans within a list of consecutive nodes are all consistent.
Private Sub VerifyListSpans(list As SyntaxNodeOrTokenList, expectedFullSpan As TextSpan)
If list.Count > 0 Then
' List should fill up the full span.
Assert.Equal(expectedFullSpan.Start, list(0).FullSpan.Start)
Assert.Equal(expectedFullSpan.End, list(list.Count - 1).FullSpan.End)
For i = 0 To list.Count - 1
' Make sure children's full spans are adjacent
If i > 0 Then
Assert.Equal(list(i - 1).FullSpan.End, list(i).FullSpan.Start)
End If
If i < list.Count - 1 Then
Assert.Equal(list(i).FullSpan.End, list(i + 1).FullSpan.Start)
End If
' Recursively verify
If list(i).IsNode Then
VerifyAllSpans(list(i).AsNode)
End If
Next
End If
End Sub
' Verify spans within a list of consecutive nodes are all consistent.
Private Sub VerifyListSpans(list As SyntaxTokenList, expectedFullSpan As TextSpan)
If list.Count > 0 Then
' List should fill up the full span.
Assert.Equal(expectedFullSpan.Start, list(0).FullSpan.Start)
Assert.Equal(expectedFullSpan.End, list(list.Count - 1).FullSpan.End)
For i = 0 To list.Count - 1
' Make sure children's full spans are adjacent
If i > 0 Then
Assert.Equal(list(i - 1).FullSpan.End, list(i).FullSpan.Start)
End If
If i < list.Count - 1 Then
Assert.Equal(list(i).FullSpan.End, list(i + 1).FullSpan.Start)
End If
Next
End If
End Sub
' Verify spans within a list of consecutive nodes are all consistent.
Private Sub VerifyListSpans(list As SyntaxTriviaList, expectedFullSpan As TextSpan)
If list.Count > 0 Then
' List should fill up the full span.
Assert.Equal(expectedFullSpan.Start, list(0).FullSpan.Start)
Assert.Equal(expectedFullSpan.End, list(list.Count - 1).FullSpan.End)
For i = 0 To list.Count - 2
' Make sure children's full spans are adjacent
Assert.Equal(list(i).FullSpan.End, list(i + 1).FullSpan.Start)
Next
End If
End Sub
' Check that spans within a given tree are all consistent. Makes sure the children's spans all
' line up correctly.
Private Sub VerifyAllSpans(tree As SyntaxNode)
Assert.True(tree.FullSpan.Contains(tree.Span))
If tree.IsStructuredTrivia Then
' For trivia, the full span and regular span must be equal.
Assert.Equal(tree.Span, tree.FullSpan)
Else
' For tokens and non-terminals, validate the trivia spans.
Dim precedingTrivia = tree.GetLeadingTrivia(), followingTrivia = tree.GetTrailingTrivia()
If precedingTrivia.Count = 0 Then
Assert.Equal(tree.SpanStart, tree.FullSpan.Start)
Else
VerifyListSpans(precedingTrivia, New TextSpan(tree.FullSpan.Start, (tree.SpanStart - tree.FullSpan.Start)))
End If
If followingTrivia.Count = 0 Then
Assert.Equal(tree.Span.End, tree.FullSpan.End)
Else
VerifyListSpans(followingTrivia, New TextSpan(tree.Span.End, (tree.FullSpan.End - tree.Span.End)))
End If
End If
' Validate the children.
VerifyListSpans(tree.ChildNodesAndTokens(), tree.FullSpan)
End Sub
' Check that spans within a given tree are all consistent. Makes sure the children's spans all
' line up correctly.
Private Sub VerifyAllSpans(tree As SyntaxToken)
Assert.True(tree.FullSpan.Contains(tree.Span))
' For tokens and non-terminals, validate the trivia spans.
Dim precedingTrivia = tree.LeadingTrivia(), followingTrivia = tree.TrailingTrivia()
If precedingTrivia.Count = 0 Then
Assert.Equal(tree.SpanStart, tree.FullSpan.Start)
Else
VerifyListSpans(precedingTrivia, New TextSpan(tree.FullSpan.Start, (tree.SpanStart - tree.FullSpan.Start)))
End If
If followingTrivia.Count = 0 Then
Assert.Equal(tree.Span.End, tree.FullSpan.End)
Else
VerifyListSpans(followingTrivia, New TextSpan(tree.Span.End, (tree.FullSpan.End - tree.Span.End)))
End If
End Sub
<Fact>
Public Sub TestSpans()
Dim dig1 = CreateIntegerLiteral(3)
Assert.Equal(New TextSpan(0, 1), dig1.Span)
Assert.Equal(New TextSpan(0, 1), dig1.FullSpan)
Dim binop = SyntaxFactory.AddExpression(
CreateIntegerLiteral(4),
SyntaxFactory.Token(SyntaxKind.PlusToken, trailing:=_spaceTrivia),
CreateIntegerLiteral(8))
Assert.Equal(New TextSpan(0, 4), binop.Span)
Assert.Equal(New TextSpan(1, 1), binop.OperatorToken.Span)
Assert.Equal(New TextSpan(1, 2), binop.OperatorToken.FullSpan)
Assert.Equal(New TextSpan(3, 1), binop.Right.Span)
Assert.Equal(New TextSpan(3, 1), binop.Right.FullSpan)
Dim simpleTree = CreateSimpleTree()
Assert.Equal(New TextSpan(0, 17), simpleTree.Span)
Assert.Equal(New TextSpan(0, 18), simpleTree.FullSpan)
Assert.Equal(New TextSpan(3, 14), DirectCast(simpleTree, BinaryExpressionSyntax).Right.Span)
Dim argList = DirectCast(DirectCast(simpleTree, BinaryExpressionSyntax).Right, InvocationExpressionSyntax).ArgumentList
Assert.Equal(New TextSpan(6, 1), argList.Arguments(0).Span)
Assert.Equal(New TextSpan(7, 1), argList.Arguments.GetWithSeparators(1).Span)
Assert.Equal(New TextSpan(9, 4), argList.Arguments(1).Span)
Assert.Equal(New TextSpan(13, 1), argList.Arguments.GetWithSeparators(3).Span)
Assert.Equal(New TextSpan(15, 1), argList.Arguments(2).Span)
End Sub
<Fact>
Public Sub TestSpans2()
Dim stmt1 = SyntaxFactory.ReturnStatement(SyntaxFactory.Token(SyntaxKind.ReturnKeyword, trailing:=_spaceTrivia), CreateIntegerLiteral(5))
Dim stmt2 = SyntaxFactory.ReturnStatement(SyntaxFactory.Token(SyntaxKind.ReturnKeyword, trailing:=_spaceTrivia), CreateIntegerLiteral(178))
Dim listBldr = SyntaxNodeOrTokenListBuilder.Create()
listBldr.Add(stmt1)
listBldr.Add(SyntaxFactory.Token(SyntaxKind.StatementTerminatorToken))
listBldr.Add(stmt2)
listBldr.Add(SyntaxFactory.Token(SyntaxKind.StatementTerminatorToken))
Dim statements = listBldr.ToList
VerifyListSpans(statements, TextSpan.FromBounds(statements(0).FullSpan.Start, statements(statements.Count - 1).FullSpan.End))
Dim item1 = SyntaxFactory.HandlesClauseItem(SyntaxFactory.KeywordEventContainer(SyntaxFactory.Token(SyntaxKind.MeKeyword, trailing:=_spaceTrivia)), SyntaxFactory.Token(SyntaxKind.DotToken, trailing:=_spaceTrivia), SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "goo", _spaceTrivia)))
Dim item2 = SyntaxFactory.HandlesClauseItem(SyntaxFactory.KeywordEventContainer(SyntaxFactory.Token(SyntaxKind.MeKeyword, trailing:=_spaceTrivia)), SyntaxFactory.Token(SyntaxKind.DotToken, trailing:=_spaceTrivia), SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "banana", _spaceTrivia)))
listBldr.Clear()
listBldr.Add(item1)
listBldr.Add(SyntaxFactory.Token(SyntaxKind.CommaToken, trailing:=_spaceTrivia))
listBldr.Add(item2)
Dim handlesClause = SyntaxFactory.HandlesClause(SyntaxFactory.Token(SyntaxKind.HandlesKeyword, trailing:=_spaceTrivia), New SeparatedSyntaxList(Of HandlesClauseItemSyntax)(listBldr.ToList))
VerifyAllSpans(handlesClause)
Dim modifiedIdent1 = SyntaxFactory.ModifiedIdentifier(SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "goo", _spaceTrivia), Nothing, Nothing, SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.Token(SyntaxKind.OpenParenToken, trailing:=_spaceTrivia), Nothing, SyntaxFactory.Token(SyntaxKind.CloseParenToken, trailing:=_spaceTrivia))))
Dim modifiedIdent2 = SyntaxFactory.ModifiedIdentifier(SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "banana", _spaceTrivia), Nothing, Nothing, SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.Token(SyntaxKind.OpenParenToken, trailing:=_spaceTrivia), Nothing, SyntaxFactory.Token(SyntaxKind.CloseParenToken, trailing:=_spaceTrivia))))
listBldr.Clear()
listBldr.Add(modifiedIdent1)
listBldr.Add(SyntaxFactory.Token(SyntaxKind.CommaToken, trailing:=_spaceTrivia))
listBldr.Add(modifiedIdent2)
Dim declarator = SyntaxFactory.VariableDeclarator(New SeparatedSyntaxList(Of ModifiedIdentifierSyntax)(listBldr.ToList), Nothing, Nothing)
VerifyAllSpans(declarator)
End Sub
<Fact>
Public Sub TestSpans2_Invalid()
' Validate the exceptions being generated when Invalid arguments are used for a TextSpan Constructor
Assert.Throws(Of ArgumentOutOfRangeException)(Sub()
Dim x As New TextSpan(-1, 0)
End Sub)
Assert.Throws(Of ArgumentOutOfRangeException)(Sub()
Dim x As New TextSpan(0, -1)
End Sub)
Assert.Throws(Of ArgumentOutOfRangeException)(Sub()
Dim x As New TextSpan(-1, -1)
End Sub)
Assert.Throws(Of ArgumentOutOfRangeException)(Sub()
Dim x As New TextSpan(2, -4)
End Sub)
End Sub
' Test that a list with 0 items works correctly.
<Fact>
Public Sub TestEmptyList()
Dim l = New SyntaxTokenList
Assert.Equal(0, l.Count)
Dim attrBlock = SyntaxFactory.AttributeList(SyntaxFactory.Token(SyntaxKind.LessThanToken, trailing:=_spaceTrivia), Nothing, SyntaxFactory.Token(SyntaxKind.GreaterThanToken, trailing:=_spaceTrivia))
Dim param = SyntaxFactory.Parameter(SyntaxFactory.SingletonList(attrBlock),
l,
SyntaxFactory.ModifiedIdentifier(SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "goo", _spaceTrivia),
Nothing, Nothing, Nothing),
Nothing,
Nothing)
Assert.NotNull(param.Modifiers)
Assert.Equal(0, param.Modifiers.Count)
param = SyntaxFactory.Parameter(SyntaxFactory.SingletonList(attrBlock), Nothing, SyntaxFactory.ModifiedIdentifier(SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "goo", _spaceTrivia), Nothing, Nothing, Nothing), Nothing, Nothing)
Assert.NotNull(param.Modifiers)
Assert.Equal(0, param.Modifiers.Count)
End Sub
' Test that list with 1 item works correctly.
<Fact>
Public Sub TestSingletonList()
Dim l = New SyntaxTokenList(SyntaxFactory.Token(SyntaxKind.ByValKeyword, trailing:=_spaceTrivia))
Assert.NotNull(l)
Assert.Equal(1, l.Count)
Assert.Equal("ByVal", l(0).ToString())
Assert.Equal(0, l(0).SpanStart)
Assert.Equal(5, l(0).Span.End)
VerifyListSpans(l, New TextSpan(0, 6))
Dim attrBlock = SyntaxFactory.AttributeList(SyntaxFactory.Token(SyntaxKind.LessThanToken, trailing:=_spaceTrivia), Nothing, SyntaxFactory.Token(SyntaxKind.GreaterThanToken, trailing:=_spaceTrivia))
Dim param = SyntaxFactory.Parameter(SyntaxFactory.SingletonList(attrBlock), l, SyntaxFactory.ModifiedIdentifier(SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "goo", _spaceTrivia), Nothing, Nothing, Nothing), Nothing, Nothing)
Assert.NotNull(param.Modifiers)
Assert.Equal(1, param.Modifiers.Count)
Assert.Equal("ByVal", l(0).ToString())
Assert.Equal(4, param.Modifiers(0).SpanStart)
Assert.Equal(9, param.Modifiers(0).Span.End)
VerifyAllSpans(param)
param = SyntaxFactory.Parameter(Nothing, SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ByValKeyword, trailing:=_spaceTrivia)), SyntaxFactory.ModifiedIdentifier(SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "goo", _spaceTrivia), Nothing, Nothing, Nothing), Nothing, Nothing)
Assert.NotNull(param.Modifiers)
Assert.Equal(1, param.Modifiers.Count)
Assert.Equal("ByVal", l(0).ToString())
Assert.Equal(0, param.Modifiers(0).SpanStart)
Assert.Equal(5, param.Modifiers(0).Span.End)
VerifyAllSpans(param)
End Sub
' Test list with 3 items.
<Fact>
Public Sub TestList()
Dim bldr = New SyntaxTokenListBuilder(8)
bldr.Add(SyntaxFactory.Token(SyntaxKind.ByValKeyword, trailing:=_spaceTrivia))
bldr.Add(SyntaxFactory.Token(SyntaxKind.OptionalKeyword, trailing:=_spaceTrivia))
bldr.Add(SyntaxFactory.Token(SyntaxKind.ByRefKeyword, trailing:=_spaceTrivia))
Dim l = bldr.ToList
Assert.NotNull(l)
Assert.Equal(3, l.Count)
Assert.Equal("ByVal", l(0).ToString())
Assert.Equal("Optional", l(1).ToString())
Assert.Equal("ByRef", l(2).ToString())
Assert.Equal(0, l(0).SpanStart)
Assert.Equal(5, l(0).Span.End)
Assert.Equal(6, l(1).SpanStart)
Assert.Equal(14, l(1).Span.End)
Assert.Equal(15, l(2).SpanStart)
Assert.Equal(20, l(2).Span.End)
VerifyListSpans(l, New TextSpan(0, 21))
Dim attrBlock = SyntaxFactory.AttributeList(SyntaxFactory.Token(SyntaxKind.LessThanToken, trailing:=_spaceTrivia), Nothing, SyntaxFactory.Token(SyntaxKind.GreaterThanToken, trailing:=_spaceTrivia))
Dim param = SyntaxFactory.Parameter(SyntaxFactory.SingletonList(attrBlock), l, SyntaxFactory.ModifiedIdentifier(SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "goo", _spaceTrivia), Nothing, Nothing, Nothing), Nothing, Nothing)
Assert.NotNull(param.Modifiers)
Assert.Equal(3, param.Modifiers.Count)
Assert.Equal("ByVal", param.Modifiers(0).ToString())
Assert.Equal("Optional", param.Modifiers(1).ToString())
Assert.Equal("ByRef", param.Modifiers(2).ToString())
Assert.Equal(4, param.Modifiers(0).SpanStart)
Assert.Equal(9, param.Modifiers(0).Span.End)
Assert.Equal(10, param.Modifiers(1).SpanStart)
Assert.Equal(18, param.Modifiers(1).Span.End)
Assert.Equal(19, param.Modifiers(2).SpanStart)
Assert.Equal(24, param.Modifiers(2).Span.End)
VerifyAllSpans(param)
param = SyntaxFactory.Parameter(SyntaxFactory.SingletonList(attrBlock), SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ByValKeyword, trailing:=_spaceTrivia), SyntaxFactory.Token(SyntaxKind.OptionalKeyword, trailing:=_spaceTrivia), SyntaxFactory.Token(SyntaxKind.ByRefKeyword, trailing:=_spaceTrivia)), SyntaxFactory.ModifiedIdentifier(SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "goo", _spaceTrivia), Nothing, Nothing, Nothing), Nothing, Nothing)
Assert.NotNull(param.Modifiers)
Assert.Equal(3, param.Modifiers.Count)
Assert.Equal("ByVal", param.Modifiers(0).ToString())
Assert.Equal("Optional", param.Modifiers(1).ToString())
Assert.Equal("ByRef", param.Modifiers(2).ToString())
Assert.Equal(4, param.Modifiers(0).SpanStart)
Assert.Equal(9, param.Modifiers(0).Span.End)
Assert.Equal(10, param.Modifiers(1).SpanStart)
Assert.Equal(18, param.Modifiers(1).Span.End)
Assert.Equal(19, param.Modifiers(2).SpanStart)
Assert.Equal(24, param.Modifiers(2).Span.End)
VerifyAllSpans(param)
param = SyntaxFactory.Parameter(Nothing, SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ByValKeyword, trailing:=_spaceTrivia), SyntaxFactory.Token(SyntaxKind.OptionalKeyword, trailing:=_spaceTrivia), SyntaxFactory.Token(SyntaxKind.ByRefKeyword, trailing:=_spaceTrivia)), SyntaxFactory.ModifiedIdentifier(SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "goo", _spaceTrivia), Nothing, Nothing, Nothing), Nothing, Nothing)
VerifyAllSpans(param)
End Sub
' Helper to create a type name from a simple string.
Private Function CreateSimpleTypeName(id As String) As TypeSyntax
Return SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, id, SyntaxFactory.WhitespaceTrivia(" ")))
End Function
'helper to check an empty separated list
Private Sub CheckEmptySeparatedList(seplist As SeparatedSyntaxList(Of TypeSyntax))
Assert.Equal(0, seplist.Count)
Assert.Equal(0, seplist.SeparatorCount)
End Sub
' Check that empty separated list works.
<Fact>
Public Sub TestEmptySeparatedList()
CheckEmptySeparatedList(New SeparatedSyntaxList(Of TypeSyntax)(DirectCast(Nothing, VisualBasicSyntaxNode), 0))
Dim statement = SyntaxFactory.InheritsStatement(SyntaxFactory.Token(SyntaxKind.InheritsKeyword, trailing:=_spaceTrivia), (New SeparatedSyntaxListBuilder(Of TypeSyntax)).ToList)
CheckEmptySeparatedList(statement.Types)
Dim arglist = SyntaxFactory.ArgumentList(SyntaxFactory.Token(SyntaxKind.OpenParenToken, trailing:=_spaceTrivia), Nothing, SyntaxFactory.Token(SyntaxKind.CloseParenToken, trailing:=_spaceTrivia))
Assert.NotNull(arglist.Arguments)
Assert.Equal(0, arglist.Arguments.Count)
Assert.Equal(0, arglist.Arguments.SeparatorCount)
Assert.Equal("( )", arglist.ToString)
Assert.Equal("( ) ", arglist.ToFullString)
End Sub
'helper to check an singleton separated list of one type name "goo"
Private Sub CheckSingletonSeparatedList(seplist As SeparatedSyntaxList(Of TypeSyntax), start As Integer)
Assert.NotNull(seplist)
Assert.Equal(1, seplist.Count)
Assert.Equal("goo", seplist(0).ToString)
Assert.Equal("goo ", seplist(0).ToFullString)
Assert.Equal(start, seplist(0).SpanStart)
Assert.Equal(start, seplist(0).FullSpan.Start)
Assert.Equal(start + 3, seplist(0).Span.End)
Assert.Equal(start + 4, seplist(0).FullSpan.End)
Assert.Equal(0, seplist.SeparatorCount)
End Sub
' Check that singleton separated list works
<Fact>
Public Sub TestSingletonSeparatedList()
CheckSingletonSeparatedList(New SeparatedSyntaxList(Of TypeSyntax)(New SyntaxNodeOrTokenList(CreateSimpleTypeName("goo"), 0)), 0)
Dim bldr = SeparatedSyntaxListBuilder(Of TypeSyntax).Create()
bldr.Add(CreateSimpleTypeName("goo"))
Dim statement = SyntaxFactory.InheritsStatement(SyntaxFactory.Token(SyntaxKind.InheritsKeyword, trailing:=_spaceTrivia), bldr.ToList)
CheckSingletonSeparatedList(statement.Types, 9)
Assert.Equal("Inherits goo", statement.ToString)
Assert.Equal("Inherits goo ", statement.ToFullString)
End Sub
' Check that separated list with separators in it works.
<Fact>
Public Sub TestSeparatedList()
Dim bldr = SeparatedSyntaxListBuilder(Of TypeSyntax).Create()
bldr.Add(CreateSimpleTypeName("aaa"))
bldr.AddSeparator(SyntaxFactory.Token(SyntaxKind.CommaToken, trailing:=_spaceTrivia))
bldr.Add(CreateSimpleTypeName("bbb"))
bldr.AddSeparator(SyntaxFactory.Token(SyntaxKind.SemicolonToken, trailing:=_spaceTrivia))
bldr.Add(CreateSimpleTypeName("cc"))
Dim sepList = bldr.ToList
Assert.Equal(3, sepList.Count)
Assert.Equal(2, sepList.SeparatorCount)
Assert.Null(sepList(1).Parent)
Assert.Null(sepList.GetWithSeparators(3).Parent)
Assert.Equal("aaa", sepList(0).ToString)
Assert.Equal("bbb", sepList(1).ToString)
Assert.Equal("cc", sepList(2).ToString)
Assert.Equal(",", sepList.GetWithSeparators(1).ToString)
Assert.Equal(";", sepList.GetWithSeparators(3).ToString)
Assert.Equal(0, sepList(0).SpanStart)
Assert.Equal(4, sepList.GetWithSeparators(1).SpanStart)
Assert.Equal(6, sepList(1).SpanStart)
Assert.Equal(10, sepList.GetWithSeparators(3).SpanStart)
Assert.Equal(12, sepList(2).SpanStart)
Dim statement = SyntaxFactory.InheritsStatement(SyntaxFactory.Token(SyntaxKind.InheritsKeyword, trailing:=_spaceTrivia), sepList)
Assert.Equal("Inherits aaa , bbb ; cc", statement.ToString)
Assert.Equal("Inherits aaa , bbb ; cc ", statement.ToFullString)
VerifyAllSpans(statement)
sepList = statement.Types
Assert.Equal(statement, sepList(1).Parent)
Assert.Equal(statement, sepList.GetWithSeparators(3).Parent)
Assert.Equal(3, sepList.Count)
Assert.Equal(2, sepList.SeparatorCount)
Assert.Equal("aaa", sepList(0).ToString)
Assert.Equal("bbb", sepList(1).ToString)
Assert.Equal("cc", sepList(2).ToString)
Assert.Equal(",", sepList.GetWithSeparators(1).ToString)
Assert.Equal(";", sepList.GetWithSeparators(3).ToString)
Assert.Equal(9 + 0, sepList(0).SpanStart)
Assert.Equal(9 + 4, sepList.GetWithSeparators(1).SpanStart)
Assert.Equal(9 + 6, sepList(1).SpanStart)
Assert.Equal(9 + 10, sepList.GetWithSeparators(3).SpanStart)
Assert.Equal(9 + 12, sepList(2).SpanStart)
End Sub
' Check that trivia seems to work.
' Note that whitespace constructor allows any text, so we leverage that in this test for simplicity.
<Fact>
Public Sub TestTrivia()
Dim white_a = SyntaxFactory.WhitespaceTrivia("AAA")
Dim white_b = SyntaxFactory.WhitespaceTrivia("B")
Dim white_c = SyntaxFactory.WhitespaceTrivia("CCCC")
Dim white_d = SyntaxFactory.WhitespaceTrivia("DD")
Dim tok = SyntaxFactory.Token(SyntaxKind.PlusToken)
Dim precTrivia = tok.LeadingTrivia()
Dim follTrivia = tok.TrailingTrivia()
Assert.NotNull(precTrivia)
Assert.Equal(1, precTrivia.Count)
Assert.NotNull(follTrivia)
Assert.Equal(1, follTrivia.Count)
Assert.Equal(0, tok.FullSpan.Start)
Assert.Equal(0, tok.SpanStart)
Assert.Equal(1, tok.FullSpan.End)
Assert.Equal(1, tok.Span.End)
VerifyAllSpans(tok)
Dim bldr = SyntaxTriviaListBuilder.Create()
bldr.Add(white_a)
bldr.Add(white_b)
tok = SyntaxFactory.Token(Nothing, SyntaxKind.PlusToken, trailing:=bldr.ToList)
precTrivia = tok.LeadingTrivia()
follTrivia = tok.TrailingTrivia()
Assert.NotNull(precTrivia)
Assert.Equal(0, precTrivia.Count)
Assert.NotNull(follTrivia)
Assert.Equal(2, follTrivia.Count)
Assert.Equal(0, tok.FullSpan.Start)
Assert.Equal(0, tok.SpanStart)
Assert.Equal(5, tok.FullSpan.End)
Assert.Equal(1, tok.Span.End)
Assert.Equal("+AAAB", tok.ToFullString())
Assert.Equal("AAA", follTrivia(0).ToString())
Assert.Equal("AAA", follTrivia(0).ToFullString)
Assert.Equal(1, follTrivia(0).SpanStart)
Assert.Equal(1, follTrivia(0).FullSpan.Start)
Assert.Equal(4, follTrivia(0).Span.End)
Assert.Equal(4, follTrivia(0).FullSpan.End)
Assert.Equal("B", follTrivia(1).ToString())
Assert.Equal("B", follTrivia(1).ToFullString)
Assert.Equal(4, follTrivia(1).SpanStart)
Assert.Equal(4, follTrivia(1).FullSpan.Start)
Assert.Equal(5, follTrivia(1).Span.End)
Assert.Equal(5, follTrivia(1).FullSpan.End)
VerifyAllSpans(tok)
bldr.Clear()
bldr.Add(white_c)
bldr.Add(white_d)
bldr.Add(white_a)
Dim leading = bldr.ToList
tok = SyntaxFactory.Token(bldr.ToList, SyntaxKind.PlusToken, trailing:=SyntaxTriviaList.Create(white_b))
precTrivia = tok.LeadingTrivia()
follTrivia = tok.TrailingTrivia()
Assert.Equal(0, tok.FullSpan.Start)
Assert.Equal(11, tok.FullSpan.End)
Assert.Equal(9, tok.SpanStart)
Assert.Equal(10, tok.Span.End)
Assert.Equal("CCCCDDAAA+B", tok.ToFullString())
VerifyAllSpans(tok)
Assert.NotNull(precTrivia)
Assert.Equal(3, precTrivia.Count)
Assert.Equal("CCCC", precTrivia(0).ToString())
Assert.Equal("CCCC", precTrivia(0).ToFullString)
Assert.Equal(0, precTrivia(0).SpanStart)
Assert.Equal(0, precTrivia(0).FullSpan.Start)
Assert.Equal(4, precTrivia(0).Span.End)
Assert.Equal(4, precTrivia(0).FullSpan.End)
Assert.Equal("DD", precTrivia(1).ToString())
Assert.Equal("DD", precTrivia(1).ToFullString)
Assert.Equal(4, precTrivia(1).SpanStart)
Assert.Equal(4, precTrivia(1).FullSpan.Start)
Assert.Equal(6, precTrivia(1).Span.End)
Assert.Equal(6, precTrivia(1).FullSpan.End)
Assert.Equal("AAA", precTrivia(2).ToString())
Assert.Equal("AAA", precTrivia(2).ToFullString)
Assert.Equal(6, precTrivia(2).SpanStart)
Assert.Equal(6, precTrivia(2).FullSpan.Start)
Assert.Equal(9, precTrivia(2).Span.End)
Assert.Equal(9, precTrivia(2).FullSpan.End)
Assert.NotNull(follTrivia)
Assert.Equal(1, follTrivia.Count)
Assert.Equal("B", follTrivia(0).ToString())
Assert.Equal("B", follTrivia(0).ToFullString)
Assert.Equal(10, follTrivia(0).SpanStart)
Assert.Equal(10, follTrivia(0).FullSpan.Start)
Assert.Equal(11, follTrivia(0).Span.End)
Assert.Equal(11, follTrivia(0).FullSpan.End)
End Sub
<Fact>
Public Sub TestKeywordFactoryMethods()
' Check simple factory for keyword.
Dim keyword = SyntaxFactory.Token(SyntaxKind.AliasKeyword, trailing:=_spaceTrivia)
Assert.Equal("Alias", keyword.ToString())
Assert.Equal(5, keyword.Span.Length)
Assert.Equal(6, keyword.FullSpan.Length)
Assert.Equal(1, keyword.LeadingTrivia().Count)
Assert.Equal(1, keyword.TrailingTrivia().Count)
Assert.Equal(" ", keyword.TrailingTrivia()(0).ToString)
' Check full factory for keyword
Dim bldr = SyntaxTriviaListBuilder.Create()
bldr.Add(SyntaxFactory.WhitespaceTrivia(" "))
bldr.Add(SyntaxFactory.CommentTrivia("'goo"))
keyword = SyntaxFactory.Token(bldr.ToList, SyntaxKind.AliasKeyword, Nothing, "ALIAs")
Assert.Equal("ALIAs", keyword.ToString())
Assert.Equal(5, keyword.Span.Length)
Assert.Equal(12, keyword.FullSpan.Length)
Assert.Equal(2, keyword.LeadingTrivia().Count)
Assert.Equal(" ", keyword.LeadingTrivia()(0).ToString)
Assert.Equal(0, keyword.TrailingTrivia().Count)
' Check factory methods giving the node kind
keyword = SyntaxFactory.Token(Nothing, SyntaxKind.AndAlsoKeyword, _spaceTrivia, "ANDALSO")
Assert.Equal("ANDALSO", keyword.ToString())
Assert.Equal(7, keyword.Span.Length)
Assert.Equal(8, keyword.FullSpan.Length)
Assert.Equal(0, keyword.LeadingTrivia().Count)
Assert.Equal(1, keyword.TrailingTrivia().Count)
Assert.Equal(" ", keyword.TrailingTrivia()(0).ToString)
bldr.Clear()
bldr.Add(SyntaxFactory.WhitespaceTrivia(" "))
bldr.Add(SyntaxFactory.CommentTrivia("'goo"))
keyword = SyntaxFactory.Token(bldr.ToList, SyntaxKind.AndAlsoKeyword, SyntaxTriviaList.Create(SyntaxFactory.WhitespaceTrivia(" ")), "andalso")
Assert.Equal("andalso", keyword.ToString())
Assert.Equal(7, keyword.Span.Length)
Assert.Equal(16, keyword.FullSpan.Length)
Assert.Equal(2, keyword.LeadingTrivia().Count)
Assert.Equal(1, keyword.TrailingTrivia().Count)
Assert.Equal(" ", keyword.TrailingTrivia()(0).ToString)
Assert.Equal("'goo", keyword.LeadingTrivia()(1).ToString)
End Sub
<Fact>
Public Sub TestNonTerminalFactoryMethods()
Dim endTry As EndBlockStatementSyntax
endTry = SyntaxFactory.EndTryStatement(SyntaxFactory.Token(SyntaxKind.EndKeyword, trailing:=_spaceTrivia), SyntaxFactory.Token(SyntaxKind.TryKeyword, trailing:=_spaceTrivia))
Assert.Equal(7, endTry.Span.Length)
Assert.Equal(8, endTry.FullSpan.Length)
Assert.Equal(SyntaxKind.EndKeyword, endTry.EndKeyword.Kind)
Assert.Equal("End", endTry.EndKeyword.ToString())
Assert.Equal(SyntaxKind.TryKeyword, endTry.BlockKeyword.Kind)
Assert.Equal("Try", endTry.BlockKeyword.ToString())
Assert.Equal(1, endTry.GetTrailingTrivia().Count)
Assert.Equal(" ", endTry.GetTrailingTrivia()(0).ToString)
End Sub
' Check that IsToken, IsTrivia, IsTerminal properties returns correct thing.
<Fact>
Public Sub TestTokenTriviaClassification()
Dim endIfStmt = SyntaxFactory.EndIfStatement(SyntaxFactory.Token(SyntaxKind.EndKeyword, trailing:=_spaceTrivia), SyntaxFactory.Token(SyntaxKind.IfKeyword, trailing:=_spaceTrivia))
Dim plusToken = SyntaxFactory.Token(SyntaxKind.PlusToken, trailing:=_spaceTrivia)
Dim comment = SyntaxFactory.CommentTrivia("'hello")
Assert.True(plusToken.Node.IsToken)
Assert.False(comment.UnderlyingNode.IsToken)
Assert.False(endIfStmt.IsStructuredTrivia)
Assert.Equal(SyntaxKind.CommentTrivia, comment.Kind)
End Sub
' Check that ToString, ToFullString, and ValueText are correct on a token.
<Fact>
Public Sub TestTokenText()
' keyword without trivia
Dim keyword = SyntaxFactory.Token(SyntaxKind.PartialKeyword, "ParTIAL")
Assert.Equal("ParTIAL", keyword.ToString())
Assert.Equal("ParTIAL", keyword.ToFullString())
Assert.Equal("ParTIAL", keyword.ValueText())
' identifier with trivia
Dim identifier = SyntaxFactory.Identifier(SyntaxFactory.WhitespaceTrivia(" "), "[goo]", True, "goo", TypeCharacter.None,
SyntaxFactory.CommentTrivia("'hi"))
Assert.Equal("[goo]", identifier.ToString())
Assert.Equal(" [goo]'hi", identifier.ToFullString())
Assert.Equal("goo", identifier.ValueText)
End Sub
' Create a sample method statement.
Private Function CreateMethodStatement() As MethodStatementSyntax
Dim bldr = SyntaxNodeOrTokenListBuilder.Create()
bldr.Add(SyntaxFactory.Parameter(Nothing, SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ByValKeyword, trailing:=_spaceTrivia)),
SyntaxFactory.ModifiedIdentifier(SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "Param1", False, "Param1", TypeCharacter.None, _spaceTrivia), Nothing, Nothing, Nothing),
SyntaxFactory.SimpleAsClause(SyntaxFactory.Token(SyntaxKind.AsKeyword, trailing:=_spaceTrivia), Nothing, SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntegerKeyword, trailing:=_spaceTrivia))), Nothing))
bldr.Add(SyntaxFactory.Token(SyntaxKind.CommaToken, trailing:=_spaceTrivia))
bldr.Add(SyntaxFactory.Parameter(Nothing, SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ByValKeyword, trailing:=_spaceTrivia)),
SyntaxFactory.ModifiedIdentifier(SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "Param2", False, "Param2", TypeCharacter.None, _spaceTrivia), Nothing, Nothing, Nothing),
SyntaxFactory.SimpleAsClause(SyntaxFactory.Token(SyntaxKind.AsKeyword, trailing:=_spaceTrivia), Nothing, SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword, trailing:=_spaceTrivia))), Nothing))
bldr.Add(SyntaxFactory.Token(SyntaxKind.CommaToken, trailing:=_spaceTrivia))
bldr.Add(SyntaxFactory.Parameter(Nothing, SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ByRefKeyword, trailing:=_spaceTrivia)),
SyntaxFactory.ModifiedIdentifier(SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "Param3", False, "Param3", TypeCharacter.None, _spaceTrivia), Nothing, Nothing, Nothing),
SyntaxFactory.SimpleAsClause(SyntaxFactory.Token(SyntaxKind.AsKeyword, trailing:=_spaceTrivia), Nothing, SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DoubleKeyword, trailing:=_spaceTrivia))), Nothing))
Return SyntaxFactory.SubStatement(Nothing,
SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxFactory.WhitespaceTrivia(" "), SyntaxKind.PublicKeyword, SyntaxFactory.WhitespaceTrivia(" "), "public"),
SyntaxFactory.Token(SyntaxKind.OverloadsKeyword, trailing:=_spaceTrivia)),
SyntaxFactory.Token(SyntaxFactory.WhitespaceTrivia(" "), SyntaxKind.SubKeyword, SyntaxFactory.WhitespaceTrivia(" "), "SUB"),
SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "MySub", False, "MySub", TypeCharacter.None, _spaceTrivia),
Nothing,
SyntaxFactory.ParameterList(SyntaxFactory.Token(SyntaxKind.OpenParenToken, trailing:=_spaceTrivia),
New SeparatedSyntaxList(Of ParameterSyntax)(bldr.ToList()),
SyntaxFactory.Token(SyntaxKind.CloseParenToken, trailing:=_spaceTrivia)),
Nothing, Nothing, Nothing)
End Function
<Fact>
Public Sub TestSpansOnMethodStatement()
VerifyAllSpans(CreateMethodStatement())
End Sub
' Check that the ToString and ToFullString are correct on a non-terminal that includes
' a list and a separated list.
<Fact>
Public Sub TestNonTerminalText()
Dim methodStatement = CreateMethodStatement()
Assert.Equal("public Overloads SUB MySub ( ByVal Param1 As Integer , ByVal Param2 As String , ByRef Param3 As Double )",
methodStatement.ToString())
Assert.Equal(" public Overloads SUB MySub ( ByVal Param1 As Integer , ByVal Param2 As String , ByRef Param3 As Double ) ",
methodStatement.ToFullString)
End Sub
' Check that IsMissing seems to do the right thing.
<Fact>
Public Sub IsMissing()
Dim ident = SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "hello", _spaceTrivia)
Assert.False(ident.IsMissing)
ident = SyntaxFactory.MissingIdentifier()
Assert.True(ident.IsMissing)
Dim punc = SyntaxFactory.Token(SyntaxKind.PlusToken, trailing:=_spaceTrivia)
Assert.False(punc.IsMissing)
punc = SyntaxFactory.MissingPunctuation(SyntaxKind.PlusToken)
Assert.True(punc.IsMissing)
Dim kw = SyntaxFactory.Token(SyntaxKind.EndKeyword, trailing:=_spaceTrivia)
Assert.False(kw.IsMissing)
kw = SyntaxFactory.MissingKeyword(SyntaxKind.EndKeyword)
Assert.True(kw.IsMissing)
Dim eof = SyntaxFactory.Token(SyntaxKind.EndOfFileToken)
Assert.False(eof.IsMissing) ' end of text token is never missing, even though it is zero length.
Assert.Equal(0, eof.Span.Length)
Dim endIfStmt = SyntaxFactory.EndIfStatement(SyntaxFactory.MissingKeyword(SyntaxKind.EndKeyword), SyntaxFactory.MissingKeyword(SyntaxKind.IfKeyword))
Assert.True(endIfStmt.IsMissing)
Assert.Equal(0, endIfStmt.Span.Length)
VerifyAllSpans(endIfStmt)
End Sub
Private Function CompareDiagnostics(err1 As Diagnostic, err2 As Diagnostic) As Integer
Dim span1 = err1.Location.SourceSpan
Dim span2 = err2.Location.SourceSpan
Dim i = span1.Start.CompareTo(span2.Start)
If i = 0 Then
Return err1.Code.CompareTo(err2.Code)
End If
Return i
End Function
' Check that a given list of errors on a node matches the given set.
Private Sub CheckErrorList(node As VisualBasicSyntaxNode, expectedErrorCodes As Integer(), expectedSpans As TextSpan())
Dim errorList As New List(Of Diagnostic)
errorList.AddRange(node.GetSyntaxErrorsNoTree())
errorList.Sort(AddressOf CompareDiagnostics)
For i = 0 To errorList.Count - 1
Assert.True(expectedSpans(i) =
errorList(i).Location.SourceSpan, "Error " & i & " have different spans")
Assert.True(expectedErrorCodes(i) = errorList(i).Code, "Error " & i & " have different codes")
Next
Assert.Equal(expectedErrorCodes.Length, errorList.Count)
' Has errors property should match expected errors.
If expectedErrorCodes.Length > 0 Then
Assert.True(node.ContainsDiagnostics)
Else
Assert.False(node.ContainsDiagnostics)
End If
End Sub
' Check that a given list of errors on a node matches the given set.
Private Sub CheckErrorList(node As SyntaxToken, expectedErrorCodes As Integer(), expectedSpans As TextSpan())
Dim errorList As New List(Of Diagnostic)
errorList.AddRange(node.GetSyntaxErrorsNoTree())
errorList.Sort(AddressOf CompareDiagnostics)
For i = 0 To errorList.Count - 1
Assert.True(expectedSpans(i) =
errorList(i).Location.SourceSpan, "Error " & i & " have different spans")
Assert.True(expectedErrorCodes(i) = errorList(i).Code, "Error " & i & " have different codes")
Next
Assert.Equal(expectedErrorCodes.Length, errorList.Count)
' Has errors property should match expected errors.
If expectedErrorCodes.Length > 0 Then
Assert.True(node.Node.ContainsDiagnostics)
Else
Assert.False(node.Node.ContainsDiagnostics)
End If
End Sub
' Test simple errors on a token and its associated trivia.
<Fact>
Public Sub SimpleTokenErrors()
Dim kwModule = SyntaxFactory.Token(SyntaxKind.ModuleKeyword, trailing:=_spaceTrivia)
CheckErrorList(kwModule, {}, {})
Assert.Equal(6, kwModule.Span.Length)
Assert.Equal(7, kwModule.FullSpan.Length)
' Add an error.
kwModule = New SyntaxToken(Nothing, CType(kwModule.Node.AddError(CreateDiagnosticInfo(17)), InternalSyntax.KeywordSyntax), 0, 0)
CheckErrorList(kwModule, {17}, {New TextSpan(0, 6)})
Assert.Equal(6, kwModule.Span.Length)
Assert.Equal(7, kwModule.FullSpan.Length)
' Add another error.
kwModule = New SyntaxToken(Nothing, CType(kwModule.Node.AddError(CreateDiagnosticInfo(42)), InternalSyntax.KeywordSyntax), 0, 0)
CheckErrorList(kwModule, {17, 42}, {New TextSpan(0, 6), New TextSpan(0, 6)})
' Add another token and put together. Make sure the spans work.
Dim trailing = New SyntaxTrivia(Nothing, CType(SyntaxFactory.WhitespaceTrivia(" ").UnderlyingNode.AddError(CreateDiagnosticInfo(101)), InternalSyntax.SyntaxTrivia), 0, 0)
Dim kwEnd = SyntaxFactory.Token(Nothing, SyntaxKind.EndKeyword, trailing, "End")
Dim endModule = SyntaxFactory.EndModuleStatement(kwEnd, kwModule)
CheckErrorList(endModule, {101, 17, 42}, {New TextSpan(3, 3), New TextSpan(6, 6), New TextSpan(6, 6)})
' add error to the whole statement
endModule = CType(endModule.AddError(CreateDiagnosticInfo(1)), EndBlockStatementSyntax)
Assert.Equal("End Module ", endModule.ToFullString)
CheckErrorList(endModule, {1, 101, 17, 42}, {New TextSpan(0, 12), New TextSpan(3, 3), New TextSpan(6, 6), New TextSpan(6, 6)})
End Sub
' Test a complex case with a few errors in it.
<Fact>
Public Sub ComplexErrors()
Dim bldr = SyntaxNodeOrTokenListBuilder.Create()
bldr.Add(SyntaxFactory.Parameter(Nothing, SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ByValKeyword, trailing:=_spaceTrivia)),
SyntaxFactory.ModifiedIdentifier(SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "Param1", False, "Param1", TypeCharacter.None, _spaceTrivia), Nothing, Nothing, Nothing),
SyntaxFactory.SimpleAsClause(SyntaxFactory.Token(SyntaxKind.AsKeyword, trailing:=_spaceTrivia), Nothing, SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntegerKeyword, trailing:=_spaceTrivia))), Nothing))
bldr.Add(SyntaxFactory.Token(SyntaxKind.CommaToken, trailing:=_spaceTrivia))
bldr.Add(SyntaxFactory.Parameter(Nothing, SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ByValKeyword, trailing:=_spaceTrivia)),
SyntaxFactory.ModifiedIdentifier(SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "Param2", False, "Param2", TypeCharacter.None, _spaceTrivia), Nothing, Nothing, Nothing),
SyntaxFactory.SimpleAsClause(SyntaxFactory.Token(SyntaxKind.AsKeyword, trailing:=_spaceTrivia), Nothing, SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword, trailing:=_spaceTrivia))), Nothing).AddError(CreateDiagnosticInfo(101)))
bldr.Add(DirectCast(SyntaxFactory.Token(SyntaxKind.CommaToken, trailing:=_spaceTrivia).Node.AddError(CreateDiagnosticInfo(33)), InternalSyntax.VisualBasicSyntaxNode))
bldr.Add(SyntaxFactory.Parameter(Nothing, SyntaxFactory.TokenList(New SyntaxToken(Nothing, CType(SyntaxFactory.Token(SyntaxKind.ByRefKeyword, trailing:=_spaceTrivia).Node.AddError(CreateDiagnosticInfo(44)), InternalSyntax.KeywordSyntax), 0, 0)),
SyntaxFactory.ModifiedIdentifier(SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "Param3", False, "Param3", TypeCharacter.None, _spaceTrivia), Nothing, Nothing, Nothing),
SyntaxFactory.SimpleAsClause(SyntaxFactory.Token(SyntaxKind.AsKeyword, trailing:=_spaceTrivia), Nothing, SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DoubleKeyword, trailing:=_spaceTrivia))), Nothing))
Dim methodDecl As MethodStatementSyntax =
SyntaxFactory.SubStatement(Nothing,
SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxFactory.WhitespaceTrivia(" "), SyntaxKind.PublicKeyword, SyntaxFactory.WhitespaceTrivia(" "), "public"),
SyntaxFactory.Token(SyntaxKind.OverloadsKeyword, trailing:=_spaceTrivia)),
SyntaxFactory.Token(New SyntaxTrivia(Nothing, CType(SyntaxFactory.WhitespaceTrivia(" ").UnderlyingNode.AddError(CreateDiagnosticInfo(22)).AddError(CreateDiagnosticInfo(23)), InternalSyntax.SyntaxTrivia), 0, 0), SyntaxKind.SubKeyword, SyntaxFactory.WhitespaceTrivia(" "), "SUB"),
SyntaxFactory.Identifier(SyntaxFactory.ElasticMarker, "MySub", False, "MySyb", TypeCharacter.None, _spaceTrivia),
Nothing,
SyntaxFactory.ParameterList(SyntaxFactory.Token(SyntaxKind.OpenParenToken, trailing:=_spaceTrivia),
New SeparatedSyntaxList(Of ParameterSyntax)(bldr.ToList),
SyntaxFactory.Token(SyntaxKind.CloseParenToken, trailing:=_spaceTrivia)),
Nothing, Nothing, Nothing)
Assert.Equal(" public Overloads SUB MySub ( ByVal Param1 As Integer , ByVal Param2 As String , ByRef Param3 As Double ) ",
methodDecl.ToFullString)
CheckErrorList(methodDecl, {22, 23, 101, 33, 44},
{New TextSpan(26, 5), New TextSpan(26, 5), New TextSpan(71, 22), New TextSpan(94, 1), New TextSpan(96, 5)})
End Sub
Private Shared ReadOnly s_messageProvider As New MockMessageProvider()
Private Function CreateDiagnosticInfo(code As Integer) As DiagnosticInfo
Return New DiagnosticInfo(s_messageProvider, code)
End Function
' A mock message provider
Private Class MockMessageProvider
Inherits TestMessageProvider
Public Overrides ReadOnly Property CodePrefix As String
Get
Return "MOCK"
End Get
End Property
Public Overrides Function GetSeverity(code As Integer) As DiagnosticSeverity
Return DiagnosticSeverity.Error
End Function
Public Overrides Function LoadMessage(code As Integer, language As CultureInfo) As String
Return String.Format("Error {0}", code)
End Function
Public Overrides Function GetDescription(code As Integer) As LocalizableString
Return String.Empty
End Function
Public Overrides Function GetTitle(code As Integer) As LocalizableString
Return String.Empty
End Function
Public Overrides Function GetMessageFormat(code As Integer) As LocalizableString
Return String.Empty
End Function
Public Overrides Function GetHelpLink(code As Integer) As String
Return String.Empty
End Function
Public Overrides Function GetCategory(code As Integer) As String
Return String.Empty
End Function
Public Overrides Function GetWarningLevel(code As Integer) As Integer
Return 0
End Function
Public Overrides Function GetErrorDisplayString(symbol As ISymbol) As String
Return MessageProvider.Instance.GetErrorDisplayString(symbol)
End Function
End Class
' A test rewriting visitor
Private Class TestVisitor
Inherits VisualBasicSyntaxRewriter
' Optional to control which rewritings we do
Public IncrementInts As Boolean = False
Public CapitalizeKeywords As Boolean = False
Public CapitalizeIdentifiers As Boolean = False
Public SwapParameters As Boolean = False
Public Overrides Function VisitToken(token As SyntaxToken) As SyntaxToken
Select Case token.Kind
Case SyntaxKind.IntegerLiteralToken
If IncrementInts Then
Dim node = DirectCast(token.Node, InternalSyntax.IntegerLiteralTokenSyntax)
Dim value = CULng(node.ObjectValue)
value = CULng(value + 1)
Return SyntaxFactory.IntegerLiteralToken(token.LeadingTrivia, value.ToString(), LiteralBase.Decimal, node.TypeSuffix, value, token.TrailingTrivia())
End If
Case SyntaxKind.IdentifierToken
If CapitalizeIdentifiers Then
Dim node = DirectCast(token.Node, InternalSyntax.IdentifierTokenSyntax)
Return SyntaxFactory.Identifier(token.LeadingTrivia(), node.Text.ToUpperInvariant(), node.IsBracketed, node.IdentifierText.ToUpperInvariant(),
node.TypeCharacter, token.TrailingTrivia())
End If
Case Else
If SyntaxFacts.IsKeywordKind(token.Kind) Then
If CapitalizeKeywords Then
Dim node = DirectCast(token.Node, InternalSyntax.KeywordSyntax)
Return SyntaxFactory.Token(token.LeadingTrivia(), node.Kind, token.TrailingTrivia(), node.Text.ToUpperInvariant())
End If
End If
End Select
Return MyBase.VisitToken(token)
End Function
Public Overrides Function VisitMethodStatement(node As MethodStatementSyntax) As SyntaxNode
If SwapParameters Then
node = CType(MyBase.VisitMethodStatement(node), MethodStatementSyntax)
Return SyntaxFactory.MethodStatement(node.Kind,
node.AttributeLists,
node.Modifiers,
node.DeclarationKeyword,
node.Identifier,
node.TypeParameterList,
SyntaxFactory.ParameterList(
node.ParameterList.OpenParenToken,
SwitchParameters(node.ParameterList.Parameters),
node.ParameterList.CloseParenToken),
node.AsClause,
node.HandlesClause,
node.ImplementsClause)
Else
Return MyBase.VisitMethodStatement(node)
End If
End Function
Private Function SwitchParameters(params As SeparatedSyntaxList(Of ParameterSyntax)) As SeparatedSyntaxList(Of ParameterSyntax)
If params.Count >= 2 Then
Dim bldr = SeparatedSyntaxListBuilder(Of ParameterSyntax).Create()
bldr.Add(params(1))
bldr.AddSeparator(params.GetSeparator(0))
bldr.Add(params(0))
bldr.AddSeparator(params.GetSeparator(1))
For i As Integer = 2 To params.Count - 1
bldr.Add(params(i))
If i < params.SeparatorCount Then
bldr.AddSeparator(params.GetSeparator(i))
End If
Next
Return bldr.ToList
Else
Return params
End If
End Function
End Class
<Fact>
Public Sub TestRewritingVisitor()
Dim rewriter As VisualBasicSyntaxRewriter
Dim simpleTree = CreateSimpleTree()
Assert.Equal(simpleTree.ToString, "1- X( 3, 4+ 8, 9)")
' null rewriting should return exact same node.
rewriter = New TestVisitor()
Dim newTree = rewriter.Visit(simpleTree)
Assert.Same(simpleTree, newTree)
' incremental all integers
rewriter = New TestVisitor() With {.IncrementInts = True}
newTree = rewriter.Visit(simpleTree)
Assert.Equal(newTree.ToString, "2- X( 4, 5+ 9, 10)")
Dim methodStmt = CreateMethodStatement()
Assert.Equal("public Overloads SUB MySub ( ByVal Param1 As Integer , ByVal Param2 As String , ByRef Param3 As Double )", methodStmt.ToString)
' null rewriting should return exact same node.
rewriter = New TestVisitor()
Dim newMethod = rewriter.Visit(methodStmt)
Assert.Same(methodStmt, newMethod)
' capitalize all keywords.
rewriter = New TestVisitor() With {.CapitalizeKeywords = True}
newMethod = rewriter.Visit(methodStmt)
Assert.Equal("PUBLIC OVERLOADS SUB MySub ( BYVAL Param1 AS INTEGER , BYVAL Param2 AS STRING , BYREF Param3 AS DOUBLE )", newMethod.ToString)
' capitalize all identifiers.
rewriter = New TestVisitor() With {.CapitalizeIdentifiers = True}
newMethod = rewriter.Visit(methodStmt)
Assert.Equal("public Overloads SUB MYSUB ( ByVal PARAM1 As Integer , ByVal PARAM2 As String , ByRef PARAM3 As Double )", newMethod.ToString)
' reorder parameters.
rewriter = New TestVisitor() With {.SwapParameters = True}
newMethod = rewriter.Visit(methodStmt)
Assert.Equal("public Overloads SUB MySub ( ByVal Param2 As String , ByVal Param1 As Integer , ByRef Param3 As Double )", newMethod.ToString)
'all 3
rewriter = New TestVisitor() With {.SwapParameters = True, .CapitalizeIdentifiers = True, .CapitalizeKeywords = True}
newMethod = rewriter.Visit(methodStmt)
Assert.Equal("PUBLIC OVERLOADS SUB MYSUB ( BYVAL PARAM2 AS STRING , BYVAL PARAM1 AS INTEGER , BYREF PARAM3 AS DOUBLE )", newMethod.ToString)
End Sub
<Fact>
Public Sub TestReplacer()
Dim simpleTree = CreateSimpleTree()
Assert.Equal("1- X( 3, 4+ 8, 9)", simpleTree.ToString)
Dim firstOper = simpleTree.Left
simpleTree = simpleTree.ReplaceNode(firstOper, SyntaxFactory.StringLiteralExpression(SyntaxFactory.StringLiteralToken("""Hi""", "Hi")))
Assert.Equal("""Hi""- X( 3, 4+ 8, 9)", simpleTree.ToString)
' if first arg is not in tree then returns same instance
simpleTree = simpleTree.ReplaceNode(firstOper, SyntaxFactory.StringLiteralExpression(SyntaxFactory.StringLiteralToken("""ha""", "ha")))
Assert.Equal("""Hi""- X( 3, 4+ 8, 9)", simpleTree.ToString)
Dim secondOper = simpleTree.Right
simpleTree = simpleTree.ReplaceNode(secondOper, SyntaxFactory.StringLiteralExpression(SyntaxFactory.MissingStringLiteral()))
Assert.Equal("""Hi""- ", simpleTree.ToFullString)
Dim newSecondOper = simpleTree.Right
simpleTree = simpleTree.ReplaceNode(newSecondOper, SyntaxFactory.StringLiteralExpression(SyntaxFactory.StringLiteralToken("""Bye""", "Bye")))
Assert.Equal("""Hi""- ""Bye""", simpleTree.ToFullString)
Dim op = simpleTree.OperatorToken
simpleTree = simpleTree.ReplaceToken(op, SyntaxFactory.MissingPunctuation(SyntaxKind.MinusToken))
Assert.Equal("""Hi""""Bye""", simpleTree.ToFullString)
op = simpleTree.OperatorToken
simpleTree = simpleTree.ReplaceToken(op, SyntaxFactory.Token(SyntaxKind.EqualsToken, trailing:=_spaceTrivia))
Assert.Equal("""Hi""= ""Bye""", simpleTree.ToFullString)
End Sub
<Fact>
Public Sub TestReplaceNode()
Dim expr = SyntaxFactory.ParseExpression("a + b")
Dim bex = DirectCast(expr, BinaryExpressionSyntax)
Dim expr2 = expr.ReplaceNode(bex.Right, SyntaxFactory.ParseExpression("c"))
Assert.Equal("a + c", expr2.ToFullString())
End Sub
<Fact>
Public Sub TestReplaceNodes()
Dim expr = SyntaxFactory.ParseExpression("a + b + c + d")
' replace each expression with a parenthesized expression
Dim replaced = expr.ReplaceNodes(
expr.DescendantNodes().OfType(Of ExpressionSyntax)(),
Function(node, rewritten) SyntaxFactory.ParenthesizedExpression(rewritten))
Dim replacedText = replaced.ToFullString()
Assert.Equal("(((a )+ (b ))+ (c ))+ (d)", replacedText)
End Sub
<Fact>
Public Sub TestReplaceNodesInListWithMultiple()
Dim invocation = DirectCast(SyntaxFactory.ParseExpression("m(a, b)"), InvocationExpressionSyntax)
Dim argC = SyntaxFactory.SimpleArgument(SyntaxFactory.ParseExpression("c"))
Dim argD = SyntaxFactory.SimpleArgument(SyntaxFactory.ParseExpression("d"))
' replace first with multiple
Dim newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments(0), {argC, argD})
Assert.Equal("m(c,d, b)", newNode.ToFullString())
' replace last with multiple
newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments(1), {argC, argD})
Assert.Equal("m(a, c,d)", newNode.ToFullString())
' replace first with empty list
newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments(0), New SyntaxNode() {})
Assert.Equal("m(b)", newNode.ToFullString())
' replace last with empty list
newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments(1), New SyntaxNode() {})
Assert.Equal("m(a)", newNode.ToFullString())
End Sub
<Fact>
Public Sub TestReplaceNonListNodeWithList()
Dim invocation = DirectCast(SyntaxFactory.ParseExpression("m(a, b)"), InvocationExpressionSyntax)
Dim expA = invocation.DescendantNodes().OfType(Of ExpressionSyntax).First(Function(n) n.ToString() = "a")
Dim expC = SyntaxFactory.ParseExpression("c")
Dim expD = SyntaxFactory.ParseExpression("d")
' cannot replace a node that is not in a list with multiple nodes
Assert.Throws(Of InvalidOperationException)(Function() invocation.ReplaceNode(expA, {expC, expD}))
' cannot replace a node that is not in a list with and empty list of nodes
Assert.Throws(Of InvalidOperationException)(Function() invocation.ReplaceNode(expA, New ExpressionSyntax() {}))
End Sub
<Fact>
Public Sub TestInsertNodesInList()
Dim invocation = DirectCast(SyntaxFactory.ParseExpression("m(a, b)"), InvocationExpressionSyntax)
Dim argC = SyntaxFactory.SimpleArgument(SyntaxFactory.ParseExpression("c"))
Dim argD = SyntaxFactory.SimpleArgument(SyntaxFactory.ParseExpression("d"))
' insert before first
Dim newNode = invocation.InsertNodesBefore(invocation.ArgumentList.Arguments(0), {argC, argD})
Assert.Equal("m(c,d,a, b)", newNode.ToFullString())
'' insert after first
newNode = invocation.InsertNodesAfter(invocation.ArgumentList.Arguments(0), {argC, argD})
Assert.Equal("m(a,c,d, b)", newNode.ToFullString())
' insert before last
newNode = invocation.InsertNodesBefore(invocation.ArgumentList.Arguments(1), {argC, argD})
Assert.Equal("m(a,c,d, b)", newNode.ToFullString())
' insert after last
newNode = invocation.InsertNodesAfter(invocation.ArgumentList.Arguments(1), {argC, argD})
Assert.Equal("m(a, b,c,d)", newNode.ToFullString())
End Sub
<Fact>
Public Sub TestInsertNodesRelativeToNonListNode()
Dim invocation = DirectCast(SyntaxFactory.ParseExpression("m(a, b)"), InvocationExpressionSyntax)
Dim expA = invocation.DescendantNodes().OfType(Of ExpressionSyntax).First(Function(n) n.ToString() = "a")
Dim expC = SyntaxFactory.ParseExpression("c")
Dim expD = SyntaxFactory.ParseExpression("d")
' cannot replace a node that is not in a list with multiple nodes
Assert.Throws(Of InvalidOperationException)(Function() invocation.InsertNodesBefore(expA, {expC, expD}))
' cannot replace a node that is not in a list with and empty list of nodes
Assert.Throws(Of InvalidOperationException)(Function() invocation.InsertNodesAfter(expA, {expC, expD}))
End Sub
<Fact>
Public Sub TestReplaceStatementInListWithMultiple()
Dim ifBlock = DirectCast(SyntaxFactory.ParseExecutableStatement(
<x>If a != b Then
Dim x = 10
Dim y = 20
End If</x>.Value), MultiLineIfBlockSyntax)
Dim stmt1 = SyntaxFactory.ParseExecutableStatement(
<x>Dim z = 30
</x>.Value)
Dim stmt2 = SyntaxFactory.ParseExecutableStatement(
<x>Dim q = 40
</x>.Value)
'' replace first with multiple
Dim newBlock = ifBlock.ReplaceNode(ifBlock.Statements(0), {stmt1, stmt2})
Assert.Equal(
<x>If a != b Then
Dim z = 30
Dim q = 40
Dim y = 20
End If</x>.Value, newBlock.ToFullString())
'' replace second with multiple
newBlock = ifBlock.ReplaceNode(ifBlock.Statements(1), {stmt1, stmt2})
Assert.Equal(
<x>If a != b Then
Dim x = 10
Dim z = 30
Dim q = 40
End If</x>.Value, newBlock.ToFullString())
' replace first with empty list
newBlock = ifBlock.ReplaceNode(ifBlock.Statements(0), New SyntaxNode() {})
Assert.Equal(
<x>If a != b Then
Dim y = 20
End If</x>.Value, newBlock.ToFullString())
' replace second with empty list
newBlock = ifBlock.ReplaceNode(ifBlock.Statements(1), New SyntaxNode() {})
Assert.Equal(
<x>If a != b Then
Dim x = 10
End If</x>.Value, newBlock.ToFullString())
End Sub
<Fact>
Public Sub TestInsertStatementsInList()
Dim ifBlock = DirectCast(SyntaxFactory.ParseExecutableStatement(
<x>If a != b Then
Dim x = 10
Dim y = 20
End If</x>.Value), MultiLineIfBlockSyntax)
Dim stmt1 = SyntaxFactory.ParseExecutableStatement(
<x>Dim z = 30
</x>.Value)
Dim stmt2 = SyntaxFactory.ParseExecutableStatement(
<x>Dim q = 40
</x>.Value)
' insert before first
Dim newBlock = ifBlock.InsertNodesBefore(ifBlock.Statements(0), {stmt1, stmt2})
Assert.Equal(
<x>If a != b Then
Dim z = 30
Dim q = 40
Dim x = 10
Dim y = 20
End If</x>.Value, newBlock.ToFullString())
' insert after first
newBlock = ifBlock.InsertNodesAfter(ifBlock.Statements(0), {stmt1, stmt2})
Assert.Equal(
<x>If a != b Then
Dim x = 10
Dim z = 30
Dim q = 40
Dim y = 20
End If</x>.Value, newBlock.ToFullString())
' insert before last
newBlock = ifBlock.InsertNodesBefore(ifBlock.Statements(1), {stmt1, stmt2})
Assert.Equal(
<x>If a != b Then
Dim x = 10
Dim z = 30
Dim q = 40
Dim y = 20
End If</x>.Value, newBlock.ToFullString())
' insert after last
newBlock = ifBlock.InsertNodesAfter(ifBlock.Statements(1), {stmt1, stmt2})
Assert.Equal(
<x>If a != b Then
Dim x = 10
Dim y = 20
Dim z = 30
Dim q = 40
End If</x>.Value, newBlock.ToFullString())
End Sub
<Fact>
Public Sub TestReplaceToken()
Dim expr = SyntaxFactory.ParseExpression("a + b")
Dim bToken = expr.DescendantTokens().First(Function(t) t.Text = "b")
Dim expr2 = expr.ReplaceToken(bToken, SyntaxFactory.ParseToken("c"))
Assert.Equal("a + c", expr2.ToString())
End Sub
<Fact>
Public Sub TestReplaceMultipleTokens()
Dim expr = SyntaxFactory.ParseExpression("a + b + c")
Dim d = SyntaxFactory.ParseToken("d ")
Dim tokens = expr.DescendantTokens().Where(Function(t) t.IsKind(SyntaxKind.IdentifierToken)).ToList()
Dim replaced = expr.ReplaceTokens(tokens, Function(tok, tok2) d)
Assert.Equal("d + d + d ", replaced.ToFullString())
End Sub
<Fact>
Public Sub TestReplaceTokenWithMultipleTokens()
Dim cu = SyntaxFactory.ParseCompilationUnit(
<x>Private Class C
End Class</x>.Value)
Dim privateToken = DirectCast(cu.Members(0), ClassBlockSyntax).BlockStatement.Modifiers(0)
Dim publicToken = SyntaxFactory.ParseToken("Public ")
Dim partialToken = SyntaxFactory.ParseToken("Partial ")
Dim cu1 = cu.ReplaceToken(privateToken, publicToken)
Assert.Equal(
<x>Public Class C
End Class</x>.Value, cu1.ToFullString())
Dim cu2 = cu.ReplaceToken(privateToken, {publicToken, partialToken})
Assert.Equal(
<x>Public Partial Class C
End Class</x>.Value, cu2.ToFullString())
Dim cu3 = cu.ReplaceToken(privateToken, New SyntaxToken() {})
Assert.Equal(
<x>Class C
End Class</x>.Value, cu3.ToFullString())
End Sub
<Fact>
Public Sub TestReplaceNonListTokenWithMultipleTokensFails()
Dim cu = SyntaxFactory.ParseCompilationUnit(
<x>Private Class C
End Class</x>.Value)
Dim identifierC = cu.DescendantTokens().First(Function(t) t.Text = "C")
Dim identifierA = SyntaxFactory.ParseToken("A")
Dim identifierB = SyntaxFactory.ParseToken("B")
' you cannot replace a token that Is a single token member with multiple tokens
Assert.Throws(Of InvalidOperationException)(Function() cu.ReplaceToken(identifierC, {identifierA, identifierB}))
' you cannot replace a token that Is a single token member with an empty list of tokens
Assert.Throws(Of InvalidOperationException)(Function() cu.ReplaceToken(identifierC, New SyntaxToken() {}))
End Sub
<Fact>
Public Sub TestInsertTokensInList()
Dim cu = SyntaxFactory.ParseCompilationUnit(
<x>Public Class C
End Class</x>.Value)
Dim publicToken = DirectCast(cu.Members(0), ClassBlockSyntax).BlockStatement.Modifiers(0)
Dim partialToken = SyntaxFactory.ParseToken("Partial ")
Dim sharedToken = SyntaxFactory.ParseToken("Shared ")
Dim cu1 = cu.InsertTokensBefore(publicToken, {sharedToken})
Assert.Equal(
<x>Shared Public Class C
End Class</x>.Value, cu1.ToFullString())
Dim cu2 = cu.InsertTokensAfter(publicToken, {sharedToken})
Assert.Equal(
<x>Public Shared Class C
End Class</x>.Value, cu2.ToFullString())
End Sub
<Fact>
Public Sub TestInsertTokensRelativeToNonListToken()
Dim cu = SyntaxFactory.ParseCompilationUnit(
<x>Private Class C
End Class</x>.Value)
Dim identifierC = cu.DescendantTokens().First(Function(t) t.Text = "C")
Dim identifierA = SyntaxFactory.ParseToken("A")
Dim identifierB = SyntaxFactory.ParseToken("B")
' you cannot insert tokens before/after a token that is not part of a list
Assert.Throws(Of InvalidOperationException)(Function() cu.InsertTokensBefore(identifierC, {identifierA, identifierB}))
' you cannot insert tokens before/after a token that is not part of a list
Assert.Throws(Of InvalidOperationException)(Function() cu.InsertTokensAfter(identifierC, New SyntaxToken() {}))
End Sub
<Fact>
Public Sub TestReplaceSingleTriviaInNode()
Dim expr = SyntaxFactory.ParseExpression("a + b")
Dim trivia = expr.DescendantTokens().First(Function(t) t.Text = "a").TrailingTrivia(0)
Dim twoSpaces = SyntaxFactory.Whitespace(" ")
Dim expr2 = expr.ReplaceTrivia(trivia, twoSpaces)
Assert.Equal("a + b", expr2.ToFullString())
End Sub
<Fact>
Public Sub TestReplaceMultipleTriviaInNode()
Dim expr = SyntaxFactory.ParseExpression("a + b")
Dim twoSpaces = SyntaxFactory.Whitespace(" ")
Dim trivia = expr.DescendantTrivia().Where(Function(tr) tr.IsKind(SyntaxKind.WhitespaceTrivia)).ToList()
Dim replaced = expr.ReplaceTrivia(trivia, Function(tr, tr2) twoSpaces)
Assert.Equal("a + b", replaced.ToFullString())
End Sub
<Fact>
Public Sub TestReplaceSingleTriviaWithMultipleTriviaInNode()
Dim ex = SyntaxFactory.ParseExpression("identifier 'c")
Dim trivia = ex.GetTrailingTrivia()
Assert.Equal(2, trivia.Count)
Dim comment1 = trivia(1)
Assert.Equal(SyntaxKind.CommentTrivia, Kind(comment1))
Dim newComment1 = SyntaxFactory.ParseTrailingTrivia("'a")(0)
Dim newComment2 = SyntaxFactory.ParseTrailingTrivia("'b")(0)
Dim ex1 = ex.ReplaceTrivia(comment1, newComment1)
Assert.Equal("identifier 'a", ex1.ToFullString())
Dim ex2 = ex.ReplaceTrivia(comment1, {newComment1, newComment2})
Assert.Equal("identifier 'a'b", ex2.ToFullString())
Dim ex3 = ex.ReplaceTrivia(comment1, New SyntaxTrivia() {})
Assert.Equal("identifier ", ex3.ToFullString())
End Sub
<Fact>
Public Sub TestInsertTriviaInNode()
Dim ex = SyntaxFactory.ParseExpression("identifier 'c")
Dim trivia = ex.GetTrailingTrivia()
Assert.Equal(2, trivia.Count)
Dim comment1 = trivia(1)
Assert.Equal(SyntaxKind.CommentTrivia, Kind(comment1))
Dim newComment1 = SyntaxFactory.ParseTrailingTrivia("'a")(0)
Dim newComment2 = SyntaxFactory.ParseTrailingTrivia("'b")(0)
Dim ex1 = ex.InsertTriviaBefore(comment1, {newComment1, newComment2})
Assert.Equal("identifier 'a'b'c", ex1.ToFullString())
Dim ex2 = ex.InsertTriviaAfter(comment1, {newComment1, newComment2})
Assert.Equal("identifier 'c'a'b", ex2.ToFullString())
End Sub
<Fact>
Public Sub TestReplaceSingleTriviaInToken()
Dim id = SyntaxFactory.ParseToken("a ")
Dim trivia = id.TrailingTrivia(0)
Dim twoSpace = SyntaxFactory.Whitespace(" ")
Dim id2 = id.ReplaceTrivia(trivia, twoSpace)
Assert.Equal("a ", id2.ToFullString())
End Sub
<Fact>
Public Sub TestReplaceMultipleTriviaInToken()
Dim id = SyntaxFactory.ParseToken(
<x>a 'goo
</x>.Value)
' replace each trivia with a single space
Dim id2 = id.ReplaceTrivia(id.GetAllTrivia(), Function(tr, tr2) SyntaxFactory.Space)
' should be 3 spaces (one for original space, comment and end-of-line)
Assert.Equal("a ", id2.ToFullString())
End Sub
<Fact>
Public Sub TestTriviaExtensions()
Dim simpleTree = CreateSimpleTree()
Assert.Equal("1- X( 3, 4+ 8, 9) ", simpleTree.ToFullString())
Dim tk = simpleTree.GetLastToken(includeZeroWidth:=True)
Assert.Equal(") ", tk.ToFullString())
tk = simpleTree.GetFirstToken(includeZeroWidth:=True)
Assert.Equal("1", tk.ToFullString())
tk = tk.WithLeadingTrivia(SyntaxFactory.WhitespaceTrivia(" "))
Assert.Equal(" 1", tk.ToFullString())
tk = tk.WithLeadingTrivia(SyntaxFactory.WhitespaceTrivia(" "))
tk = tk.WithTrailingTrivia(SyntaxFactory.WhitespaceTrivia(" "))
Assert.Equal(" 1 ", tk.ToFullString())
End Sub
<WorkItem(872867, "DevDiv/Personal")>
<WorkItem(878887, "DevDiv/Personal")>
<WorkItem(878902, "DevDiv/Personal")>
<Fact>
Public Sub TestCommonSyntaxNode()
'Dim node As SyntaxNode = ParseAndVerify(" Module M1" & vbCrLf & "End Module")
'Assert.False(node.Errors.Any())
'Assert.Equal(0, node.GetTrailingTrivia.Count)
'Assert.Equal(1, node.GetLeadingTrivia.Count)
'Assert.False(node.IsTerminal)
'Assert.Equal(3, node.ChildNodesAndTokens().Count)
'Assert.Equal(1, node.SpanStart)
'Assert.Equal(22, node.Span.End)
'Assert.Equal(0, node.FullSpan.Start)
'Assert.Equal(22, node.FullSpan.End)
'Assert.Null(node.Parent)
'
' When this breaks, uncomment above
Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText(SourceText.From(" Module M1" & vbCrLf & "End Module"))
Dim node As SyntaxNode = tree.GetRoot()
Assert.Equal(False, tree.GetDiagnostics(node).Any)
Assert.Equal(0, tree.GetRoot().FindToken(node.FullSpan.Length - 1).TrailingTrivia.Count)
Assert.Equal(1, tree.GetRoot().FindToken(0).LeadingTrivia.Count)
Assert.Equal(False, node.ChildNodesAndTokens().Count = 0)
Assert.Equal(2, node.ChildNodesAndTokens().Count)
'Assert.Equal(1, tree.GetSpan(node).Start)
'Assert.Equal(22, tree.GetSpan(node).End)
'Assert.Equal(0, tree.GetFullSpan(node).Start)
'Assert.Equal(22, tree.GetFullSpan(node).End)
'Assert.Equal(Nothing, tree.GetParent(node))
End Sub
<WorkItem(879737, "DevDiv/Personal")>
<Fact>
Public Sub TestDiagnostic()
'Dim node As SyntaxNode =
' ParseAndVerify(
' "Module M1" & vbCrLf & "End",
' <errors>
' <error id="30678"/>
' <error id="30625"/>
' </errors>)
'Assert.True(node.Errors.Any)
'Assert.Equal(2, node.Errors.Count)
'Assert.Equal(DiagnosticSeverity.Error, node.Errors(0).Severity)
'Assert.Contains(30678, From d In node.Errors Select d.Code)
'
' When this breaks, uncomment above
Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText(SourceText.From("Module M1" & vbCrLf & "End"))
Dim node As SyntaxNode = tree.GetRoot()
Assert.Equal(True, tree.GetDiagnostics(node).Any)
Assert.Equal(2, tree.GetDiagnostics(node).Count)
Assert.Equal(DiagnosticSeverity.Error, tree.GetDiagnostics(node)(0).Severity)
Assert.Equal(30625, tree.GetDiagnostics(node)(0).Code)
Assert.Equal(30678, tree.GetDiagnostics(node)(1).Code)
End Sub
<Fact>
Public Sub TestStructuredTrivia()
Dim xmlStartElement = SyntaxFactory.XmlElementStartTag(
SyntaxFactory.Token(_spaceTrivia, SyntaxKind.LessThanToken, trailing:=Nothing),
SyntaxFactory.XmlName(Nothing,
SyntaxFactory.XmlNameToken("goo", SyntaxKind.XmlNameToken)),
Nothing,
SyntaxFactory.Token(SyntaxKind.GreaterThanToken, trailing:=_spaceTrivia))
Dim xmlEndElement = SyntaxFactory.XmlElementEndTag(
SyntaxFactory.Token(SyntaxKind.LessThanSlashToken, trailing:=_spaceTrivia),
Nothing,
SyntaxFactory.Token(Nothing, SyntaxKind.GreaterThanToken, trailing:=SyntaxTriviaList.Create(_spaceTrivia).Concat(_spaceTrivia).ToSyntaxTriviaList()))
Dim xmlElement = SyntaxFactory.XmlElement(xmlStartElement, Nothing, xmlEndElement)
Assert.Equal(" <goo> </ > ", xmlElement.ToFullString)
Assert.Equal("<goo> </ >", xmlElement.ToString)
Dim docComment = SyntaxFactory.DocumentationCommentTrivia(SyntaxFactory.SingletonList(Of XmlNodeSyntax)(xmlElement))
Assert.Equal(" <goo> </ > ", docComment.ToFullString)
Assert.Equal("<goo> </ >", docComment.ToString)
Assert.Equal(" <goo> </ > ", docComment.Content(0).ToFullString)
Assert.Equal("<goo> </ >", docComment.Content(0).ToString)
Assert.Equal(" <goo> ", DirectCast(docComment.Content(0), XmlElementSyntax).StartTag.ToFullString)
Assert.Equal("<goo>", DirectCast(docComment.Content(0), XmlElementSyntax).StartTag.ToString)
Dim sTrivia = SyntaxFactory.Trivia(docComment)
Dim ident = SyntaxFactory.Identifier(sTrivia, "banana", _spaceTrivia)
Assert.Equal(" <goo> </ > banana ", ident.ToFullString())
Assert.Equal("banana", ident.ToString())
Assert.Equal(" <goo> </ > ", ident.LeadingTrivia()(0).ToFullString)
Assert.Equal("<goo> </ >", ident.LeadingTrivia()(0).ToString())
Dim identExpr = SyntaxFactory.IdentifierName(ident)
' make sure FindLeaf digs into the structured trivia.
Dim result = identExpr.FindToken(3, True)
Assert.Equal(SyntaxKind.XmlNameToken, result.Kind)
Assert.Equal("goo", result.ToString())
Dim trResult = identExpr.FindTrivia(6, True)
Assert.Equal(SyntaxKind.WhitespaceTrivia, trResult.Kind)
Assert.Equal(" ", trResult.ToString())
Dim foundDocComment = result.Parent.Parent.Parent.Parent
Assert.Equal(Nothing, foundDocComment.Parent)
Dim identTrivia = identExpr.GetLeadingTrivia(0)
Dim foundTrivia = DirectCast(foundDocComment, DocumentationCommentTriviaSyntax).ParentTrivia
Assert.Equal(identTrivia, foundTrivia)
' make sure FindLeafNodesOverlappingWithSpan does not dig into the structured trivia.
Dim resultList = identExpr.DescendantTokens(New TextSpan(3, 18))
Assert.Equal(1, resultList.Count)
End Sub
' Check that the children list preserved identity.
<Fact>
Public Sub ChildrenListObjectIdentity()
Dim tree = CreateSimpleTree()
Dim children1 = tree.ChildNodesAndTokens()
Dim children2 = tree.ChildNodesAndTokens()
Assert.Equal(children1, children2)
Dim child2_1 = tree.ChildNodesAndTokens()(1)
Dim child2_2 = tree.ChildNodesAndTokens()(1)
Assert.Equal(child2_1, child2_2)
End Sub
Private Function CreateNamespaceBlock() As NamespaceBlockSyntax
Dim statementBuilder = SyntaxListBuilder(Of StatementSyntax).Create()
statementBuilder.Add(SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxKind.EmptyToken)))
statementBuilder.Add(SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxKind.EmptyToken)))
statementBuilder.Add(SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxKind.EmptyToken)))
Return SyntaxFactory.NamespaceBlock(SyntaxFactory.NamespaceStatement(
SyntaxFactory.Token(SyntaxKind.NamespaceKeyword, trailing:=_spaceTrivia), SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("goo"))),
statementBuilder.ToList,
SyntaxFactory.EndNamespaceStatement(SyntaxFactory.Token(SyntaxKind.EndKeyword), SyntaxFactory.Token(SyntaxKind.NamespaceKeyword)))
End Function
' Check that specific children accessors preserve object identifier
<Fact>
Public Sub ChildAccessorObjectIdentity()
Dim tree = CreateSimpleTree()
Dim left1 = tree.Left
Dim left2 = tree.Left
Assert.Same(left1, left2)
Dim nsBlock = CreateNamespaceBlock()
Dim membs1 = nsBlock.Members
Dim membs2 = nsBlock.Members
Assert.Same(membs1.Node, membs2.Node)
Dim begin1 = nsBlock.NamespaceStatement
Dim begin2 = nsBlock.NamespaceStatement
Assert.Same(begin1, begin2)
Dim firstMember1 = nsBlock.Members(0)
Dim firstMember2 = nsBlock.Members(0)
Dim firstMember3 = nsBlock.ChildNodesAndTokens()(1)
Assert.Same(firstMember1, firstMember2)
Assert.Same(firstMember1, firstMember3.AsNode)
nsBlock = CreateNamespaceBlock()
firstMember3 = nsBlock.ChildNodesAndTokens()(1)
firstMember1 = nsBlock.Members(0)
firstMember2 = nsBlock.Members(0)
Assert.Same(firstMember1, firstMember2)
Assert.Same(firstMember1, firstMember3.AsNode)
End Sub
' Check that specific children accessors preserve object identifier
<Fact>
Public Sub TestTreeIterator()
Dim tree = CreateSimpleTree()
Dim txt As String = ""
Dim terminals = tree.DescendantTokens(tree.FullSpan)
For Each n In terminals
txt &= n.ToFullString()
Next
Assert.Equal(tree.ToFullString, txt)
Assert.Equal(12, terminals.Count)
Dim op = tree.Right
Dim newOp = SyntaxFactory.StringLiteralExpression(SyntaxFactory.StringLiteralToken("""Hi""", "Hi"))
tree = tree.ReplaceNode(op, newOp)
terminals = tree.DescendantTokens(tree.FullSpan)
txt = ""
For Each n In terminals
txt &= n.ToFullString()
Next
Assert.Equal(tree.ToFullString, txt)
Assert.Equal(3, terminals.Count)
End Sub
<Fact>
Public Sub TestGetNextToken()
Dim prog = ParseAndVerify(<![CDATA[Module Module1
dim xxxx :: Dim yyyy
End Module
]]>)
Dim tk0 = prog.GetRoot().FindToken(25)
Assert.Equal("xxxx", tk0.ToString)
Dim colons = tk0.TrailingTrivia().Where(Function(t) t.Kind = SyntaxKind.ColonTrivia).ToArray()
Assert.Equal(colons.Length, 2)
For Each colon In colons
Assert.Equal(":", colon.ToString)
Next
Dim tk_nonzero1 = tk0.GetNextToken
Assert.Equal("Dim", tk_nonzero1.ToString)
Dim tk_nonzero2 = tk_nonzero1.GetNextToken
Assert.Equal("yyyy", tk_nonzero2.ToString)
Dim tk_zero1 = tk_nonzero1.GetNextToken(includeZeroWidth:=True)
Assert.Equal("yyyy", tk_zero1.ToString)
Dim newline = tk_zero1.TrailingTrivia.Where(Function(t) t.Kind = SyntaxKind.EndOfLineTrivia).First
Assert.Equal(vbLf, newline.ToString)
End Sub
<Fact, WorkItem(789824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/789824"), WorkItem(530316, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530316")>
Public Sub TestGetPreviousToken()
Dim prog = ParseAndVerify(<![CDATA[
Module Module1
dim xxxx :: Dim yyyy
End Module
]]>)
Dim tk0 = prog.GetRoot().FindToken(32)
Assert.Equal("Dim", tk0.ToString)
Dim tk_nonzero1 = tk0.GetPreviousToken
Assert.Equal("xxxx", tk_nonzero1.ToString)
Dim trivia = tk_nonzero1.TrailingTrivia
Assert.Equal(" ::", trivia.ToString)
Dim tk_nonzero3 = tk_nonzero1.GetPreviousToken
Assert.Equal("dim", tk_nonzero3.ToString)
Dim tk_zero1 = tk_nonzero1.GetPreviousToken(includeZeroWidth:=True)
Assert.Equal("dim", tk_zero1.ToString)
Dim tk_zero2 = tk_zero1.GetPreviousToken(includeZeroWidth:=True)
Assert.Equal("Module1", tk_zero2.ToString)
Dim tk_zero3 = tk_zero2.GetPreviousToken(includeZeroWidth:=True)
Assert.Equal(vbLf, tk_zero3.LeadingTrivia.ToString)
End Sub
<Fact>
Public Sub TestCommonSyntaxTokenGetPreviousToken()
Dim text =
"Class C(Of T)" & vbCrLf &
" Dim l As List(Of T)" &
"End Class"
Dim tree = VisualBasicSyntaxTree.ParseText(text)
Dim location = text.IndexOf("List(Of T)", StringComparison.Ordinal)
Dim openParenToken = CType(tree.GetRoot().FindToken(location + "List".Length), SyntaxToken)
Assert.Equal(SyntaxKind.OpenParenToken, openParenToken.Kind)
Dim listToken = CType(openParenToken.GetPreviousToken(), SyntaxToken)
Assert.Equal(SyntaxKind.IdentifierToken, listToken.Kind)
End Sub
<Fact, WorkItem(789824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/789824"), WorkItem(530316, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530316")>
Public Sub TestGetNextSibling()
Dim prog = ParseAndVerify(<![CDATA[Module Module1
dim xxxx ::: Dim yyyy
End Module
]]>)
Dim trivia = prog.GetRoot().FindToken(28).TrailingTrivia
Assert.Equal(" :::", trivia.ToString)
Dim tk_nonzero1 = CType(trivia.First().Token.Parent.Parent.Parent, SyntaxNodeOrToken).GetNextSibling()
Assert.Equal("Dim yyyy", tk_nonzero1.ToString)
Dim tk_nonzero2 = tk_nonzero1.GetNextSibling
Assert.Equal("End Module", tk_nonzero2.ToString)
End Sub
<Fact, WorkItem(789824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/789824"), WorkItem(530316, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530316")>
Public Sub TestGetPreviousSibling()
Dim prog = ParseAndVerify(<![CDATA[Module Module1
dim xxxx ::: Dim yyyy
End Module
]]>)
Dim tk0 As SyntaxNodeOrToken = prog.GetRoot().FindToken(31)
Assert.Equal("Dim", tk0.ToString)
Dim tk_nonzero1 = tk0.GetPreviousSibling
Assert.Equal(Nothing, tk_nonzero1)
tk0 = tk0.Parent
tk_nonzero1 = tk0.GetPreviousSibling
Assert.Equal("dim xxxx", tk_nonzero1.ToString)
Dim trivia = tk_nonzero1.GetTrailingTrivia()
Assert.Equal(" :::", trivia.ToString)
End Sub
<Fact>
Public Sub TestFirstLastDirective()
Dim prog = ParseAndVerify(<![CDATA[
#const x =1
#const y = 2
Module Module1
dim xxxx ::: Dim yyyy
End Module
]]>)
Dim tk0 As SyntaxNodeOrToken = prog.GetRoot().FindToken(35)
Dim mDecl = tk0.Parent
Dim fDir = mDecl.GetFirstDirective
Assert.Equal("#const x =1", fDir.ToString)
Dim lDir = mDecl.GetLastDirective
Assert.Equal("#const y = 2", lDir.ToString)
Dim fDir1 = mDecl.GetFirstDirective(Function(d) d.ToString = "#const y = 2")
Assert.Equal("#const y = 2", fDir1.ToString)
fDir1 = mDecl.GetFirstDirective(Function(d) d.ToString = "#const y = 42")
Assert.Equal(Nothing, fDir1)
Dim lDir1 = mDecl.GetLastDirective(Function(d) d.ToString = "#const x =1")
Assert.Equal("#const x =1", lDir1.ToString)
lDir1 = mDecl.GetLastDirective(Function(d) d.ToString = "#const x =42")
Assert.Equal(Nothing, lDir1)
End Sub
<Fact>
Public Sub TestNextPrevDirective()
Dim prog = ParseAndVerify(<![CDATA[
#const x =1
#const y = 2
#const y = 3
Module Module1
dim xxxx ::: Dim yyyy
End Module
]]>)
Dim tk0 As SyntaxNodeOrToken = prog.GetRoot().FindToken(35)
Dim mDecl = tk0.Parent
Dim fDir = mDecl.GetFirstDirective
Dim fDir1 = fDir.GetNextDirective
Assert.Equal("#const y = 2", fDir1.ToString)
Dim lDir = mDecl.GetLastDirective
Dim lDir1 = fDir.GetNextDirective
Assert.Equal("#const y = 2", lDir1.ToString)
Dim fDir2 = fDir1.GetNextDirective(Function(d) d.ToString = "#const y = 3")
Assert.Equal("#const y = 3", fDir2.ToString)
fDir2 = fDir1.GetNextDirective(Function(d) d.ToString = "#const y = 42")
Assert.Equal(Nothing, fDir2)
Dim lDir2 = lDir1.GetPreviousDirective(Function(d) d.ToString = "#const x =1")
Assert.Equal("#const x =1", lDir2.ToString)
lDir2 = lDir1.GetPreviousDirective(Function(d) d.ToString = "#const x =42")
Assert.Equal(Nothing, lDir2)
End Sub
<WorkItem(537404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537404")>
<Fact>
Public Sub TestNodeTokenConversion01()
Dim prog = ParseAndVerify(<![CDATA[ Class A
dim x As
End Class
]]>,
<errors>
<error id="30182"/>
</errors>)
Dim sN As SyntaxNodeOrToken = prog.GetRoot()
Dim cS As SyntaxNodeOrToken = sN
Assert.Equal(sN.IsNode, cS.IsNode)
Assert.Equal(sN.IsToken, cS.IsToken)
Assert.Equal(sN.IsMissing, cS.IsMissing)
Assert.Equal(sN.ContainsDiagnostics, cS.ContainsDiagnostics)
Assert.Equal(sN.ContainsDirectives, cS.ContainsDirectives)
Assert.Equal(sN.HasLeadingTrivia, cS.HasLeadingTrivia)
Assert.Equal(sN.HasTrailingTrivia, cS.HasTrailingTrivia)
Assert.Equal(Kind(sN), Kind(cS))
Assert.Equal(sN.FullWidth, cS.FullSpan.Length)
Assert.Equal(sN.Width, cS.Span.Length)
End Sub
<WorkItem(537403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537403")>
<Fact>
Public Sub TestNodeTokenConversion02()
Dim node As VisualBasicSyntaxNode = Nothing
' This should not throw - it should convert to a 'null' (default) struct
Dim sn As SyntaxNodeOrToken = node
Assert.True(sn.IsNode)
End Sub
<WorkItem(537673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537673")>
<Fact>
Public Sub SyntaxTriviaDefaultIsDirective()
Dim trivia As New SyntaxTrivia()
Assert.False(trivia.IsDirective)
End Sub
<WorkItem(538362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538362")>
<Fact, WorkItem(530316, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530316")>
Public Sub TestGetNextTokenCommon()
Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText("public class goo : end class")
Dim tokens As List(Of SyntaxToken) = tree.GetRoot().DescendantTokens().ToList()
Dim list As List(Of SyntaxToken) = New List(Of SyntaxToken)()
Dim token As SyntaxToken = tree.GetRoot().GetFirstToken()
While token.Kind <> 0
list.Add(token)
token = token.GetNextToken()
End While
' Descendant nodes contain EOF
Assert.Equal(tokens.Count - 1, list.Count)
For i = 0 To list.Count - 1
Assert.Equal(list(i), tokens(i))
Next
' Verify that EOF is returned when calling with Any predicate.
list.Clear()
token = tree.GetRoot().GetFirstToken()
While token.Kind <> 0
list.Add(token)
token = token.GetNextToken(includeZeroWidth:=True)
End While
Debug.Assert(list(list.Count - 1).Kind = SyntaxKind.EndOfFileToken)
Dim lastToken = tree.GetRoot().DescendantTokens().Last
Debug.Assert(lastToken.Kind = SyntaxKind.EndOfFileToken)
End Sub
<WorkItem(755236, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755236")>
<WorkItem(9896, "https://github.com/dotnet/roslyn/issues/9896")>
<Fact>
Public Sub TestFindNode()
Dim code = <code><![CDATA[
''' <see cref="Goo"/>
Class Goo
End Class
Class Bar
End Class]]>
</code>.Value
Dim tree = VisualBasicSyntaxTree.ParseText(code)
Dim root = tree.GetRoot()
Assert.Equal(root, root.FindNode(root.Span, findInsideTrivia:=False))
Assert.Equal(root, root.FindNode(root.Span, findInsideTrivia:=True))
Dim classDecl = DirectCast(root.ChildNodes().First(), TypeBlockSyntax)
Dim classStatement = classDecl.BlockStatement
' IdentifierNameSyntax in trivia.
Dim identifier = root.DescendantNodes(descendIntoTrivia:=True).Single(Function(n) TypeOf n Is IdentifierNameSyntax)
Dim position = identifier.Span.Start + 1
Assert.Equal(classStatement, root.FindNode(identifier.Span, findInsideTrivia:=False))
Assert.Equal(identifier.Parent, root.FindNode(identifier.Span, findInsideTrivia:=True))
Assert.Equal(identifier.Parent.Span, identifier.Span)
' Token span.
Assert.Equal(classStatement, root.FindNode(classStatement.Identifier.Span, findInsideTrivia:=False))
Dim EOFSpan = New TextSpan(root.FullSpan.End, 0)
Assert.Equal(root, root.FindNode(EOFSpan, findInsideTrivia:=False))
Assert.Equal(root, root.FindNode(EOFSpan, findInsideTrivia:=True))
' EOF Invalid span for childnode
Dim classDecl2 = DirectCast(root.ChildNodes().Last(), TypeBlockSyntax)
Dim classStatement2 = classDecl2.BlockStatement
Assert.Throws(Of ArgumentOutOfRangeException)(Sub() classDecl2.FindNode(EOFSpan))
' Check end position included in node span
Dim nodeEndPositionSpan = New TextSpan(classDecl.FullSpan.End, 0)
Assert.Equal(classStatement2, root.FindNode(nodeEndPositionSpan, findInsideTrivia:=False))
Assert.Equal(classStatement2, root.FindNode(nodeEndPositionSpan, findInsideTrivia:=True))
Assert.Equal(classStatement2, classDecl2.FindNode(nodeEndPositionSpan, findInsideTrivia:=False))
Assert.Equal(classStatement2, classDecl2.FindNode(nodeEndPositionSpan, findInsideTrivia:=True))
' End position of node
Assert.Throws(Of ArgumentOutOfRangeException)(Sub() classDecl.FindNode(nodeEndPositionSpan))
' Invalid spans.
Dim invalidSpan = New TextSpan(100, 100)
Assert.Throws(Of ArgumentOutOfRangeException)(Sub() root.FindNode(invalidSpan))
invalidSpan = New TextSpan(root.FullSpan.End - 1, 2)
Assert.Throws(Of ArgumentOutOfRangeException)(Sub() root.FindNode(invalidSpan))
invalidSpan = New TextSpan(classDecl2.FullSpan.Start - 1, root.FullSpan.End)
Assert.Throws(Of ArgumentOutOfRangeException)(Sub() classDecl2.FindNode(invalidSpan))
invalidSpan = New TextSpan(classDecl.FullSpan.End, root.FullSpan.End)
Assert.Throws(Of ArgumentOutOfRangeException)(Sub() classDecl2.FindNode(invalidSpan))
' Parent node's span.
Assert.Throws(Of ArgumentOutOfRangeException)(Sub() classDecl.FindNode(root.FullSpan))
End Sub
<Fact>
Public Sub TestFindTokenInLargeList()
Dim identifier = SyntaxFactory.Identifier("x")
Dim missingIdentifier = SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)
Dim name = SyntaxFactory.IdentifierName(identifier)
Dim missingName = SyntaxFactory.IdentifierName(missingIdentifier)
Dim comma = SyntaxFactory.Token(SyntaxKind.CommaToken)
Dim missingComma = SyntaxFactory.MissingToken(SyntaxKind.CommaToken)
Dim argument = SyntaxFactory.SimpleArgument(name)
Dim missingArgument = SyntaxFactory.SimpleArgument(missingName)
'' make a large list that has lots of zero-length nodes (that shouldn't be found)
Dim nodesAndTokens = SyntaxFactory.NodeOrTokenList(
missingArgument, missingComma,
missingArgument, missingComma,
missingArgument, missingComma,
missingArgument, missingComma,
missingArgument, missingComma,
missingArgument, missingComma,
missingArgument, missingComma,
missingArgument, missingComma,
argument)
Dim argumentList = SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(Of ArgumentSyntax)(SyntaxFactory.NodeOrTokenList(nodesAndTokens)))
Dim invocation = SyntaxFactory.InvocationExpression(name, argumentList)
CheckFindToken(invocation)
End Sub
Private Sub CheckFindToken(node As SyntaxNode)
For i As Integer = 1 To node.FullSpan.End - 1
Dim token = node.FindToken(i)
Assert.Equal(True, token.FullSpan.Contains(i))
Next
End Sub
<WorkItem(539940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539940")>
<Fact>
Public Sub TestFindTriviaNoTriviaExistsAtPosition()
Dim code = <code>Class Goo
Sub Bar()
End Sub
End Class</code>.Value
Dim tree = VisualBasicSyntaxTree.ParseText(code)
Dim position = tree.GetText().Lines(1).End
'position points to the end of the line that has "Sub Bar()"
'There should be end of line trivia there.
Dim trivia = tree.GetRoot().FindTrivia(position)
Assert.Equal(SyntaxKind.EndOfLineTrivia, trivia.Kind)
Assert.Equal(23, trivia.SpanStart)
Assert.Equal(24, trivia.Span.End)
End Sub
<Fact>
Public Sub TestChildNodes()
Dim text = "m(a,b,c)"
Dim expression = SyntaxFactory.ParseExpression(text)
Dim nodes = expression.ChildNodes().ToList()
Assert.Equal(2, nodes.Count)
Assert.Equal(SyntaxKind.IdentifierName, nodes(0).Kind)
Assert.Equal(SyntaxKind.ArgumentList, nodes(1).Kind)
End Sub
<Fact>
Public Sub TestAncestors()
Dim text = "a + (b - (c * (d / e)))"
Dim expression = SyntaxFactory.ParseExpression(text)
Dim e = expression.DescendantNodes().OfType(Of IdentifierNameSyntax)().First(Function(n) n.Identifier.ValueText = "e")
Dim nodes = e.Ancestors().ToList()
Assert.Equal(7, nodes.Count)
Assert.Equal(SyntaxKind.DivideExpression, nodes(0).Kind)
Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes(1).Kind)
Assert.Equal(SyntaxKind.MultiplyExpression, nodes(2).Kind)
Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes(3).Kind)
Assert.Equal(SyntaxKind.SubtractExpression, nodes(4).Kind)
Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes(5).Kind)
Assert.Equal(SyntaxKind.AddExpression, nodes(6).Kind)
End Sub
<Fact>
Public Sub TestAncestorsOrSelf()
Dim text = "a + (b - (c * (d / e)))"
Dim expression = SyntaxFactory.ParseExpression(text)
Dim e = expression.DescendantNodes().OfType(Of IdentifierNameSyntax)().First(Function(n) n.Identifier.ValueText = "e")
Dim nodes = e.AncestorsAndSelf().ToList()
Assert.Equal(8, nodes.Count)
Assert.Equal(SyntaxKind.IdentifierName, nodes(0).Kind)
Assert.Equal(SyntaxKind.DivideExpression, nodes(1).Kind)
Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes(2).Kind)
Assert.Equal(SyntaxKind.MultiplyExpression, nodes(3).Kind)
Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes(4).Kind)
Assert.Equal(SyntaxKind.SubtractExpression, nodes(5).Kind)
Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes(6).Kind)
Assert.Equal(SyntaxKind.AddExpression, nodes(7).Kind)
End Sub
<Fact>
Public Sub TestDescendantNodes()
Dim text = <![CDATA[
''' Goo
Return True
]]>.Value
Dim statement = SyntaxFactory.ParseExecutableStatement(text)
Dim nodes = statement.DescendantNodes().ToList()
Assert.Equal(1, nodes.Count)
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes(0).Kind)
nodes = statement.DescendantNodes(descendIntoTrivia:=True).ToList()
Assert.Equal(4, nodes.Count)
Assert.Equal(SyntaxKind.DocumentationCommentTrivia, nodes(0).Kind)
Assert.Equal(SyntaxKind.XmlText, nodes(1).Kind)
Assert.Equal(SyntaxKind.XmlText, nodes(2).Kind)
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes(3).Kind)
' again with spans
nodes = statement.DescendantNodes(statement.FullSpan).ToList()
Assert.Equal(1, nodes.Count)
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes(0).Kind)
nodes = statement.DescendantNodes(statement.FullSpan, descendIntoTrivia:=True).ToList()
Assert.Equal(4, nodes.Count)
Assert.Equal(SyntaxKind.DocumentationCommentTrivia, nodes(0).Kind)
Assert.Equal(SyntaxKind.XmlText, nodes(1).Kind)
Assert.Equal(SyntaxKind.XmlText, nodes(2).Kind)
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes(3).Kind)
End Sub
<Fact>
Public Sub TestDescendantNodesOrSelf()
Dim text = <![CDATA[
''' Goo
Return True
]]>.Value
Dim statement = SyntaxFactory.ParseExecutableStatement(text)
Dim nodes = statement.DescendantNodesAndSelf().ToList()
Assert.Equal(2, nodes.Count)
Assert.Equal(SyntaxKind.ReturnStatement, nodes(0).Kind)
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes(1).Kind)
nodes = statement.DescendantNodesAndSelf(descendIntoTrivia:=True).ToList()
Assert.Equal(5, nodes.Count)
Assert.Equal(SyntaxKind.ReturnStatement, nodes(0).Kind)
Assert.Equal(SyntaxKind.DocumentationCommentTrivia, nodes(1).Kind)
Assert.Equal(SyntaxKind.XmlText, nodes(2).Kind)
Assert.Equal(SyntaxKind.XmlText, nodes(3).Kind)
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes(4).Kind)
' again with spans
nodes = statement.DescendantNodesAndSelf(statement.FullSpan).ToList()
Assert.Equal(2, nodes.Count)
Assert.Equal(SyntaxKind.ReturnStatement, nodes(0).Kind)
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes(1).Kind)
nodes = statement.DescendantNodesAndSelf(statement.FullSpan, descendIntoTrivia:=True).ToList()
Assert.Equal(5, nodes.Count)
Assert.Equal(SyntaxKind.ReturnStatement, nodes(0).Kind)
Assert.Equal(SyntaxKind.DocumentationCommentTrivia, nodes(1).Kind)
Assert.Equal(SyntaxKind.XmlText, nodes(2).Kind)
Assert.Equal(SyntaxKind.XmlText, nodes(3).Kind)
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes(4).Kind)
End Sub
<Fact, WorkItem(530316, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530316")>
Public Sub TestDescendantTrivia()
Dim text = <![CDATA[' Goo
a + b
]]>.Value
Dim expr = SyntaxFactory.ParseExpression(text)
Dim list = expr.DescendantTrivia().ToList()
Assert.Equal(6, list.Count)
Assert.Equal(SyntaxKind.CommentTrivia, list(0).Kind)
Assert.Equal(SyntaxKind.EndOfLineTrivia, list(1).Kind)
Assert.Equal(SyntaxKind.WhitespaceTrivia, list(2).Kind)
Assert.Equal(SyntaxKind.WhitespaceTrivia, list(3).Kind)
End Sub
<Fact, WorkItem(530316, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530316")>
Public Sub TestDescendantTriviaIntoStructuredTrivia()
Dim text = <![CDATA[
''' <goo >
''' </goo>
a + b
]]>.Value
Dim expr = SyntaxFactory.ParseExpression(text)
Dim list = expr.DescendantTrivia(descendIntoTrivia:=True).ToList()
Assert.Equal(9, list.Count)
Assert.Equal(SyntaxKind.EndOfLineTrivia, list(0).Kind)
Assert.Equal(SyntaxKind.DocumentationCommentTrivia, list(1).Kind)
Assert.Equal(SyntaxKind.DocumentationCommentExteriorTrivia, list(2).Kind)
Assert.Equal(SyntaxKind.WhitespaceTrivia, list(3).Kind)
Assert.Equal(SyntaxKind.DocumentationCommentExteriorTrivia, list(4).Kind)
Assert.Equal(SyntaxKind.WhitespaceTrivia, list(5).Kind)
Assert.Equal(SyntaxKind.WhitespaceTrivia, list(6).Kind)
End Sub
<Fact>
Public Sub SyntaxNodeToString()
Dim text = "Imports System"
Dim root = SyntaxFactory.ParseCompilationUnit(text)
Dim children = root.DescendantNodesAndTokens()
Dim nodeOrToken = children.First()
'Assert.Equal("SyntaxNodeOrToken ImportsStatement Imports System", nodeOrToken.DebuggerDisplay)
Assert.Equal(text, nodeOrToken.ToString())
Dim node = children.First(Function(n) n.IsNode).AsNode()
'Assert.Equal("ImportsStatementSyntax ImportsStatement Imports System", node.DebuggerDisplay)
Assert.Equal(text, node.ToString())
Dim token = children.First(Function(n) n.IsToken).AsToken()
'Assert.Equal("SyntaxToken ImportsKeyword Imports", token.DebuggerDisplay)
Assert.Equal("Imports ", token.ToFullString())
Assert.Equal("Imports", token.ToString())
Dim trivia = root.DescendantTrivia().First()
'Assert.Equal("SyntaxTrivia WhitespaceTrivia ", trivia.DebuggerDisplay)
Assert.Equal(" ", trivia.ToFullString())
End Sub
<Fact>
Public Sub TestRemoveNodeInSeparatedList_KeepExteriorTrivia()
Dim expr = SyntaxFactory.ParseExpression("m(a, b, c)")
Dim b = expr.DescendantTokens().Where(Function(t) t.ToString() = "b").Select(Function(t) t.Parent.FirstAncestorOrSelf(Of ArgumentSyntax)()).FirstOrDefault()
Assert.NotNull(b)
Dim expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia)
Dim text = expr2.ToFullString()
Assert.Equal("m(a , c)", text)
End Sub
<Fact>
Public Sub TestRemoveNodeInSeparatedList_KeepNoTrivia()
Dim expr = SyntaxFactory.ParseExpression("m(a, b, c)")
Dim b = expr.DescendantTokens().Where(Function(t) t.ToString() = "b").Select(Function(t) t.Parent.FirstAncestorOrSelf(Of ArgumentSyntax)()).FirstOrDefault()
Assert.NotNull(b)
Dim expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia)
Dim text = expr2.ToFullString()
Assert.Equal("m(a, c)", text)
End Sub
<Fact>
Public Sub TestRemoveOnlyNodeInSeparatedList_KeepExteriorTrivia()
Dim expr = SyntaxFactory.ParseExpression("m( a )")
Dim n = expr.DescendantTokens().Where(Function(t) t.ToString() = "a").Select(Function(t) t.Parent.FirstAncestorOrSelf(Of ArgumentSyntax)()).FirstOrDefault()
Assert.NotNull(n)
Dim expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia)
Dim text = expr2.ToFullString()
Assert.Equal("m( )", text)
End Sub
<Fact>
Public Sub TestRemoveFirstNodeInSeparatedList_KeepExteriorTrivia()
Dim expr = SyntaxFactory.ParseExpression("m( a , b, c)")
Dim n = expr.DescendantTokens().Where(Function(t) t.ToString() = "a").Select(Function(t) t.Parent.FirstAncestorOrSelf(Of ArgumentSyntax)()).FirstOrDefault()
Assert.NotNull(n)
Dim expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia)
Dim text = expr2.ToFullString()
Assert.Equal("m( b, c)", text)
End Sub
<Fact>
Public Sub TestRemoveLastNodeInSeparatedList_KeepExteriorTrivia()
Dim expr = SyntaxFactory.ParseExpression("m(a, b , c )")
Dim n = expr.DescendantTokens().Where(Function(t) t.ToString() = "c").Select(Function(t) t.Parent.FirstAncestorOrSelf(Of ArgumentSyntax)()).FirstOrDefault()
Assert.NotNull(n)
Dim expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia)
Dim text = expr2.ToFullString()
Assert.Equal("m(a, b )", text)
End Sub
<Fact>
Public Sub TestRemoveFirstNodeInList_KeepExteriorTrivia()
Dim text = <![CDATA[
<A> <B> <C>
Class Goo
End Class
]]>.Value.Replace(vbLf, vbCrLf)
Dim expected = <![CDATA[
<B> <C>
Class Goo
End Class
]]>.Value.Replace(vbLf, vbCrLf)
Dim cu = SyntaxFactory.ParseCompilationUnit(text)
Dim n = cu.DescendantTokens().Where(Function(t) t.ToString() = "A").Select(Function(t) t.Parent.FirstAncestorOrSelf(Of AttributeListSyntax)()).FirstOrDefault()
Dim cu2 = cu.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia)
Dim result = cu2.ToFullString()
Assert.Equal(expected, result)
End Sub
<Fact>
Public Sub TestRemoveLastNodeInList_KeepExteriorTrivia()
Dim text = <![CDATA[
<A> <B> <C>
Class Goo
End Class
]]>.Value.Replace(vbLf, vbCrLf)
Dim expected = <![CDATA[
<A> <B>
Class Goo
End Class
]]>.Value.Replace(vbLf, vbCrLf)
Dim cu = SyntaxFactory.ParseCompilationUnit(text)
Dim n = cu.DescendantTokens().Where(Function(t) t.ToString() = "C").Select(Function(t) t.Parent.FirstAncestorOrSelf(Of AttributeListSyntax)()).FirstOrDefault()
Dim cu2 = cu.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia)
Dim result = cu2.ToFullString()
Assert.Equal(expected, result)
End Sub
<Fact>
Public Sub TestMiddleLastNodeInList_KeepExteriorTrivia()
Dim text = <![CDATA[
<A> <B> <C>
Class Goo
End Class
]]>.Value.Replace(vbLf, vbCrLf)
Dim expected = <![CDATA[
<A> <C>
Class Goo
End Class
]]>.Value.Replace(vbLf, vbCrLf)
Dim cu = SyntaxFactory.ParseCompilationUnit(text)
Dim n = cu.DescendantTokens().Where(Function(t) t.ToString() = "B").Select(Function(t) t.Parent.FirstAncestorOrSelf(Of AttributeListSyntax)()).FirstOrDefault()
Dim cu2 = cu.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia)
Dim result = cu2.ToFullString()
Assert.Equal(expected, result)
End Sub
<Fact>
Public Sub TestRemove_KeepUnbalancedDirectives()
Dim text = <![CDATA[
#If True
Class Goo
End Class
Class Bar
End Class
#End If
]]>.Value.Replace(vbLf, vbCrLf)
Dim expected = <![CDATA[
#If True
Class Bar
End Class
#End If
]]>.Value.Replace(vbLf, vbCrLf)
Dim cu = SyntaxFactory.ParseCompilationUnit(text)
Dim n = cu.DescendantTokens().Where(Function(t) t.ToString() = "Goo").Select(Function(t) t.Parent.FirstAncestorOrSelf(Of ClassBlockSyntax)()).FirstOrDefault()
Dim cu2 = cu.RemoveNode(n, SyntaxRemoveOptions.KeepUnbalancedDirectives)
Dim result = cu2.ToFullString()
Assert.Equal(expected, result)
End Sub
<Fact, WorkItem(530316, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530316")>
Public Sub TestRemove_KeepExternalTrivia_KeepUnbalancedDirectives()
Dim text = <![CDATA[
#If True
Class Goo
#If True
End Class
Class Bar
#End If
End Class
#End If
]]>.Value.Replace(vbLf, vbCrLf)
Dim expected = <![CDATA[
#If True
#If True
Class Bar
#End If
End Class
#End If
]]>.Value.Replace(vbLf, vbCrLf)
Dim cu = SyntaxFactory.ParseCompilationUnit(text)
Dim n = cu.DescendantTokens().Where(Function(t) t.ToString() = "Goo").Select(Function(t) t.Parent.FirstAncestorOrSelf(Of ClassBlockSyntax)()).FirstOrDefault()
Dim cu2 = cu.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia Or SyntaxRemoveOptions.KeepUnbalancedDirectives)
Dim result = cu2.ToFullString()
Assert.Equal(expected, result)
End Sub
<Fact>
Public Sub TestRemove_KeepDirectives()
Dim text = <![CDATA[
#If True
Class Goo
#If True
#Region "A Region"
#End Region
End Class
Class Bar
#End If
End Class
#End If
]]>.Value.Replace(vbLf, vbCrLf)
Dim expected = <![CDATA[
#If True
#If True
#Region "A Region"
#End Region
Class Bar
#End If
End Class
#End If
]]>.Value.Replace(vbLf, vbCrLf)
Dim cu = SyntaxFactory.ParseCompilationUnit(text)
Dim n = cu.DescendantTokens().Where(Function(t) t.ToString() = "Goo").Select(Function(t) t.Parent.FirstAncestorOrSelf(Of ClassBlockSyntax)()).FirstOrDefault()
Dim cu2 = cu.RemoveNode(n, SyntaxRemoveOptions.KeepDirectives)
Dim result = cu2.ToFullString()
Assert.Equal(expected, result)
End Sub
<Fact>
Public Sub Test_SyntaxTree_ParseTextInvalid()
Dim treeFromSourceWithPath_valid1 = VisualBasicSyntaxTree.ParseText("", path:=Nothing)
Assert.Throws(Of ArgumentNullException)(Sub()
Dim st As SourceText = Nothing
Dim treeFromSource_invalid = VisualBasicSyntaxTree.ParseText(st)
End Sub)
End Sub
<Fact>
Public Sub TestSyntaxTree_GetChangesValid()
' Added for coverage on GetChanges and SyntaxDiffer
Dim SourceText = <String>
Imports System
Imports Microsoft.VisualBasic
Imports System.Collections
Module Module1
Sub Main
Dim a as Integer = 1
Console.Writeline(a)
End Sub
End Module
</String>
Dim tree = VisualBasicSyntaxTree.ParseText(SourceText.ToString)
Dim Root As CompilationUnitSyntax = CType(tree.GetRoot(), CompilationUnitSyntax)
'Get the Imports Clauses
Dim FirstImportsClause As ImportsStatementSyntax = Root.Imports(0)
Dim SecondImportsClause As ImportsStatementSyntax = Root.Imports(1)
Dim ThirdImportsClause As ImportsStatementSyntax = Root.Imports(2)
Dim ChangesForDifferentTrees = FirstImportsClause.SyntaxTree.GetChanges(SecondImportsClause.SyntaxTree)
Assert.Equal(0, ChangesForDifferentTrees.Count)
'Do a transform to Replace and Existing Tree
Dim name As NameSyntax = SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("System"), SyntaxFactory.IdentifierName("Collections.Generic"))
Dim oldImportClause As SimpleImportsClauseSyntax = CType(ThirdImportsClause.ImportsClauses(0), SimpleImportsClauseSyntax)
Dim newImportsClause = oldImportClause.WithName(name)
'Replace Node with a different Imports Clause
Root = Root.ReplaceNode(oldImportClause, newImportsClause)
Dim ChangesFromTransform = ThirdImportsClause.SyntaxTree.GetChanges(newImportsClause.SyntaxTree)
Assert.Equal(1, ChangesFromTransform.Count)
'Using the Common Syntax Changes Method as well for coverage
Dim x As SyntaxTree = ThirdImportsClause.SyntaxTree
Dim y As SyntaxTree = newImportsClause.SyntaxTree
Dim changes2UsingCommonSyntax = x.GetChanges(y)
Assert.Equal(1, changes2UsingCommonSyntax.Count)
'Verify Changes from VB Specific SyntaxTree and Common SyntaxTree are the same
Assert.Equal(ChangesFromTransform, changes2UsingCommonSyntax)
End Sub
<Fact, WorkItem(658329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658329")>
Public Sub TestSyntaxTree_GetChangesInValid()
'GetChanges with two Scenarios where either new or old tree is nothing
Dim SourceText = <String>
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub Main
End Sub
End Module
</String>
Dim tree = VisualBasicSyntaxTree.ParseText(SourceText.ToString)
Dim Root As CompilationUnitSyntax = CType(tree.GetRoot(), CompilationUnitSyntax)
Dim FirstImportsClause As ImportsStatementSyntax = Root.Imports(0)
Dim BlankTree As SyntaxTree = Nothing
Assert.Throws(Of ArgumentNullException)(Sub() FirstImportsClause.SyntaxTree.GetChanges(BlankTree))
End Sub
<Fact, WorkItem(658329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658329")>
Public Sub TestSyntaxTree_GetChangeSpans()
Dim oldTree = VisualBasicSyntaxTree.ParseText("class A : End Class")
Dim newTree = oldTree.WithInsertAt(0, "class B : End Class")
' Valid operations
Dim spans = newTree.GetChangedSpans(oldTree)
Assert.Equal(1, spans.Count)
'Test Overload with CommonSyntaxTree
Dim span2 = CType(newTree, SyntaxTree).GetChangedSpans(CType(oldTree, SyntaxTree))
Assert.Equal(1, spans.Count)
Assert.Equal(spans(0), span2(0)) ' Ensure Both spans from overloads returns same
' Invalid operations with a null tree
Dim BlankTree As SyntaxTree = Nothing
Assert.Throws(Of ArgumentNullException)(Sub() newTree.GetChangedSpans(BlankTree))
End Sub
<Fact>
Public Sub TestSyntaxList_Failures()
'Validate the exceptions being generated when Invalid arguments are used for a TextSpan Constructor
Dim SourceText = <String>
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub Main
End Sub
End Module
</String>
'Construct a SyntaxList and verify the bounds exceptions
Dim tree = VisualBasicSyntaxTree.ParseText(SourceText.ToString)
Dim x As New SyntaxList(Of SyntaxNode)
For Each node In tree.GetRoot.ChildNodes
x = x.Add(node)
Next
Assert.Equal(4, x.Count)
Assert.Throws(Of ArgumentOutOfRangeException)(Sub()
Dim value1 = x(-1)
End Sub)
Assert.Throws(Of ArgumentOutOfRangeException)(Sub()
Dim value1 = x(20)
End Sub)
End Sub
<Fact>
Public Sub Test_CConst_CreateWithTypeCharacters()
'Added for Code Coverage
Dim compilationDef =
<compilation name="CConst.vb">
<file name="a.vb">
Imports System
#Const char_a = "c"c
#Const single_a = 1.2!
#Const Date_a = #1/1/2000#
Public Module Module1
#If char_a = "c"c Then
Public Value_char As Boolean = True
#Else
Public Value_char As Boolean = False
#End If
#If Single_a = 1.2! Then
Public Value_single As Boolean = True
#Else
Public Value_single As Boolean = False
#End If
#If Date_a = #1/1/2000# Then
Public Value_Date As Boolean = True
#Else
Public Value_Date As Boolean = False
#End If
Sub main()
Console.WriteLine(Value_char)
Console.WriteLine(Value_single)
Console.WriteLine(Value_Date)
End Sub
End Module </file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef)
compilation.VerifyDiagnostics()
End Sub
<Fact>
Public Sub Test_UnaryOperators()
Dim compilationDef =
<compilation name="CConst.vb">
<file name="a.vb">
'Type Types
#If -1S Then
'Short
#End If
#If -1% Then
'Integer
#End If
#If -1@ Then
'Decimal
#End If
#If -1.0! Then
'Single
#End If
#If -1.0# Then
'Double
#End If
'Forced Literal Types
#If -1S Then
'Short
#End If
#If -1I Then
'Integer
#End If
#If -1L Then
'Long
#End If
#If -1.0F Then
'Single
#End If
#If -1D Then
'Double
#End If
#If -1UI Then
'unsigned Integer
#End If
#If -1UL Then
'unsigned Long
#End If
'Type Types
#If +1S Then
'Short
#End If
#If +1% Then
'Integer
#End If
#If +1@ Then
'Decimal
#End If
#If +1.0! Then
'Single
#End If
#If +1.0# Then
'Double
#End If
'Forced Literal Types
#If +1S Then
'Short
#End If
#If +1I Then
'Integer
#End If
#If +1L Then
'Long
#End If
#If +1.0F Then
'Single
#End If
#If +1D Then
'Double
#End If
#If +1UI Then
'unsigned Integer
#End If
#If +1UL Then
'unsigned Long
#End If
'Type Types
#If Not 1S Then
'Short
#End If
#If Not 1% Then
'Integer
#End If
#If Not 1@ Then
'Decimal
#End If
#If Not 1.0! Then
'Single
#End If
#If Not 1.0# Then
'Double
#End If
'Forced Literal Types
#If Not 1S Then
'Short
#End If
#If Not 1I Then
'Integer
#End If
#If Not 1L Then
'Long
#End If
#If Not 1.0F Then
'Single
#End If
#If Not 1D Then
'Double
#End If
#If Not 1UI Then
'unsigned Integer
#End If
#If Not 1UL Then
'unsigned Long
#End If
Module Module1
Sub main()
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef)
compilation.VerifyDiagnostics()
End Sub
<Fact>
<WorkItem(111538, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems?_a=edit&id=111538")>
<WorkItem(658398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems?_a=edit&id=658398")>
Public Sub Test_UnaryOperatorsInvalid()
'Added for Code Coverage
Dim compilationDef =
<compilation name="CConst.vb">
<file name="a.vb">
Imports System
Imports Microsoft.VisualBasic
#If -"1"c Then
#End If
#If +"1" Then
#End If
#If +" "c Then
#End If
#If +"test"$ Then
#End If
#If Not " "c Then
#End If
#If NOT "test"$ Then
#End If
#If - Then
#End If
#If + Then
#End If
#If NOT Then
#End If
Module Module1
Sub main()
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef)
compilation.AssertTheseDiagnostics(
<expected>
BC30487: Operator '-' is not defined for type 'Char'.
#If -"1"c Then
~~~~~~~~~~~~~~
BC30487: Operator '+' is not defined for type 'String'.
#If +"1" Then
~~~~~~~~~~~~~
BC30487: Operator '+' is not defined for type 'Char'.
#If +" "c Then
~~~~~~~~~~~~~~
BC30037: Character is not valid.
#If +"test"$ Then
~
BC30205: End of statement expected.
#If +"test"$ Then
~
BC30487: Operator 'Not' is not defined for type 'Char'.
#If Not " "c Then
~~~~~~~~~~~~~~~~~
BC30037: Character is not valid.
#If NOT "test"$ Then
~
BC30205: End of statement expected.
#If NOT "test"$ Then
~
BC31427: Syntax error in conditional compilation expression.
#If - Then
~~~~
BC31427: Syntax error in conditional compilation expression.
#If + Then
~~~~
BC31427: Syntax error in conditional compilation expression.
#If NOT Then
~~~~
</expected>)
End Sub
<Fact>
Public Sub TestInvalidModuleScenario_AddingTreesWithImplementsAndInherits()
'Verifies we can hit the inheritable and implements slots on module blocks through usage of the AddInherits/AddImplements methods in the ModuleBlockSyntax.
' Although Modules do not support inheritance or Implements
Dim SourceText = <String>
Module Module1
Sub Main
End Sub
End Module
Module Module2
End Module
Module Module3
End Module
Interface IGoo
End Interface
</String>
Dim text = SourceText.Value
'Construct a SyntaxList and verify the bounds exceptions
Dim tree = VisualBasicSyntaxTree.ParseText(text)
Dim Root As CompilationUnitSyntax = CType(tree.GetRoot(), CompilationUnitSyntax)
'We want to insert a Implements clause or Implements into Modules
Dim Module1 = CType(Root.Members(0), ModuleBlockSyntax)
Dim Module2 = CType(Root.Members(1), ModuleBlockSyntax)
Dim Module3 = CType(Root.Members(2), ModuleBlockSyntax)
Assert.Equal(0, Root.GetDiagnostics().Count)
Dim bldr = SeparatedSyntaxListBuilder(Of TypeSyntax).Create()
bldr.Add(CreateSimpleTypeName("aaa"))
Dim sepList = bldr.ToList
Dim statement = SyntaxFactory.InheritsStatement(SyntaxFactory.Token(SyntaxKind.InheritsKeyword, trailing:=_spaceTrivia), sepList)
Module2 = Module2.AddInherits(statement)
Root = Root.ReplaceNode(Root.Members(1), Module2)
Assert.Equal(0, Root.GetDiagnostics().Count)
Dim bldr2 = SeparatedSyntaxListBuilder(Of TypeSyntax).Create()
bldr2.Add(CreateSimpleTypeName("Ifoo"))
Dim sepList2 = bldr2.ToList
Dim statement2 = SyntaxFactory.ImplementsStatement(SyntaxFactory.Token(SyntaxKind.ImplementsKeyword, trailing:=_spaceTrivia), sepList2)
Module3 = Module3.AddImplements(statement2)
Root = Root.ReplaceNode(Root.Members(2), Module3)
Assert.Equal(0, Root.GetDiagnostics().Count) ' No updated diagnostics until the re-parsing
'//Verify the syntax Tree contains strings
Assert.True(Root.ToFullString.Contains("Inherits aaa"))
Assert.True(Root.ToFullString.Contains("Implements Ifoo"))
Dim compilationDef =
<compilation name="Test">
<file name="a.vb">
<%= Root.ToFullString %>
</file>
</compilation>
'Verify Compile Errors when try to use
Dim c = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(
compilationDef,
New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Custom))
c.VerifyDiagnostics(
Diagnostic(ERRID.ERR_ModuleCantInherit, "Inherits aaa"),
Diagnostic(ERRID.ERR_ModuleCantImplement, "Implements Ifoo"))
End Sub
<Fact>
Public Sub TestSyntaxNode_GetDirectivesMultiplePresent()
Dim SourceText = <String>
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub Main
End Sub
End Module
#if True then
Module Module2
End Module
#End If
#if False then
Module Module3
End Module
#End IF
</String>
Dim text = SourceText.Value
Dim tree = VisualBasicSyntaxTree.ParseText(text)
Dim Root As CompilationUnitSyntax = CType(tree.GetRoot(), CompilationUnitSyntax)
Dim x = Root.GetDirectives()
Assert.Equal(4, x.Count)
Assert.Equal("#if True then", x(0).GetText.ToString.TrimEnd)
Assert.Equal("Microsoft.CodeAnalysis.VisualBasic.Syntax.IfDirectiveTriviaSyntax", x(0).GetType.ToString)
End Sub
<Fact>
Public Sub TestSyntaxNode_GetDirectivesNonePresent()
Dim SourceText = <String>
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub Main
End Sub
End Module
Module Module2
End Module
Module Module3
End Module
</String>
Dim text = SourceText.Value
Dim tree = VisualBasicSyntaxTree.ParseText(text)
Dim Root As CompilationUnitSyntax = CType(tree.GetRoot(), CompilationUnitSyntax)
Dim x = Root.GetDirectives()
Assert.Equal(0, x.Count)
End Sub
<Fact>
Public Sub TestSyntaxNode_GetDirectivesIncorrectUnbalanced()
Dim SourceText = <String>
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub Main
End Sub
End Module
#if True then
Module Module2
End Module
Module Module3
End Module
</String>
Dim text = SourceText.Value
Dim tree = VisualBasicSyntaxTree.ParseText(text)
Dim Root As CompilationUnitSyntax = CType(tree.GetRoot(), CompilationUnitSyntax)
Dim x = Root.GetDirectives()
Assert.Equal(1, x.Count)
End Sub
<WorkItem(6536, "https://github.com/dotnet/roslyn/issues/6536")>
<Fact>
Public Sub TestFindTrivia_NoStackOverflowOnLargeExpression()
Dim code As New StringBuilder()
code.Append(<![CDATA[
Module Module1
Sub Test()
Dim c = ]]>.Value)
For i = 0 To 3000
code.Append("""asdf"" + ")
Next
code.AppendLine(<![CDATA["last"
End Sub
End Module]]>.Value)
Dim tree = VisualBasicSyntaxTree.ParseText(code.ToString())
Dim trivia = tree.GetRoot().FindTrivia(4000)
' no stack overflow
End Sub
#Region "Equality Verifications"
<Fact>
Public Sub Test_GlobalImportsEqual()
Dim SourceText = <String>
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub Main
End Sub
End Module
#if True then
Module Module2
End Module
Module Module3
End Module
</String>
Dim text = SourceText.Value
Dim tree = VisualBasicSyntaxTree.ParseText(text)
Dim Root As CompilationUnitSyntax = CType(tree.GetRoot(), CompilationUnitSyntax)
Dim x = Root.GetDirectives()
Assert.Equal(1, x.Count)
End Sub
<Fact>
Public Sub Test_GlobalImports_Equals()
Dim SourceText = <String>
Imports System
Module Module1
Sub Main
Dim a as Integer = 1
Console.Writeline(a)
End Sub
End Module
</String>
Dim tree = VisualBasicSyntaxTree.ParseText(SourceText.ToString)
Dim Root As CompilationUnitSyntax = CType(tree.GetRoot(), CompilationUnitSyntax)
Dim FirstImportsClause As ImportsStatementSyntax = Root.Imports(0)
Dim Obj1 As New GlobalImport(FirstImportsClause.ImportsClauses(0), "ttt")
Dim Obj2 As New GlobalImport(FirstImportsClause.ImportsClauses(0), "uuu")
Dim obj3 As GlobalImport = Obj1
Assert.Equal(Obj1, obj3)
Assert.NotEqual(Obj1, Obj2)
If Obj1 = Obj2 Then
Assert.True(False, "GlobalImports equal Failure")
End If
If Obj1 <> obj3 Then
Assert.True(False, "GlobalImports Not equal Failure")
End If
End Sub
<Fact>
Public Sub Test_CompilationOptions_Equals()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="GetSemanticInfo">
<file name="allon.vb">
Option Strict On
Option Infer On
Option Explicit On
Option Compare Text
</file>
</compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom).WithOptionInfer(False).WithOptionExplicit(True).WithOptionCompareText(False))
Dim compilation2 = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="GetSemanticInfo">
<file name="allon.vb">
Option Strict On
Option Infer On
Option Explicit On
Option Compare Text
</file>
</compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom).WithOptionInfer(False).WithOptionExplicit(False).WithOptionCompareText(False))
Dim Compilation3 = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="GetSemanticInfo">
<file name="allon.vb">
Option Strict On
Option Infer On
Option Explicit On
Option Compare Text
</file>
</compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom).WithOptionInfer(False).WithOptionExplicit(True).WithOptionCompareText(False))
Dim vbpo1 = compilation.Options
Dim vbpo2 = compilation2.Options
Dim vbpo3 = Compilation3.Options
Assert.Equal(vbpo1, vbpo1)
Assert.Equal(vbpo1, vbpo3)
Assert.NotEqual(vbpo1, vbpo2)
Dim Objvbpo1 As Object = vbpo3
Assert.Equal(vbpo1, Objvbpo1)
Dim compilation4 = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="CompileOptions">
<file name="allon.vb">
Option Strict Off
Module Module1
Sub Main
End Sub
End Module
</file>
</compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom).WithOptionInfer(False).WithOptionExplicit(True).WithOptionCompareText(False))
vbpo1 = compilation4.Options
Dim ObjCommonCompilationOptions As CompilationOptions = vbpo1
Dim RetValue = ObjCommonCompilationOptions.Equals(ObjectDisplay.NullLiteral)
Assert.False(RetValue)
End Sub
<Fact>
Public Sub Test_ParseOptions_Equals()
Dim po1 = New VisualBasicParseOptions(languageVersion:=LanguageVersion.VisualBasic10)
Dim po2 = New VisualBasicParseOptions(languageVersion:=LanguageVersion.VisualBasic9)
Dim po3 = New VisualBasicParseOptions(languageVersion:=LanguageVersion.VisualBasic10)
Dim POcompilation1 = CompilationUtils.CreateCompilationWithMscorlib(
<compilation name="Compile1">
<file name="a.vb"><![CDATA[
Imports System
Module Module1
Sub Main
End Sub
End Module
]]></file>
</compilation>, parseOptions:=po1)
Assert.Equal(po1, po1)
Assert.Equal(po1, po3)
Assert.NotEqual(po1, po2)
Dim Objpo1 As Object = po3
Assert.Equal(po1, Objpo1)
End Sub
#End Region
#Region "SyntaxWalker Verification Tests For Specific Node Types"
<Fact>
Public Sub SyntaxWalkerMethod_VerifyGroupByClause()
Dim Compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="LinqQueryGroupBy">
<file name="Test.vb">
Module Module1
Sub main()
Dim words = New String() {"blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese"}
Dim wordGroups = From w In words _
Group w By Key = w(0) Into Group _
Select FirstLetter = Key, WordGroup = Group
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees(0)
Dim root = tree.GetCompilationUnitRoot()
Dim collector = New SyntaxWalkerVerifier()
collector.Visit(root)
Assert.Equal(1, collector.GetCount(SyntaxKind.GroupByClause.ToString))
End Sub
<Fact>
Public Sub SyntaxWalkerMethod_VerifyCatchFilterClause()
Dim Compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="SyntaxWalkerTestTypes">
<file name="Test.vb">
Module Module1
Sub Main()
Try
Catch ex As Exception When TypeOf (ex) Is ArgumentException
Catch ex As Exception
End Try
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees(0)
Dim root = tree.GetCompilationUnitRoot()
Dim collector = New SyntaxWalkerVerifier()
collector.Visit(root)
Assert.Equal(1, collector.GetCount(SyntaxKind.CatchFilterClause.ToString))
End Sub
<Fact>
Public Sub SyntaxWalkerMethod_VerifyDistinctClause()
Dim Compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="SyntaxWalkerTestTypes">
<file name="Test.vb">
Module Module1
Sub Main()
Dim q = From c In {1, 2, 3, 4, 5, 3, 2}
Select c Distinct
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees(0)
Dim root = tree.GetCompilationUnitRoot()
Dim collector = New SyntaxWalkerVerifier()
collector.Visit(root)
Assert.Equal(1, collector.GetCount(SyntaxKind.DistinctClause.ToString))
End Sub
<Fact>
Public Sub SyntaxWalkerMethod_VerifyCaseRange()
Dim Compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="SyntaxWalkerTestTypes">
<file name="Test.vb">
Module Module1
Sub Main()
Dim number As Integer = 8
Select Case number
Case 1 To 5
Case Else
End Select
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees(0)
Dim root = tree.GetCompilationUnitRoot()
Dim collector = New SyntaxWalkerVerifier()
collector.Visit(root)
Assert.Equal(1, collector.GetCount(SyntaxKind.RangeCaseClause.ToString))
End Sub
<Fact>
Public Sub SyntaxWalkerMethod_VerifyHandlesClause()
Dim Compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="SyntaxWalkerTestTypes">
<file name="Test.vb">
Imports System
Public Class ContainerClass
' Module or class level declaration.
WithEvents Obj As New Class1
Public Class Class1
' Declare an event.
Public Event Ev_Event()
Sub CauseSomeEvent()
' Raise an event.
RaiseEvent Ev_Event()
End Sub
End Class
Sub EventHandler() Handles Obj.Ev_Event
' Handle the event.
End Sub
' Call the TestEvents procedure from an instance of the ContainerClass
' class to test the Ev_Event event and the event handler.
Public Sub TestEvents()
Obj.CauseSomeEvent()
End Sub
End Class
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees(0)
Dim root = tree.GetCompilationUnitRoot()
Dim collector = New SyntaxWalkerVerifier()
collector.Visit(root)
Assert.Equal(1, collector.GetCount(SyntaxKind.HandlesClause.ToString))
Assert.Equal(1, collector.GetCount(SyntaxKind.HandlesClauseItem.ToString))
Assert.Equal(1, collector.GetCount(SyntaxKind.WithEventsEventContainer.ToString))
End Sub
<Fact>
Public Sub SyntaxWalkerMethod_VerifyKeywordEventContainerSyntax()
Dim Compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="SyntaxWalkerTestTypes">
<file name="Test.vb">
Imports System
Module Module1
Sub Main()
End Sub
End Module
Class ContainerClass
WithEvents obj As New Class1
Public Class Class1
Public Event ev_events()
Public Sub causeEvent()
RaiseEvent ev_events()
End Sub
Sub EventHandlerInClass1() Handles Me.ev_events
End Sub
End Class
End Class
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees(0)
Dim root = tree.GetCompilationUnitRoot()
Dim collector = New SyntaxWalkerVerifier()
collector.Visit(root)
Assert.Equal(1, collector.GetCount(SyntaxKind.KeywordEventContainer.ToString))
End Sub
<Fact>
Public Sub SyntaxWalkerMethod_VerifyOmittedArgument()
Dim Compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="SyntaxWalkerTestTypes">
<file name="Test.vb">
Imports System
Module Module1
Sub Main()
goo(1, , 2)
End Sub
Sub goo(x As Integer, Optional y As Integer = 2, Optional z As Integer = 2)
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees(0)
Dim root = tree.GetCompilationUnitRoot()
Dim collector = New SyntaxWalkerVerifier()
collector.Visit(root)
Assert.Equal(1, collector.GetCount(SyntaxKind.OmittedArgument.ToString))
End Sub
<Fact>
Public Sub SyntaxWalkerMethod_VerifyMidExpressionClause()
Dim Compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="SyntaxWalkerTestTypes">
<file name="Test.vb">
Module Module1
Sub Main()
Dim s As String = "abcdef"
Mid(s, 2, 1) = "Z"
Dim s2 As String = ""
s2 = Mid(s, 2, 1)
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees(0)
Dim root = tree.GetCompilationUnitRoot()
Dim collector = New SyntaxWalkerVerifier()
collector.Visit(root)
Assert.Equal(1, collector.GetCount(SyntaxKind.MidExpression.ToString))
End Sub
<Fact>
Public Sub SyntaxWalkerMethod_VerifyAggregateClause()
Dim Compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="SyntaxWalkerTestTypes">
<file name="Test.vb">
Module Module1
Sub main()
Dim words() = {"cherry", "apple", "blueberry", "cherry"}
Dim ag1 = aggregate w in words
where w = "cherry"
into count
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees(0)
Dim root = tree.GetCompilationUnitRoot()
Dim collector = New SyntaxWalkerVerifier()
collector.Visit(root)
Assert.Equal(1, collector.GetCount(SyntaxKind.AggregateClause.ToString))
End Sub
<Fact>
Public Sub SyntaxWalkerMethod_VerifyDirectives()
Dim Compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="SyntaxWalkerTestTypes">
<file name="Test.vb">
Imports System
Imports System.Collections.Generic
Imports System.Linq
#ExternalChecksum ("Test.vb", "{12345678-1234-1234-1234-123456789abc}", "1a2b3c4e5f617239a49b9a9c0391849d34950f923fab9484")
Module Program
#Const a = 1
Sub Main(args As String())
#ExternalSource ("test.txt", 1)
#End ExternalSource
#If a = 1 Then
#ElseIf a = 2 Then
#Else
#End If
End Sub
#Region "Test"
Sub Goo()
End Sub
#End Region
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees(0)
Dim root = tree.GetCompilationUnitRoot()
Dim collector = New SyntaxWalkerVerifier(SyntaxWalkerDepth.StructuredTrivia)
collector.Visit(root)
Assert.Equal(1, collector.GetCount(SyntaxKind.ConstDirectiveTrivia.ToString))
Assert.Equal(1, collector.GetCount(SyntaxKind.IfDirectiveTrivia.ToString))
Assert.Equal(1, collector.GetCount(SyntaxKind.ElseIfDirectiveTrivia.ToString))
Assert.Equal(1, collector.GetCount(SyntaxKind.ElseDirectiveTrivia.ToString))
Assert.Equal(1, collector.GetCount(SyntaxKind.ExternalSourceDirectiveTrivia.ToString))
Assert.Equal(1, collector.GetCount(SyntaxKind.EndExternalSourceDirectiveTrivia.ToString))
Assert.Equal(1, collector.GetCount(SyntaxKind.ExternalChecksumDirectiveTrivia.ToString))
Assert.Equal(1, collector.GetCount(SyntaxKind.RegionDirectiveTrivia.ToString))
Assert.Equal(1, collector.GetCount(SyntaxKind.EndRegionDirectiveTrivia.ToString))
End Sub
<Fact>
Public Sub SyntaxWalkerMethod_VerifyPartitionClause()
Dim Compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="SyntaxWalkerTestTypes">
<file name="Test.vb">
Module Module1
Sub Main()
Dim numbers() = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}
Dim first3Numbers = from w in numbers
Take(3)
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees(0)
Dim root = tree.GetCompilationUnitRoot()
Dim collector = New SyntaxWalkerVerifier()
collector.Visit(root)
Assert.Equal(1, collector.GetCount("PartitionClauseSyntax"))
End Sub
<Fact>
Public Sub SyntaxWalkerMethod_VerifyPartitionWhileClause()
Dim Compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="SyntaxWalkerTestTypes">
<file name="Test.vb">
Module Module1
Sub Main()
Dim numbers() = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}
Dim laterNumbers = from n in numbers
Take While(3)
Select i
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees(0)
Dim root = tree.GetCompilationUnitRoot()
Dim collector = New SyntaxWalkerVerifier()
collector.Visit(root)
Assert.Equal(1, collector.GetCount("PartitionWhileClauseSyntax"))
End Sub
<Fact>
Public Sub SyntaxWalkerMethod_VerifyRangeArgument()
Dim Compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="SyntaxWalkerTestTypes">
<file name="Test.vb">
Imports System
Module Module1
Sub Main()
ReDim myarray(0 to 10) ' Resize to 11 elements.
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees(0)
Dim root = tree.GetCompilationUnitRoot()
Dim collector = New SyntaxWalkerVerifier()
collector.Visit(root)
Assert.Equal(1, collector.GetCount(SyntaxKind.RangeArgument.ToString))
End Sub
<Fact>
Public Sub SyntaxWalkerMethod_VerifyXMLBracketName()
Dim Compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="SyntaxWalkerTestTypes">
<file name="Test.vb">
Imports System
Module Module1
Sub Main()
Dim x = <Goo>
<Bar>1</Goo>
</Goo>
Dim y = x.<Goo>.<Bar>.Value
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees(0)
Dim root = tree.GetCompilationUnitRoot()
Dim collector = New SyntaxWalkerVerifier()
collector.Visit(root)
Assert.Equal(2, collector.GetCount(SyntaxKind.XmlBracketedName.ToString))
End Sub
<Fact>
Public Sub SyntaxWalkerMethod_VerifyIncompleteSyntaxClause()
Dim Compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="SyntaxWalkerTestTypes">
<file name="Test.vb">
<Dim:clscompliant(true)>
Module Module1
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees(0)
Dim root = tree.GetCompilationUnitRoot()
Dim collector = New SyntaxWalkerVerifier()
collector.Visit(root)
Assert.Equal(1, collector.GetCount(SyntaxKind.IncompleteMember.ToString))
End Sub
<Fact>
Public Sub SyntaxWalkerMethod_VerifySkippedTokenTrivia()
Dim Compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="SyntaxWalkerTestTypes">
<file name="Test.vb">
OptImports System
Module Module1
Sub main
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees(0)
Dim root = tree.GetCompilationUnitRoot()
Dim collector = New SyntaxWalkerVerifier(SyntaxWalkerDepth.StructuredTrivia)
collector.Visit(root)
Assert.Equal(1, collector.GetCount(SyntaxKind.SkippedTokensTrivia.ToString))
End Sub
<Fact>
Public Sub SyntaxWalkerMethod_VerifyInferredFieldName()
Dim Compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="SyntaxWalkerTestTypes">
<file name="Test.vb">
Imports System
Module Module1
Sub Main()
Dim productName As String = "paperclips"
Dim productPrice As Double = 1.29
Dim anonProduct = New With {Key productName, Key productPrice}
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees(0)
Dim root = tree.GetCompilationUnitRoot()
Dim collector = New SyntaxWalkerVerifier()
collector.Visit(root)
Assert.Equal(2, collector.GetCount(SyntaxKind.InferredFieldInitializer.ToString))
End Sub
#End Region
End Class
End Namespace
|
jkotas/roslyn
|
src/Compilers/VisualBasic/Test/Syntax/TestSyntaxNodes.vb
|
Visual Basic
|
apache-2.0
| 162,878
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Queries
Public Class FromKeywordRecommenderTests
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromNotInStatementTest()
VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "From")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterReturnTest()
VerifyRecommendationsContain(<MethodBody>Return |</MethodBody>, "From")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterArgument1Test()
VerifyRecommendationsContain(<MethodBody>Goo(|</MethodBody>, "From")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterArgument2Test()
VerifyRecommendationsContain(<MethodBody>Goo(bar, |</MethodBody>, "From")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterBinaryExpressionTest()
VerifyRecommendationsContain(<MethodBody>Goo(bar + |</MethodBody>, "From")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterNotTest()
VerifyRecommendationsContain(<MethodBody>Goo(Not |</MethodBody>, "From")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterTypeOfTest()
VerifyRecommendationsContain(<MethodBody>If TypeOf |</MethodBody>, "From")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterDoWhileTest()
VerifyRecommendationsContain(<MethodBody>Do While |</MethodBody>, "From")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterDoUntilTest()
VerifyRecommendationsContain(<MethodBody>Do Until |</MethodBody>, "From")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterLoopWhileTest()
VerifyRecommendationsContain(<MethodBody>
Do
Loop While |</MethodBody>, "From")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterLoopUntilTest()
VerifyRecommendationsContain(<MethodBody>
Do
Loop Until |</MethodBody>, "From")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterIfTest()
VerifyRecommendationsContain(<MethodBody>If |</MethodBody>, "From")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterElseIfTest()
VerifyRecommendationsContain(<MethodBody>ElseIf |</MethodBody>, "From")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterElseSpaceIfTest()
VerifyRecommendationsContain(<MethodBody>Else If |</MethodBody>, "From")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterErrorTest()
VerifyRecommendationsContain(<MethodBody>Error |</MethodBody>, "From")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterThrowTest()
VerifyRecommendationsContain(<MethodBody>Throw |</MethodBody>, "From")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterArrayInitializerSquiggleTest()
VerifyRecommendationsContain(<MethodBody>Dim x = {|</MethodBody>, "From")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterArrayInitializerCommaTest()
VerifyRecommendationsContain(<MethodBody>Dim x = {0, |</MethodBody>, "From")
End Sub
<WorkItem(543173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543173")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterMultiLineFunctionLambdaExprTest()
VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By Function()
Return 5
End Function |</MethodBody>, "From")
End Sub
<WorkItem(543174, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543174")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterAnonymousObjectCreationExprTest()
VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By New With {.Key = 10} |</MethodBody>, "From")
End Sub
<WorkItem(543219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543219")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterIntoClauseTest()
VerifyRecommendationsContain(<MethodBody>Dim q1 = From i1 In arr Group By i1 Into Count |</MethodBody>, "From")
End Sub
<WorkItem(543232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543232")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FromAfterNestedAggregateFromClauseTest()
VerifyRecommendationsContain(<MethodBody>Dim q1 = Aggregate i1 In arr From i4 In arr |</MethodBody>, "From")
End Sub
<WorkItem(543270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543270")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInDelegateCreationTest()
Dim code =
<File>
Module Program
Sub Main(args As String())
Dim f1 As New Goo2( |
End Sub
Delegate Sub Goo2()
Function Bar2() As Object
Return Nothing
End Function
End Module
</File>
VerifyRecommendationsMissing(code, "From")
End Sub
End Class
End Namespace
|
physhi/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/Queries/FromKeywordRecommenderTests.vb
|
Visual Basic
|
apache-2.0
| 6,431
|
Namespace ApplicationInformation
Public Class Expenses
Inherits ApplicationInformationBase
Public Sub New()
_ApplicationName = "Expenses"
_Name = "Expenses"
_ServiceURL = nubServerServiceURL
_SourceDirectory = "C:\Projects\GitHub\Expenses\bin\"
CreateControls()
End Sub
End Class
End Namespace
|
nublet/AutoUpdates
|
Updater/ApplicationInformation/Expenses.vb
|
Visual Basic
|
mit
| 393
|
'------------------------------------------------------------------------------
' <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 ParamResultadosEncuesta
'''<summary>
'''Control ImageButton2.
'''</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 ImageButton2 As Global.System.Web.UI.WebControls.ImageButton
'''<summary>
'''Control RadNumericTextBox1.
'''</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 RadNumericTextBox1 As Global.Telerik.Web.UI.RadNumericTextBox
'''<summary>
'''Control RadComboBox1.
'''</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 RadComboBox1 As Global.Telerik.Web.UI.RadComboBox
'''<summary>
'''Control ImageButton3.
'''</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 ImageButton3 As Global.System.Web.UI.WebControls.ImageButton
'''<summary>
'''Control RadGrid1.
'''</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 RadGrid1 As Global.Telerik.Web.UI.RadGrid
'''<summary>
'''Control SqlResultados.
'''</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 SqlResultados As Global.System.Web.UI.WebControls.SqlDataSource
'''<summary>
'''Control SqlEncuestas.
'''</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 SqlEncuestas As Global.System.Web.UI.WebControls.SqlDataSource
'''<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/RRHH/Formulario/ParamResultadosEncuesta.aspx.designer.vb
|
Visual Basic
|
mit
| 3,238
|
' 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.Globalization
Imports System.Reflection
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend Class ErrorFactory
Private Const s_titleSuffix As String = "_Title"
Private Const s_descriptionSuffix As String = "_Description"
Private Shared ReadOnly s_helpLinksMap As Lazy(Of ImmutableDictionary(Of ERRID, String)) = New Lazy(Of ImmutableDictionary(Of ERRID, String))(AddressOf CreateHelpLinks)
Private Shared ReadOnly s_categoriesMap As Lazy(Of ImmutableDictionary(Of ERRID, String)) = New Lazy(Of ImmutableDictionary(Of ERRID, String))(AddressOf CreateCategoriesMap)
Private Shared Function CreateHelpLinks() As ImmutableDictionary(Of ERRID, String)
Dim map = New Dictionary(Of ERRID, String) From
{ ' { ERROR_CODE, HELP_LINK }
}
Return map.ToImmutableDictionary
End Function
Private Shared Function CreateCategoriesMap() As ImmutableDictionary(Of ERRID, String)
Dim map = New Dictionary(Of ERRID, String) From
{ ' { ERROR_CODE, CATEGORY }
}
Return map.ToImmutableDictionary
End Function
Public Shared ReadOnly EmptyErrorInfo As DiagnosticInfo = ErrorInfo(0)
Public Shared ReadOnly VoidDiagnosticInfo As DiagnosticInfo = ErrorInfo(ERRID.Void)
Public Shared ReadOnly GetErrorInfo_ERR_WithEventsRequiresClass As Func(Of DiagnosticInfo) =
Function() ErrorInfo(ERRID.ERR_WithEventsRequiresClass)
Public Shared ReadOnly GetErrorInfo_ERR_StrictDisallowImplicitObject As Func(Of DiagnosticInfo) =
Function() ErrorInfo(ERRID.ERR_StrictDisallowImplicitObject)
Public Shared ReadOnly GetErrorInfo_WRN_ObjectAssumedVar1_WRN_StaticLocalNoInference As Func(Of DiagnosticInfo) =
Function() ErrorInfo(ERRID.WRN_ObjectAssumedVar1, ErrorInfo(ERRID.WRN_StaticLocalNoInference))
Public Shared ReadOnly GetErrorInfo_WRN_ObjectAssumedVar1_WRN_MissingAsClauseinVarDecl As Func(Of DiagnosticInfo) =
Function() ErrorInfo(ERRID.WRN_ObjectAssumedVar1, ErrorInfo(ERRID.WRN_MissingAsClauseinVarDecl))
Public Shared ReadOnly GetErrorInfo_ERR_StrictDisallowsImplicitProc As Func(Of DiagnosticInfo) =
Function() ErrorInfo(ERRID.ERR_StrictDisallowsImplicitProc)
Public Shared ReadOnly GetErrorInfo_ERR_StrictDisallowsImplicitArgs As Func(Of DiagnosticInfo) =
Function() ErrorInfo(ERRID.ERR_StrictDisallowsImplicitArgs)
Public Shared ReadOnly GetErrorInfo_WRN_ObjectAssumed1_WRN_MissingAsClauseinFunction As Func(Of DiagnosticInfo) =
Function() ErrorInfo(ERRID.WRN_ObjectAssumed1, ErrorInfo(ERRID.WRN_MissingAsClauseinFunction))
Public Shared ReadOnly GetErrorInfo_WRN_ObjectAssumed1_WRN_MissingAsClauseinOperator As Func(Of DiagnosticInfo) =
Function() ErrorInfo(ERRID.WRN_ObjectAssumed1, ErrorInfo(ERRID.WRN_MissingAsClauseinOperator))
Public Shared ReadOnly GetErrorInfo_WRN_ObjectAssumedProperty1_WRN_MissingAsClauseinProperty As Func(Of DiagnosticInfo) =
Function() ErrorInfo(ERRID.WRN_ObjectAssumedProperty1, ErrorInfo(ERRID.WRN_MissingAsClauseinProperty))
Public Shared Function ErrorInfo(id As ERRID) As DiagnosticInfo
Return New DiagnosticInfo(MessageProvider.Instance, id)
End Function
Public Shared Function ErrorInfo(id As ERRID, ParamArray arguments As Object()) As DiagnosticInfo
Return New DiagnosticInfo(MessageProvider.Instance, id, arguments)
End Function
Public Shared Function ErrorInfo(id As ERRID, ByRef syntaxToken As SyntaxToken) As DiagnosticInfo
Return ErrorInfo(id, SyntaxFacts.GetText(syntaxToken.Kind))
End Function
Public Shared Function ErrorInfo(id As ERRID, ByRef syntaxTokenKind As SyntaxKind) As DiagnosticInfo
Return ErrorInfo(id, SyntaxFacts.GetText(syntaxTokenKind))
End Function
Public Shared Function ErrorInfo(id As ERRID, ByRef syntaxToken As SyntaxToken, type As TypeSymbol) As DiagnosticInfo
Return ErrorInfo(id, SyntaxFacts.GetText(syntaxToken.Kind), type)
End Function
Public Shared Function ErrorInfo(id As ERRID, ByRef syntaxToken As SyntaxToken, type1 As TypeSymbol, type2 As TypeSymbol) As DiagnosticInfo
Return ErrorInfo(id, SyntaxFacts.GetText(syntaxToken.Kind), type1, type2)
End Function
Private Shared s_resourceManager As Resources.ResourceManager
Friend Shared ReadOnly Property ResourceManager As Resources.ResourceManager
Get
If s_resourceManager Is Nothing Then
s_resourceManager = New Resources.ResourceManager(GetType(VBResources).FullName, GetType(ERRID).GetTypeInfo().Assembly)
End If
Return s_resourceManager
End Get
End Property
'The function is a gigantic num->string switch, so verifying it is not interesting, but expensive.
Friend Shared Function IdToString(id As ERRID) As String
Return IdToString(id, CultureInfo.CurrentUICulture)
End Function
'The function is a gigantic num->string switch, so verifying it is not interesting, but expensive.
Public Shared Function IdToString(id As ERRID, language As CultureInfo) As String
Return ResourceManager.GetString(id.ToString(), language)
End Function
Public Shared Function GetMessageFormat(id As ERRID) As LocalizableResourceString
Return New LocalizableResourceString(id.ToString(), ResourceManager, GetType(ErrorFactory))
End Function
Public Shared Function GetTitle(id As ERRID) As LocalizableResourceString
Return New LocalizableResourceString(id.ToString() + s_titleSuffix, ResourceManager, GetType(ErrorFactory))
End Function
Public Shared Function GetDescription(id As ERRID) As LocalizableResourceString
Return New LocalizableResourceString(id.ToString() + s_descriptionSuffix, ResourceManager, GetType(ErrorFactory))
End Function
Public Shared Function GetHelpLink(id As ERRID) As String
Dim helpLink As String = Nothing
If s_helpLinksMap.Value.TryGetValue(id, helpLink) Then
Return helpLink
End If
Return String.Empty
End Function
Public Shared Function GetCategory(id As ERRID) As String
Dim category As String = Nothing
If s_categoriesMap.Value.TryGetValue(id, category) Then
Return category
End If
Return Diagnostic.CompilerDiagnosticCategory
End Function
End Class
''' <summary>
''' Concatenates messages for a set of DiagnosticInfo.
''' </summary>
Friend Class CompoundDiagnosticInfo
Inherits DiagnosticInfo
Friend Sub New(arguments As DiagnosticInfo())
MyBase.New(VisualBasic.MessageProvider.Instance, 0, arguments)
End Sub
Public Overrides Function GetMessage(Optional formatProvider As IFormatProvider = Nothing) As String
Dim builder = PooledStringBuilder.GetInstance()
If Arguments IsNot Nothing Then
For Each info As DiagnosticInfo In Arguments
builder.Builder.Append(info.GetMessage(formatProvider))
Next
End If
Dim message = builder.Builder.ToString()
builder.Free()
Return message
End Function
End Class
End Namespace
|
agocke/roslyn
|
src/Compilers/VisualBasic/Portable/Errors/ErrorFactories.vb
|
Visual Basic
|
mit
| 8,050
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.SignatureHelp
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators
Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp
Friend MustInherit Class AbstractIntrinsicOperatorSignatureHelpProvider(Of TSyntaxNode As SyntaxNode)
Inherits AbstractVisualBasicSignatureHelpProvider
Protected MustOverride Function IsTriggerToken(token As SyntaxToken) As Boolean
Protected MustOverride Function IsArgumentListToken(node As TSyntaxNode, token As SyntaxToken) As Boolean
Protected MustOverride Function GetIntrinsicOperatorDocumentationAsync(node As TSyntaxNode, document As Document, cancellationToken As CancellationToken) As ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))
Private Function TryGetSyntaxNode(root As SyntaxNode, position As Integer, syntaxFacts As ISyntaxFactsService, triggerReason As SignatureHelpTriggerReason, cancellationToken As CancellationToken, ByRef node As TSyntaxNode) As Boolean
Return CommonSignatureHelpUtilities.TryGetSyntax(
root,
position,
syntaxFacts,
triggerReason,
AddressOf IsTriggerToken,
AddressOf IsArgumentListToken,
cancellationToken,
node)
End Function
Protected Overrides Async Function GetItemsWorkerAsync(document As Document, position As Integer, triggerInfo As SignatureHelpTriggerInfo, cancellationToken As CancellationToken) As Task(Of SignatureHelpItems)
Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
Dim node As TSyntaxNode = Nothing
If Not TryGetSyntaxNode(root, position, document.GetLanguageService(Of ISyntaxFactsService), triggerInfo.TriggerReason, cancellationToken, node) Then
Return Nothing
End If
Dim items As New List(Of SignatureHelpItem)
Dim semanticModel = Await document.GetSemanticModelForNodeAsync(node, cancellationToken).ConfigureAwait(False)
For Each documentation In Await GetIntrinsicOperatorDocumentationAsync(node, document, cancellationToken).ConfigureAwait(False)
Dim signatureHelpItem = GetSignatureHelpItemForIntrinsicOperator(document, semanticModel, node.SpanStart, documentation, cancellationToken)
items.Add(signatureHelpItem)
Next
Dim textSpan = CommonSignatureHelpUtilities.GetSignatureHelpSpan(node, node.SpanStart, Function(n) n.ChildTokens.FirstOrDefault(Function(c) c.Kind = SyntaxKind.CloseParenToken))
Dim syntaxFacts = document.GetLanguageService(Of ISyntaxFactsService)
Return CreateSignatureHelpItems(
items, textSpan,
GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem:=Nothing)
End Function
Friend Function GetSignatureHelpItemForIntrinsicOperator(document As Document, semanticModel As SemanticModel, position As Integer, documentation As AbstractIntrinsicOperatorDocumentation, cancellationToken As CancellationToken) As SignatureHelpItem
Dim parameters As New List(Of SignatureHelpSymbolParameter)
For i = 0 To documentation.ParameterCount - 1
Dim capturedIndex = i
parameters.Add(
New SignatureHelpSymbolParameter(
name:=documentation.GetParameterName(i),
isOptional:=False,
documentationFactory:=Function(c As CancellationToken) documentation.GetParameterDocumentation(capturedIndex).ToSymbolDisplayParts().ToTaggedText(),
displayParts:=documentation.GetParameterDisplayParts(i)))
Next
Dim suffixParts = documentation.GetSuffix(semanticModel, position, Nothing, cancellationToken)
Dim symbolDisplayService = document.GetLanguageService(Of ISymbolDisplayService)()
Dim anonymousTypeDisplayService = document.GetLanguageService(Of IAnonymousTypeDisplayService)()
Return CreateItem(
Nothing, semanticModel, position,
symbolDisplayService, anonymousTypeDisplayService,
isVariadic:=False,
documentationFactory:=Function(c) SpecializedCollections.SingletonEnumerable(New TaggedText(TextTags.Text, documentation.DocumentationText)),
prefixParts:=documentation.PrefixParts,
separatorParts:=GetSeparatorParts(),
suffixParts:=suffixParts,
parameters:=parameters)
End Function
Protected Overridable Function GetCurrentArgumentStateWorker(node As SyntaxNode, position As Integer) As SignatureHelpState
Dim commaTokens As New List(Of SyntaxToken)
commaTokens.AddRange(node.ChildTokens().Where(Function(token) token.Kind = SyntaxKind.CommaToken))
' Also get any leading skipped tokens on the next token after this node
Dim nextToken = node.GetLastToken().GetNextToken()
For Each leadingTrivia In nextToken.LeadingTrivia
If leadingTrivia.Kind = SyntaxKind.SkippedTokensTrivia Then
commaTokens.AddRange(leadingTrivia.GetStructure().ChildTokens().Where(Function(token) token.Kind = SyntaxKind.CommaToken))
End If
Next
' Count how many commas are before us
Return New SignatureHelpState(
argumentIndex:=commaTokens.Where(Function(token) token.SpanStart < position).Count(),
argumentCount:=commaTokens.Count() + 1,
argumentName:=Nothing, argumentNames:=Nothing)
End Function
Public Overrides Function GetCurrentArgumentState(root As SyntaxNode, position As Integer, syntaxFacts As ISyntaxFactsService, currentSpan As TextSpan, cancellationToken As CancellationToken) As SignatureHelpState
Dim node As TSyntaxNode = Nothing
If TryGetSyntaxNode(root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, node) AndAlso
currentSpan.Start = node.SpanStart Then
Return GetCurrentArgumentStateWorker(node, position)
End If
Return Nothing
End Function
End Class
End Namespace
|
abock/roslyn
|
src/Features/VisualBasic/Portable/SignatureHelp/AbstractIntrinsicOperatorSignatureHelpProvider.vb
|
Visual Basic
|
mit
| 6,788
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module ObjectCreationExpressionExtensions
<Extension>
Public Function CanRemoveEmptyArgumentList(objectCreationExpression As ObjectCreationExpressionSyntax, semanticModel As SemanticModel) As Boolean
If objectCreationExpression.ArgumentList Is Nothing Then
Return False
End If
If objectCreationExpression.ArgumentList.Arguments.Count > 0 Then
Return False
End If
Dim nextToken = objectCreationExpression.GetLastToken.GetNextToken()
If nextToken.IsKindOrHasMatchingText(SyntaxKind.OpenParenToken) Then
Return False
End If
If nextToken.IsKindOrHasMatchingText(SyntaxKind.DotToken) Then
If Not TypeOf objectCreationExpression.Type Is PredefinedTypeSyntax Then
Return False
End If
End If
Return True
End Function
End Module
End Namespace
|
abock/roslyn
|
src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/ObjectCreationExpressionExtensions.vb
|
Visual Basic
|
mit
| 1,481
|
' 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.Completion
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.Editor.CommandHandlers
Imports Microsoft.CodeAnalysis.Editor.Shared.Options
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests
Imports Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.Commanding
Imports Microsoft.VisualStudio.Composition
Imports Microsoft.VisualStudio.Editor
Imports Microsoft.VisualStudio.Language.Intellisense
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
Imports Microsoft.VisualStudio.Shell
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands
Imports Microsoft.VisualStudio.TextManager.Interop
Imports Moq
Imports MSXML
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Snippets
Friend NotInheritable Class SnippetTestState
Inherits AbstractCommandHandlerTestState
Public Sub New(workspaceElement As XElement, languageName As String, startActiveSession As Boolean, extraParts As IEnumerable(Of Type), Optional workspaceKind As String = Nothing)
' Remove the default completion presenters to prevent them from conflicting with the test one
' that we are adding.
MyBase.New(workspaceElement, extraParts:=CreatePartCatalog(extraParts), workspaceKind:=workspaceKind, excludedTypes:={GetType(IIntelliSensePresenter(Of ICompletionPresenterSession, ICompletionSession))})
Workspace.Options = Workspace.Options.WithChangedOption(InternalFeatureOnOffOptions.Snippets, True)
SessionTestState = Workspace.GetService(Of IIntelliSenseTestState)
Dim mockEditorAdaptersFactoryService = New Mock(Of IVsEditorAdaptersFactoryService)
Dim mockSVsServiceProvider = New Mock(Of SVsServiceProvider)
SnippetCommandHandler = If(languageName = LanguageNames.CSharp,
DirectCast(New CSharp.Snippets.SnippetCommandHandler(Workspace.ExportProvider.GetExportedValue(Of IThreadingContext), mockEditorAdaptersFactoryService.Object, mockSVsServiceProvider.Object), AbstractSnippetCommandHandler),
New VisualBasic.Snippets.SnippetCommandHandler(Workspace.ExportProvider.GetExportedValue(Of IThreadingContext), mockEditorAdaptersFactoryService.Object, mockSVsServiceProvider.Object))
If languageName = LanguageNames.VisualBasic Then
Dim snippetProvider As CompletionProvider = New VisualBasic.Snippets.SnippetCompletionProvider(Workspace.ExportProvider.GetExportedValue(Of IThreadingContext), Nothing)
Dim completionService = DirectCast(Workspace.Services.GetLanguageServices(languageName).GetService(Of CompletionService), CommonCompletionService)
completionService.SetTestProviders({snippetProvider})
_completionCommandHandler = Workspace.GetService(Of CompletionCommandHandler)
End If
SnippetExpansionClient = New MockSnippetExpansionClient(Workspace.ExportProvider.GetExportedValue(Of IThreadingContext), startActiveSession)
TextView.Properties.AddProperty(GetType(AbstractSnippetExpansionClient), SnippetExpansionClient)
End Sub
Public ReadOnly SnippetCommandHandler As AbstractSnippetCommandHandler
Private ReadOnly _completionCommandHandler As CompletionCommandHandler
Private _currentCompletionPresenterSession As TestCompletionPresenterSession
Private ReadOnly SessionTestState As IIntelliSenseTestState
Public Property SnippetExpansionClient As MockSnippetExpansionClient
Private Shared Function CreatePartCatalog(types As IEnumerable(Of Type)) As ComposableCatalog
Return ExportProviderCache.CreateTypeCatalog(types).WithParts(GetType(TestCompletionPresenter), GetType(IntelliSenseTestState))
End Function
Friend ReadOnly Property CurrentSignatureHelpPresenterSession As TestSignatureHelpPresenterSession
Get
Return SessionTestState.CurrentSignatureHelpPresenterSession
End Get
End Property
Friend ReadOnly Property CurrentCompletionPresenterSession As TestCompletionPresenterSession
Get
Return SessionTestState.CurrentCompletionPresenterSession
End Get
End Property
Public Shared Function CreateTestState(markup As String, languageName As String, Optional startActiveSession As Boolean = False, Optional extraParts As IEnumerable(Of Type) = Nothing) As SnippetTestState
extraParts = If(extraParts, Type.EmptyTypes)
Dim workspaceXml = <Workspace>
<Project Language=<%= languageName %> CommonReferences="true">
<Document><%= markup %></Document>
</Project>
</Workspace>
Return New SnippetTestState(workspaceXml, languageName, startActiveSession, extraParts)
End Function
Public Shared Function CreateSubmissionTestState(markup As String, languageName As String, Optional startActiveSession As Boolean = False, Optional extraParts As IEnumerable(Of Type) = Nothing) As SnippetTestState
extraParts = If(extraParts, Type.EmptyTypes)
Dim workspaceXml = <Workspace>
<Submission Language=<%= languageName %> CommonReferences="true">
<%= markup %>
</Submission>
</Workspace>
Dim state = New SnippetTestState(workspaceXml, languageName, startActiveSession, extraParts, WorkspaceKind.Interactive)
state.Workspace.Options = state.Workspace.Options.WithChangedOption(InternalFeatureOnOffOptions.Snippets, False)
Return state
End Function
Friend Overloads Sub SendTabToCompletion()
Dim handler = DirectCast(_completionCommandHandler, IChainedCommandHandler(Of TabKeyCommandArgs))
SendTab(AddressOf handler.ExecuteCommand, AddressOf SendTab)
End Sub
Friend Overloads Sub SendTab()
If Not SendTab(AddressOf SnippetCommandHandler.ExecuteCommand) Then
EditorOperations.InsertText(" ")
End If
End Sub
Friend Overloads Sub SendBackTab()
If Not SendBackTab(AddressOf SnippetCommandHandler.ExecuteCommand) Then
EditorOperations.Unindent()
End If
End Sub
Friend Overloads Sub SendReturn()
If Not SendReturn(AddressOf SnippetCommandHandler.ExecuteCommand) Then
EditorOperations.InsertNewLine()
End If
End Sub
Friend Overloads Sub SendEscape()
If Not SendEscape(AddressOf SnippetCommandHandler.ExecuteCommand) Then
EditorOperations.InsertText("EscapePassedThrough!")
End If
End Sub
Public Overloads Sub SendTypeChars(typeChars As String)
Dim handler = DirectCast(_completionCommandHandler, IChainedCommandHandler(Of TypeCharCommandArgs))
MyBase.SendTypeChars(typeChars, AddressOf handler.ExecuteCommand)
End Sub
Private Class MockOrderableContentTypeMetadata
Inherits OrderableContentTypeMetadata
Public Sub New(contentType As String)
MyBase.New(New Dictionary(Of String, Object) From {{"ContentTypes", New List(Of String) From {contentType}},
{"Name", String.Empty}})
End Sub
End Class
Friend Class MockSnippetExpansionClient
Inherits AbstractSnippetExpansionClient
Private _startActiveSession As Boolean
Public Sub New(threadingContext As IThreadingContext, startActiveSession As Boolean)
MyBase.New(threadingContext, Nothing, Nothing, Nothing, Nothing)
If startActiveSession Then
TryHandleTabReturnValue = True
TryHandleBackTabReturnValue = True
TryHandleEscapeReturnValue = True
TryHandleReturnReturnValue = True
End If
End Sub
Public Property TryHandleReturnCalled As Boolean
Public Property TryHandleReturnReturnValue As Boolean
Public Property TryHandleTabCalled As Boolean
Public Property TryHandleTabReturnValue As Boolean
Public Property TryHandleBackTabCalled As Boolean
Public Property TryHandleBackTabReturnValue As Boolean
Public Property TryHandleEscapeCalled As Boolean
Public Property TryHandleEscapeReturnValue As Boolean
Public Property TryInsertExpansionCalled As Boolean
Public Property TryInsertExpansionReturnValue As Boolean
Public Property InsertExpansionSpan As Span
Public Overrides Function TryHandleTab() As Boolean
TryHandleTabCalled = True
Return TryHandleTabReturnValue
End Function
Public Overrides Function TryHandleBackTab() As Boolean
TryHandleBackTabCalled = True
Return TryHandleBackTabReturnValue
End Function
Public Overrides Function TryHandleEscape() As Boolean
TryHandleEscapeCalled = True
Return TryHandleEscapeReturnValue
End Function
Public Overrides Function TryHandleReturn() As Boolean
TryHandleReturnCalled = True
Return TryHandleReturnReturnValue
End Function
Public Overrides Function TryInsertExpansion(startPosition As Integer, endPosition As Integer) As Boolean
TryInsertExpansionCalled = True
InsertExpansionSpan = New Span(startPosition, endPosition - startPosition)
Return TryInsertExpansionReturnValue
End Function
Public Overrides Function GetExpansionFunction(xmlFunctionNode As IXMLDOMNode, bstrFieldName As String, ByRef pFunc As IVsExpansionFunction) As Integer
Throw New NotImplementedException()
End Function
Protected Overrides Function InsertEmptyCommentAndGetEndPositionTrackingSpan() As ITrackingSpan
Throw New NotImplementedException()
End Function
Friend Overrides Function AddImports(document As Document, position As Integer, snippetNode As XElement, placeSystemNamespaceFirst As Boolean, cancellationToken As CancellationToken) As Document
Return document
End Function
End Class
End Class
End Namespace
|
AdamSpeight2008/roslyn-AdamSpeight2008
|
src/VisualStudio/Core/Test/Snippets/SnippetTestState.vb
|
Visual Basic
|
apache-2.0
| 11,184
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting
Public Class PropertyDeclarationHighlighterTests
Inherits AbstractVisualBasicKeywordHighlighterTests
Friend Overrides Function CreateHighlighter() As IHighlighter
Return New PropertyDeclarationHighlighter()
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestAutoProperty1() As Task
Await TestAsync(<Text>
Class C
{|Cursor:[|Public Property|]|} Foo As Integer [|Implements|] IFoo.Foo
End Class</Text>)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestAutoProperty2() As Task
Await TestAsync(<Text>
Class C
[|Public Property|] Foo As Integer {|Cursor:[|Implements|]|} IFoo.Foo
End Class</Text>)
End Function
End Class
End Namespace
|
VPashkov/roslyn
|
src/EditorFeatures/VisualBasicTest/KeywordHighlighting/PropertyDeclarationHighlighterTests.vb
|
Visual Basic
|
apache-2.0
| 1,213
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports System.Runtime.ExceptionServices
Imports System.Runtime.InteropServices
Imports EnvDTE
Imports EnvDTE80
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Shared.TestHooks
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.ComponentModelHost
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Interop
Imports Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.Mocks
Imports Microsoft.VisualStudio.Shell.Interop
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel
Friend Module CodeModelTestHelpers
Public SystemWindowsFormsPath As String
Public SystemDrawingPath As String
#Disable Warning IDE0040 ' Add accessibility modifiers - https://github.com/dotnet/roslyn/issues/45962
Sub New()
#Enable Warning IDE0040 ' Add accessibility modifiers
SystemWindowsFormsPath = GetType(System.Windows.Forms.Form).Assembly.Location
SystemDrawingPath = GetType(System.Drawing.Point).Assembly.Location
End Sub
' If something is *really* wrong with our COM marshalling stuff, the creation of the CodeModel will probably
' throw some sort of AV or other Very Bad exception. We still want to be able to catch them, so we can clean up
' the workspace. If we don't, we leak the workspace and it'll take down the process when it throws in a
' finalizer complaining we didn't clean it up. Catching AVs is of course not safe, but this is balancing
' "probably not crash" as an improvement over "will crash when the finalizer throws."
<HandleProcessCorruptedStateExceptions()>
Public Function CreateCodeModelTestState(definition As XElement) As CodeModelTestState
Dim workspace = TestWorkspace.Create(definition, composition:=VisualStudioTestCompositions.LanguageServices)
Dim result As CodeModelTestState = Nothing
Try
Dim mockComponentModel = New MockComponentModel(workspace.ExportProvider)
Dim mockServiceProvider = New MockServiceProvider(mockComponentModel)
Dim mockVisualStudioWorkspace = New MockVisualStudioWorkspace(workspace)
WrapperPolicy.s_ComWrapperFactory = MockComWrapperFactory.Instance
' The Code Model test infrastructure assumes that a test workspace only ever contains a single project.
' If tests are written that require multiple projects, additional support will need to be added.
Dim project = workspace.CurrentSolution.Projects.Single()
Dim threadingContext = workspace.ExportProvider.GetExportedValue(Of IThreadingContext)
Dim listenerProvider = workspace.ExportProvider.GetExportedValue(Of AsynchronousOperationListenerProvider)()
Dim state = New CodeModelState(
threadingContext,
mockServiceProvider,
project.LanguageServices,
mockVisualStudioWorkspace,
New ProjectCodeModelFactory(
mockVisualStudioWorkspace,
mockServiceProvider,
threadingContext,
listenerProvider))
Dim projectCodeModel = DirectCast(state.ProjectCodeModelFactory.CreateProjectCodeModel(project.Id, Nothing), ProjectCodeModel)
For Each document In project.Documents
' Note that a parent is not specified below. In Visual Studio, this would normally be an EnvDTE.Project instance.
Dim fcm = projectCodeModel.GetOrCreateFileCodeModel(document.FilePath, parent:=Nothing)
fcm.Object.TextManagerAdapter = New MockTextManagerAdapter()
mockVisualStudioWorkspace.SetFileCodeModel(document.Id, fcm)
Next
Dim root = New ComHandle(Of EnvDTE.CodeModel, RootCodeModel)(RootCodeModel.Create(state, Nothing, project.Id))
Dim firstFCM = mockVisualStudioWorkspace.GetFileCodeModelComHandle(project.DocumentIds.First())
result = New CodeModelTestState(workspace, mockVisualStudioWorkspace, root, firstFCM, state.CodeModelService)
Finally
If result Is Nothing Then
workspace.Dispose()
End If
End Try
Return result
End Function
Public Class MockServiceProvider
Implements IServiceProvider
Private ReadOnly _componentModel As MockComponentModel
Public Sub New(componentModel As MockComponentModel)
_componentModel = componentModel
End Sub
Public Function GetService(serviceType As Type) As Object Implements IServiceProvider.GetService
If serviceType = GetType(SComponentModel) Then
Return Me._componentModel
End If
If serviceType = GetType(EnvDTE.IVsExtensibility) Then
Return Nothing
End If
Throw New NotImplementedException($"No service exists for {serviceType.FullName}")
End Function
End Class
Friend Class MockComWrapperFactory
Implements IComWrapperFactory
Public Shared ReadOnly Instance As IComWrapperFactory = New MockComWrapperFactory
Public Function CreateAggregatedObject(managedObject As Object) As Object Implements IComWrapperFactory.CreateAggregatedObject
Dim wrapperUnknown = BlindAggregatorFactory.CreateWrapper()
Try
Dim innerUnknown = Marshal.CreateAggregatedObject(wrapperUnknown, managedObject)
Try
Dim handle = GCHandle.Alloc(managedObject, GCHandleType.Normal)
Dim freeHandle = True
Try
#Disable Warning RS0042 ' Do not copy value
BlindAggregatorFactory.SetInnerObject(wrapperUnknown, innerUnknown, GCHandle.ToIntPtr(handle))
#Enable Warning RS0042 ' Do not copy value
freeHandle = False
Finally
If freeHandle Then handle.Free()
End Try
Dim wrapperRCW = Marshal.GetObjectForIUnknown(wrapperUnknown)
Return CType(wrapperRCW, IComWrapperFixed)
Finally
Marshal.Release(innerUnknown)
End Try
Finally
Marshal.Release(wrapperUnknown)
End Try
End Function
End Class
<Extension()>
Public Function GetDocumentAtCursor(state As CodeModelTestState) As Microsoft.CodeAnalysis.Document
Dim cursorDocument = state.Workspace.Documents.First(Function(d) d.CursorPosition.HasValue)
Dim document = state.Workspace.CurrentSolution.GetDocument(cursorDocument.Id)
Assert.NotNull(document)
Return document
End Function
<Extension()>
Public Function GetCodeElementAtCursor(Of T As Class)(state As CodeModelTestState, Optional scope As EnvDTE.vsCMElement = EnvDTE.vsCMElement.vsCMElementOther) As T
Dim cursorPosition = state.Workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
' Here we use vsCMElementOther to mean "Figure out the scope from the type parameter".
Dim candidateScopes = If(scope = EnvDTE.vsCMElement.vsCMElementOther,
s_map(GetType(T)),
{scope})
Dim result As EnvDTE.CodeElement = Nothing
For Each candidateScope In candidateScopes
WpfTestRunner.RequireWpfFact($"{NameOf(GetCodeElementAtCursor)} creates {NameOf(EnvDTE.CodeElement)}s and thus uses the affinited {NameOf(CleanableWeakComHandleTable(Of SyntaxNodeKey, EnvDTE.CodeElement))}")
Try
result = state.FileCodeModelObject.CodeElementFromPosition(cursorPosition, candidateScope)
Catch ex As COMException
' Loop around and try the next candidate scope
result = Nothing
End Try
If result IsNot Nothing Then
Exit For
End If
Next
If result Is Nothing Then
Assert.True(False, "Could not locate code element")
End If
Return CType(result, T)
End Function
''' <summary>
''' Creates an "external" version of the given code element.
''' </summary>
<Extension()>
Public Function AsExternal(Of T As Class)(element As T) As T
Dim codeElement = TryCast(element, EnvDTE.CodeElement)
Assert.True(codeElement IsNot Nothing, "Expected code element")
Assert.True(codeElement.InfoLocation = EnvDTE.vsCMInfoLocation.vsCMInfoLocationProject, "Expected internal code element")
If TypeOf codeElement Is EnvDTE.CodeParameter Then
Dim codeParameter = DirectCast(codeElement, EnvDTE.CodeParameter)
Dim externalParentCodeElement = codeParameter.Parent.AsExternal()
Dim externalParentCodeElementImpl = ComAggregate.GetManagedObject(Of AbstractExternalCodeMember)(externalParentCodeElement)
Return DirectCast(externalParentCodeElementImpl.Parameters.Item(codeParameter.Name), T)
End If
Dim codeElementImpl = ComAggregate.GetManagedObject(Of AbstractCodeElement)(codeElement)
Dim state = codeElementImpl.State
Dim projectId = codeElementImpl.FileCodeModel.GetProjectId()
Dim symbol = codeElementImpl.LookupSymbol()
Dim externalCodeElement = codeElementImpl.CodeModelService.CreateExternalCodeElement(state, projectId, symbol)
Assert.True(externalCodeElement IsNot Nothing, "Could not create external code element")
Dim result = TryCast(externalCodeElement, T)
Assert.True(result IsNot Nothing, $"Created external code element was not of type, {GetType(T).FullName}")
Return result
End Function
<Extension()>
Public Function GetMethodXML(func As EnvDTE.CodeFunction) As XElement
Dim methodXml = TryCast(func, IMethodXML)
Assert.NotNull(methodXml)
Dim xml = methodXml.GetXML()
Return XElement.Parse(xml)
End Function
Private ReadOnly s_map As New Dictionary(Of Type, EnvDTE.vsCMElement()) From
{{GetType(EnvDTE.CodeAttribute), {EnvDTE.vsCMElement.vsCMElementAttribute}},
{GetType(EnvDTE80.CodeAttribute2), {EnvDTE.vsCMElement.vsCMElementAttribute}},
{GetType(EnvDTE.CodeClass), {EnvDTE.vsCMElement.vsCMElementClass, EnvDTE.vsCMElement.vsCMElementModule}},
{GetType(EnvDTE80.CodeClass2), {EnvDTE.vsCMElement.vsCMElementClass, EnvDTE.vsCMElement.vsCMElementModule}},
{GetType(EnvDTE.CodeDelegate), {EnvDTE.vsCMElement.vsCMElementDelegate}},
{GetType(EnvDTE80.CodeDelegate2), {EnvDTE.vsCMElement.vsCMElementDelegate}},
{GetType(EnvDTE80.CodeElement2), {EnvDTE.vsCMElement.vsCMElementOptionStmt, EnvDTE.vsCMElement.vsCMElementInheritsStmt, EnvDTE.vsCMElement.vsCMElementImplementsStmt}},
{GetType(EnvDTE.CodeEnum), {EnvDTE.vsCMElement.vsCMElementEnum}},
{GetType(EnvDTE80.CodeEvent), {EnvDTE.vsCMElement.vsCMElementEvent}},
{GetType(EnvDTE.CodeFunction), {EnvDTE.vsCMElement.vsCMElementFunction, EnvDTE.vsCMElement.vsCMElementDeclareDecl}},
{GetType(EnvDTE80.CodeFunction2), {EnvDTE.vsCMElement.vsCMElementFunction, EnvDTE.vsCMElement.vsCMElementDeclareDecl}},
{GetType(EnvDTE80.CodeImport), {EnvDTE.vsCMElement.vsCMElementImportStmt}},
{GetType(EnvDTE.CodeInterface), {EnvDTE.vsCMElement.vsCMElementInterface}},
{GetType(EnvDTE80.CodeInterface2), {EnvDTE.vsCMElement.vsCMElementInterface}},
{GetType(EnvDTE.CodeNamespace), {EnvDTE.vsCMElement.vsCMElementNamespace}},
{GetType(EnvDTE.CodeParameter), {EnvDTE.vsCMElement.vsCMElementParameter}},
{GetType(EnvDTE80.CodeParameter2), {EnvDTE.vsCMElement.vsCMElementParameter}},
{GetType(EnvDTE.CodeProperty), {EnvDTE.vsCMElement.vsCMElementProperty}},
{GetType(EnvDTE80.CodeProperty2), {EnvDTE.vsCMElement.vsCMElementProperty}},
{GetType(EnvDTE.CodeStruct), {EnvDTE.vsCMElement.vsCMElementStruct}},
{GetType(EnvDTE80.CodeStruct2), {EnvDTE.vsCMElement.vsCMElementStruct}},
{GetType(EnvDTE.CodeVariable), {EnvDTE.vsCMElement.vsCMElementVariable}},
{GetType(EnvDTE80.CodeVariable2), {EnvDTE.vsCMElement.vsCMElementVariable}}}
<Extension>
Public Function Find(Of T)(elements As EnvDTE.CodeElements, name As String) As T
For Each element As EnvDTE.CodeElement In elements
If element.Name = name Then
Return CType(element, T)
End If
Next
Return Nothing
End Function
End Module
End Namespace
|
physhi/roslyn
|
src/VisualStudio/TestUtilities2/CodeModel/CodeModelTestHelpers.vb
|
Visual Basic
|
apache-2.0
| 14,197
|
' 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.UnitTests.AutomaticCompletion
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.AutomaticCompletion
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.VisualStudio.Commanding
Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands
Imports Microsoft.VisualStudio.Text.Operations
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AutomaticCompletion
Public Class AutomaticLineEnderTests
Inherits AbstractAutomaticLineEnderTests
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestCreation()
Test(<code>
$$</code>, <code>$$</code>)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestImports()
Test(<code>Imports _
$$
</code>, <code>Imports$$
</code>)
End Sub
<WorkItem(530591, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530591")>
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestNamespace()
Test(<code>Namespace NS
$$
End Namespace</code>, <code>Namespace NS$$</code>)
End Sub
<WorkItem(530591, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530591")>
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestClass()
Test(<code>Class C
$$
End Class</code>, <code>Class C$$</code>)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestMethod()
Test(<code>Class C
Sub Method()
$$
End Sub
End Class</code>, <code>Class C
Sub Method()$$
End Class</code>)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestDim()
Test(<code>Class C
Sub Method()
Dim _
$$
End Sub
End Class</code>, <code>Class C
Sub Method()
Dim$$
End Sub
End Class</code>)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestDim1()
Test(<code>Class C
Sub Method()
Dim i =
$$
End Sub
End Class</code>, <code>Class C
Sub Method()
Dim i =$$
End Sub
End Class</code>)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestDim2()
Test(<code>Class C
Sub Method()
Dim i
$$
End Sub
End Class</code>, <code>Class C
Sub Method()
Dim i$$
End Sub
End Class</code>)
End Sub
<WorkItem(712977, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/712977")>
<WpfFact(), Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestDim3()
Test(<code>Class C
Sub Method()
Dim _
_
$$
End Sub
End Class</code>, <code>Class C
Sub Method()
Dim _
$$
End Sub
End Class</code>)
End Sub
<WorkItem(530591, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530591")>
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestDim_After_MalformedStatement()
Test(<code>Class C
Sub Method()
Dim _ test
$$
End Sub
End Class</code>, <code>Class C
Sub Method()
Dim _ test
$$
End Sub
End Class</code>)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestIf()
Test(
<code>
Class C
Sub Method()
If True Then
$$
End If
End Sub
End Class
</code>,
<code>
Class C
Sub Method()
If True$$
End Sub
End Class
</code>)
End Sub
<WorkItem(530591, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530591")>
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestIf_Trivia()
Test(
<code>
Class C
Sub Method()
If True Then ' comment
$$
End If
End Sub
End Class
</code>,
<code>
Class C
Sub Method()
If True $$' comment
End Sub
End Class
</code>)
End Sub
<WorkItem(530591, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530591")>
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestIf_Trivia2()
Test(
<code>
Class C
Sub Method()
If True Then ' comment
$$
End If
End Sub
End Class
</code>,
<code>
Class C
Sub Method()
If True ' comment$$
End Sub
End Class
</code>)
End Sub
<WorkItem(577920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/577920")>
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestEndOfFile_SkippedToken()
Test(
<code>
Module M
Sub Main()
End Sub
End Module
"
$$
</code>,
<code>
Module M
Sub Main()
End Sub
End Module
"$$
</code>)
End Sub
' The test verifies the integrated behavior which keeps the space '_'.
' This corresponds to the actual VS behavior.
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestWithLineContinuation()
Test(
<code>
Module M
Sub Main()
Dim _
$$
End Sub
End Module
</code>,
<code>
Module M
Sub Main()
Dim _ $$
End Sub
End Module
</code>)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestWithLineContinuationCommentsAfterLineContinuation()
Test(
<code>
Module M
Sub Main()
Dim _ ' Test
$$
End Sub
End Module
</code>,
<code>
Module M
Sub Main()
Dim _ ' Test$$
End Sub
End Module
</code>)
End Sub
Private Overloads Sub Test(expected As XElement, code As XElement)
Test(expected.NormalizedValue(), code.NormalizedValue())
End Sub
Friend Overrides Function GetCommandHandler(workspace As TestWorkspace) As IChainedCommandHandler(Of AutomaticLineEnderCommandArgs)
Return Assert.IsType(Of AutomaticLineEnderCommandHandler)(
workspace.GetService(Of ICommandHandler)(
ContentTypeNames.VisualBasicContentType,
PredefinedCommandHandlerNames.AutomaticLineEnder))
End Function
Protected Overrides Function CreateNextHandler(workspace As TestWorkspace) As Action
Dim endConstructor = New EndConstructCommandHandler(
workspace.GetService(Of IEditorOperationsFactoryService),
workspace.GetService(Of ITextUndoHistoryRegistry),
workspace.GetService(Of IGlobalOptionService))
Dim view = workspace.Documents.Single().GetTextView()
Dim buffer = workspace.Documents.Single().GetTextBuffer()
Return Sub()
endConstructor.ExecuteCommand_AutomaticLineEnderCommandHandler(
New AutomaticLineEnderCommandArgs(view, buffer), Sub() Exit Sub, TestCommandExecutionContext.Create())
End Sub
End Function
Protected Overrides ReadOnly Property Language As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
End Class
End Namespace
|
CyrusNajmabadi/roslyn
|
src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticLineEnderTests.vb
|
Visual Basic
|
mit
| 8,023
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.Text
Imports Roslyn.Test.EditorUtilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration
Public Class CharacterTypingTests
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub XmlEndConstructApplied()
VerifyEndConstructAppliedAfterChar(
before:=<Code>
<![CDATA[
Class C1
Sub M1()
Dim x = <xml$$
End Sub
End Class]]>
</Code>.NormalizedValue,
after:=<Code>
<![CDATA[
Class C1
Sub M1()
Dim x = <xml></xml>
End Sub
End Class]]>
</Code>.NormalizedValue,
typedChar:=">"c,
endCaretPos:={3, 21})
End Sub
<WpfFact(), Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub XmlEndConstructNotApplied()
VerifyEndConstructNotAppliedAfterChar(
before:=<Code>
<![CDATA[
Class C1
Sub M1()
If x $$
End Sub
End Class]]>
</Code>.NormalizedValue,
after:=<Code>
<![CDATA[
Class C1
Sub M1()
If x >
End Sub
End Class]]>
</Code>.NormalizedValue,
typedChar:=">"c,
endCaretPos:={3, 14})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub XmlCommentEndConstructApplied()
VerifyEndConstructAppliedAfterChar(
before:=<Code>
<![CDATA[
Class C1
Sub M1()
Dim x = <xml><!-$$</xml>
End Sub
End Class]]>
</Code>.NormalizedValue,
after:=<Code>
<![CDATA[
Class C1
Sub M1()
Dim x = <xml><!----></xml>
End Sub
End Class]]>
</Code>.NormalizedValue,
typedChar:="-"c,
endCaretPos:={3, 25})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub XmlCommentEndConstructNotApplied()
VerifyEndConstructNotAppliedAfterChar(
before:=<Code>
<![CDATA[
Class C1
Sub M1()
Dim x = 1 $$
End Sub
End Class]]>
</Code>.NormalizedValue,
after:=<Code>
<![CDATA[
Class C1
Sub M1()
Dim x = 1 -
End Sub
End Class]]>
</Code>.NormalizedValue,
typedChar:="-"c,
endCaretPos:={3, 19})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub XmlEmbeddedExpressionEndConstructApplied()
VerifyEndConstructAppliedAfterChar(
before:=<Code>
<![CDATA[
Class C1
Sub M1()
Dim x = <xml attr=<%$$></xml>
End Sub
End Class]]>
</Code>.NormalizedValue,
after:=<Code>
<![CDATA[
Class C1
Sub M1()
Dim x = <xml attr=<%= %>></xml>
End Sub
End Class]]>
</Code>.NormalizedValue,
typedChar:="="c,
endCaretPos:={3, 30})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub XmlEmbeddedExpressionEndConstructNotApplied()
VerifyEndConstructNotAppliedAfterChar(
before:=<Code>
<![CDATA[
Class C1
Sub M1()
Dim x $$
End Sub
End Class]]>
</Code>.NormalizedValue,
after:=<Code>
<![CDATA[
Class C1
Sub M1()
Dim x =
End Sub
End Class]]>
</Code>.NormalizedValue,
typedChar:="="c,
endCaretPos:={3, 15})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub XmlCDataEndConstructApplied()
VerifyEndConstructAppliedAfterChar(
before:=<Code>
<![CDATA[
Class C1
Sub M1()
Dim x = <xml><![CDATA$$</xml>
End Sub
End Class]]>
</Code>.NormalizedValue,
after:=<Code>
<![CDATA[
Class C1
Sub M1()
Dim x = <xml><![CDATA[]]>]]><![CDATA[</xml>
End Sub
End Class]]>
</Code>.NormalizedValue,
typedChar:="["c,
endCaretPos:={3, 30})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub XmlCDataEndConstructNotApplied()
VerifyEndConstructNotAppliedAfterChar(
before:=<Code>
<![CDATA[
Class C1
Sub M1()
Dim x = "$$"
End Sub
End Class]]>
</Code>.NormalizedValue,
after:=<Code>
<![CDATA[
Class C1
Sub M1()
Dim x = "["
End Sub
End Class]]>
</Code>.NormalizedValue,
typedChar:="["c,
endCaretPos:={3, 18})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub XmlProcessingInstructionEndConstructApplied()
VerifyEndConstructAppliedAfterChar(
before:=<Code>
<![CDATA[
Class C1
Sub M1()
Dim x = <$$
End Sub
End Class]]>
</Code>.NormalizedValue,
after:=<Code>
<![CDATA[
Class C1
Sub M1()
Dim x = <??>
End Sub
End Class]]>
</Code>.NormalizedValue,
typedChar:="?"c,
endCaretPos:={3, 18})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub XmlProcessingInstructionEndConstructNotApplied()
VerifyEndConstructNotAppliedAfterChar(
before:=<Code>
<![CDATA[
Class C1
Sub M1()
Dim x = "$$"
End Sub
End Class]]>
</Code>.NormalizedValue,
after:=<Code>
<![CDATA[
Class C1
Sub M1()
Dim x = "?"
End Sub
End Class]]>
</Code>.NormalizedValue,
typedChar:="?"c,
endCaretPos:={3, 18})
End Sub
End Class
End Namespace
|
jbhensley/roslyn
|
src/EditorFeatures/VisualBasicTest/EndConstructGeneration/CharacterTypingTests.vb
|
Visual Basic
|
apache-2.0
| 7,260
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.RemoveUnusedMembers
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedMembers
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Friend NotInheritable Class VisualBasicRemoveUnusedMembersDiagnosticAnalyzer
Inherits AbstractRemoveUnusedMembersDiagnosticAnalyzer(Of DocumentationCommentTriviaSyntax, IdentifierNameSyntax)
Protected Overrides Sub HandleNamedTypeSymbolStart(context As SymbolStartAnalysisContext, onSymbolUsageFound As Action(Of ISymbol, ValueUsageInfo))
' Mark all methods with handles clause as having a read reference
' to ensure that we consider the method as "used".
' Such methods are essentially event handlers and are normally
' not referenced directly.
For Each method In DirectCast(context.Symbol, INamedTypeSymbol).GetMembers().OfType(Of IMethodSymbol)
If Not method.HandledEvents.IsEmpty Then
onSymbolUsageFound(method, ValueUsageInfo.Read)
End If
Next
' Register syntax node action for HandlesClause
' This is a workaround for following bugs:
' 1. https://github.com/dotnet/roslyn/issues/30978
' 2. https://github.com/dotnet/roslyn/issues/30979
context.RegisterSyntaxNodeAction(
Sub(syntaxNodeContext As SyntaxNodeAnalysisContext)
AnalyzeHandlesClause(syntaxNodeContext, onSymbolUsageFound)
End Sub,
SyntaxKind.HandlesClause)
End Sub
Private Sub AnalyzeHandlesClause(context As SyntaxNodeAnalysisContext, onSymbolUsageFound As Action(Of ISymbol, ValueUsageInfo))
' Identify all symbol references within the HandlesClause.
For Each node In context.Node.DescendantNodes()
Dim symbolInfo = context.SemanticModel.GetSymbolInfo(node, context.CancellationToken)
For Each symbol In symbolInfo.GetAllSymbols()
onSymbolUsageFound(symbol, ValueUsageInfo.Read)
Next
Next
End Sub
End Class
End Namespace
|
VSadov/roslyn
|
src/Features/VisualBasic/Portable/RemoveUnusedMembers/VisualBasicRemoveUnusedMembersDiagnosticAnalyzer.vb
|
Visual Basic
|
apache-2.0
| 2,426
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Imports System.Reflection
Namespace Microsoft.CodeAnalysis.VisualBasic
' This portion of the binder converts an ExpressionSyntax into a BoundExpression
Partial Friend Class Binder
' !!! PLEASE KEEP BindExpression FUNCTION AT THE TOP !!!
Public Function BindExpression(
node As ExpressionSyntax,
diagnostics As DiagnosticBag
) As BoundExpression
Return BindExpression(node, False, False, False, diagnostics)
End Function
''' <summary>
''' The dispatcher method that handles syntax nodes for all stand-alone expressions.
''' </summary>
Public Function BindExpression(
node As ExpressionSyntax,
isInvocationOrAddressOf As Boolean,
isOperandOfConditionalBranch As Boolean,
eventContext As Boolean,
diagnostics As DiagnosticBag
) As BoundExpression
If IsEarlyAttributeBinder AndAlso Not EarlyWellKnownAttributeBinder.CanBeValidAttributeArgument(node, Me) Then
Return BadExpression(node, ErrorTypeSymbol.UnknownResultType)
End If
Select Case node.Kind
Case SyntaxKind.MeExpression
Return BindMeExpression(DirectCast(node, MeExpressionSyntax), diagnostics)
Case SyntaxKind.MyBaseExpression
Return BindMyBaseExpression(DirectCast(node, MyBaseExpressionSyntax), diagnostics)
Case SyntaxKind.MyClassExpression
Return BindMyClassExpression(DirectCast(node, MyClassExpressionSyntax), diagnostics)
Case SyntaxKind.IdentifierName, SyntaxKind.GenericName
Return BindSimpleName(DirectCast(node, SimpleNameSyntax), isInvocationOrAddressOf, diagnostics)
Case SyntaxKind.PredefinedType, SyntaxKind.NullableType
Return BindNamespaceOrTypeExpression(DirectCast(node, TypeSyntax), diagnostics)
Case SyntaxKind.SimpleMemberAccessExpression
Return BindMemberAccess(DirectCast(node, MemberAccessExpressionSyntax), eventContext, allowIntrinsicAliases:=False, diagnostics:=diagnostics)
Case SyntaxKind.DictionaryAccessExpression
Return BindDictionaryAccess(DirectCast(node, MemberAccessExpressionSyntax), diagnostics)
Case SyntaxKind.InvocationExpression
Return BindInvocationExpression(DirectCast(node, InvocationExpressionSyntax), diagnostics)
Case SyntaxKind.CollectionInitializer
Return BindArrayLiteralExpression(DirectCast(node, CollectionInitializerSyntax), diagnostics)
Case SyntaxKind.AnonymousObjectCreationExpression
Return BindAnonymousObjectCreationExpression(DirectCast(node, AnonymousObjectCreationExpressionSyntax), diagnostics)
Case SyntaxKind.ArrayCreationExpression
Return BindArrayCreationExpression(DirectCast(node, ArrayCreationExpressionSyntax), diagnostics)
Case SyntaxKind.ObjectCreationExpression
Return BindObjectCreationExpression(DirectCast(node, ObjectCreationExpressionSyntax), diagnostics)
Case SyntaxKind.NumericLiteralExpression,
SyntaxKind.StringLiteralExpression,
SyntaxKind.CharacterLiteralExpression,
SyntaxKind.TrueLiteralExpression,
SyntaxKind.FalseLiteralExpression,
SyntaxKind.NothingLiteralExpression,
SyntaxKind.DateLiteralExpression
Return BindLiteralConstant(DirectCast(node, LiteralExpressionSyntax), diagnostics)
Case SyntaxKind.ParenthesizedExpression
' Parenthesis tokens are ignored, and operand is bound in the context of
' parent expression.
' Dev10 allows parenthesized type expressions, let's bind as a general expression first.
Dim operand As BoundExpression = BindExpression(DirectCast(node, ParenthesizedExpressionSyntax).Expression, False, False, eventContext, diagnostics)
If operand.Kind = BoundKind.TypeExpression Then
Dim asType = DirectCast(operand, BoundTypeExpression)
Return New BoundTypeExpression(node, asType.UnevaluatedReceiverOpt, asType.AliasOpt, operand.Type, operand.HasErrors)
ElseIf operand.Kind = BoundKind.ArrayLiteral Then
' Convert the array literal to its inferred array type, reporting warnings/errors if necessary.
' It would have been nice to put this reclassification in ReclassifyAsValue, however, that is called in too many situations. We only
' want to reclassify the array literal this early when it is within parentheses.
Dim arrayLiteral = DirectCast(operand, BoundArrayLiteral)
Dim reclassified = ReclassifyArrayLiteralExpression(SyntaxKind.CTypeKeyword, arrayLiteral.Syntax, ConversionKind.Widening, False, arrayLiteral, arrayLiteral.InferredType, diagnostics)
Return New BoundParenthesized(node, reclassified, reclassified.Type)
Else
Return New BoundParenthesized(node, operand, operand.Type)
End If
Case SyntaxKind.UnaryPlusExpression,
SyntaxKind.UnaryMinusExpression,
SyntaxKind.NotExpression
Return BindUnaryOperator(DirectCast(node, UnaryExpressionSyntax), diagnostics)
Case SyntaxKind.AddExpression,
SyntaxKind.ConcatenateExpression,
SyntaxKind.LikeExpression,
SyntaxKind.EqualsExpression,
SyntaxKind.NotEqualsExpression,
SyntaxKind.LessThanOrEqualExpression,
SyntaxKind.GreaterThanOrEqualExpression,
SyntaxKind.LessThanExpression,
SyntaxKind.GreaterThanExpression,
SyntaxKind.SubtractExpression,
SyntaxKind.MultiplyExpression,
SyntaxKind.ExponentiateExpression,
SyntaxKind.DivideExpression,
SyntaxKind.ModuloExpression,
SyntaxKind.IntegerDivideExpression,
SyntaxKind.LeftShiftExpression,
SyntaxKind.RightShiftExpression,
SyntaxKind.ExclusiveOrExpression,
SyntaxKind.OrExpression,
SyntaxKind.OrElseExpression,
SyntaxKind.AndExpression,
SyntaxKind.AndAlsoExpression
Return BindBinaryOperator(DirectCast(node, BinaryExpressionSyntax), isOperandOfConditionalBranch, diagnostics)
Case SyntaxKind.IsExpression,
SyntaxKind.IsNotExpression
Return BindIsExpression(DirectCast(node, BinaryExpressionSyntax), diagnostics)
Case SyntaxKind.GetTypeExpression
Return BindGetTypeExpression(DirectCast(node, GetTypeExpressionSyntax), diagnostics)
Case SyntaxKind.NameOfExpression
Return BindNameOfExpression(DirectCast(node, NameOfExpressionSyntax), diagnostics)
Case SyntaxKind.AddressOfExpression
Return BindAddressOfExpression(node, diagnostics)
Case SyntaxKind.CTypeExpression,
SyntaxKind.TryCastExpression,
SyntaxKind.DirectCastExpression
Return BindCastExpression(DirectCast(node, CastExpressionSyntax), diagnostics)
Case SyntaxKind.PredefinedCastExpression
Return BindPredefinedCastExpression(DirectCast(node, PredefinedCastExpressionSyntax), diagnostics)
Case SyntaxKind.TypeOfIsExpression,
SyntaxKind.TypeOfIsNotExpression
Return BindTypeOfExpression(DirectCast(node, TypeOfExpressionSyntax), diagnostics)
Case SyntaxKind.BinaryConditionalExpression
Return BindBinaryConditionalExpression(DirectCast(node, BinaryConditionalExpressionSyntax), diagnostics)
Case SyntaxKind.TernaryConditionalExpression
Return BindTernaryConditionalExpression(DirectCast(node, TernaryConditionalExpressionSyntax), diagnostics)
Case SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression,
SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression
Return BindLambdaExpression(DirectCast(node, LambdaExpressionSyntax), diagnostics)
Case SyntaxKind.GlobalName
Return New BoundNamespaceExpression(node, Nothing, Compilation.GlobalNamespace)
Case SyntaxKind.QueryExpression
Return BindQueryExpression(DirectCast(node, QueryExpressionSyntax), diagnostics)
Case SyntaxKind.GroupAggregation
Return BindGroupAggregationExpression(DirectCast(node, GroupAggregationSyntax), diagnostics)
Case SyntaxKind.FunctionAggregation
Return BindFunctionAggregationExpression(DirectCast(node, FunctionAggregationSyntax), diagnostics)
Case SyntaxKind.NextLabel,
SyntaxKind.NumericLabel,
SyntaxKind.IdentifierLabel
Return BindLabel(DirectCast(node, LabelSyntax), diagnostics)
Case SyntaxKind.QualifiedName
' This code is not used during method body binding, but it might be used by SemanticModel for erroneous cases.
Return BindQualifiedName(DirectCast(node, QualifiedNameSyntax), diagnostics)
Case SyntaxKind.GetXmlNamespaceExpression
Return BindGetXmlNamespace(DirectCast(node, GetXmlNamespaceExpressionSyntax), diagnostics)
Case SyntaxKind.XmlComment
Return BindXmlComment(DirectCast(node, XmlCommentSyntax), rootInfoOpt:=Nothing, diagnostics:=diagnostics)
Case SyntaxKind.XmlDocument
Return BindXmlDocument(DirectCast(node, XmlDocumentSyntax), diagnostics)
Case SyntaxKind.XmlProcessingInstruction
Return BindXmlProcessingInstruction(DirectCast(node, XmlProcessingInstructionSyntax), diagnostics)
Case SyntaxKind.XmlEmptyElement
Return BindXmlEmptyElement(DirectCast(node, XmlEmptyElementSyntax), rootInfoOpt:=Nothing, diagnostics:=diagnostics)
Case SyntaxKind.XmlElement
Return BindXmlElement(DirectCast(node, XmlElementSyntax), rootInfoOpt:=Nothing, diagnostics:=diagnostics)
Case SyntaxKind.XmlEmbeddedExpression
' This case handles embedded expressions that are outside of XML
' literals (error cases). The parser will have reported BC31172
' already, so no error is reported here. (Valid uses of embedded
' expressions are handled explicitly in BindXmlElement, etc.)
Return BindXmlEmbeddedExpression(DirectCast(node, XmlEmbeddedExpressionSyntax), diagnostics:=diagnostics)
Case SyntaxKind.XmlCDataSection
Return BindXmlCData(DirectCast(node, XmlCDataSectionSyntax), rootInfoOpt:=Nothing, diagnostics:=diagnostics)
Case SyntaxKind.XmlElementAccessExpression
Return BindXmlElementAccess(DirectCast(node, XmlMemberAccessExpressionSyntax), diagnostics)
Case SyntaxKind.XmlAttributeAccessExpression
Return BindXmlAttributeAccess(DirectCast(node, XmlMemberAccessExpressionSyntax), diagnostics)
Case SyntaxKind.XmlDescendantAccessExpression
Return BindXmlDescendantAccess(DirectCast(node, XmlMemberAccessExpressionSyntax), diagnostics)
Case SyntaxKind.AwaitExpression
Return BindAwait(DirectCast(node, AwaitExpressionSyntax), diagnostics)
Case SyntaxKind.ConditionalAccessExpression
Return BindConditionalAccessExpression(DirectCast(node, ConditionalAccessExpressionSyntax), diagnostics)
Case SyntaxKind.InterpolatedStringExpression
Return BindInterpolatedStringExpression(DirectCast(node, InterpolatedStringExpressionSyntax), diagnostics)
Case Else
' e.g. SyntaxKind.MidExpression is handled elsewhere
' NOTE: There were too many "else" cases to justify listing them explicitly and throwing on
' anything unexpected.
Debug.Assert(node.ContainsDiagnostics, String.Format("Unexpected {0} syntax does not have diagnostics", node.Kind))
Return BadExpression(node, ImmutableArray(Of BoundNode).Empty, ErrorTypeSymbol.UnknownResultType)
End Select
End Function
''' <summary>
''' Create a BoundBadExpression node for the given syntax node. No symbols or bound nodes are associated with it.
''' </summary>
Protected Shared Function BadExpression(node As VisualBasicSyntaxNode, resultType As TypeSymbol) As BoundBadExpression
Return New BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundNode).Empty, resultType, hasErrors:=True)
End Function
''' <summary>
''' Create a BoundBadExpression node for the given childexpression, which is preserved as a sub-expression.
''' No ResultKind is associated
''' </summary>
Private Shared Function BadExpression(node As VisualBasicSyntaxNode, expr As BoundNode, resultType As TypeSymbol) As BoundBadExpression
Return New BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(Of BoundNode)(expr), resultType, hasErrors:=True)
End Function
''' <summary>
''' Create a BoundBadExpression node for the given childexpression, which is preserved as a sub-expression.
''' A ResultKind explains why the node is bad.
''' </summary>
Private Shared Function BadExpression(node As VisualBasicSyntaxNode, expr As BoundNode, resultKind As LookupResultKind, resultType As TypeSymbol) As BoundBadExpression
Return New BoundBadExpression(node, resultKind, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(Of BoundNode)(expr), resultType, hasErrors:=True)
End Function
''' <summary>
''' Create a BoundBadExpression node for the given child expression, which is preserved as a sub-expression. Symbols
''' associated with the child node are not given a result kind.
''' </summary>
Private Shared Function BadExpression(node As VisualBasicSyntaxNode, exprs As ImmutableArray(Of BoundNode), resultType As TypeSymbol) As BoundBadExpression
Return New BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray(Of Symbol).Empty, exprs, resultType, hasErrors:=True)
End Function
Private Shared Function BadExpression(expr As BoundExpression) As BoundBadExpression
Return BadExpression(LookupResultKind.Empty, expr)
End Function
' Use this for a bad expression with no known type, and a single child whose type and syntax is preserved as the type of the bad expression.
Private Shared Function BadExpression(resultKind As LookupResultKind, wrappedExpression As BoundExpression) As BoundBadExpression
Dim wrappedBadExpression As BoundBadExpression = TryCast(wrappedExpression, BoundBadExpression)
If wrappedBadExpression IsNot Nothing Then
Return New BoundBadExpression(wrappedBadExpression.Syntax, resultKind, wrappedBadExpression.Symbols, wrappedBadExpression.ChildBoundNodes, wrappedBadExpression.Type, hasErrors:=True)
Else
Return New BoundBadExpression(wrappedExpression.Syntax, resultKind, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(Of BoundNode)(wrappedExpression), wrappedExpression.Type, hasErrors:=True)
End If
End Function
Public Function BindNamespaceOrTypeExpression(node As TypeSyntax, diagnostics As DiagnosticBag) As BoundExpression
Dim symbol = Me.BindNamespaceOrTypeOrAliasSyntax(node, diagnostics)
Dim [alias] = TryCast(symbol, AliasSymbol)
If [alias] IsNot Nothing Then
symbol = [alias].Target
' check for use site errors
ReportUseSiteError(diagnostics, node, symbol)
End If
Dim [type] = TryCast(symbol, TypeSymbol)
If [type] IsNot Nothing Then
Return New BoundTypeExpression(node, Nothing, [alias], [type])
End If
Dim ns = TryCast(symbol, NamespaceSymbol)
If ns IsNot Nothing Then
Return New BoundNamespaceExpression(node, Nothing, [alias], ns)
End If
' BindNamespaceOrTypeSyntax should always return a type or a namespace (might be an error type).
Throw ExceptionUtilities.Unreachable
End Function
Public Function BindNamespaceOrTypeOrExpressionSyntaxForSemanticModel(node As ExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression
If (node.Kind = SyntaxKind.PredefinedType) OrElse
(((TypeOf node Is NameSyntax) OrElse node.Kind = SyntaxKind.ArrayType) AndAlso SyntaxFacts.IsInNamespaceOrTypeContext(node)) Then
Dim result As BoundExpression = Me.BindNamespaceOrTypeExpression(DirectCast(node, TypeSyntax), diagnostics)
' 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 node.Parent IsNot Nothing AndAlso
node.Parent.Kind = SyntaxKind.QualifiedName AndAlso
DirectCast(node.Parent, QualifiedNameSyntax).Left Is node AndAlso
result.Kind = BoundKind.NamespaceExpression Then
Dim namespaceExpr = DirectCast(result, BoundNamespaceExpression)
If namespaceExpr.NamespaceSymbol.NamespaceKind = NamespaceKindNamespaceGroup Then
Dim boundParent As BoundExpression = BindNamespaceOrTypeOrExpressionSyntaxForSemanticModel(DirectCast(node.Parent, QualifiedNameSyntax), New DiagnosticBag())
Dim symbols = ArrayBuilder(Of Symbol).GetInstance()
BindNamespaceOrTypeSyntaxForSemanticModelGetExpressionSymbols(boundParent, symbols)
If symbols.Count = 0 Then
' If we didn't get anything, let's bind normally and see if any symbol comes out.
boundParent = BindExpression(DirectCast(node.Parent, QualifiedNameSyntax), New DiagnosticBag())
BindNamespaceOrTypeSyntaxForSemanticModelGetExpressionSymbols(boundParent, symbols)
End If
result = AdjustReceiverNamespace(namespaceExpr, symbols)
symbols.Free()
End If
End If
Return result
Else
Return Me.BindExpression(node, isInvocationOrAddressOf:=SyntaxFacts.IsInvocationOrAddressOfOperand(node), diagnostics:=diagnostics, isOperandOfConditionalBranch:=False, eventContext:=False)
End If
End Function
Private Shared Sub BindNamespaceOrTypeSyntaxForSemanticModelGetExpressionSymbols(expression As BoundExpression, symbols As ArrayBuilder(Of Symbol))
expression.GetExpressionSymbols(symbols)
If symbols.Count = 1 AndAlso symbols(0).Kind = SymbolKind.ErrorType Then
Dim errorType = DirectCast(symbols(0), ErrorTypeSymbol)
symbols.Clear()
Dim diagnosticInfo = TryCast(errorType.ErrorInfo, IDiagnosticInfoWithSymbols)
If diagnosticInfo IsNot Nothing Then
diagnosticInfo.GetAssociatedSymbols(symbols)
End If
End If
End Sub
''' <summary>
''' This function is only needed for SemanticModel to perform binding for erroneous cases.
''' </summary>
Private Function BindQualifiedName(name As QualifiedNameSyntax, diagnostics As DiagnosticBag) As BoundExpression
Return Me.BindMemberAccess(name, BindExpression(name.Left, diagnostics), name.Right, eventContext:=False, allowIntrinsicAliases:=False, diagnostics:=diagnostics)
End Function
Private Function BindGetTypeExpression(node As GetTypeExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression
' Create a special binder that allows unbound types
Dim getTypeBinder = New GetTypeBinder(node.Type, Me)
' GetType is more permissive on what is considered a valid type.
' for example it allows modules, System.Void or open generic types.
'returns either a type, an alias that refers to a type, or an error type
Dim typeOrAlias As Symbol = TypeBinder.BindTypeOrAliasSyntax(node.Type, getTypeBinder, diagnostics,
suppressUseSiteError:=False, inGetTypeContext:=True, resolvingBaseType:=False)
Dim aliasSym As AliasSymbol = TryCast(typeOrAlias, AliasSymbol)
Dim typeSym As TypeSymbol = DirectCast(If(aliasSym IsNot Nothing, aliasSym.Target, typeOrAlias), TypeSymbol)
Dim typeExpression = New BoundTypeExpression(node.Type, Nothing, aliasSym, typeSym, typeSym.IsErrorType())
' System.Void() is not allowed for VB.
If typeSym.IsArrayType AndAlso DirectCast(typeSym, ArrayTypeSymbol).ElementType.SpecialType = SpecialType.System_Void Then
ReportDiagnostic(diagnostics, node.Type, ErrorFactory.ErrorInfo(ERRID.ERR_VoidArrayDisallowed))
End If
Return New BoundGetType(node, typeExpression, GetWellKnownType(WellKnownType.System_Type, node, diagnostics))
End Function
Private Function BindNameOfExpression(node As NameOfExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression
' Suppress diagnostocs if argument has syntax errors
If node.Argument.HasErrors Then
diagnostics = New DiagnosticBag()
End If
Dim value As String = Nothing
Select Case node.Argument.Kind
Case SyntaxKind.SimpleMemberAccessExpression
value = DirectCast(node.Argument, MemberAccessExpressionSyntax).Name.Identifier.ValueText
Case SyntaxKind.IdentifierName,
SyntaxKind.GenericName
value = DirectCast(node.Argument, SimpleNameSyntax).Identifier.ValueText
Case Else
' Must be a syntax error
Debug.Assert(node.Argument.HasErrors)
End Select
' Bind the argument
Dim argument As BoundExpression = BindExpression(node.Argument, diagnostics)
Select Case argument.Kind
Case BoundKind.MethodGroup
Dim group = DirectCast(argument, BoundMethodGroup)
If group.ResultKind = LookupResultKind.Inaccessible Then
ReportDiagnostic(diagnostics,
If(node.Argument.Kind = SyntaxKind.SimpleMemberAccessExpression,
DirectCast(node.Argument, MemberAccessExpressionSyntax).Name,
node.Argument),
GetInaccessibleErrorInfo(group.Methods.First, useSiteDiagnostics:=Nothing))
ElseIf group.ResultKind = LookupResultKind.Good AndAlso group.TypeArgumentsOpt IsNot Nothing
ReportDiagnostic(diagnostics, group.TypeArgumentsOpt.Syntax, ERRID.ERR_MethodTypeArgsUnexpected)
End If
Case BoundKind.PropertyGroup
Dim group = DirectCast(argument, BoundPropertyGroup)
If group.ResultKind = LookupResultKind.Inaccessible Then
ReportDiagnostic(diagnostics,
If(node.Argument.Kind = SyntaxKind.SimpleMemberAccessExpression,
DirectCast(node.Argument, MemberAccessExpressionSyntax).Name,
node.Argument),
GetInaccessibleErrorInfo(group.Properties.First, useSiteDiagnostics:=Nothing))
End If
End Select
Return New BoundNameOfOperator(node, argument, ConstantValue.Create(value), GetSpecialType(SpecialType.System_String, node, diagnostics))
End Function
Private Sub VerifyNameOfLookupResult(container As NamespaceOrTypeSymbol, member As SimpleNameSyntax, lookupResult As LookupResult, diagnostics As DiagnosticBag)
If lookupResult.HasDiagnostic Then
' Ambiguous result is Ok
If Not lookupResult.IsAmbiguous Then
ReportDiagnostic(diagnostics, member, lookupResult.Diagnostic)
End If
ElseIf lookupResult.HasSymbol Then
Debug.Assert(lookupResult.IsGood)
ElseIf container IsNot Nothing
ReportDiagnostic(diagnostics, member, ErrorFactory.ErrorInfo(ERRID.ERR_NameNotMember2, member.Identifier.ValueText, container))
Else
ReportDiagnostic(diagnostics, member, ErrorFactory.ErrorInfo(ERRID.ERR_NameNotDeclared1, member.Identifier.ValueText))
End If
End Sub
Private Function BindTypeOfExpression(node As TypeOfExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression
Dim operand = BindRValue(node.Expression, diagnostics, isOperandOfConditionalBranch:=False)
Dim operandType = operand.Type
Dim operatorIsIsNot = (node.Kind = SyntaxKind.TypeOfIsNotExpression)
Dim targetSymbol As Symbol = BindTypeOrAliasSyntax(node.Type, diagnostics)
Dim targetType = DirectCast(If(TryCast(targetSymbol, TypeSymbol), DirectCast(targetSymbol, AliasSymbol).Target), TypeSymbol)
Dim resultType As TypeSymbol = GetSpecialType(SpecialType.System_Boolean, node, diagnostics)
If operand.HasErrors OrElse operandType.IsErrorType() OrElse targetType.IsErrorType() Then
' If operand is bad or either the source or target types have errors, bail out preventing more cascading errors.
Return New BoundTypeOf(node, operand, operatorIsIsNot, targetType, resultType)
End If
If Not operandType.IsReferenceType AndAlso
Not operandType.IsTypeParameter() Then
ReportDiagnostic(diagnostics, node.Expression, ERRID.ERR_TypeOfRequiresReferenceType1, operandType)
Else
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Dim convKind As ConversionKind = Conversions.ClassifyTryCastConversion(operandType, targetType, useSiteDiagnostics)
If diagnostics.Add(node, useSiteDiagnostics) Then
' Suppress any additional diagnostics
diagnostics = New DiagnosticBag()
ElseIf Not Conversions.ConversionExists(convKind) Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_TypeOfExprAlwaysFalse2, operandType, targetType)
End If
End If
If operandType.IsTypeParameter() Then
operand = ApplyImplicitConversion(node, GetSpecialType(SpecialType.System_Object, node.Expression, diagnostics), operand, diagnostics)
End If
Return New BoundTypeOf(node, operand, operatorIsIsNot, targetType, resultType)
End Function
''' <summary>
''' BindValue evaluates the node and returns a BoundExpression. BindValue snaps expressions to values. For now that means that method groups
''' become invocations.
''' </summary>
Friend Function BindValue(
node As ExpressionSyntax,
diagnostics As DiagnosticBag,
Optional isOperandOfConditionalBranch As Boolean = False
) As BoundExpression
Dim expr = BindExpression(node, diagnostics:=diagnostics, isOperandOfConditionalBranch:=isOperandOfConditionalBranch, isInvocationOrAddressOf:=False, eventContext:=False)
Return MakeValue(expr, diagnostics)
End Function
Private Function AdjustReceiverTypeOrValue(receiver As BoundExpression,
node As VisualBasicSyntaxNode,
isShared As Boolean,
diagnostics As DiagnosticBag,
ByRef resolvedTypeOrValueExpression As BoundExpression) As BoundExpression
Dim unused As QualificationKind
Return AdjustReceiverTypeOrValue(receiver, node, isShared, True, diagnostics, unused, resolvedTypeOrValueExpression)
End Function
Private Function AdjustReceiverTypeOrValue(receiver As BoundExpression,
node As VisualBasicSyntaxNode,
isShared As Boolean,
diagnostics As DiagnosticBag,
ByRef qualKind As QualificationKind) As BoundExpression
Dim unused As BoundExpression = Nothing
Return AdjustReceiverTypeOrValue(receiver, node, isShared, False, diagnostics, qualKind, unused)
End Function
''' <summary>
''' Adjusts receiver of a call or a member access.
''' * will turn Unknown property access into Get property access
''' * will turn TypeOrValueExpression into a value expression
''' </summary>
Private Function AdjustReceiverTypeOrValue(receiver As BoundExpression,
node As VisualBasicSyntaxNode,
isShared As Boolean,
clearIfShared As Boolean,
diagnostics As DiagnosticBag,
ByRef qualKind As QualificationKind,
ByRef resolvedTypeOrValueExpression As BoundExpression) As BoundExpression
If receiver Is Nothing Then
Return receiver
End If
If isShared Then
If receiver.Kind = BoundKind.TypeOrValueExpression Then
Dim typeOrValue = DirectCast(receiver, BoundTypeOrValueExpression)
diagnostics.AddRange(typeOrValue.Data.TypeDiagnostics)
receiver = typeOrValue.Data.TypeExpression
qualKind = QualificationKind.QualifiedViaTypeName
resolvedTypeOrValueExpression = receiver
End If
If clearIfShared Then
receiver = Nothing
End If
Else
If receiver.Kind = BoundKind.TypeOrValueExpression Then
Dim typeOrValue = DirectCast(receiver, BoundTypeOrValueExpression)
diagnostics.AddRange(typeOrValue.Data.ValueDiagnostics)
receiver = MakeValue(typeOrValue.Data.ValueExpression, diagnostics)
qualKind = QualificationKind.QualifiedViaValue
resolvedTypeOrValueExpression = receiver
End If
receiver = AdjustReceiverValue(receiver, node, diagnostics)
End If
Return receiver
End Function
''' <summary>
''' Adjusts receiver of a call or a member access if the receiver is an
''' ambiguous BoundTypeOrValueExpression. This can only happen if the
''' receiver is the LHS of a member access expression in which the
''' RHS cannot be resolved (i.e. the RHS is an error or a late-bound
''' invocation/access).
''' </summary>
Private Function AdjustReceiverAmbiguousTypeOrValue(receiver As BoundExpression, diagnostics As DiagnosticBag) As BoundExpression
If receiver IsNot Nothing AndAlso receiver.Kind = BoundKind.TypeOrValueExpression Then
Dim typeOrValue = DirectCast(receiver, BoundTypeOrValueExpression)
diagnostics.AddRange(typeOrValue.Data.ValueDiagnostics)
receiver = typeOrValue.Data.ValueExpression
End If
Return receiver
End Function
Private Function AdjustReceiverAmbiguousTypeOrValue(ByRef group As BoundMethodOrPropertyGroup, diagnostics As DiagnosticBag) As BoundExpression
Debug.Assert(group IsNot Nothing)
Dim receiver = group.ReceiverOpt
If receiver IsNot Nothing AndAlso receiver.Kind = BoundKind.TypeOrValueExpression Then
receiver = AdjustReceiverAmbiguousTypeOrValue(receiver, diagnostics)
Select Case group.Kind
Case BoundKind.MethodGroup
Dim methodGroup = DirectCast(group, BoundMethodGroup)
group = methodGroup.Update(methodGroup.TypeArgumentsOpt,
methodGroup.Methods,
methodGroup.PendingExtensionMethodsOpt,
methodGroup.ResultKind,
receiver,
methodGroup.QualificationKind)
Case BoundKind.PropertyGroup
Dim propertyGroup = DirectCast(group, BoundPropertyGroup)
group = propertyGroup.Update(propertyGroup.Properties,
propertyGroup.ResultKind,
receiver,
propertyGroup.QualificationKind)
Case Else
Throw ExceptionUtilities.UnexpectedValue(group.Kind)
End Select
End If
Return receiver
End Function
''' <summary>
''' Adjusts receiver of a call or a member access if it is a value
''' * will turn Unknown property access into Get property access
''' </summary>
Private Function AdjustReceiverValue(receiver As BoundExpression,
node As VisualBasicSyntaxNode,
diagnostics As DiagnosticBag) As BoundExpression
If Not receiver.IsValue() Then
receiver = MakeValue(receiver, diagnostics)
End If
If Not receiver.IsLValue AndAlso Not receiver.IsPropertyOrXmlPropertyAccess() Then
receiver = MakeRValue(receiver, diagnostics)
End If
Dim type = receiver.Type
If type Is Nothing OrElse type.IsErrorType() Then
Return BadExpression(node, receiver, LookupResultKind.NotAValue, ErrorTypeSymbol.UnknownResultType)
End If
Return receiver
End Function
Friend Function ReclassifyAsValue(
expr As BoundExpression,
diagnostics As DiagnosticBag
) As BoundExpression
If expr.HasErrors Then
Return expr
End If
Select Case expr.Kind
Case BoundKind.Parenthesized
If Not expr.IsNothingLiteral() Then
Return MakeRValue(expr, diagnostics)
End If
Case BoundKind.MethodGroup,
BoundKind.PropertyGroup
Dim group = DirectCast(expr, BoundMethodOrPropertyGroup)
If IsGroupOfConstructors(group) Then
' cannot reclassify a constructor call
ReportDiagnostic(diagnostics, group.Syntax, ERRID.ERR_InvalidConstructorCall)
Return New BoundBadVariable(expr.Syntax, expr, ErrorTypeSymbol.UnknownResultType, hasErrors:=True)
Else
expr = BindInvocationExpression(expr.Syntax,
expr.Syntax,
ExtractTypeCharacter(expr.Syntax),
group,
s_noArguments,
Nothing,
diagnostics,
callerInfoOpt:=expr.Syntax)
End If
Case BoundKind.TypeExpression
' Try default instance property through DefaultInstanceAlias
Dim instance As BoundExpression = TryDefaultInstanceProperty(DirectCast(expr, BoundTypeExpression), diagnostics)
If instance Is Nothing Then
Dim type = expr.Type
ReportDiagnostic(diagnostics, expr.Syntax, GetTypeNotExpressionErrorId(type), type)
Return New BoundBadVariable(expr.Syntax, expr, ErrorTypeSymbol.UnknownResultType, hasErrors:=True)
End If
expr = instance
Case BoundKind.EventAccess
ReportDiagnostic(diagnostics, expr.Syntax, ERRID.ERR_CannotCallEvent1, DirectCast(expr, BoundEventAccess).EventSymbol)
Return New BoundBadVariable(expr.Syntax, expr, ErrorTypeSymbol.UnknownResultType, hasErrors:=True)
Case BoundKind.NamespaceExpression
ReportDiagnostic(diagnostics, expr.Syntax, ERRID.ERR_NamespaceNotExpression1, DirectCast(expr, BoundNamespaceExpression).NamespaceSymbol)
Return New BoundBadVariable(expr.Syntax, expr, ErrorTypeSymbol.UnknownResultType, hasErrors:=True)
Case BoundKind.Label
ReportDiagnostic(diagnostics, expr.Syntax, ERRID.ERR_VoidValue, DirectCast(expr, BoundLabel).Label.Name)
Return New BoundBadVariable(expr.Syntax, expr, ErrorTypeSymbol.UnknownResultType, hasErrors:=True)
End Select
Debug.Assert(expr.IsValue)
Return expr
End Function
Friend Overridable ReadOnly Property IsDefaultInstancePropertyAllowed As Boolean
Get
Return m_containingBinder.IsDefaultInstancePropertyAllowed
End Get
End Property
Friend Overridable ReadOnly Property SuppressCallerInfo As Boolean
Get
Return m_containingBinder.SuppressCallerInfo
End Get
End Property
Friend Function TryDefaultInstanceProperty(typeExpr As BoundTypeExpression, diagnosticsBagFor_ERR_CantReferToMyGroupInsideGroupType1 As DiagnosticBag) As BoundExpression
If Not IsDefaultInstancePropertyAllowed Then
Return Nothing
End If
' See Semantics::CheckForDefaultInstanceProperty.
Dim type As TypeSymbol = typeExpr.Type
If type.IsErrorType() OrElse
SourceModule IsNot type.ContainingModule OrElse
type.TypeKind <> TypeKind.Class Then
Return Nothing
End If
Dim classType = DirectCast(type, NamedTypeSymbol)
If classType.IsGenericType Then
Return Nothing
End If
Dim prop As SynthesizedMyGroupCollectionPropertySymbol = SourceModule.GetMyGroupCollectionPropertyWithDefaultInstanceAlias(classType)
If prop Is Nothing Then
Return Nothing
End If
Debug.Assert(prop.Type Is classType)
' Lets try to parse and bind an expression of the following form:
' <DefaultInstanceAlias>.<MyGroupCollectionProperty name>
' If any error happens, return Nothing without reporting any diagnostics.
' Note, native compiler doesn't escape DefaultInstanceAlias if it is a reserved keyword.
Dim codeToParse As String =
"Class DefaultInstanceAlias" & vbCrLf &
"Function DefaultInstanceAlias()" & vbCrLf &
"Return " & prop.DefaultInstanceAlias & "." & prop.Name & vbCrLf &
"End Function" & vbCrLf &
"End Class" & vbCrLf
' It looks like Dev11 ignores project level conditional compilation here, which makes sense since expression cannot contain #If directives.
Dim tree = VisualBasicSyntaxTree.ParseText(codeToParse)
Dim root As CompilationUnitSyntax = tree.GetCompilationUnitRoot()
Dim hasErrors As Boolean = False
For Each diag As Diagnostic In tree.GetDiagnostics(root)
Dim cdiag = TryCast(diag, DiagnosticWithInfo)
Debug.Assert(cdiag Is Nothing OrElse Not cdiag.HasLazyInfo,
"If we decide to allow lazy syntax diagnostics, we'll have to check all call sites of SyntaxTree.GetDiagnostics")
If diag.Severity = DiagnosticSeverity.Error Then
Return Nothing
End If
Next
Dim classBlock = DirectCast(root.Members(0), ClassBlockSyntax)
Dim functionBlock = DirectCast(classBlock.Members(0), MethodBlockSyntax)
' We expect there to be only one statement, which is [Return] statement.
If functionBlock.Statements.Count > 1 Then
Return Nothing
End If
Dim ret = DirectCast(functionBlock.Statements(0), ReturnStatementSyntax)
Dim exprDiagnostics = DiagnosticBag.GetInstance()
Dim result As BoundExpression = (New DefaultInstancePropertyBinder(Me)).BindValue(ret.Expression, exprDiagnostics)
If result.HasErrors OrElse exprDiagnostics.HasAnyErrors() Then
exprDiagnostics.Free()
Return Nothing
End If
exprDiagnostics.Free()
' if the default inst expression cannot be correctly bound to an instance of the same type as the class
' ignore it.
If result.Type IsNot classType Then
Return Nothing
End If
If diagnosticsBagFor_ERR_CantReferToMyGroupInsideGroupType1 IsNot Nothing AndAlso
ContainingType Is classType AndAlso Not ContainingMember.IsShared Then
ReportDiagnostic(diagnosticsBagFor_ERR_CantReferToMyGroupInsideGroupType1, typeExpr.Syntax, ERRID.ERR_CantReferToMyGroupInsideGroupType1, classType)
End If
Return result
End Function
Private Class DefaultInstancePropertyBinder
Inherits Binder
Public Sub New(containingBinder As Binder)
MyBase.New(containingBinder)
End Sub
Public Overrides ReadOnly Property ImplicitVariableDeclarationAllowed As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property IsDefaultInstancePropertyAllowed As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property SuppressCallerInfo As Boolean
Get
Return True
End Get
End Property
End Class
Private Function GetTypeNotExpressionErrorId(type As TypeSymbol) As ERRID
Select Case type.TypeKind
Case TypeKind.Class
Return ERRID.ERR_ClassNotExpression1
Case TypeKind.Interface
Return ERRID.ERR_InterfaceNotExpression1
Case TypeKind.Enum
Return ERRID.ERR_EnumNotExpression1
Case TypeKind.Structure
Return ERRID.ERR_StructureNotExpression1
' TODO Modules??
Case Else
Return ERRID.ERR_TypeNotExpression1
End Select
End Function
Private Function MakeValue(
expr As BoundExpression,
diagnostics As DiagnosticBag
) As BoundExpression
If expr.Kind = BoundKind.Parenthesized Then
If Not expr.IsNothingLiteral() Then
Dim parenthesized = DirectCast(expr, BoundParenthesized)
Dim enclosed As BoundExpression = MakeValue(parenthesized.Expression, diagnostics)
Return parenthesized.Update(enclosed, enclosed.Type)
End If
ElseIf expr.Kind = BoundKind.ConditionalAccess AndAlso expr.Type Is Nothing Then
Dim conditionalAccess = DirectCast(expr, BoundConditionalAccess)
Dim access As BoundExpression = Me.MakeRValue(conditionalAccess.AccessExpression, diagnostics)
Dim resultType As TypeSymbol = access.Type
If Not resultType.IsErrorType() Then
If resultType.IsValueType Then
If Not resultType.IsNullableType() Then
resultType = GetSpecialType(SpecialType.System_Nullable_T, expr.Syntax, diagnostics).Construct(resultType)
End If
ElseIf Not resultType.IsReferenceType Then
' Access cannot have unconstrained generic type
ReportDiagnostic(diagnostics, access.Syntax, ERRID.ERR_CannotBeMadeNullable1, resultType)
resultType = ErrorTypeSymbol.UnknownResultType
End If
End If
Return conditionalAccess.Update(conditionalAccess.Receiver, conditionalAccess.Placeholder, access, resultType)
End If
expr = ReclassifyAsValue(expr, diagnostics)
If expr.HasErrors Then
If Not expr.IsValue OrElse expr.Type Is Nothing OrElse expr.Type.IsVoidType Then
Return BadExpression(expr.Syntax, expr, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
Else
Return expr
End If
End If
Dim exprType = expr.Type
Dim syntax = expr.Syntax
If Not expr.IsValue() OrElse
(exprType IsNot Nothing AndAlso exprType.SpecialType = SpecialType.System_Void) Then
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_VoidValue)
Return BadExpression(syntax, expr, LookupResultKind.NotAValue, ErrorTypeSymbol.UnknownResultType)
ElseIf expr.Kind = BoundKind.PropertyAccess Then
Dim propertyAccess = DirectCast(expr, BoundPropertyAccess)
Select Case propertyAccess.AccessKind
Case PropertyAccessKind.Set
Debug.Assert(False)
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_VoidValue)
Return BadExpression(syntax, expr, LookupResultKind.NotAValue, ErrorTypeSymbol.UnknownResultType)
Case PropertyAccessKind.Unknown
Dim hasError = True
Dim propertySymbol = propertyAccess.PropertySymbol
If Not propertySymbol.IsReadable Then
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_NoGetProperty1, CustomSymbolDisplayFormatter.ShortErrorName(propertySymbol))
Else
Dim getMethod = propertySymbol.GetMostDerivedGetMethod()
Debug.Assert(getMethod IsNot Nothing)
If Not ReportUseSiteError(diagnostics, syntax, getMethod) Then
Dim accessThroughType = GetAccessThroughType(propertyAccess.ReceiverOpt)
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
If IsAccessible(getMethod, useSiteDiagnostics, accessThroughType) OrElse
Not IsAccessible(propertySymbol, useSiteDiagnostics, accessThroughType) Then
hasError = False
Else
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_NoAccessibleGet, CustomSymbolDisplayFormatter.ShortErrorName(propertySymbol))
End If
diagnostics.Add(syntax, useSiteDiagnostics)
End If
End If
If hasError Then
Return BadExpression(syntax, expr, LookupResultKind.NotAValue, propertySymbol.Type)
End If
End Select
ElseIf expr.IsLateBound() Then
If (expr.GetLateBoundAccessKind() And (LateBoundAccessKind.Set Or LateBoundAccessKind.Call)) <> 0 Then
Debug.Assert(False)
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_VoidValue)
Return BadExpression(syntax, expr, LookupResultKind.NotAValue, ErrorTypeSymbol.UnknownResultType)
End If
ElseIf expr.Kind = BoundKind.AddressOfOperator Then
Return expr
End If
Return expr
End Function
Private Function GetAccessThroughType(receiverOpt As BoundExpression) As TypeSymbol
If receiverOpt Is Nothing OrElse receiverOpt.Kind = BoundKind.MyBaseReference Then
' NOTE: If we are accessing the symbol via MyBase reference we may
' assume the access is being performed via 'Me'
Return ContainingType
Else
Debug.Assert(receiverOpt.Type IsNot Nothing)
Return receiverOpt.Type
End If
End Function
''' <summary>
''' BindRValue evaluates the node and returns a BoundExpression.
''' It ensures that the expression is a value that can be used on the right hand side of an assignment.
''' If not, it reports an error.
'''
''' Note that this function will reclassify all expressions to have their "default" type, i.e.
''' Anonymous Delegate for a lambda, default array type for an array literal, will report an error
''' for an AddressOf, etc. So, if you are in a context where there is a known target type for the
''' expression, do not use this function. Instead, use BindValue followed by
''' ApplyImplicitConversion/ApplyConversion.
''' </summary>
Private Function BindRValue(
node As ExpressionSyntax,
diagnostics As DiagnosticBag,
Optional isOperandOfConditionalBranch As Boolean = False
) As BoundExpression
Dim expr = BindExpression(node, diagnostics:=diagnostics, isOperandOfConditionalBranch:=isOperandOfConditionalBranch, isInvocationOrAddressOf:=False, eventContext:=False)
Return MakeRValue(expr, diagnostics)
End Function
Friend Function MakeRValue(
expr As BoundExpression,
diagnostics As DiagnosticBag
) As BoundExpression
If expr.Kind = BoundKind.Parenthesized AndAlso Not expr.IsNothingLiteral() Then
Dim parenthesized = DirectCast(expr, BoundParenthesized)
Dim enclosed As BoundExpression = MakeRValue(parenthesized.Expression, diagnostics)
Return parenthesized.Update(enclosed, enclosed.Type)
ElseIf expr.Kind = BoundKind.XmlMemberAccess Then
Dim memberAccess = DirectCast(expr, BoundXmlMemberAccess)
Dim enclosed = MakeRValue(memberAccess.MemberAccess, diagnostics)
Return memberAccess.Update(enclosed)
End If
expr = MakeValue(expr, diagnostics)
If expr.HasErrors Then
Return expr.MakeRValue()
End If
Debug.Assert(expr.IsValue())
Dim exprType = expr.Type
If exprType Is Nothing Then
Return ReclassifyExpression(expr, diagnostics)
End If
' Transform LValue to RValue.
If expr.IsLValue Then
expr = expr.MakeRValue()
ElseIf expr.Kind = BoundKind.PropertyAccess Then
Dim propertyAccess = DirectCast(expr, BoundPropertyAccess)
Dim getMethod = propertyAccess.PropertySymbol.GetMostDerivedGetMethod()
Debug.Assert(getMethod IsNot Nothing)
ReportDiagnosticsIfObsolete(diagnostics, getMethod, expr.Syntax)
Select Case propertyAccess.AccessKind
Case PropertyAccessKind.Get
' Nothing to do.
Case PropertyAccessKind.Unknown
Debug.Assert(propertyAccess.PropertySymbol.IsReadable)
WarnOnRecursiveAccess(propertyAccess, PropertyAccessKind.Get, diagnostics)
expr = propertyAccess.SetAccessKind(PropertyAccessKind.Get)
Case Else
Throw ExceptionUtilities.UnexpectedValue(propertyAccess.AccessKind)
End Select
ElseIf expr.IsLateBound() Then
Select Case expr.GetLateBoundAccessKind()
Case LateBoundAccessKind.Get
' Nothing to do.
Case LateBoundAccessKind.Unknown
expr = expr.SetLateBoundAccessKind(LateBoundAccessKind.Get)
Case Else
Throw ExceptionUtilities.UnexpectedValue(expr.GetLateBoundAccessKind())
End Select
End If
Return expr
End Function
Private Function MakeRValueAndIgnoreDiagnostics(
expr As BoundExpression
) As BoundExpression
Dim ignoreErrors = DiagnosticBag.GetInstance()
expr = MakeRValue(expr, ignoreErrors)
ignoreErrors.Free()
Return expr
End Function
Friend Function ReclassifyExpression(
expr As BoundExpression,
diagnostics As DiagnosticBag
) As BoundExpression
If expr.IsNothingLiteral() Then
' This is a Nothing literal without a type.
' Reclassify as Object.
Return New BoundConversion(expr.Syntax, expr, ConversionKind.WideningNothingLiteral, False, False, expr.ConstantValueOpt,
GetSpecialType(SpecialType.System_Object, expr.Syntax, diagnostics), Nothing)
End If
Select Case expr.Kind
Case BoundKind.Parenthesized
' Reclassify enclosed expression.
Dim parenthesized = DirectCast(expr, BoundParenthesized)
Dim enclosed As BoundExpression = ReclassifyExpression(parenthesized.Expression, diagnostics)
Return parenthesized.Update(enclosed, enclosed.Type)
Case BoundKind.UnboundLambda
Return ReclassifyUnboundLambdaExpression(DirectCast(expr, UnboundLambda), diagnostics)
Case BoundKind.AddressOfOperator
Dim address = DirectCast(expr, BoundAddressOfOperator)
If address.MethodGroup.ResultKind = LookupResultKind.Inaccessible Then
If address.MethodGroup.Methods.Length = 1 Then
ReportDiagnostic(diagnostics, address.MethodGroup.Syntax, GetInaccessibleErrorInfo(address.MethodGroup.Methods(0), useSiteDiagnostics:=Nothing))
Else
ReportDiagnostic(diagnostics, address.MethodGroup.Syntax, ERRID.ERR_NoViableOverloadCandidates1,
address.MethodGroup.Methods(0).Name)
End If
Else
Debug.Assert(address.MethodGroup.ResultKind = LookupResultKind.Good)
End If
ReportDiagnostic(diagnostics, expr.Syntax, ERRID.ERR_VoidValue)
Return BadExpression(expr.Syntax, expr, ErrorTypeSymbol.UnknownResultType)
Case BoundKind.ArrayLiteral
Return ReclassifyArrayLiteralExpression(DirectCast(expr, BoundArrayLiteral), diagnostics)
Case Else
'TODO: We need to do other expression reclassifications here.
' For now, we simply report an error.
ReportDiagnostic(diagnostics, expr.Syntax, ERRID.ERR_VoidValue)
Return BadExpression(expr.Syntax, expr, ErrorTypeSymbol.UnknownResultType)
End Select
End Function
Private Function ReclassifyArrayLiteralExpression(conversionSemantics As SyntaxKind,
tree As VisualBasicSyntaxNode,
conv As ConversionKind,
isExplicit As Boolean,
arrayLiteral As BoundArrayLiteral,
destination As TypeSymbol,
diagnostics As DiagnosticBag) As BoundExpression
Debug.Assert((conv And ConversionKind.UserDefined) = 0)
Debug.Assert(Not (TypeOf destination Is ArrayLiteralTypeSymbol)) 'An array literal should never be reclassified as an array literal.
If Conversions.NoConversion(conv) AndAlso (conv And ConversionKind.FailedDueToArrayLiteralElementConversion) = 0 Then
If Not arrayLiteral.HasDominantType Then
' When there is a conversion error and there isn't a dominant type, report "error BC36717: Cannot infer an element type.
' Specifying the type of the array might correct this error." instead of the specific conversion error because the inferred
' type used in classification was just a guess.
ReportDiagnostic(diagnostics, arrayLiteral.Syntax, ERRID.ERR_ArrayInitNoType)
Else
ReportNoConversionError(arrayLiteral.Syntax, arrayLiteral.InferredType, destination, diagnostics, Nothing)
End If
Dim ignoredDiagnostics = DiagnosticBag.GetInstance
' Because we've already reported a no conversion error, ignore any diagnostics in ApplyImplicitConversion
Dim argument As BoundExpression = ApplyImplicitConversion(arrayLiteral.Syntax, arrayLiteral.InferredType, arrayLiteral, ignoredDiagnostics)
ignoredDiagnostics.Free()
If conversionSemantics = SyntaxKind.CTypeKeyword Then
argument = New BoundConversion(tree, argument, conv, False, isExplicit, destination)
ElseIf conversionSemantics = SyntaxKind.DirectCastKeyword Then
argument = New BoundDirectCast(tree, argument, conv, destination)
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
argument = New BoundTryCast(tree, argument, conv, destination)
Else
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End If
Return argument
End If
' This code must be kept in sync with Conversions.ClassifyArrayLiteralConversion
Dim sourceType = arrayLiteral.InferredType
Dim targetType = TryCast(destination, NamedTypeSymbol)
Dim originalTargetType = If(targetType IsNot Nothing, targetType.OriginalDefinition, Nothing)
Dim targetArrayType As ArrayTypeSymbol = TryCast(destination, ArrayTypeSymbol)
Dim targetElementType As TypeSymbol = Nothing
If targetArrayType IsNot Nothing AndAlso (sourceType.Rank = targetArrayType.Rank OrElse arrayLiteral.IsEmptyArrayLiteral) Then
targetElementType = targetArrayType.ElementType
sourceType = targetArrayType
ElseIf (sourceType.Rank = 1 OrElse arrayLiteral.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.TypeArgumentsNoUseSiteDiagnostics(0)
sourceType = New ArrayTypeSymbol(targetElementType, Nothing, 1, Compilation)
Else
' Use the inferred type
targetArrayType = sourceType
targetElementType = sourceType.ElementType
End If
ReportArrayLiteralDiagnostics(arrayLiteral, targetArrayType, diagnostics)
Dim arrayInitialization As BoundArrayInitialization
Dim bounds As ImmutableArray(Of BoundExpression)
If arrayLiteral.IsEmptyArrayLiteral Then
Dim knownSizes(sourceType.Rank - 1) As DimensionSize
arrayInitialization = ReclassifyEmptyArrayInitialization(arrayLiteral, sourceType.Rank)
bounds = CreateArrayBounds(arrayLiteral.Syntax, knownSizes, diagnostics)
Else
arrayInitialization = ReclassifyArrayInitialization(arrayLiteral.Initializer, targetElementType, diagnostics)
bounds = arrayLiteral.Bounds
End If
' Mark as compiler generated so that semantic model does not select the array initialization bound node.
' The array initialization node is not a real expression and lacks a type.
arrayInitialization.SetWasCompilerGenerated()
Debug.Assert(Not Conversions.IsIdentityConversion(conv))
Dim arrayCreation = New BoundArrayCreation(arrayLiteral.Syntax, bounds, arrayInitialization, arrayLiteral, conv, sourceType)
If conversionSemantics = SyntaxKind.CTypeKeyword Then
Return ApplyConversion(tree, destination, arrayCreation, isExplicit, diagnostics)
Else
Dim expr As BoundExpression = arrayCreation
' Apply char() to string conversion before directcast/trycast
conv = Conversions.ClassifyStringConversion(sourceType, destination)
If Conversions.IsWideningConversion(conv) Then
expr = CreatePredefinedConversion(arrayLiteral.Syntax, arrayCreation, conv, isExplicit, destination, diagnostics)
End If
If conversionSemantics = SyntaxKind.DirectCastKeyword Then
Return ApplyDirectCastConversion(tree, expr, destination, diagnostics)
ElseIf conversionSemantics = SyntaxKind.TryCastKeyword Then
Return ApplyTryCastConversion(tree, expr, destination, diagnostics)
Else
Throw ExceptionUtilities.UnexpectedValue(conversionSemantics)
End If
End If
End Function
Private Sub ReportArrayLiteralDiagnostics(arrayLiteral As BoundArrayLiteral, targetArrayType As ArrayTypeSymbol, diagnostics As DiagnosticBag)
If targetArrayType Is arrayLiteral.InferredType Then
' Note, array type symbols do not preserve identity. If the target array is the same as the inferred array then we
' assume that the target has inferred its type from the array literal.
ReportArrayLiteralInferredTypeDiagnostics(arrayLiteral, diagnostics)
End If
End Sub
Private Sub ReportArrayLiteralInferredTypeDiagnostics(arrayLiteral As BoundArrayLiteral, diagnostics As DiagnosticBag)
Dim targetElementType = arrayLiteral.InferredType.ElementType
If targetElementType.IsRestrictedType Then
ReportDiagnostic(diagnostics, arrayLiteral.Syntax, ERRID.ERR_RestrictedType1, targetElementType)
ElseIf Not arrayLiteral.HasDominantType Then
ReportDiagnostic(diagnostics, arrayLiteral.Syntax, ERRID.ERR_ArrayInitNoType)
Else
' Possibly warn or report an error depending on the value of option strict
Select Case OptionStrict
Case VisualBasic.OptionStrict.On
If arrayLiteral.NumberOfCandidates = 0 Then
ReportDiagnostic(diagnostics, arrayLiteral.Syntax, ERRID.ERR_ArrayInitNoTypeObjectDisallowed)
ElseIf arrayLiteral.NumberOfCandidates > 1 Then
ReportDiagnostic(diagnostics, arrayLiteral.Syntax, ERRID.ERR_ArrayInitTooManyTypesObjectDisallowed)
End If
Case VisualBasic.OptionStrict.Custom
If arrayLiteral.NumberOfCandidates = 0 Then
ReportDiagnostic(diagnostics, arrayLiteral.Syntax, ErrorFactory.ErrorInfo(ERRID.WRN_ObjectAssumed1,
ErrorFactory.ErrorInfo(ERRID.WRN_ArrayInitNoTypeObjectAssumed)))
ElseIf arrayLiteral.NumberOfCandidates > 1 Then
ReportDiagnostic(diagnostics, arrayLiteral.Syntax, ErrorFactory.ErrorInfo(ERRID.WRN_ObjectAssumed1,
ErrorFactory.ErrorInfo(ERRID.WRN_ArrayInitTooManyTypesObjectAssumed)))
End If
End Select
End If
End Sub
Private Function ReclassifyArrayInitialization(arrayInitialization As BoundArrayInitialization, elementType As TypeSymbol, diagnostics As DiagnosticBag) As BoundArrayInitialization
Dim initializers = ArrayBuilder(Of BoundExpression).GetInstance
' Apply implicit conversion to the elements.
For Each expr In arrayInitialization.Initializers
If expr.Kind = BoundKind.ArrayInitialization Then
expr = ReclassifyArrayInitialization(DirectCast(expr, BoundArrayInitialization), elementType, diagnostics)
Else
expr = ApplyImplicitConversion(expr.Syntax, elementType, expr, diagnostics)
End If
initializers.Add(expr)
Next
arrayInitialization = New BoundArrayInitialization(arrayInitialization.Syntax, initializers.ToImmutableAndFree, Nothing)
Return arrayInitialization
End Function
Private Function ReclassifyEmptyArrayInitialization(arrayLiteral As BoundArrayLiteral, rank As Integer) As BoundArrayInitialization
Dim arrayInitialization As BoundArrayInitialization = arrayLiteral.Initializer
If rank = 1 Then
Return arrayInitialization
End If
Dim initializers = ImmutableArray(Of BoundExpression).Empty
For i = 1 To rank
arrayInitialization = New BoundArrayInitialization(arrayInitialization.Syntax, initializers, Nothing)
initializers = ImmutableArray.Create(Of BoundExpression)(arrayInitialization)
Next
Return arrayInitialization
End Function
Private Function ReclassifyArrayLiteralExpression(
arrayLiteral As BoundArrayLiteral,
diagnostics As DiagnosticBag
) As BoundExpression
Return ApplyImplicitConversion(arrayLiteral.Syntax,
arrayLiteral.InferredType,
arrayLiteral,
diagnostics)
End Function
Private Function ReclassifyUnboundLambdaExpression(
lambda As UnboundLambda,
diagnostics As DiagnosticBag
) As BoundExpression
Return ApplyImplicitConversion(lambda.Syntax,
lambda.InferredAnonymousDelegate.Key,
lambda,
diagnostics,
isOperandOfConditionalBranch:=False)
End Function
Private Function BindAssignmentTarget(
node As ExpressionSyntax,
diagnostics As DiagnosticBag
) As BoundExpression
Dim expression = BindExpression(node, diagnostics)
Return BindAssignmentTarget(node, expression, diagnostics)
End Function
Private Function BindAssignmentTarget(
node As VisualBasicSyntaxNode,
expression As BoundExpression,
diagnostics As DiagnosticBag
) As BoundExpression
expression = ReclassifyAsValue(expression, diagnostics)
If Not IsValidAssignmentTarget(expression) Then
If Not expression.HasErrors Then
ReportAssignmentToRValue(expression, diagnostics)
End If
expression = BadExpression(node, expression, LookupResultKind.NotAVariable, ErrorTypeSymbol.UnknownResultType)
ElseIf expression.Kind = BoundKind.LateInvocation Then
' Since this is a target of an assignment, it is guaranteed to be an array or a property,
' therefore, arguments will be passed ByVal, let's capture this fact in the tree,
' this will simplify analysis later.
Dim invocation = DirectCast(expression, BoundLateInvocation)
If Not invocation.ArgumentsOpt.IsEmpty Then
Dim newArguments(invocation.ArgumentsOpt.Length - 1) As BoundExpression
For i As Integer = 0 To newArguments.Length - 1
newArguments(i) = MakeRValue(invocation.ArgumentsOpt(i), diagnostics)
Next
expression = invocation.Update(invocation.Member,
newArguments.AsImmutableOrNull(),
invocation.ArgumentNamesOpt,
invocation.AccessKind,
invocation.MethodOrPropertyGroupOpt,
invocation.Type)
End If
End If
Return expression
End Function
Friend Shared Function IsValidAssignmentTarget(expression As BoundExpression) As Boolean
Select Case expression.Kind
Case BoundKind.PropertyAccess
Dim propertyAccess = DirectCast(expression, BoundPropertyAccess)
Dim [property] = propertyAccess.PropertySymbol
Dim receiver = propertyAccess.ReceiverOpt
Debug.Assert(propertyAccess.AccessKind <> PropertyAccessKind.Get)
Return propertyAccess.AccessKind <> PropertyAccessKind.Get AndAlso
([property].IsShared OrElse
receiver Is Nothing OrElse
receiver.IsLValue() OrElse
receiver.IsMeReference() OrElse
receiver.IsMyClassReference() OrElse
Not receiver.Type.IsValueType) ' If this logic changes, logic in UseTwiceRewriter.UseTwicePropertyAccess might need to change too.
Case BoundKind.XmlMemberAccess
Return IsValidAssignmentTarget(DirectCast(expression, BoundXmlMemberAccess).MemberAccess)
Case BoundKind.LateInvocation
Dim invocation = DirectCast(expression, BoundLateInvocation)
Debug.Assert(invocation.AccessKind <> LateBoundAccessKind.Get AndAlso invocation.AccessKind <> LateBoundAccessKind.Call)
Return invocation.AccessKind <> LateBoundAccessKind.Get AndAlso invocation.AccessKind <> LateBoundAccessKind.Call
Case BoundKind.LateMemberAccess
Dim member = DirectCast(expression, BoundLateMemberAccess)
Debug.Assert(member.AccessKind <> LateBoundAccessKind.Get AndAlso member.AccessKind <> LateBoundAccessKind.Call)
Return member.AccessKind <> LateBoundAccessKind.Get AndAlso member.AccessKind <> LateBoundAccessKind.Call
Case Else
Return expression.IsLValue()
End Select
End Function
Private Sub ReportAssignmentToRValue(expr As BoundExpression, diagnostics As DiagnosticBag)
Dim err As ERRID
If expr.IsConstant Then
err = ERRID.ERR_CantAssignToConst
ElseIf ExpressionRefersToReadonlyVariable(expr) Then
err = ERRID.ERR_ReadOnlyAssignment
Else
err = ERRID.ERR_LValueRequired
End If
ReportDiagnostic(diagnostics, expr.Syntax, err)
End Sub
Public Shared Function ExpressionRefersToReadonlyVariable(
node As BoundExpression,
Optional digThroughProperty As Boolean = True
) As Boolean
' TODO: Check base expressions for properties if digThroughProperty==true.
If node.Kind = BoundKind.FieldAccess Then
Dim field = DirectCast(node, BoundFieldAccess)
If field.FieldSymbol.IsReadOnly Then
Return True
End If
Dim base = field.ReceiverOpt
If base IsNot Nothing AndAlso base.IsValue() AndAlso
base.Type.IsValueType Then
Return ExpressionRefersToReadonlyVariable(base, False)
End If
ElseIf node.Kind = BoundKind.Local Then
Return DirectCast(node, BoundLocal).LocalSymbol.IsReadOnly
End If
Return False
End Function
''' <summary>
''' Determine whether field access should be treated as LValue.
''' </summary>
Friend Function IsLValueFieldAccess(field As FieldSymbol, receiver As BoundExpression) As Boolean
If field.IsConst Then
Return False
End If
If Not field.IsShared AndAlso
receiver IsNot Nothing AndAlso
receiver.IsValue() Then
Dim receiverType = receiver.Type
Debug.Assert(Not receiverType.IsTypeParameter() OrElse receiverType.IsReferenceType,
"Member variable access through non-class constrained type param unexpected!!!")
' Dev10 comment:
' Note that this is needed so that we can determine whether the structure
' is not an LValue (eg: RField.m_x = 20 where foo is a readonly field of a
' structure type). In such cases, the structure's field m_x cannot be modified.
'
' This does not apply to type params because for type params we do want to
' allow setting the fields even in such scenarios because only class constrained
' type params have fields and readonly reference typed fields' fields can be
' modified.
If Not receiverType.IsTypeParameter() AndAlso
receiverType.IsValueType AndAlso
Not receiver.IsLValue() AndAlso
Not receiver.IsMeReference() AndAlso
Not receiver.IsMyClassReference() Then
Return False
End If
End If
If Not field.IsReadOnly Then
Return True
End If
Dim containingMethodKind As MethodKind = Me.KindOfContainingMethodAtRunTime()
If containingMethodKind = MethodKind.Constructor Then
If field.IsShared OrElse Not (receiver IsNot Nothing AndAlso receiver.IsInstanceReference()) Then
Return False
End If
ElseIf containingMethodKind = MethodKind.SharedConstructor Then
If Not field.IsShared Then
Return False
End If
Else
Return False
End If
' We are in constructor, now verify that the field belongs to constructor's type.
' Note, ReadOnly fields accessed in lambda within the constructor are not LValues because the
' lambda in the end will be generated as a separate procedure where the ReadOnly field is not
' an LValue. In this case, containingMember will be a LambdaSymbol rather than a symbol for
' constructor.
' We duplicate a bug in the native compiler for compatibility in non-strict mode
Return If(Me.Compilation.FeatureStrictEnabled,
Me.ContainingMember.ContainingSymbol Is field.ContainingSymbol,
Me.ContainingMember.ContainingSymbol.OriginalDefinition Is field.ContainingSymbol.OriginalDefinition)
End Function
''' <summary>
''' Return MethodKind corresponding to the method the code being interpreted is going to end up in.
''' </summary>
Private Function KindOfContainingMethodAtRunTime() As MethodKind
Dim containingMember = Me.ContainingMember
If containingMember IsNot Nothing Then
Select Case containingMember.Kind
Case SymbolKind.Method
' Binding a method body.
Return DirectCast(containingMember, MethodSymbol).MethodKind
Case SymbolKind.Field, SymbolKind.Property
' Binding field or property initializer.
If containingMember.IsShared Then
Return MethodKind.SharedConstructor
Else
Return MethodKind.Constructor
End If
Case SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Parameter
Exit Select
Case Else
' What else can it be?
Debug.Assert(False)
End Select
End If
Return MethodKind.Ordinary ' Looks like a good default.
End Function
Private Function BindTernaryConditionalExpression(node As TernaryConditionalExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression
' bind arguments as values
Dim boundConditionArg = BindBooleanExpression(node.Condition, diagnostics)
Dim boundWhenTrueArg = BindValue(node.WhenTrue, diagnostics)
Dim boundWhenFalseArg = BindValue(node.WhenFalse, diagnostics)
Dim hasErrors = boundConditionArg.HasErrors OrElse boundWhenTrueArg.HasErrors OrElse boundWhenFalseArg.HasErrors
' infer dominant type of the resulting expression
Dim dominantType As TypeSymbol
If boundWhenTrueArg.IsNothingLiteral AndAlso boundWhenFalseArg.IsNothingLiteral Then
' From Dev10: backwards compatibility with Orcas... IF(b,Nothing,Nothing) infers Object with no complaint
dominantType = GetSpecialType(SpecialType.System_Object, node, diagnostics)
Else
Dim numCandidates As Integer = 0
Dim array = ArrayBuilder(Of BoundExpression).GetInstance(2)
array.Add(boundWhenTrueArg)
array.Add(boundWhenFalseArg)
dominantType = InferDominantTypeOfExpressions(node, array, diagnostics, numCandidates)
array.Free()
' check the resulting type
If Not hasErrors Then
hasErrors = GenerateDiagnosticsForDominantTypeInferenceInIfExpression(dominantType, numCandidates, node, diagnostics)
End If
End If
' Void type will be filtered out in BindValue calls
Debug.Assert(dominantType Is Nothing OrElse Not dominantType.IsVoidType())
' convert arguments to the dominant type if necessary
If Not hasErrors OrElse dominantType IsNot Nothing Then
boundWhenTrueArg = Me.ApplyImplicitConversion(node.WhenTrue, dominantType, boundWhenTrueArg, diagnostics)
boundWhenFalseArg = Me.ApplyImplicitConversion(node.WhenFalse, dominantType, boundWhenFalseArg, diagnostics)
hasErrors = hasErrors OrElse boundWhenTrueArg.HasErrors OrElse boundWhenFalseArg.HasErrors
Else
boundWhenTrueArg = MakeRValueAndIgnoreDiagnostics(boundWhenTrueArg)
boundWhenFalseArg = MakeRValueAndIgnoreDiagnostics(boundWhenFalseArg)
End If
' check for a constant value
Dim constVal As ConstantValue = Nothing
If Not hasErrors AndAlso IsConstantAllowingCompileTimeFolding(boundWhenTrueArg) AndAlso
IsConstantAllowingCompileTimeFolding(boundWhenFalseArg) AndAlso IsConstantAllowingCompileTimeFolding(boundConditionArg) Then
constVal = If(boundConditionArg.ConstantValueOpt.BooleanValue, boundWhenTrueArg.ConstantValueOpt, boundWhenFalseArg.ConstantValueOpt)
End If
Return New BoundTernaryConditionalExpression(node,
boundConditionArg,
boundWhenTrueArg,
boundWhenFalseArg,
constVal,
If(dominantType, ErrorTypeSymbol.UnknownResultType),
hasErrors:=hasErrors)
End Function
Private Function IsConstantAllowingCompileTimeFolding(candidate As BoundExpression) As Boolean
Return candidate.IsConstant AndAlso
Not candidate.ConstantValueOpt.IsBad AndAlso
(candidate.IsNothingLiteral OrElse (candidate.Type IsNot Nothing AndAlso candidate.Type.AllowsCompileTimeOperations()))
End Function
Private Function BindBinaryConditionalExpression(node As BinaryConditionalExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression
' bind arguments
Dim boundFirstArg = BindValue(node.FirstExpression, diagnostics)
Dim boundSecondArg = BindValue(node.SecondExpression, diagnostics)
Dim hasErrors = boundFirstArg.HasErrors OrElse boundSecondArg.HasErrors OrElse node.ContainsDiagnostics
' infer dominant type of the resulting expression
Dim dominantType As TypeSymbol
If boundFirstArg.IsNothingLiteral AndAlso boundSecondArg.IsNothingLiteral Then
' SPECIAL CASE (Dev10): IF(Nothing,Nothing) yields type System.Object
' NOTE: Reuse System.Object from boundFirstArg or boundSecondArg if exists
dominantType = If(boundFirstArg.Type, If(boundSecondArg.Type, GetSpecialType(SpecialType.System_Object, node, diagnostics)))
ElseIf boundFirstArg.Type IsNot Nothing AndAlso boundFirstArg.Type.IsNullableType AndAlso boundSecondArg.IsNothingLiteral Then
' SPECIAL CASE (Dev10): IF(Nullable<T>, Nothing) yields type Nullable<T>, whereas IF(Nullable<Int>, Int) yields Int.
dominantType = boundFirstArg.Type
Else
' calculate dominant type
Dim numCandidates As Integer = 0
Dim array = ArrayBuilder(Of BoundExpression).GetInstance(2)
If boundFirstArg.Type IsNot Nothing AndAlso boundFirstArg.Type.IsNullableType AndAlso
Not (boundSecondArg.Type IsNot Nothing AndAlso boundSecondArg.Type.IsNullableType) Then
' From Dev10: Special case: "nullable lifting": when the first argument has a value of nullable
' data type and the second does not, the first is being converted to underlying type
' create a temp variable
Dim underlyingType = boundFirstArg.Type.GetNullableUnderlyingType
array.Add(New BoundRValuePlaceholder(node.FirstExpression,
underlyingType))
Else
array.Add(boundFirstArg)
End If
array.Add(boundSecondArg)
dominantType = InferDominantTypeOfExpressions(node, array, diagnostics, numCandidates)
array.Free()
' check the resulting type
If Not hasErrors Then
hasErrors = GenerateDiagnosticsForDominantTypeInferenceInIfExpression(dominantType, numCandidates, node, diagnostics)
End If
End If
' check for a constant value
If Not hasErrors AndAlso IsConstantAllowingCompileTimeFolding(boundFirstArg) AndAlso
IsConstantAllowingCompileTimeFolding(boundSecondArg) AndAlso
(boundFirstArg.IsNothingLiteral OrElse boundFirstArg.ConstantValueOpt.IsString) Then
Dim constVal As ConstantValue
If (boundFirstArg.IsNothingLiteral) Then
constVal = boundSecondArg.ConstantValueOpt
If Not boundSecondArg.IsNothingLiteral Then
dominantType = boundSecondArg.Type
Else
Debug.Assert(dominantType.IsObjectType)
End If
Else
constVal = boundFirstArg.ConstantValueOpt
dominantType = boundFirstArg.Type
End If
' return binary conditional expression to be constant-folded later
Return AnalyzeConversionAndCreateBinaryConditionalExpression(
node,
testExpression:=boundFirstArg,
elseExpression:=boundSecondArg,
constantValueOpt:=constVal,
type:=dominantType,
hasErrors:=False,
diagnostics:=diagnostics)
End If
' NOTE: no constant folding after this point
' By this time Void type will be filtered out in BindValue calls, and empty dominant type reported as an error
Debug.Assert(hasErrors OrElse (dominantType IsNot Nothing AndAlso Not dominantType.IsVoidType()))
' address some cases of Type being Nothing before making an RValue of it
If Not hasErrors AndAlso boundFirstArg.Type Is Nothing Then
If boundFirstArg.IsNothingLiteral Then
' leave Nothing literal unchanged
Else
' convert lambdas, AddressOf, etc. to dominant type
boundFirstArg = Me.ApplyImplicitConversion(node.FirstExpression, dominantType, boundFirstArg, diagnostics)
hasErrors = boundFirstArg.HasErrors
End If
End If
' TODO: Address array initializers, they might need to change type.
' make r-value out of boundFirstArg; this will reclassify property access from Unknown to Get and
' also mark not-nothing expressions without type with errors
If boundFirstArg.IsNothingLiteral Then
' Don't do anything for nothing literal
ElseIf Not hasErrors Then
boundFirstArg = MakeRValue(boundFirstArg, diagnostics)
hasErrors = boundFirstArg.HasErrors
Else
boundFirstArg = MakeRValueAndIgnoreDiagnostics(boundFirstArg)
End If
' Type of the first expression should be set by now
Debug.Assert(hasErrors OrElse boundFirstArg.IsNothingLiteral OrElse boundFirstArg.Type IsNot Nothing)
Dim boundSecondArgWithConversions As BoundExpression = boundSecondArg
If Not hasErrors Then
boundSecondArgWithConversions = Me.ApplyImplicitConversion(node.SecondExpression, dominantType, boundSecondArg, diagnostics)
hasErrors = boundSecondArgWithConversions.HasErrors
Else
boundSecondArgWithConversions = MakeRValueAndIgnoreDiagnostics(boundSecondArg)
End If
' if there are still no errors check the original type of the first argument to be
' of a reference or nullable type, generate IllegalCondTypeInIIF otherwise
If Not hasErrors AndAlso Not (boundFirstArg.IsNothingLiteral OrElse boundFirstArg.Type.IsNullableType OrElse boundFirstArg.Type.IsReferenceType) Then
ReportDiagnostic(diagnostics, node.FirstExpression, ERRID.ERR_IllegalCondTypeInIIF)
hasErrors = True
End If
Return AnalyzeConversionAndCreateBinaryConditionalExpression(
node,
testExpression:=boundFirstArg,
elseExpression:=boundSecondArgWithConversions,
constantValueOpt:=Nothing,
type:=If(dominantType, ErrorTypeSymbol.UnknownResultType),
hasErrors:=hasErrors,
diagnostics:=diagnostics)
End Function
Private Function AnalyzeConversionAndCreateBinaryConditionalExpression(
syntax As VisualBasicSyntaxNode,
testExpression As BoundExpression,
elseExpression As BoundExpression,
constantValueOpt As ConstantValue,
type As TypeSymbol,
hasErrors As Boolean,
diagnostics As DiagnosticBag,
Optional explicitConversion As Boolean = False) As BoundExpression
Dim convertedTestExpression As BoundExpression = Nothing
Dim placeholder As BoundRValuePlaceholder = Nothing
If Not hasErrors Then
' Do we need to apply a placeholder?
If Not testExpression.IsConstant Then
Debug.Assert(Not testExpression.IsLValue)
placeholder = New BoundRValuePlaceholder(testExpression.Syntax, testExpression.Type.GetNullableUnderlyingTypeOrSelf())
End If
' apply a conversion
convertedTestExpression = ApplyConversion(testExpression.Syntax, type,
If(placeholder, testExpression),
explicitConversion, diagnostics)
If convertedTestExpression Is If(placeholder, testExpression) Then
convertedTestExpression = Nothing
placeholder = Nothing
End If
End If
Return New BoundBinaryConditionalExpression(syntax,
testExpression:=testExpression,
convertedTestExpression:=convertedTestExpression,
testExpressionPlaceholder:=placeholder,
elseExpression:=elseExpression,
constantValueOpt:=constantValueOpt,
type:=type,
hasErrors:=hasErrors)
End Function
''' <summary> Process the result of dominant type inference, generate diagnostics </summary>
Private Function GenerateDiagnosticsForDominantTypeInferenceInIfExpression(dominantType As TypeSymbol, numCandidates As Integer,
node As ExpressionSyntax, diagnostics As DiagnosticBag) As Boolean
Dim hasErrors As Boolean = False
If dominantType Is Nothing Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_IfNoType)
hasErrors = True
ElseIf numCandidates = 0 Then
' TODO: Is this reachable? Check and add tests
If OptionStrict = VisualBasic.OptionStrict.On Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_IfNoTypeObjectDisallowed)
hasErrors = True
ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then
ReportDiagnostic(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.WRN_ObjectAssumed1, ErrorFactory.ErrorInfo(ERRID.WRN_IfNoTypeObjectAssumed)))
End If
ElseIf numCandidates > 1 Then
If OptionStrict = VisualBasic.OptionStrict.On Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_IfTooManyTypesObjectDisallowed)
hasErrors = True
ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then
ReportDiagnostic(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.WRN_ObjectAssumed1, ErrorFactory.ErrorInfo(ERRID.WRN_IfTooManyTypesObjectAssumed)))
End If
End If
Return hasErrors
End Function
''' <summary>
''' True if inside in binding arguments of constructor
''' call with {'Me'/'MyClass'/'MyBase'}.New(...) from anothir constructor
''' </summary>
Protected Overridable ReadOnly Property IsInsideChainedConstructorCallArguments As Boolean
Get
Return Me.ContainingBinder.IsInsideChainedConstructorCallArguments
End Get
End Property
Private Function IsMeOrMyBaseOrMyClassInSharedContext() As Boolean
' If we are inside an attribute then we are not in an instance context.
If Me.BindingLocation = VisualBasic.BindingLocation.Attribute Then
Return True
End If
Dim containingMember = Me.ContainingMember
If containingMember IsNot Nothing Then
Select Case containingMember.Kind
Case SymbolKind.Method, SymbolKind.Property
Return containingMember.IsShared OrElse
Me.ContainingType.IsModuleType
Case SymbolKind.Field
Return containingMember.IsShared OrElse
Me.ContainingType.IsModuleType OrElse
DirectCast(containingMember, FieldSymbol).IsConst
End Select
End If
Return True
End Function
Private Function CheckMeOrMyBaseOrMyClassInSharedOrDisallowedContext(implicitReference As Boolean, <Out()> ByRef errorId As ERRID) As Boolean
errorId = Nothing
' Any executable statement in a script class can access Me/MyClass/MyBase implicitly but not explicitly.
' No code in a script class is shared.
Dim containingType = Me.ContainingType
If containingType IsNot Nothing AndAlso containingType.IsScriptClass Then
If implicitReference Then
Return True
Else
errorId = ERRID.ERR_KeywordNotAllowedInScript
Return False
End If
End If
If IsMeOrMyBaseOrMyClassInSharedContext() Then
errorId = If(implicitReference,
ERRID.ERR_BadInstanceMemberAccess,
If(containingType IsNot Nothing AndAlso containingType.IsModuleType,
ERRID.ERR_UseOfKeywordFromModule1,
ERRID.ERR_UseOfKeywordNotInInstanceMethod1))
Return False
ElseIf IsInsideChainedConstructorCallArguments Then
errorId = If(implicitReference, ERRID.ERR_InvalidImplicitMeReference, ERRID.ERR_InvalidMeReference)
Return False
End If
Return True
End Function
''' <summary>
''' Can we access MyBase in this location. If False is returned,
''' also returns the error id associated with that.
''' </summary>
Private Function CanAccessMyBase(implicitReference As Boolean, <Out()> ByRef errorId As ERRID) As Boolean
errorId = Nothing
If Not CheckMeOrMyBaseOrMyClassInSharedOrDisallowedContext(implicitReference, errorId) Then
Return False
End If
If ContainingType.IsStructureType Then
errorId = ERRID.ERR_UseOfKeywordFromStructure1
Return False
End If
' TODO: Find a test case for ERRID_UseOfKeywordOutsideClass1
Debug.Assert(ContainingType.IsClassType)
' TODO: Check for closures
Return True
End Function
Private Function CanAccessMeOrMyClass(implicitReference As Boolean, <Out()> ByRef errorId As ERRID) As Boolean
errorId = Nothing
Return CheckMeOrMyBaseOrMyClassInSharedOrDisallowedContext(implicitReference, errorId)
End Function
''' <summary>
''' Can we access Me in this location. If False is returned,
''' also returns the error id associated with that.
''' </summary>
Friend Function CanAccessMe(implicitReference As Boolean, <Out()> ByRef errorId As ERRID) As Boolean
errorId = Nothing
' TODO: Find a test case for ERRID_UseOfKeywordOutsideClass1
Return CanAccessMeOrMyClass(implicitReference, errorId)
End Function
''' <summary>
''' Can we access MyClass in this location. If False is returned,
''' also returns the error id associated with that.
''' </summary>
Private Function CanAccessMyClass(implicitReference As Boolean, <Out()> ByRef errorId As ERRID) As Boolean
errorId = Nothing
If Me.ContainingType IsNot Nothing AndAlso Me.ContainingType.IsModuleType Then
errorId = ERRID.ERR_MyClassNotInClass
Return False
End If
Return CanAccessMeOrMyClass(implicitReference, errorId)
End Function
Private Function BindMeExpression(node As MeExpressionSyntax, diagnostics As DiagnosticBag) As BoundMeReference
Dim err As ERRID = Nothing
If Not CanAccessMe(False, err) Then
ReportDiagnostic(diagnostics, node, err, SyntaxFacts.GetText(node.Keyword.Kind))
Return New BoundMeReference(node, If(Me.ContainingType, ErrorTypeSymbol.UnknownResultType), hasErrors:=True)
End If
Return CreateMeReference(node)
End Function
' Create a reference to Me, without error checking.
Private Function CreateMeReference(node As VisualBasicSyntaxNode, Optional isSynthetic As Boolean = False) As BoundMeReference
Dim containingMethod = TryCast(ContainingMember, MethodSymbol)
Dim result = New BoundMeReference(node, If(Me.ContainingType, ErrorTypeSymbol.UnknownResultType))
If isSynthetic Then
result.SetWasCompilerGenerated()
End If
Return result
End Function
Private Function BindMyBaseExpression(node As MyBaseExpressionSyntax, diagnostics As DiagnosticBag) As BoundMyBaseReference
Dim err As ERRID = Nothing
If Not CanAccessMyBase(False, err) Then
ReportDiagnostic(diagnostics, node, err, SyntaxFacts.GetText(node.Keyword.Kind))
Return New BoundMyBaseReference(node, If(Me.ContainingType IsNot Nothing, Me.ContainingType.BaseTypeNoUseSiteDiagnostics, ErrorTypeSymbol.UnknownResultType), hasErrors:=True)
End If
Dim containingMethod = TryCast(ContainingMember, MethodSymbol)
Return New BoundMyBaseReference(node, If(Me.ContainingType IsNot Nothing, Me.ContainingType.BaseTypeNoUseSiteDiagnostics, ErrorTypeSymbol.UnknownResultType))
End Function
Private Function BindMyClassExpression(node As MyClassExpressionSyntax, diagnostics As DiagnosticBag) As BoundMyClassReference
Dim err As ERRID = Nothing
If Not CanAccessMyClass(False, err) Then
ReportDiagnostic(diagnostics, node, err, SyntaxFacts.GetText(node.Keyword.Kind))
Return New BoundMyClassReference(node, If(Me.ContainingType, ErrorTypeSymbol.UnknownResultType), hasErrors:=True)
End If
Dim containingMethod = TryCast(ContainingMember, MethodSymbol)
Return New BoundMyClassReference(node, If(Me.ContainingType, ErrorTypeSymbol.UnknownResultType))
End Function
' Can the given name syntax be an implicit declared variables. Only some syntactic locations are permissible
' for implicitly declared variables. They are disallowed in:
' target of invocation
' LHS of member access
'
' Also, For, For Each, and Catch can implicitly declare a variable, but that implicit declaration has
' different rules that is handled directly in the binding of those statements. Thus, they are disallowed here.
'
' Finally, Dev10 disallows 3 special names: "Null", "Empty", and "Rnd".
Private Function CanBeImplicitVariableDeclaration(nameSyntax As SimpleNameSyntax) As Boolean
' Disallow generic names.
If nameSyntax.Kind <> SyntaxKind.IdentifierName Then
Return False
End If
Dim parent As VisualBasicSyntaxNode = nameSyntax.Parent
If parent IsNot Nothing Then
Select Case parent.Kind
Case SyntaxKind.SimpleMemberAccessExpression ' intentionally NOT SyntaxKind.DictionaryAcess
If DirectCast(parent, MemberAccessExpressionSyntax).Expression Is nameSyntax Then
Return False
End If
Case SyntaxKind.InvocationExpression
If DirectCast(parent, InvocationExpressionSyntax).Expression Is nameSyntax Then
' Name is the expression part of an invocation.
Return False
End If
Case SyntaxKind.ConditionalAccessExpression
Dim conditionalAccess = DirectCast(parent, ConditionalAccessExpressionSyntax)
If conditionalAccess.Expression Is nameSyntax Then
Dim leaf As ExpressionSyntax = conditionalAccess.GetLeafAccess()
If leaf IsNot Nothing AndAlso
(leaf.Kind = SyntaxKind.SimpleMemberAccessExpression OrElse leaf.Kind = SyntaxKind.InvocationExpression) Then
Return False
End If
End If
Case SyntaxKind.CatchStatement
If DirectCast(parent, CatchStatementSyntax).IdentifierName Is nameSyntax Then
Return False
End If
End Select
End If
' Dev10 disallows implicit variable creation for "Null", "Empty", and "RND".
Dim name As String = MakeHalfWidthIdentifier(nameSyntax.Identifier.ValueText)
If CaseInsensitiveComparison.Equals(name, "Null") OrElse CaseInsensitiveComparison.Equals(name, "Empty") OrElse CaseInsensitiveComparison.Equals(name, "RND") Then
Return False
End If
Return True
End Function
' "isInvocationOrAddressOf" indicates that the name is being bound as the left hand side of an invocation
' or the argument of an AddressOf, and the return value variable should not be bound to.
Private Function BindSimpleName(node As SimpleNameSyntax,
isInvocationOrAddressOf As Boolean,
diagnostics As DiagnosticBag,
Optional skipLocalsAndParameters As Boolean = False) As BoundExpression
Dim name As String
Dim typeArguments As TypeArgumentListSyntax
#If DEBUG Then
If CanBeImplicitVariableDeclaration(node) Then
CheckSimpleNameBindingOrder(node)
End If
#End If
If node.Kind = SyntaxKind.GenericName Then
Dim genericName = DirectCast(node, GenericNameSyntax)
typeArguments = genericName.TypeArgumentList
name = genericName.Identifier.ValueText
Else
Debug.Assert(node.Kind = SyntaxKind.IdentifierName)
typeArguments = Nothing
name = DirectCast(node, IdentifierNameSyntax).Identifier.ValueText
End If
If String.IsNullOrEmpty(name) Then
' Empty string must have been a syntax error.
' Just produce a bad expression and get out without producing any new errors.
Return BadExpression(node, ErrorTypeSymbol.UnknownResultType)
End If
Dim options As LookupOptions = LookupOptions.AllMethodsOfAnyArity ' overload resolution filters methods by arity.
If isInvocationOrAddressOf Then
options = options Or LookupOptions.MustNotBeReturnValueVariable
End If
If skipLocalsAndParameters Then
options = options Or LookupOptions.MustNotBeLocalOrParameter
End If
Dim arity As Integer = If(typeArguments IsNot Nothing, typeArguments.Arguments.Count, 0)
Dim result As LookupResult = LookupResult.GetInstance()
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Me.Lookup(result, name, arity, options, useSiteDiagnostics)
diagnostics.Add(node, useSiteDiagnostics)
If Not result.IsGoodOrAmbiguous AndAlso
Me.ImplicitVariableDeclarationAllowed AndAlso
Not Me.AllImplicitVariableDeclarationsAreHandled AndAlso
CanBeImplicitVariableDeclaration(node) Then
' Declare an implicit local variable.
Dim implicitLocal As LocalSymbol = DeclareImplicitLocalVariable(DirectCast(node, IdentifierNameSyntax), diagnostics)
result.SetFrom(implicitLocal)
End If
If Not result.HasSymbol Then
' Did not find anything with that name.
result.Free()
' If the name represents an imported XML namespace prefix, report a specific error.
Dim [namespace] As String = Nothing
Dim fromImports = False
If LookupXmlNamespace(name, ignoreXmlNodes:=True, [namespace]:=[namespace], fromImports:=fromImports) Then
Return ReportDiagnosticAndProduceBadExpression(diagnostics, node, ERRID.ERR_XmlPrefixNotExpression, name)
End If
Dim errorInfo As DiagnosticInfo = Nothing
If node.Kind = SyntaxKind.IdentifierName Then
Select Case KeywordTable.TokenOfString(name)
Case SyntaxKind.AwaitKeyword
errorInfo = GetAwaitInNonAsyncError()
End Select
End If
If errorInfo Is Nothing Then
'Check for My and use of VB Embed Runtime usage for different diagnostic
If IdentifierComparison.Equals(MissingRuntimeMemberDiagnosticHelper.MyVBNamespace, name) AndAlso Me.Compilation.Options.EmbedVbCoreRuntime Then
errorInfo = ErrorFactory.ErrorInfo(ERRID.ERR_PlatformDoesntSupport, MissingRuntimeMemberDiagnosticHelper.MyVBNamespace)
Else
errorInfo = ErrorFactory.ErrorInfo(If(Me.IsInQuery, ERRID.ERR_QueryNameNotDeclared, ERRID.ERR_NameNotDeclared1),
name)
End If
End If
Return ReportDiagnosticAndProduceBadExpression(diagnostics, node, errorInfo)
End If
Dim boundExpr As BoundExpression = BindSimpleName(result, node, options, typeArguments, diagnostics)
result.Free()
Return boundExpr
End Function
''' <summary>
''' Second part of BindSimpleName.
''' It is a separate function so that it could be called directly
''' when we have already looked up for the name.
''' </summary>
Private Function BindSimpleName(result As LookupResult,
node As VisualBasicSyntaxNode,
options As LookupOptions,
typeArguments As TypeArgumentListSyntax,
diagnostics As DiagnosticBag) As BoundExpression
' An implicit Me is inserted if we found something in the immediate containing type.
' Note that validation of whether Me can actually be used in this case is deferred until after
' overload resolution determines if we are accessing a static or instance member.
Dim receiver As BoundExpression = Nothing
Dim containingType = Me.ContainingType
If containingType IsNot Nothing Then
If containingType.IsScriptClass Then
Dim memberDeclaringType = result.Symbols(0).ContainingType
If memberDeclaringType IsNot Nothing Then
receiver = TryBindInteractiveReceiver(node, Me.ContainingMember, containingType, memberDeclaringType)
End If
End If
If receiver Is Nothing Then
Dim symbol = result.Symbols(0)
If symbol.IsReducedExtensionMethod() OrElse BindSimpleNameIsMemberOfType(symbol, containingType) Then
receiver = CreateMeReference(node, isSynthetic:=True)
End If
End If
End If
Dim boundExpr As BoundExpression = BindSymbolAccess(node, result, options, receiver, typeArguments, QualificationKind.Unqualified, diagnostics)
Return boundExpr
End Function
Private Shared Function BindSimpleNameIsMemberOfType(member As Symbol, type As NamedTypeSymbol) As Boolean
Debug.Assert(type IsNot Nothing)
Debug.Assert(member IsNot Nothing)
Select Case member.Kind
Case SymbolKind.Field, SymbolKind.Method, SymbolKind.Property, SymbolKind.Event
Dim container = member.ContainingType
If container Is Nothing Then Return False
Dim currentType = type
Do While currentType IsNot Nothing
If container.Equals(currentType) Then
Return True
End If
currentType = currentType.BaseTypeNoUseSiteDiagnostics
Loop
End Select
Return False
End Function
Private Function TryBindInteractiveReceiver(syntax As VisualBasicSyntaxNode, currentMember As Symbol, currentType As NamedTypeSymbol, memberDeclaringType As NamedTypeSymbol) As BoundExpression
If currentType.TypeKind = TypeKind.Submission AndAlso Not currentMember.IsShared Then
If memberDeclaringType.TypeKind = TypeKind.Submission Then
Return New BoundPreviousSubmissionReference(syntax, currentType, memberDeclaringType)
Else
' TODO (tomat): host object binding
'Dim hostObjectType As TypeSymbol = Compilation.GetHostObjectTypeSymbol()
'If hostObjectType IsNot Nothing AndAlso (hostObjectType = memberDeclaringType OrElse hostObjectType.BaseClassesContain(memberDeclaringType)) Then
' Return New BoundHostObjectMemberReference(syntax, hostObjectType)
'End If
End If
End If
Return Nothing
End Function
Private Function BindMemberAccess(node As MemberAccessExpressionSyntax, eventContext As Boolean, allowIntrinsicAliases As Boolean, diagnostics As DiagnosticBag) As BoundExpression
Dim leftOpt = node.Expression
Dim boundLeft As BoundExpression = Nothing
Dim rightName As SimpleNameSyntax = node.Name
If leftOpt Is Nothing Then
' 11.6 Member Access Expressions: "1. If E is omitted, then the expression from the
' immediately containing With statement is substituted for E and the member access
' is performed. If there is no containing With statement, a compile-time error occurs."
' NOTE: If there are no enclosing anonymous type creation or With statement, the method below will
' report error ERR_BadWithRef; otherwise 'the closest' binder (either AnonymousTypeCreationBinder
' or WithStatementBinder (to be created)) should handle binding of such expression
Dim wholeMemberAccessExpressionBound As Boolean = False
Dim conditionalAccess As ConditionalAccessExpressionSyntax = node.GetCorrespondingConditionalAccessExpression()
If conditionalAccess IsNot Nothing Then
boundLeft = GetConditionalAccessReceiver(conditionalAccess)
Else
boundLeft = Me.TryBindOmittedLeftForMemberAccess(node, diagnostics, Me, wholeMemberAccessExpressionBound)
End If
If boundLeft Is Nothing Then
Debug.Assert(Not wholeMemberAccessExpressionBound)
Return ReportDiagnosticAndProduceBadExpression(diagnostics, node, ERRID.ERR_BadWithRef)
End If
If wholeMemberAccessExpressionBound Then
' In case TryBindOmittedLeftForMemberAccess bound the whole member
' access expression syntax node just return the result
Return boundLeft
End If
Else
boundLeft = BindLeftOfPotentialColorColorMemberAccess(node, leftOpt, diagnostics)
End If
Return Me.BindMemberAccess(node, boundLeft, rightName, eventContext, allowIntrinsicAliases, diagnostics)
End Function
Private Function BindLeftOfPotentialColorColorMemberAccess(parentNode As MemberAccessExpressionSyntax, leftOpt As ExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression
' handle for Color Color case:
'
' ======= 11.6.1 Identical Type and Member Names
' It is not uncommon to name members using the same name as their type. In that situation, however,
' inconvenient name hiding can occur:
'
' Enum Color
' Red
' Green
' Yellow
' End Enum
'
' Class Test
' ReadOnly Property Color() As Color
' Get
' Return Color.Red
' End Get
' End Property
'
' Shared Function DefaultColor() As Color
' Return Color.Green ' Binds to the instance property!
' End Function
' End Class
'
' In the previous example, the simple name Color in DefaultColor binds to the instance property
' instead of the type. Because an instance member cannot be referenced in a shared member,
' this would normally be an error.
'
' However, a special rule allows access to the type in this case. If the base expression
' of a member access expression is a simple name and binds to a constant, field, property,
' local variable or parameter whose type has the same name, then the base expression can refer
' either to the member or the type. This can never result in ambiguity because the members
' that can be accessed off of either one are the same.
'
' In the case that such a base expression binds to an instance member but the binding occurs
' within a context in which "Me" is not accessible, the expression instead binds to the
' type (if applicable).
'
' If the base expression cannot be successfully disambiguated by the context in which it
' occurs, it binds to the member. This can occur in particular in late-bound calls or
' error conditions.
If leftOpt.Kind = SyntaxKind.IdentifierName Then
Dim node = DirectCast(leftOpt, SimpleNameSyntax)
Dim leftDiagnostics = DiagnosticBag.GetInstance()
Dim boundLeft = Me.BindSimpleName(node, False, leftDiagnostics)
Dim boundValue = boundLeft
Dim propertyDiagnostics As DiagnosticBag = Nothing
If boundLeft.Kind = BoundKind.PropertyGroup Then
propertyDiagnostics = DiagnosticBag.GetInstance()
boundValue = Me.AdjustReceiverValue(boundLeft, node, propertyDiagnostics)
End If
Dim leftSymbol = boundValue.ExpressionSymbol
If leftSymbol IsNot Nothing Then
Dim leftType As TypeSymbol
Dim isInstanceMember As Boolean
Select Case leftSymbol.Kind
Case SymbolKind.Field, SymbolKind.Property
Debug.Assert(boundValue.Type IsNot Nothing)
leftType = boundValue.Type
isInstanceMember = Not leftSymbol.IsShared
Case SymbolKind.Local, SymbolKind.Parameter, SymbolKind.RangeVariable
Debug.Assert(boundValue.Type IsNot Nothing)
leftType = boundValue.Type
isInstanceMember = False
Case Else
leftType = Nothing
isInstanceMember = False
End Select
If leftType IsNot Nothing Then
Dim leftName = node.Identifier.ValueText
If CaseInsensitiveComparison.Equals(leftType.Name, leftName) AndAlso leftType.TypeKind <> TypeKind.TypeParameter Then
Dim typeDiagnostics = New DiagnosticBag()
Dim boundType = Me.BindNamespaceOrTypeExpression(node, typeDiagnostics)
If boundType.Type = leftType Then
Dim err As ERRID = Nothing
If isInstanceMember AndAlso (Not CanAccessMe(implicitReference:=True, errorId:=err) OrElse Not BindSimpleNameIsMemberOfType(leftSymbol, ContainingType)) Then
diagnostics.AddRange(typeDiagnostics)
leftDiagnostics.Free()
Return boundType
End If
Dim valueDiagnostics = New DiagnosticBag()
valueDiagnostics.AddRangeAndFree(leftDiagnostics)
If propertyDiagnostics IsNot Nothing Then
valueDiagnostics.AddRangeAndFree(propertyDiagnostics)
End If
Return New BoundTypeOrValueExpression(leftOpt, New BoundTypeOrValueData(boundValue, valueDiagnostics, boundType, typeDiagnostics), leftType)
End If
End If
End If
End If
If propertyDiagnostics IsNot Nothing Then
propertyDiagnostics.Free()
End If
diagnostics.AddRangeAndFree(leftDiagnostics)
Return boundLeft
End If
' Not a Color Color case; just bind the LHS as an expression.
If leftOpt.Kind = SyntaxKind.SimpleMemberAccessExpression Then
Return BindMemberAccess(DirectCast(leftOpt, MemberAccessExpressionSyntax), eventContext:=False, allowIntrinsicAliases:=True, diagnostics:=diagnostics)
Else
Return Me.BindExpression(leftOpt, diagnostics)
End If
End Function
''' <summary>
''' Method binds member access in case when we got hold
''' of a bound node representing the left expression
''' </summary>
''' <remarks>
''' The method is protected, so that it can be called from other
''' binders overriding TryBindMemberAccessWithLeftOmitted
''' </remarks>
Protected Function BindMemberAccess(node As VisualBasicSyntaxNode, left As BoundExpression, right As SimpleNameSyntax, eventContext As Boolean, allowIntrinsicAliases As Boolean, diagnostics As DiagnosticBag) As BoundExpression
Debug.Assert(node IsNot Nothing)
Debug.Assert(left IsNot Nothing)
Debug.Assert(right IsNot Nothing)
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
' Check if 'left' is of type which is a class or struct and 'name' is "New"
Dim leftTypeSymbol As TypeSymbol = left.Type
If leftTypeSymbol IsNot Nothing AndAlso (right.Kind = SyntaxKind.IdentifierName OrElse right.Kind = SyntaxKind.GenericName) Then
' Get the name syntax token
Dim identifier = If(right.Kind = SyntaxKind.IdentifierName,
DirectCast(right, IdentifierNameSyntax).Identifier,
DirectCast(right, GenericNameSyntax).Identifier)
If Not identifier.IsBracketed AndAlso
CaseInsensitiveComparison.Equals(identifier.ValueText, SyntaxFacts.GetText(SyntaxKind.NewKeyword)) Then
If leftTypeSymbol.IsArrayType() Then
' No instance constructors found. Can't call constructor on an array type.
If (left.HasErrors) Then
Return BadExpression(node, left, ErrorTypeSymbol.UnknownResultType)
End If
Return Me.ReportDiagnosticAndProduceBadExpression(
diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_ConstructorNotFound1, leftTypeSymbol), left)
End If
Dim leftTypeKind As TypeKind = leftTypeSymbol.TypeKind
If leftTypeKind = TypeKind.Class OrElse leftTypeKind = TypeKind.Structure OrElse leftTypeKind = TypeKind.Module Then
' Bind to method group representing available instance constructors
Dim namedLeftTypeSymbol = DirectCast(leftTypeSymbol, NamedTypeSymbol)
Dim accessibleConstructors = GetAccessibleConstructors(namedLeftTypeSymbol, useSiteDiagnostics)
diagnostics.Add(node, useSiteDiagnostics)
useSiteDiagnostics = Nothing
If accessibleConstructors.IsEmpty Then
' No instance constructors found
If (left.HasErrors) Then
Return BadExpression(node, left, ErrorTypeSymbol.UnknownResultType)
End If
Return Me.ReportDiagnosticAndProduceBadExpression(
diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_ConstructorNotFound1, namedLeftTypeSymbol), left)
Else
Dim hasErrors As Boolean = left.HasErrors
If Not hasErrors AndAlso right.Kind = SyntaxKind.GenericName Then
' Report error BC30282
ReportDiagnostic(diagnostics, node, ERRID.ERR_InvalidConstructorCall)
hasErrors = True
End If
' Create a method group consisting of all instance constructors
Return New BoundMethodGroup(node, Nothing, accessibleConstructors, LookupResultKind.Good, left,
If(left.Kind = BoundKind.TypeExpression, QualificationKind.QualifiedViaTypeName, QualificationKind.QualifiedViaValue),
hasErrors)
End If
End If
End If
End If
Dim type As TypeSymbol
Dim rightName As String
Dim typeArguments As TypeArgumentListSyntax
If right.Kind = SyntaxKind.GenericName Then
Dim genericName = DirectCast(right, GenericNameSyntax)
typeArguments = genericName.TypeArgumentList
rightName = genericName.Identifier.ValueText
Else
Debug.Assert(right.Kind = SyntaxKind.IdentifierName)
typeArguments = Nothing
rightName = DirectCast(right, IdentifierNameSyntax).Identifier.ValueText
End If
Dim rightArity As Integer = If(typeArguments IsNot Nothing, typeArguments.Arguments.Count, 0)
Dim lookupResult As LookupResult = LookupResult.GetInstance()
Const options As LookupOptions = LookupOptions.AllMethodsOfAnyArity
Try
If left.Kind = BoundKind.NamespaceExpression Then
If String.IsNullOrEmpty(rightName) Then
' Must have been a syntax error.
Return BadExpression(node, left, ErrorTypeSymbol.UnknownResultType)
End If
Dim ns As NamespaceSymbol = DirectCast(left, BoundNamespaceExpression).NamespaceSymbol
Dim intrinsic As New SingleLookupResult()
' Handle a case of being able to refer to System.Int32 through System.Integer,
' Same for other intrinsic types with intrinsic name different from emitted name.
If allowIntrinsicAliases AndAlso right.Kind = SyntaxKind.IdentifierName Then
Debug.Assert(rightArity = 0)
Dim container As Symbol = ns.ContainingSymbol
If container IsNot Nothing AndAlso container.Kind = SymbolKind.Namespace Then
Dim containingNs = DirectCast(container, NamespaceSymbol)
If containingNs.IsGlobalNamespace AndAlso CaseInsensitiveComparison.Equals(ns.Name, "System") Then
Dim rightAsKeyword As SyntaxKind = SyntaxFacts.GetKeywordKind(rightName)
Select Case rightAsKeyword
Case SyntaxKind.ShortKeyword,
SyntaxKind.UShortKeyword,
SyntaxKind.IntegerKeyword,
SyntaxKind.UIntegerKeyword,
SyntaxKind.LongKeyword,
SyntaxKind.ULongKeyword,
SyntaxKind.DateKeyword
' Note, we are not interested in any diagnostics from this lookup.
intrinsic = TypeBinder.LookupPredefinedTypeName(node, rightAsKeyword, Me,
New DiagnosticBag(),
reportedAnError:=Nothing, suppressUseSiteError:=True)
End Select
End If
End If
End If
If intrinsic.Kind <> LookupResultKind.Empty Then
lookupResult.SetFrom(intrinsic)
Else
MemberLookup.Lookup(lookupResult, ns, rightName, rightArity, options, Me, useSiteDiagnostics) ' overload resolution filters methods by arity.
End If
If lookupResult.HasSymbol Then
Return BindSymbolAccess(node, lookupResult, options, left, typeArguments, QualificationKind.QualifiedViaNamespace, diagnostics)
Else
Return ReportDiagnosticAndProduceBadExpression(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_NameNotMember2, rightName, ns), left)
End If
ElseIf left.Kind = BoundKind.TypeExpression Then
type = DirectCast(left, BoundTypeExpression).Type
If type.TypeKind = TypeKind.TypeParameter Then
Return ReportDiagnosticAndProduceBadExpression(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_TypeParamQualifierDisallowed), left)
Else
If String.IsNullOrEmpty(rightName) Then
' Must have been a syntax error.
Return BadExpression(node, left, ErrorTypeSymbol.UnknownResultType)
End If
LookupMember(lookupResult, type, rightName, rightArity, options, useSiteDiagnostics) ' overload resolution filters methods by arity.
If lookupResult.HasSymbol Then
Return BindSymbolAccess(node, lookupResult, options, left, typeArguments, QualificationKind.QualifiedViaTypeName, diagnostics)
Else
Return ReportDiagnosticAndProduceBadExpression(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_NameNotMember2, rightName, type), left)
End If
End If
Else
left = AdjustReceiverValue(left, node, diagnostics)
type = left.Type
If type Is Nothing OrElse type.IsErrorType() Then
Return BadExpression(node, left, ErrorTypeSymbol.UnknownResultType)
End If
If String.IsNullOrEmpty(rightName) Then
' Must have been a syntax error.
Return BadExpression(node, left, ErrorTypeSymbol.UnknownResultType)
End If
Dim effectiveOptions = If(left.Kind <> BoundKind.MyBaseReference, options,
options Or LookupOptions.UseBaseReferenceAccessibility)
If eventContext Then
effectiveOptions = effectiveOptions Or LookupOptions.EventsOnly
End If
LookupMember(lookupResult, type, rightName, rightArity, effectiveOptions, useSiteDiagnostics) ' overload resolution filters methods by arity.
If lookupResult.HasSymbol Then
Return BindSymbolAccess(node, lookupResult, effectiveOptions, left, typeArguments, QualificationKind.QualifiedViaValue, diagnostics)
ElseIf (type.IsObjectType AndAlso Not left.IsMyBaseReference) OrElse type.IsExtensibleInterfaceNoUseSiteDiagnostics Then
Return BindLateBoundMemberAccess(node, rightName, typeArguments, left, type, diagnostics)
ElseIf left.HasErrors Then
Return BadExpression(node, left, ErrorTypeSymbol.UnknownResultType)
Else
If type.IsInterfaceType() Then
' In case IsExtensibleInterfaceNoUseSiteDiagnostics above failed because there were bad inherited interfaces.
type.AllInterfacesWithDefinitionUseSiteDiagnostics(useSiteDiagnostics)
End If
Return ReportDiagnosticAndProduceBadExpression(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_NameNotMember2, rightName, type), left)
End If
End If
Finally
diagnostics.Add(node, useSiteDiagnostics)
lookupResult.Free()
End Try
End Function
''' <summary>
''' Returns a bound node for left part of member access node with omitted left syntax.
''' In particular it handles member access inside With statement.
'''
''' By default the method delegates the work to it's containing binder or returns Nothing.
''' </summary>
''' <param name="accessingBinder">
''' Specifies the binder which requests an access to the bound node for omitted left.
''' </param>
''' <param name="wholeMemberAccessExpressionBound">
''' NOTE: in some cases, like for binding inside anonymous object creation expression, this
''' method returns bound node for the whole expression rather than only for omitted left part.
''' </param>
Protected Friend Overridable Function TryBindOmittedLeftForMemberAccess(node As MemberAccessExpressionSyntax,
diagnostics As DiagnosticBag,
accessingBinder As Binder,
<Out> ByRef wholeMemberAccessExpressionBound As Boolean) As BoundExpression
Debug.Assert(Me.ContainingBinder IsNot Nothing)
Return Me.ContainingBinder.TryBindOmittedLeftForMemberAccess(node, diagnostics, accessingBinder, wholeMemberAccessExpressionBound)
End Function
Protected Friend Overridable Function TryBindOmittedLeftForXmlMemberAccess(node As XmlMemberAccessExpressionSyntax,
diagnostics As DiagnosticBag,
accessingBinder As Binder) As BoundExpression
Debug.Assert(Me.ContainingBinder IsNot Nothing)
Return Me.ContainingBinder.TryBindOmittedLeftForXmlMemberAccess(node, diagnostics, accessingBinder)
End Function
Private Function IsBindingImplicitlyTypedLocal(symbol As LocalSymbol) As Boolean
For Each s In Me.ImplicitlyTypedLocalsBeingBound
If s = symbol Then
Return True
End If
Next
Return False
End Function
''' <summary>
''' Given a localSymbol and a syntaxNode where the symbol is used, safely return the symbol's type.
''' </summary>
''' <param name="localSymbol">The local symbol</param>
''' <param name="node">The syntax node that references the symbol</param>
''' <param name="diagnostics">diagnostic bag if errors are to be reported</param>
''' <returns>Returns the symbol's type or an ErrorTypeSymbol if the local is referenced before its definition or if the symbol is still being bound.</returns>
''' <remarks>This method safely returns a local symbol's type by checking for circular references or references before declaration.</remarks>
Private Function GetLocalSymbolType(localSymbol As LocalSymbol, node As VisualBasicSyntaxNode, Optional diagnostics As DiagnosticBag = Nothing) As TypeSymbol
Dim localType As TypeSymbol = Nothing
' Check if local symbol is used before it's definition.
' Do span comparison first in order to optimize performance for non-error cases.
If node IsNot Nothing AndAlso
node.SpanStart < localSymbol.IdentifierToken.SpanStart Then
Dim declarationLocation As Location = localSymbol.IdentifierLocation
Dim referenceLocation As Location = node.GetLocation()
If Not localSymbol.IsImplicitlyDeclared AndAlso
declarationLocation.IsInSource AndAlso
referenceLocation IsNot Nothing AndAlso referenceLocation.IsInSource AndAlso
declarationLocation.SourceTree Is referenceLocation.SourceTree Then
localType = LocalSymbol.UseBeforeDeclarationResultType
If diagnostics IsNot Nothing Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_UseOfLocalBeforeDeclaration1, localSymbol)
End If
End If
ElseIf IsBindingImplicitlyTypedLocal(localSymbol) Then
' We are currently in the process of binding this symbol.
' if constant knows its type, there is no circularity
' Example:
' Const x as Color = x.Red
If localSymbol.IsConst AndAlso localSymbol.ConstHasType Then
Return localSymbol.Type
End If
' NOTE: OptionInfer does not need to be checked before reporting the error
' locals only get to ImplicitlyTypedLocalsBeingBound if we actually infer
' their type, either because Option Infer is On or for other reason,
' we use UnknownResultType for such locals.
If diagnostics IsNot Nothing Then
If localSymbol.IsConst Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_CircularEvaluation1, localSymbol)
Else
ReportDiagnostic(diagnostics, node, ERRID.ERR_CircularInference1, localSymbol)
End If
End If
localType = ErrorTypeSymbol.UnknownResultType
End If
If localType Is Nothing Then
' It is safe to get the type from the symbol.
localType = localSymbol.Type
End If
Return localType
End Function
' Bind access to a symbol, either qualified (LHS.Symbol) or unqualified (Symbol). This kind of qualification is indicated by qualKind.
' receiver is set to a value expression indicating the receiver that the symbol is being accessed off of.
' lookupResult must refer to one or more symbols. If lookupResult has a diagnostic associated with it, that diagnostic is reported.
Private Function BindSymbolAccess(node As VisualBasicSyntaxNode,
lookupResult As LookupResult,
lookupOptionsUsed As LookupOptions,
receiver As BoundExpression,
typeArgumentsOpt As TypeArgumentListSyntax,
qualKind As QualificationKind,
diagnostics As DiagnosticBag) As BoundExpression
Debug.Assert(lookupResult.HasSymbol)
Dim hasError As Boolean = False ' Is there an ERROR (not a warning).
If receiver IsNot Nothing Then
hasError = receiver.HasErrors ' don't report subsequent errors if LHS was already an error.
' If receiver is a namespace group, let's check if we can collapse it to a single or more narrow namespace
receiver = AdjustReceiverNamespace(lookupResult, receiver)
End If
Dim reportedLookupError As Boolean = False
Dim resultKind As LookupResultKind = lookupResult.Kind
If lookupResult.HasDiagnostic AndAlso
((lookupResult.Symbols(0).Kind <> SymbolKind.Method AndAlso lookupResult.Symbols(0).Kind <> SymbolKind.Property) OrElse
resultKind <> LookupResultKind.Inaccessible) Then
Debug.Assert(resultKind <> LookupResultKind.Good)
' Report the diagnostic with the symbol.
Dim di As DiagnosticInfo = lookupResult.Diagnostic
If Not hasError Then
If typeArgumentsOpt IsNot Nothing AndAlso
(lookupResult.Kind = LookupResultKind.WrongArity OrElse lookupResult.Kind = LookupResultKind.WrongArityAndStopLookup) Then
' Arity errors are reported on the type arguments only.
ReportDiagnostic(diagnostics, typeArgumentsOpt, di)
Else
ReportDiagnostic(diagnostics, node, di)
End If
If di.Severity = DiagnosticSeverity.Error Then
hasError = True
reportedLookupError = True
End If
End If
' For non-overloadable symbols (everything but property/method)
' Create a BoundBadExpression to encapsulate all the
' symbols and the result kind.
' The type of the expression is the common type of the symbols, so further Intellisense
' works well if all the symbols are of common type.
' For property/method, we create a BoundMethodGroup/PropertyGroup so that we continue to do overload
' resolution.
Dim symbols As ImmutableArray(Of Symbol)
If TypeOf di Is AmbiguousSymbolDiagnostic Then
' Lookup had an ambiguity between Imports or Modules.
Debug.Assert(lookupResult.Kind = LookupResultKind.Ambiguous)
symbols = DirectCast(di, AmbiguousSymbolDiagnostic).AmbiguousSymbols
Else
symbols = lookupResult.Symbols.ToImmutable()
End If
Return New BoundBadExpression(node,
lookupResult.Kind,
symbols,
If(receiver IsNot Nothing, ImmutableArray.Create(Of BoundNode)(receiver), ImmutableArray(Of BoundNode).Empty),
GetCommonExpressionType(node, symbols, ConstantFieldsInProgress), hasErrors:=True)
End If
Select Case lookupResult.Symbols(0).Kind ' all symbols in a lookupResult must be of the same kind.
Case SymbolKind.Method
'TODO: Deal with errors reported by BindTypeArguments. Should we adjust hasError?
Return CreateBoundMethodGroup(
node,
lookupResult,
lookupOptionsUsed,
receiver,
BindTypeArguments(typeArgumentsOpt, diagnostics),
qualKind,
hasError)
Case SymbolKind.Property
' UNDONE: produce error if type arguments were present.
Debug.Assert(lookupResult.Kind = LookupResultKind.Good OrElse lookupResult.Kind = LookupResultKind.Inaccessible)
Return New BoundPropertyGroup(
node,
lookupResult.Symbols.ToDowncastedImmutable(Of PropertySymbol),
lookupResult.Kind,
receiver,
qualKind,
hasErrors:=hasError)
Case SymbolKind.Event
Dim eventSymbol = DirectCast(lookupResult.SingleSymbol, EventSymbol)
If eventSymbol.IsShared And qualKind = QualificationKind.Unqualified Then
receiver = Nothing
End If
If Not reportedLookupError Then
ReportUseSiteError(diagnostics, node, eventSymbol)
End If
If Not hasError Then
If receiver IsNot Nothing AndAlso receiver.Kind = BoundKind.TypeOrValueExpression Then
receiver = AdjustReceiverTypeOrValue(receiver, node, isShared:=eventSymbol.IsShared, diagnostics:=diagnostics, qualKind:=qualKind)
End If
hasError = CheckSharedSymbolAccess(node, eventSymbol.IsShared, receiver, qualKind, diagnostics)
End If
ReportDiagnosticsIfObsolete(diagnostics, eventSymbol, node)
If receiver IsNot Nothing AndAlso receiver.IsPropertyOrXmlPropertyAccess() Then
receiver = MakeRValue(receiver, diagnostics)
End If
Return New BoundEventAccess(
node,
receiver,
eventSymbol,
eventSymbol.Type,
hasErrors:=hasError)
Case SymbolKind.Field
Dim fieldSymbol As FieldSymbol = DirectCast(lookupResult.SingleSymbol, FieldSymbol)
If fieldSymbol.IsShared And qualKind = QualificationKind.Unqualified Then
receiver = Nothing
End If
' TODO: Check if this is a constant field with missing or bad value and report an error.
If Not hasError Then
If receiver IsNot Nothing AndAlso receiver.Kind = BoundKind.TypeOrValueExpression Then
receiver = AdjustReceiverTypeOrValue(receiver, node, isShared:=fieldSymbol.IsShared, diagnostics:=diagnostics, qualKind:=qualKind)
End If
hasError = CheckSharedSymbolAccess(node, fieldSymbol.IsShared, receiver, qualKind, diagnostics)
End If
If Not reportedLookupError Then
If Not ReportUseSiteError(diagnostics, node, fieldSymbol) Then
CheckMemberTypeAccessibility(diagnostics, node, fieldSymbol)
End If
End If
ReportDiagnosticsIfObsolete(diagnostics, fieldSymbol, node)
' const fields may need to determine the type because it's inferred
' This is why using .Type was replaced by .GetInferredType to detect cycles.
Dim fieldAccessType = fieldSymbol.GetInferredType(ConstantFieldsInProgress)
Dim asMemberAccess = TryCast(node, MemberAccessExpressionSyntax)
If asMemberAccess IsNot Nothing AndAlso Not fieldAccessType.IsErrorType() Then
VerifyTypeCharacterConsistency(asMemberAccess.Name, fieldAccessType.GetEnumUnderlyingTypeOrSelf, diagnostics)
End If
If receiver IsNot Nothing AndAlso receiver.IsPropertyOrXmlPropertyAccess() Then
receiver = MakeRValue(receiver, diagnostics)
End If
Return New BoundFieldAccess(node,
receiver,
fieldSymbol,
isLValue:=IsLValueFieldAccess(fieldSymbol, receiver),
suppressVirtualCalls:=False,
constantsInProgressOpt:=Me.ConstantFieldsInProgress,
type:=fieldAccessType,
hasErrors:=hasError OrElse fieldAccessType.IsErrorType)
Case SymbolKind.Local
Dim localSymbol = DirectCast(lookupResult.SingleSymbol, LocalSymbol)
If localSymbol.IsFunctionValue Then
Dim method = DirectCast(localSymbol.ContainingSymbol, MethodSymbol)
If method.IsAsync OrElse method.IsIterator Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_BadResumableAccessReturnVariable)
Return BadExpression(node, ErrorTypeSymbol.UnknownResultType)
End If
End If
Dim localAccessType As TypeSymbol = GetLocalSymbolType(localSymbol, node, diagnostics)
Dim asSimpleName = TryCast(node, SimpleNameSyntax)
If asSimpleName IsNot Nothing AndAlso Not localAccessType.IsErrorType() Then
VerifyTypeCharacterConsistency(asSimpleName, localAccessType.GetEnumUnderlyingTypeOrSelf, diagnostics)
End If
If localSymbol.IsFor Then
' lifting iteration variable produces a warning
Dim localSymbolContainingSymbol As Symbol = localSymbol.ContainingSymbol
If ContainingMember IsNot localSymbolContainingSymbol Then
' Need to go up the chain of containers and see if the last lambda we see
' is a QueryLambda, before we reach local's container.
If IsTopMostEnclosingLambdaAQueryLambda(ContainingMember, localSymbolContainingSymbol) Then
ReportDiagnostic(diagnostics, node, ERRID.WRN_LiftControlVariableQuery, localSymbol.Name)
Else
ReportDiagnostic(diagnostics, node, ERRID.WRN_LiftControlVariableLambda, localSymbol.Name)
End If
End If
End If
' Debug.Assert(localSymbol.GetUseSiteErrorInfo() Is Nothing) ' Not true in the debugger.
Return New BoundLocal(node, localSymbol, localAccessType, hasErrors:=hasError)
Case SymbolKind.RangeVariable
Dim rangeVariable = DirectCast(lookupResult.SingleSymbol, RangeVariableSymbol)
Debug.Assert(rangeVariable.GetUseSiteErrorInfo() Is Nothing)
Return New BoundRangeVariable(node, rangeVariable, rangeVariable.Type, hasErrors:=hasError)
Case SymbolKind.Parameter
Dim parameterSymbol = DirectCast(lookupResult.SingleSymbol, ParameterSymbol)
Dim parameterType = parameterSymbol.Type
Dim asSimpleName = TryCast(node, SimpleNameSyntax)
If asSimpleName IsNot Nothing AndAlso Not parameterType.IsErrorType() Then
VerifyTypeCharacterConsistency(asSimpleName, parameterType.GetEnumUnderlyingTypeOrSelf, diagnostics)
End If
Debug.Assert(parameterSymbol.GetUseSiteErrorInfo() Is Nothing)
Return New BoundParameter(node, parameterSymbol, parameterType, hasErrors:=hasError)
Case SymbolKind.NamedType, SymbolKind.ErrorType
' Note: arity already checked by lookup process.
' Bind the type arguments.
Dim typeArguments As BoundTypeArguments = Nothing
If typeArgumentsOpt IsNot Nothing Then
' Bind the type arguments and report errors in the current context.
typeArguments = BindTypeArguments(typeArgumentsOpt, diagnostics)
End If
' If I identifies a type, then the result is that type constructed with the given type arguments.
' Construct the type if it is generic! See ConstructAndValidateConstraints().
Dim typeSymbol = TryCast(lookupResult.SingleSymbol, NamedTypeSymbol)
If typeSymbol IsNot Nothing AndAlso typeArguments IsNot Nothing Then
' Construct the type and validate constraints.
Dim constructedType = ConstructAndValidateConstraints(
typeSymbol, typeArguments.Arguments, node, typeArgumentsOpt.Arguments, diagnostics)
' Put the constructed type in. Note that this preserves any error associated with the lookupResult.
lookupResult.ReplaceSymbol(constructedType)
End If
ReportDiagnosticsIfObsolete(diagnostics, typeSymbol, node)
If Not hasError Then
receiver = AdjustReceiverTypeOrValue(receiver, node, isShared:=True, diagnostics:=diagnostics, qualKind:=qualKind)
hasError = CheckSharedSymbolAccess(node, True, receiver, qualKind, diagnostics)
End If
If Not reportedLookupError Then
ReportUseSiteError(diagnostics, node, If(typeSymbol, lookupResult.SingleSymbol))
End If
Dim type As TypeSymbol = DirectCast(lookupResult.SingleSymbol, TypeSymbol)
Dim asSimpleName = TryCast(node, SimpleNameSyntax)
If asSimpleName IsNot Nothing AndAlso Not type.IsErrorType() Then
VerifyTypeCharacterConsistency(asSimpleName, type.GetEnumUnderlyingTypeOrSelf, diagnostics)
End If
Return New BoundTypeExpression(node, receiver, Nothing, type, hasErrors:=hasError)
Case SymbolKind.TypeParameter
' Note: arity already checked by lookup process.
Debug.Assert(lookupResult.SingleSymbol.GetUseSiteErrorInfo() Is Nothing)
Return New BoundTypeExpression(node, DirectCast(lookupResult.SingleSymbol, TypeSymbol), hasErrors:=hasError)
Case SymbolKind.Namespace
' Note: arity already checked by lookup process.
Debug.Assert(lookupResult.SingleSymbol.GetUseSiteErrorInfo() Is Nothing)
Return New BoundNamespaceExpression(node, receiver, DirectCast(lookupResult.SingleSymbol, NamespaceSymbol), hasErrors:=hasError)
Case SymbolKind.Alias
Dim [alias] = DirectCast(lookupResult.SingleSymbol, AliasSymbol)
Debug.Assert([alias].GetUseSiteErrorInfo() Is Nothing)
Dim symbol = [alias].Target
Select Case symbol.Kind
Case SymbolKind.NamedType, SymbolKind.ErrorType
If Not reportedLookupError Then
ReportUseSiteError(diagnostics, node, symbol)
End If
Return New BoundTypeExpression(node, Nothing, [alias], DirectCast(symbol, TypeSymbol), hasErrors:=hasError)
Case SymbolKind.Namespace
Debug.Assert(symbol.GetUseSiteErrorInfo() Is Nothing)
Return New BoundNamespaceExpression(node, Nothing, [alias], DirectCast(symbol, NamespaceSymbol), hasErrors:=hasError)
Case Else
Throw ExceptionUtilities.UnexpectedValue(symbol.Kind)
End Select
Case Else
Throw ExceptionUtilities.UnexpectedValue(lookupResult.Symbols(0).Kind)
End Select
End Function
Private Function AdjustReceiverNamespace(lookupResult As LookupResult, receiver As BoundExpression) As BoundExpression
If receiver.Kind = BoundKind.NamespaceExpression Then
Dim namespaceReceiver = DirectCast(receiver, BoundNamespaceExpression)
If namespaceReceiver.NamespaceSymbol.NamespaceKind = NamespaceKindNamespaceGroup Then
Dim symbols As ArrayBuilder(Of Symbol) = lookupResult.Symbols
If lookupResult.HasDiagnostic Then
Dim di As DiagnosticInfo = lookupResult.Diagnostic
If TypeOf di Is AmbiguousSymbolDiagnostic Then
' Lookup had an ambiguity
Debug.Assert(lookupResult.Kind = LookupResultKind.Ambiguous)
Dim ambiguous As ImmutableArray(Of Symbol) = DirectCast(di, AmbiguousSymbolDiagnostic).AmbiguousSymbols
symbols = ArrayBuilder(Of Symbol).GetInstance()
symbols.AddRange(ambiguous)
End If
End If
receiver = AdjustReceiverNamespace(namespaceReceiver, symbols)
If symbols IsNot lookupResult.Symbols Then
symbols.Free()
End If
End If
End If
Return receiver
End Function
Private Function AdjustReceiverNamespace(namespaceReceiver As BoundNamespaceExpression, symbols As ArrayBuilder(Of Symbol)) As BoundNamespaceExpression
If symbols.Count > 0 Then
Dim namespaces = New SmallDictionary(Of NamespaceSymbol, Boolean)()
For Each candidate In symbols
If Not AddReceiverNamespaces(namespaces, candidate, Me.Compilation) Then
namespaces = Nothing
Exit For
End If
Next
If namespaces IsNot Nothing AndAlso namespaces.Count < namespaceReceiver.NamespaceSymbol.ConstituentNamespaces.Length Then
Return AdjustReceiverNamespace(namespaceReceiver, DirectCast(namespaceReceiver.NamespaceSymbol, MergedNamespaceSymbol).Shrink(namespaces.Keys))
End If
End If
Return namespaceReceiver
End Function
Friend Shared Function AddReceiverNamespaces(namespaces As SmallDictionary(Of NamespaceSymbol, Boolean), candidate As Symbol, compilation As VisualBasicCompilation) As Boolean
If candidate.Kind = SymbolKind.Namespace AndAlso
DirectCast(candidate, NamespaceSymbol).NamespaceKind = NamespaceKindNamespaceGroup Then
For Each constituent In DirectCast(candidate, NamespaceSymbol).ConstituentNamespaces
If Not AddContainingNamespaces(namespaces, constituent, compilation) Then
Return False
End If
Next
Return True
Else
Return AddContainingNamespaces(namespaces, candidate, compilation)
End If
End Function
Private Shared Function AddContainingNamespaces(namespaces As SmallDictionary(Of NamespaceSymbol, Boolean), candidate As Symbol, compilation As VisualBasicCompilation) As Boolean
If candidate Is Nothing OrElse candidate.Kind = SymbolKind.ErrorType Then
Return False
End If
Dim containingNamespace = candidate.ContainingNamespace
If containingNamespace IsNot Nothing Then
namespaces(compilation.GetCompilationNamespace(containingNamespace)) = False
Else
Debug.Assert(containingNamespace IsNot Nothing)
' Should not get here, I believe.
Return False
End If
Return True
End Function
Private Function AdjustReceiverNamespace(namespaceReceiver As BoundNamespaceExpression, adjustedNamespace As NamespaceSymbol) As BoundNamespaceExpression
If adjustedNamespace IsNot namespaceReceiver.NamespaceSymbol Then
Dim receiver As BoundExpression = namespaceReceiver.UnevaluatedReceiverOpt
If receiver IsNot Nothing AndAlso receiver.Kind = BoundKind.NamespaceExpression Then
Dim parentNamespace = DirectCast(receiver, BoundNamespaceExpression)
If parentNamespace.NamespaceSymbol.NamespaceKind = NamespaceKindNamespaceGroup AndAlso
IsNamespaceGroupIncludesButNotEquivalentTo(parentNamespace.NamespaceSymbol, adjustedNamespace.ContainingNamespace) Then
receiver = AdjustReceiverNamespace(parentNamespace, adjustedNamespace.ContainingNamespace)
End If
End If
Return namespaceReceiver.Update(receiver, namespaceReceiver.AliasOpt, adjustedNamespace)
End If
Return namespaceReceiver
End Function
Private Shared Function IsNamespaceGroupIncludesButNotEquivalentTo(namespaceGroup As NamespaceSymbol, other As NamespaceSymbol) As Boolean
Debug.Assert(namespaceGroup.NamespaceKind = NamespaceKindNamespaceGroup)
Dim result As Boolean
If other.NamespaceKind <> NamespaceKindNamespaceGroup Then
result = namespaceGroup.ConstituentNamespaces.Contains(other)
Else
Dim groupConstituents As ImmutableArray(Of NamespaceSymbol) = namespaceGroup.ConstituentNamespaces
Dim otherConstituents As ImmutableArray(Of NamespaceSymbol) = other.ConstituentNamespaces
If groupConstituents.Length > otherConstituents.Length Then
result = True
Dim lookup = New SmallDictionary(Of NamespaceSymbol, Boolean)()
For Each item In groupConstituents
lookup(item) = False
Next
For Each item In otherConstituents
If Not lookup.TryGetValue(item, Nothing) Then
result = False
Exit For
End If
Next
Else
result = False
End If
End If
Debug.Assert(result)
Return result
End Function
Private Sub CheckMemberTypeAccessibility(diagnostics As DiagnosticBag, node As VisualBasicSyntaxNode, member As Symbol)
' We are not doing this check during lookup due to a performance impact it has on IDE scenarios.
' In any case, an accessible member with inaccassible type is beyond language spec, so we have
' some freedom how to deal with it.
Dim memberType As TypeSymbol
Select Case member.Kind
Case SymbolKind.Method
memberType = DirectCast(member, MethodSymbol).ReturnType
Exit Select
Case SymbolKind.Property
memberType = DirectCast(member, PropertySymbol).Type
Exit Select
Case SymbolKind.Field
' Getting the type of a source field that is a constant can cause infinite
' recursion if that field has an inferred type. Rather than passing in fields
' currently being evaluated to break the recursion, we simply note that inferred
' types can never be inaccessible, so we don't check their types.
Dim fieldSym = DirectCast(member, FieldSymbol)
If fieldSym.HasDeclaredType Then
memberType = fieldSym.Type
Else
Return
End If
Case Else
' Somewhat strangely, event types are not checked.
Throw ExceptionUtilities.UnexpectedValue(member.Kind)
End Select
If CheckAccessibility(memberType, Nothing, Nothing) <> AccessCheckResult.Accessible Then
ReportDiagnostic(diagnostics, node,
New BadSymbolDiagnostic(member,
ERRID.ERR_InaccessibleReturnTypeOfMember2,
CustomSymbolDisplayFormatter.WithContainingType(member)))
End If
End Sub
Public Shared Function IsTopMostEnclosingLambdaAQueryLambda(containingMember As Symbol, stopAtContainer As Symbol) As Boolean
Dim topMostEnclosingLambdaIsQueryLambda As Boolean = False
' Need to go up the chain of containers and see if the last lambda we see
' is a QueryLambda, before we reach the stopAtContainer.
Dim currentContainer As Symbol = containingMember
While currentContainer IsNot Nothing AndAlso currentContainer IsNot stopAtContainer
Debug.Assert(currentContainer.IsLambdaMethod OrElse stopAtContainer Is Nothing)
If currentContainer.IsLambdaMethod Then
topMostEnclosingLambdaIsQueryLambda = currentContainer.IsQueryLambdaMethod
Else
Exit While
End If
currentContainer = currentContainer.ContainingSymbol
End While
Return topMostEnclosingLambdaIsQueryLambda
End Function
Public Function BindLabel(node As LabelSyntax, diagnostics As DiagnosticBag) As BoundExpression
Dim labelName As String = node.LabelToken.ValueText
Dim result = LookupResult.GetInstance()
Me.Lookup(result, labelName, arity:=0, options:=LookupOptions.LabelsOnly, useSiteDiagnostics:=Nothing)
Dim symbol As LabelSymbol = Nothing
Dim hasErrors As Boolean = False
If result.IsGood AndAlso result.HasSingleSymbol Then
symbol = DirectCast(result.Symbols.First(), LabelSymbol)
Else
If result.HasDiagnostic Then
ReportDiagnostic(diagnostics, node, result.Diagnostic)
Else
' The label is undefined
ReportDiagnostic(diagnostics, node, ERRID.ERR_LabelNotDefined1, labelName)
End If
hasErrors = True
End If
result.Free()
If symbol Is Nothing Then
Return New BoundBadExpression(node,
LookupResultKind.Empty,
ImmutableArray(Of Symbol).Empty,
ImmutableArray(Of BoundNode).Empty,
Nothing,
hasErrors:=True)
Else
Return New BoundLabel(node, symbol, Nothing, hasErrors:=hasErrors)
End If
End Function
Private Function BindTypeArguments(
typeArgumentsOpt As TypeArgumentListSyntax,
diagnostics As DiagnosticBag
) As BoundTypeArguments
If typeArgumentsOpt Is Nothing Then
Return Nothing
End If
Dim arguments = typeArgumentsOpt.Arguments
'TODO: What should we do if count is 0? Can we get in a situation like this?
' Perhaps for a missing type argument case [Foo(Of )].
Dim boundArguments(arguments.Count - 1) As TypeSymbol
For i As Integer = 0 To arguments.Count - 1 Step 1
boundArguments(i) = BindTypeSyntax(arguments(i), diagnostics)
Next
' TODO: Should we set HasError flag if any of the BindTypeSyntax calls report errors?
Return New BoundTypeArguments(typeArgumentsOpt, boundArguments.AsImmutableOrNull())
End Function
''' <summary>
''' Report diagnostics relating to access shared/nonshared symbols. Returns true if an ERROR (but not a warning)
''' was reported. Also replaces receiver as a type with DefaultPropertyInstance when appropriate.
''' </summary>
Private Function CheckSharedSymbolAccess(node As VisualBasicSyntaxNode, isShared As Boolean, <[In], Out> ByRef receiver As BoundExpression, qualKind As QualificationKind, diagnostics As DiagnosticBag) As Boolean
If isShared Then
If qualKind = QualificationKind.QualifiedViaValue AndAlso receiver IsNot Nothing AndAlso
receiver.Kind <> BoundKind.TypeOrValueExpression AndAlso receiver.Kind <> BoundKind.MyBaseReference AndAlso
Not receiver.HasErrors Then
' NOTE: Since using MyBase is the only way to call a method from base type
' in some cases, calls with 'MyBase' receiver should not be marked
' with this WRN_SharedMemberThroughInstance;
' WARNING: This differs from DEV10
' we do not want to report this diagnostic in the case of an initialization of a field/property
' through an object initializer. In that case we will output an error
' "BC30991: Member '{0}' cannot be initialized in an object initializer expression because it is shared."
' instead.
If node.Parent Is Nothing OrElse
node.Parent.Kind <> SyntaxKind.NamedFieldInitializer Then
ReportDiagnostic(diagnostics, node, ERRID.WRN_SharedMemberThroughInstance)
End If
End If
Else
If qualKind = QualificationKind.QualifiedViaTypeName OrElse
(qualKind = QualificationKind.Unqualified AndAlso receiver Is Nothing) Then
If qualKind = QualificationKind.QualifiedViaTypeName AndAlso receiver IsNot Nothing AndAlso
receiver.Kind = BoundKind.TypeExpression Then
' Try default instance property through DefaultInstanceAlias
Dim instance As BoundExpression = TryDefaultInstanceProperty(DirectCast(receiver, BoundTypeExpression), diagnostics)
If instance IsNot Nothing Then
receiver = instance
Return False
End If
End If
' We don't have a valid qualifier for this instance method.
If receiver IsNot Nothing AndAlso receiver.Kind = BoundKind.TypeExpression AndAlso IsReceiverOfNameOfArgument(receiver.Syntax) Then
receiver = New BoundTypeAsValueExpression(receiver.Syntax, DirectCast(receiver, BoundTypeExpression), receiver.Type).MakeCompilerGenerated()
Return False
Else
ReportDiagnostic(diagnostics, node, ERRID.ERR_ObjectReferenceNotSupplied)
Return True
End If
End If
Dim errorId As ERRID = Nothing
If qualKind = QualificationKind.Unqualified AndAlso Not IsNameOfArgument(node) AndAlso Not CanAccessMe(True, errorId) Then
' We can't use implicit Me here.
ReportDiagnostic(diagnostics, node, errorId)
Return True
End If
End If
Return False
End Function
Private Shared Function IsReceiverOfNameOfArgument(syntax As VisualBasicSyntaxNode) As Boolean
Dim parent = syntax.Parent
Return parent IsNot Nothing AndAlso
parent.Kind = SyntaxKind.SimpleMemberAccessExpression AndAlso
DirectCast(parent, MemberAccessExpressionSyntax).Expression Is syntax AndAlso
IsNameOfArgument(parent)
End Function
Private Shared Function IsNameOfArgument(syntax As VisualBasicSyntaxNode) As Boolean
Return syntax.Parent IsNot Nothing AndAlso
syntax.Parent.Kind = SyntaxKind.NameOfExpression AndAlso
DirectCast(syntax.Parent, NameOfExpressionSyntax).Argument Is syntax
End Function
''' <summary>
''' Returns a bound node for left part of dictionary access node with omitted left syntax.
''' In particular it handles dictionary access inside With statement.
'''
''' By default the method delegates the work to it's containing binder or returns Nothing.
''' </summary>
Protected Overridable Function TryBindOmittedLeftForDictionaryAccess(node As MemberAccessExpressionSyntax,
accessingBinder As Binder,
diagnostics As DiagnosticBag) As BoundExpression
Debug.Assert(Me.ContainingBinder IsNot Nothing)
Return Me.ContainingBinder.TryBindOmittedLeftForDictionaryAccess(node, accessingBinder, diagnostics)
End Function
Private Function BindDictionaryAccess(node As MemberAccessExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression
Dim leftOpt = node.Expression
Dim left As BoundExpression
If leftOpt Is Nothing Then
' Spec 11.7: "If an exclamation point is specified with no expression, the
' expression from the immediately containing With statement is assumed.
' If there is no containing With statement, a compile-time error occurs."
Dim conditionalAccess As ConditionalAccessExpressionSyntax = node.GetCorrespondingConditionalAccessExpression()
If conditionalAccess IsNot Nothing Then
left = GetConditionalAccessReceiver(conditionalAccess)
Else
left = TryBindOmittedLeftForDictionaryAccess(node, Me, diagnostics)
End If
If left Is Nothing Then
' Didn't find binder that can handle member access with omitted left part
Return BadExpression(
node,
ImmutableArray.Create(Of BoundNode)(
ReportDiagnosticAndProduceBadExpression(diagnostics, node, ERRID.ERR_BadWithRef),
New BoundLiteral(
node.Name,
ConstantValue.Create(node.Name.Identifier.ValueText),
GetSpecialType(SpecialType.System_String, node.Name, diagnostics))),
ErrorTypeSymbol.UnknownResultType)
End If
Else
left = Me.BindExpression(leftOpt, diagnostics)
End If
If Not left.IsLValue AndAlso left.Kind <> BoundKind.LateMemberAccess Then
left = MakeRValue(left, diagnostics)
Debug.Assert(left IsNot Nothing)
End If
Dim type = left.Type
Debug.Assert(type IsNot Nothing)
If Not type.IsErrorType() Then
If type.SpecialType = SpecialType.System_Object OrElse type.IsExtensibleInterfaceNoUseSiteDiagnostics() Then
Dim name = node.Name
Dim arg = New BoundLiteral(name, ConstantValue.Create(node.Name.Identifier.ValueText), GetSpecialType(SpecialType.System_String, name, diagnostics))
Dim boundArguments = ImmutableArray.Create(Of BoundExpression)(arg)
Return BindLateBoundInvocation(node, Nothing, left, boundArguments, Nothing, diagnostics)
End If
If type.IsInterfaceType Then
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
' In case IsExtensibleInterfaceNoUseSiteDiagnostics above failed because there were bad inherited interfaces.
type.AllInterfacesWithDefinitionUseSiteDiagnostics(useSiteDiagnostics)
diagnostics.Add(node, useSiteDiagnostics)
End If
Dim defaultPropertyGroup As BoundExpression = BindDefaultPropertyGroup(node, left, diagnostics)
Debug.Assert(defaultPropertyGroup Is Nothing OrElse defaultPropertyGroup.Kind = BoundKind.PropertyGroup OrElse
defaultPropertyGroup.Kind = BoundKind.MethodGroup OrElse defaultPropertyGroup.HasErrors)
' Dev10 limits Dictionary access to properties.
If defaultPropertyGroup IsNot Nothing AndAlso defaultPropertyGroup.Kind = BoundKind.PropertyGroup Then
Dim name = node.Name
Dim arg = New BoundLiteral(name, ConstantValue.Create(node.Name.Identifier.ValueText), GetSpecialType(SpecialType.System_String, name, diagnostics))
Return BindInvocationExpression(
node,
left.Syntax,
TypeCharacter.None,
DirectCast(defaultPropertyGroup, BoundPropertyGroup),
boundArguments:=ImmutableArray.Create(Of BoundExpression)(arg),
argumentNames:=Nothing,
diagnostics:=diagnostics,
isDefaultMemberAccess:=True,
callerInfoOpt:=node)
ElseIf defaultPropertyGroup Is Nothing OrElse Not defaultPropertyGroup.HasErrors Then
Select Case type.TypeKind
Case TypeKind.Array, TypeKind.Enum
ReportQualNotObjectRecord(left, diagnostics)
Case TypeKind.Class
If type.SpecialType = SpecialType.System_Array Then
ReportDefaultMemberNotProperty(left, diagnostics)
Else
ReportNoDefaultProperty(left, diagnostics)
End If
Case TypeKind.TypeParameter, TypeKind.Interface
ReportNoDefaultProperty(left, diagnostics)
Case TypeKind.Structure
If type.IsIntrinsicValueType() Then
ReportQualNotObjectRecord(left, diagnostics)
Else
ReportNoDefaultProperty(left, diagnostics)
End If
Case Else
ReportDefaultMemberNotProperty(left, diagnostics)
End Select
End If
End If
Return BadExpression(
node,
ImmutableArray.Create(Of BoundNode)(
left,
New BoundLiteral(
node.Name,
ConstantValue.Create(node.Name.Identifier.ValueText),
GetSpecialType(SpecialType.System_String, node.Name, diagnostics))),
ErrorTypeSymbol.UnknownResultType)
End Function
Private Sub ReportNoDefaultProperty(expr As BoundExpression, diagnostics As DiagnosticBag)
Dim type = expr.Type
Dim syntax = expr.Syntax
Select Case type.TypeKind
Case TypeKind.Class
' "Class '{0}' cannot be indexed because it has no default property."
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_NoDefaultNotExtend1, type)
Case TypeKind.Structure
' "Structure '{0}' cannot be indexed because it has no default property."
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_StructureNoDefault1, type)
Case TypeKind.Error
' We should have reported an error elsewhere.
Case Else
' "'{0}' cannot be indexed because it has no default property."
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_InterfaceNoDefault1, type)
End Select
End Sub
Private Sub ReportQualNotObjectRecord(expr As BoundExpression, diagnostics As DiagnosticBag)
' "'!' requires its left operand to have a type parameter, class or interface type, but this operand has the type '{0}'."
ReportDiagnostic(diagnostics, expr.Syntax, ERRID.ERR_QualNotObjectRecord1, expr.Type)
End Sub
Private Sub ReportDefaultMemberNotProperty(expr As BoundExpression, diagnostics As DiagnosticBag)
' "Default member '{0}' is not a property."
' Note: The error argument is the expression type
' rather than the expression text used in Dev10.
ReportDiagnostic(diagnostics, expr.Syntax, ERRID.ERR_DefaultMemberNotProperty1, expr.Type)
End Sub
Private Function GenerateBadExpression(node As InvocationExpressionSyntax, target As BoundExpression, boundArguments As ImmutableArray(Of BoundExpression)) As BoundExpression
Dim children = ArrayBuilder(Of BoundNode).GetInstance()
children.Add(target)
children.AddRange(boundArguments)
Return BadExpression(node, children.ToImmutableAndFree(), ErrorTypeSymbol.UnknownResultType)
End Function
Private Sub VerifyTypeCharacterConsistency(nodeOrToken As SyntaxNodeOrToken, type As TypeSymbol, typeChar As TypeCharacter, diagnostics As DiagnosticBag)
Dim typeCharacterString As String = Nothing
Dim specialType As SpecialType = GetSpecialTypeForTypeCharacter(typeChar, typeCharacterString)
If specialType <> Microsoft.CodeAnalysis.SpecialType.None Then
If type.IsArrayType() Then
type = DirectCast(type, ArrayTypeSymbol).ElementType
End If
type = type.GetNullableUnderlyingTypeOrSelf()
If type.SpecialType <> specialType Then
ReportDiagnostic(diagnostics, nodeOrToken, ERRID.ERR_TypecharNoMatch2, typeCharacterString, type)
End If
End If
End Sub
Private Sub VerifyTypeCharacterConsistency(name As SimpleNameSyntax, type As TypeSymbol, diagnostics As DiagnosticBag)
Dim typeChar As TypeCharacter = name.Identifier.GetTypeCharacter()
If typeChar = TypeCharacter.None Then
Return
End If
Dim typeCharacterString As String = Nothing
Dim specialType As SpecialType = GetSpecialTypeForTypeCharacter(typeChar, typeCharacterString)
If specialType <> SpecialType.None Then
If type.IsArrayType() Then
type = DirectCast(type, ArrayTypeSymbol).ElementType
End If
type = type.GetNullableUnderlyingTypeOrSelf()
If type.SpecialType <> specialType Then
ReportDiagnostic(diagnostics, name, ERRID.ERR_TypecharNoMatch2, typeCharacterString, type)
End If
End If
End Sub
Private Function BindArrayAccess(node As InvocationExpressionSyntax, expr As BoundExpression, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), diagnostics As DiagnosticBag) As BoundExpression
Debug.Assert(node IsNot Nothing)
Debug.Assert(expr IsNot Nothing)
If expr.IsLValue Then
expr = expr.MakeRValue()
End If
Dim builder As ArrayBuilder(Of BoundExpression) = Nothing
For i = 0 To boundArguments.Length - 1
Dim index As BoundExpression = boundArguments(i)
If builder Is Nothing AndAlso index.IsLValue Then
builder = ArrayBuilder(Of BoundExpression).GetInstance()
For k = 0 To i - 1
builder.Add(boundArguments(k))
Next
End If
If builder IsNot Nothing Then
builder.Add(index.MakeRValue)
End If
Next
If builder IsNot Nothing Then
boundArguments = builder.ToImmutableAndFree()
End If
Dim exprType = expr.Type
If exprType Is Nothing Then
Return New BoundArrayAccess(node, expr, boundArguments, Nothing, hasErrors:=True)
End If
If Not argumentNames.IsDefault AndAlso argumentNames.Length > 0 Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_NamedSubscript)
End If
Dim arrayType As ArrayTypeSymbol = DirectCast(expr.Type, ArrayTypeSymbol)
Dim rank As Integer = arrayType.Rank
If boundArguments.Length <> arrayType.Rank Then
Dim err As ERRID
If boundArguments.Length > arrayType.Rank Then
err = ERRID.ERR_TooManyIndices
Else
err = ERRID.ERR_TooFewIndices
End If
ReportDiagnostic(diagnostics, node.ArgumentList, err, node.ToString())
Return New BoundArrayAccess(node, expr, boundArguments, arrayType.ElementType, hasErrors:=True)
End If
Dim convertedArguments As BoundExpression() = New BoundExpression(boundArguments.Length - 1) {}
Dim int32Type = GetSpecialType(SpecialType.System_Int32, node.ArgumentList, diagnostics)
For i = 0 To boundArguments.Length - 1
convertedArguments(i) = ApplyImplicitConversion(boundArguments(i).Syntax, int32Type, boundArguments(i), diagnostics)
Next i
Return New BoundArrayAccess(node, expr, convertedArguments.AsImmutableOrNull(), arrayType.ElementType)
End Function
' Get the common return type of a set of symbols, or error type if no common return type. Used
' in error cases to give a type in ambiguity situations.
' If we can't find a common type, create an error type. If all the types have a common name,
' that name is used as the type of the error type (useful in ambiguous type lookup situations)
Private Function GetCommonExpressionType(
symbolReference As VisualBasicSyntaxNode,
symbols As ImmutableArray(Of Symbol),
constantFieldsInProgress As SymbolsInProgress(Of FieldSymbol)
) As TypeSymbol
Dim commonType As TypeSymbol = Nothing
Dim commonName As String = Nothing
Dim noCommonType As Boolean = False
Dim noCommonName As Boolean = False
Dim diagnostics As DiagnosticBag = DiagnosticBag.GetInstance()
For i As Integer = 0 To symbols.Length - 1
Dim expressionType As TypeSymbol = GetExpressionType(symbolReference, symbols(i), constantFieldsInProgress, diagnostics)
If expressionType IsNot Nothing Then
If commonType Is Nothing Then
commonType = expressionType
ElseIf Not noCommonType AndAlso Not commonType.Equals(expressionType) Then
noCommonType = True
End If
If commonName Is Nothing Then
commonName = expressionType.Name
ElseIf Not noCommonName AndAlso Not CaseInsensitiveComparison.Equals(commonName, expressionType.Name) Then
noCommonName = True
End If
End If
Next
diagnostics.Free()
If noCommonType Then
If noCommonName Then
Return ErrorTypeSymbol.UnknownResultType
Else
Return New ExtendedErrorTypeSymbol(Nothing, commonName)
End If
Else
Return commonType
End If
End Function
' Get the "expression type" of a symbol when used in an expression.
Private Function GetExpressionType(
symbolReference As VisualBasicSyntaxNode,
s As Symbol,
constantFieldsInProgress As SymbolsInProgress(Of FieldSymbol),
diagnostics As DiagnosticBag
) As TypeSymbol
Select Case s.Kind
Case SymbolKind.Method
Return DirectCast(s, MethodSymbol).ReturnType
Case SymbolKind.Field
' const fields may need to determine the type because it's inferred
' This is why using .Type was replaced by .GetInferredType to detect cycles.
Return DirectCast(s, FieldSymbol).GetInferredType(constantFieldsInProgress)
Case SymbolKind.Property
Return DirectCast(s, PropertySymbol).Type
Case SymbolKind.Parameter
Return DirectCast(s, ParameterSymbol).Type
Case SymbolKind.Local
Return GetLocalSymbolType(DirectCast(s, LocalSymbol), symbolReference, diagnostics)
Case SymbolKind.RangeVariable
Return DirectCast(s, RangeVariableSymbol).Type
Case Else
Dim type = TryCast(s, TypeSymbol)
If type IsNot Nothing Then
Return type
End If
End Select
Return Nothing
End Function
' Given the expression part of a named argument, get the token of it's name. We use this for error reported, and its more efficient
' to calculate it only when needed when reported a diagnostic.
Private Shared Function GetNamedArgumentIdentifier(argumentExpression As VisualBasicSyntaxNode) As SyntaxToken
Dim parent = TryCast(argumentExpression.Parent, SimpleArgumentSyntax)
If parent Is Nothing OrElse Not parent.IsNamed Then
Debug.Assert(False, "Did not found a NamedArgumentSyntax where one should have been")
Return argumentExpression.GetFirstToken() ' since we use this for error reporting, this gives us something close, anyway.
Else
Return parent.NameColonEquals.Name.Identifier
End If
End Function
Private Structure DimensionSize
Public Enum SizeKind As Byte
Unknown
Constant
NotConstant
End Enum
Public ReadOnly Kind As SizeKind
Public ReadOnly Size As Integer
Private Sub New(size As Integer, kind As SizeKind)
Me.Size = size
Me.Kind = kind
End Sub
Public Shared Function ConstantSize(size As Integer) As DimensionSize
Return New DimensionSize(size, SizeKind.Constant)
End Function
Public Shared Function VariableSize() As DimensionSize
Return New DimensionSize(0, SizeKind.NotConstant)
End Function
End Structure
''' <summary>
''' Handle ArrayCreationExpressionSyntax
''' new integer(n)(,) {...}
''' new integer() {...}
''' </summary>
Private Function BindArrayCreationExpression(node As ArrayCreationExpressionSyntax, diagnostics As DiagnosticBag) As BoundExpression
' Bind the type
Dim baseType = BindTypeSyntax(node.Type, diagnostics)
Dim arrayBoundsOpt = node.ArrayBounds
Dim boundArguments As ImmutableArray(Of BoundExpression) = Nothing
' Get the resulting array type by applying the array rank specifiers and the array bounds
Dim arrayType = CreateArrayOf(baseType, node.RankSpecifiers, arrayBoundsOpt, diagnostics)
Dim knownSizes(arrayType.Rank - 1) As DimensionSize
' Bind the bounds. This returns the known sizes of each dimension from the optional bounds
boundArguments = BindArrayBounds(arrayBoundsOpt, diagnostics, knownSizes)
' Bind the array initializer. This may update the known sizes for dimensions with initializers but that are missing explicit bounds
Dim boundInitializers = BindArrayInitializerList(node.Initializer, arrayType, knownSizes, diagnostics)
'Construct a set of size expressions if we were not given any.
If boundArguments.Length = 0 Then
boundArguments = CreateArrayBounds(node, knownSizes, diagnostics)
End If
Return New BoundArrayCreation(node, boundArguments, boundInitializers, arrayType)
End Function
Private Function BindArrayLiteralExpression(node As CollectionInitializerSyntax,
diagnostics As DiagnosticBag) As BoundExpression
' Inspect the collection initializer to determine the literal's rank
' Per 11.1.1, the array literal is reclassified to a value whose type is an array of rank equal to the level of nesting is used.
Dim rank = ComputeArrayLiteralRank(node)
Dim knownSizes(rank - 1) As DimensionSize
Dim hasDominantType As Boolean
Dim numberOfCandidates As Integer
Dim inferredElementType As TypeSymbol = Nothing
Dim arrayInitializer = BindArrayInitializerList(node, knownSizes, hasDominantType, numberOfCandidates, inferredElementType, diagnostics)
Dim inferredArrayType = New ArrayTypeSymbol(inferredElementType, Nothing, knownSizes.Length, Compilation)
Dim sizes As ImmutableArray(Of BoundExpression) = CreateArrayBounds(node, knownSizes, diagnostics)
Return New BoundArrayLiteral(node, hasDominantType, numberOfCandidates, inferredArrayType, sizes, arrayInitializer, Me)
End Function
Private Function CreateArrayBounds(node As VisualBasicSyntaxNode, knownSizes() As DimensionSize, diagnostics As DiagnosticBag) As ImmutableArray(Of BoundExpression)
Dim rank = knownSizes.Length
Dim sizes = New BoundExpression(rank - 1) {}
Dim Int32Type = GetSpecialType(SpecialType.System_Int32, node, diagnostics)
For i As Integer = 0 To knownSizes.Length - 1
Dim size = knownSizes(i)
'It is possible in error scenarios that some of the bounds were not determined.
'Use default values (0) for those.
Dim sizeExpr = New BoundLiteral(
node,
ConstantValue.Create(size.Size),
Int32Type
)
sizeExpr.SetWasCompilerGenerated()
sizes(i) = sizeExpr
Next
Return sizes.AsImmutableOrNull
End Function
Private Function ComputeArrayLiteralRank(node As CollectionInitializerSyntax) As Integer
Dim rank As Integer = 1
Do
Dim initializers = node.Initializers
If initializers.Count = 0 Then
Exit Do
End If
Dim expr = initializers(0)
node = TryCast(expr, CollectionInitializerSyntax)
If node Is Nothing Then
Exit Do
End If
rank += 1
Loop
Return rank
End Function
''' <summary>
''' Binds CollectionInitializeSyntax. i.e. { expr, ... } from an ArrayCreationExpressionSyntax
''' </summary>
''' <param name="node">The collection initializer syntax</param>
''' <param name="type">The type of array.</param>
''' <param name="knownSizes">This is in/out. It comes in with sizes from explicit bounds but will be updated based on the number of initializers for dimensions without bounds</param>
''' <param name="diagnostics">Where to put errors</param>
Private Function BindArrayInitializerList(node As CollectionInitializerSyntax,
type As ArrayTypeSymbol,
knownSizes As DimensionSize(),
diagnostics As DiagnosticBag) As BoundArrayInitialization
Debug.Assert(type IsNot Nothing)
Dim result = BindArrayInitializerList(node, type, knownSizes, 1, Nothing, diagnostics)
Return result
End Function
''' <summary>
''' Binds CollectionInitializeSyntax. i.e. { expr, ... } from an ArrayCreationExpressionSyntax
''' </summary>
''' <param name="node">The collection initializer syntax</param>
''' <param name="knownSizes">This is in/out. It comes in with sizes from explicit bounds but will be updated based on the number of initializers for dimensions without bounds</param>
''' <param name="hasDominantType">When the inferred type is Object() indicates that the dominant type algorithm computed this type.</param>
''' <param name="numberOfCandidates" >The number of candidates found during inference</param>
''' <param name="inferredElementType" >The inferred element type</param>
''' <param name="diagnostics">Where to put errors</param>
Private Function BindArrayInitializerList(node As CollectionInitializerSyntax,
knownSizes As DimensionSize(),
<Out> ByRef hasDominantType As Boolean,
<Out> ByRef numberOfCandidates As Integer,
<Out> ByRef inferredElementType As TypeSymbol,
diagnostics As DiagnosticBag) As BoundArrayInitialization
' Infer the type for this array literal
Dim initializers As ArrayBuilder(Of BoundExpression) = ArrayBuilder(Of BoundExpression).GetInstance
Dim result = BindArrayInitializerList(node, Nothing, knownSizes, 1, initializers, diagnostics)
inferredElementType = InferDominantTypeOfExpressions(node, initializers, diagnostics, numberOfCandidates)
If inferredElementType Is Nothing Then
' When no dominant type exists, use Object but remember that there wasn't a dominant type.
inferredElementType = GetSpecialType(SpecialType.System_Object, node, diagnostics)
hasDominantType = False
Else
hasDominantType = True
End If
initializers.Free()
Return result
End Function
Private Function BindArrayInitializerList(node As CollectionInitializerSyntax,
type As ArrayTypeSymbol,
knownSizes As DimensionSize(),
dimension As Integer,
allInitializers As ArrayBuilder(Of BoundExpression),
diagnostics As DiagnosticBag) As BoundArrayInitialization
Debug.Assert(type IsNot Nothing OrElse allInitializers IsNot Nothing)
Dim initializers = ArrayBuilder(Of BoundExpression).GetInstance
Dim arrayInitType As TypeSymbol
If dimension = 1 Then
' binding the outer-most initializer list; the result type is the array type being created.
arrayInitType = type
Else
' binding an inner initializer list; the result type is nothing.
arrayInitType = Nothing
End If
Dim rank As Integer = knownSizes.Length
If dimension <> 1 OrElse node.Initializers.Count <> 0 Then
Debug.Assert(type Is Nothing OrElse type.Rank = rank)
If dimension = rank Then
' We are processing the nth dimension of a rank-n array. We expect
' that these will only be values, not array initializers.
Dim elemType As TypeSymbol = If(type IsNot Nothing, type.ElementType, Nothing)
For Each expressionSyntax In node.Initializers
Dim boundExpression As BoundExpression
If expressionSyntax.Kind <> SyntaxKind.CollectionInitializer Then
boundExpression = BindValue(expressionSyntax, diagnostics)
If elemType IsNot Nothing Then
boundExpression = ApplyImplicitConversion(expressionSyntax, elemType, boundExpression, diagnostics)
End If
Else
boundExpression = ReportDiagnosticAndProduceBadExpression(diagnostics, expressionSyntax, ERRID.ERR_ArrayInitializerTooManyDimensions)
End If
initializers.Add(boundExpression)
If allInitializers IsNot Nothing Then
allInitializers.Add(boundExpression)
End If
Next
Else
' Inductive case; we'd better have another array initializer
For Each expr In node.Initializers
Dim init As BoundArrayInitialization = Nothing
If expr.Kind = SyntaxKind.CollectionInitializer Then
init = Me.BindArrayInitializerList(DirectCast(expr, CollectionInitializerSyntax), type, knownSizes, dimension + 1, allInitializers, diagnostics)
Else
ReportDiagnostic(diagnostics, expr, ERRID.ERR_ArrayInitializerTooFewDimensions)
init = New BoundArrayInitialization(expr, ImmutableArray(Of BoundExpression).Empty, arrayInitType, hasErrors:=True)
End If
initializers.Add(init)
Next
End If
Dim curSize = knownSizes(dimension - 1)
If curSize.Kind = DimensionSize.SizeKind.Unknown Then
knownSizes(dimension - 1) = DimensionSize.ConstantSize(initializers.Count)
ElseIf curSize.Kind = DimensionSize.SizeKind.NotConstant Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_ArrayInitializerForNonConstDim)
Return New BoundArrayInitialization(node, initializers.ToImmutableAndFree(), arrayInitType, hasErrors:=True)
ElseIf curSize.Size < initializers.Count Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_InitializerTooManyElements1, initializers.Count - curSize.Size)
Return New BoundArrayInitialization(node, initializers.ToImmutableAndFree(), arrayInitType, hasErrors:=True)
ElseIf curSize.Size > initializers.Count Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_InitializerTooFewElements1, curSize.Size - initializers.Count)
Return New BoundArrayInitialization(node, initializers.ToImmutableAndFree(), arrayInitType, hasErrors:=True)
End If
End If
Return New BoundArrayInitialization(node, initializers.ToImmutableAndFree(), arrayInitType)
End Function
Private Sub CheckRangeArgumentLowerBound(rangeArgument As RangeArgumentSyntax, diagnostics As DiagnosticBag)
Dim lowerBound = BindValue(rangeArgument.LowerBound, diagnostics)
' This check was moved from the parser to the binder. For backwards compatibility with Dev10, the constant must
' be integral. This seems a bit inconsistent because the range argument allows (0 to 5.0) but not (0.0 to 5.0)
Dim lowerBoundConstantValueOpt As ConstantValue = lowerBound.ConstantValueOpt
If lowerBoundConstantValueOpt Is Nothing OrElse Not lowerBoundConstantValueOpt.IsIntegral OrElse Not lowerBoundConstantValueOpt.IsDefaultValue Then
ReportDiagnostic(diagnostics, rangeArgument.LowerBound, ERRID.ERR_OnlyNullLowerBound)
End If
End Sub
''' <summary>
''' Bind the array bounds and return the sizes for each dimension.
''' </summary>
''' <param name="arrayBoundsOpt">The bounds</param>
''' <param name="diagnostics">Where to put the errors</param>
''' <param name="knownSizes">The bounds if they are constants, if argument is not specified this info is not returned </param>
Private Function BindArrayBounds(arrayBoundsOpt As ArgumentListSyntax,
diagnostics As DiagnosticBag,
Optional knownSizes As DimensionSize() = Nothing,
Optional errorOnEmptyBound As Boolean = False) As ImmutableArray(Of BoundExpression)
If arrayBoundsOpt Is Nothing Then
Return s_noArguments
End If
Dim arguments As SeparatedSyntaxList(Of ArgumentSyntax) = arrayBoundsOpt.Arguments
Dim boundArgumentsBuilder As ArrayBuilder(Of BoundExpression) = ArrayBuilder(Of BoundExpression).GetInstance
Dim int32Type = GetSpecialType(SpecialType.System_Int32, arrayBoundsOpt, diagnostics)
' check if there is any nonempty array bound
' in such case we will require all other bounds be nonempty
For Each argumentSyntax In arguments
Select Case argumentSyntax.Kind
Case SyntaxKind.SimpleArgument, SyntaxKind.RangeArgument
errorOnEmptyBound = True
Exit For
End Select
Next
For i As Integer = 0 To arguments.Count - 1
Dim upperBound As BoundExpression = Nothing
Dim upperBoundSyntax As ExpressionSyntax = Nothing
Dim argumentSyntax = arguments(i)
Select Case argumentSyntax.Kind
Case SyntaxKind.SimpleArgument
Dim simpleArgument = DirectCast(argumentSyntax, SimpleArgumentSyntax)
If simpleArgument.NameColonEquals IsNot Nothing Then
ReportDiagnostic(diagnostics, argumentSyntax, ERRID.ERR_NamedSubscript)
End If
upperBoundSyntax = simpleArgument.Expression
Case SyntaxKind.RangeArgument
Dim rangeArgument = DirectCast(argumentSyntax, RangeArgumentSyntax)
CheckRangeArgumentLowerBound(rangeArgument, diagnostics)
upperBoundSyntax = rangeArgument.UpperBound
Case SyntaxKind.OmittedArgument
If errorOnEmptyBound Then
ReportDiagnostic(diagnostics, argumentSyntax, ERRID.ERR_MissingSubscript)
GoTo lElseClause
Else
Continue For
End If
Case Else
lElseClause:
' TODO - What expression should be generated in this case? Note, the parser already generates a syntax error.
' The syntax is a missing Identifier and not an OmittedArgumentSyntax.
upperBound = BadExpression(argumentSyntax, ErrorTypeSymbol.UnknownResultType)
End Select
If upperBoundSyntax IsNot Nothing Then
upperBound = BindValue(upperBoundSyntax, diagnostics)
upperBound = ApplyImplicitConversion(upperBoundSyntax, int32Type, upperBound, diagnostics)
End If
' Add 1 to the upper bound to get the array size
' Dev10 does not consider checked/unchecked here when folding the addition
' in a case of overflow exception will be thrown at run time
Dim upperBoundConstantValueOpt As ConstantValue = upperBound.ConstantValueOpt
If upperBoundConstantValueOpt IsNot Nothing AndAlso Not upperBoundConstantValueOpt.IsBad Then
' -1 is a valid value it means 0 - length array
' anything less is invalid.
If upperBoundConstantValueOpt.Int32Value < -1 Then
ReportDiagnostic(diagnostics, argumentSyntax, ERRID.ERR_NegativeArraySize)
End If
End If
Dim one = New BoundLiteral(argumentSyntax, ConstantValue.Create(1), int32Type)
one.SetWasCompilerGenerated()
' Try folding the size.
Dim integerOverflow As Boolean = False
Dim divideByZero As Boolean = False
' Note: the value may overflow, but we ignore this and use the overflown value.
Dim value = OverloadResolution.TryFoldConstantBinaryOperator(BinaryOperatorKind.Add, upperBound, one, int32Type, integerOverflow, divideByZero, Nothing)
If knownSizes IsNot Nothing Then
If value IsNot Nothing Then
knownSizes(i) = DimensionSize.ConstantSize(value.Int32Value)
Else
knownSizes(i) = DimensionSize.VariableSize
End If
End If
Dim actualSize = New BoundBinaryOperator(
argumentSyntax,
BinaryOperatorKind.Add,
upperBound,
one,
CheckOverflow,
value,
int32Type
)
actualSize.SetWasCompilerGenerated()
boundArgumentsBuilder.Add(actualSize)
Next
Return boundArgumentsBuilder.ToImmutableAndFree
End Function
Private Function BindLiteralConstant(node As LiteralExpressionSyntax, diagnostics As DiagnosticBag) As BoundLiteral
Dim value = node.Token.Value
Dim cv As ConstantValue
Dim type As TypeSymbol = Nothing
If value Is Nothing Then
' this is for Null
cv = ConstantValue.Null
Else
Debug.Assert(Not value.GetType().GetTypeInfo().IsEnum)
Dim specialType As SpecialType = SpecialTypeExtensions.FromRuntimeTypeOfLiteralValue(value)
' VB literals can't be of type byte, sbyte
Debug.Assert(specialType <> SpecialType.None AndAlso
specialType <> SpecialType.System_Byte AndAlso
specialType <> SpecialType.System_SByte)
cv = ConstantValue.Create(value, specialType)
type = GetSpecialType(specialType, node, diagnostics)
End If
Return New BoundLiteral(node, cv, type)
End Function
Friend Function InferDominantTypeOfExpressions(
syntax As VisualBasicSyntaxNode,
Expressions As ArrayBuilder(Of BoundExpression),
diagnostics As DiagnosticBag,
ByRef numCandidates As Integer,
Optional ByRef errorReasons As InferenceErrorReasons = InferenceErrorReasons.Other
) As TypeSymbol
' Arguments: "expressions" is a list of expressions from which to infer dominant type
' Output: we might return Nothing / NumCandidates==0 (if we couldn't find a dominant type)
' Or we might return Object / NumCandidates==0 (if we had to assume Object because no dominant type was found)
' Or we might return Object / NumCandidates>=2 (if we had to assume Object because multiple candidates were found)
' Or we might return a real dominant type from one of the candidates / NumCandidates==1
' In the last case, "winner" is set to one of the expressions who proposed that winning dominant type.
' "Winner" information might be useful if you are calculating the dominant type of "{}" and "{Nothing}"
' and you need to know who the winner is so you can report appropriate warnings on him.
' The dominant type of a list of elements means:
' (1) for each element, attempt to classify it as a value in a context where the target
' type is unknown. So unbound lambdas get classified as anonymous delegates, and array literals get
' classified according to their dominant type (if they have one), and Nothing is ignored, and AddressOf too.
' But skip over empty array literals.
' (2) Consider the types of all elements for which we got a type, and feed these into the dominant-type
' algorithm: if there are multiple candidates such that all other types convert to it through identity/widening,
' then pick the dominant type out of this set. Otherwise, if there is a single all-widening/identity candidate,
' pick this. Otherwise, if there is a single all-widening/identity/narrowing candidate, then pick this.
' (3) Otherwise, if the dominant type algorithm has failed and every element was an empty array literal {}
' then pick Object() and report a warning "Object assumed"
' (4) Otherwise, if every element converts to Object, then pick Object and report a warning "Object assumed".
' (5) Otherwise, there is no dominant type; return Nothing and report an error.
numCandidates = 0
Dim count As Integer = 0
Dim countOfEmptyArrays As Integer = 0 ' To detect case (3)
Dim anEmptyArray As BoundArrayLiteral = Nothing ' Used for case (3), so we'll return one of them
Dim allConvertibleToObject As Boolean = True ' To detect case (4)
Dim typeList As New TypeInferenceCollection()
For Each expression As BoundExpression In Expressions
count += 1
Debug.Assert(expression IsNot Nothing)
Debug.Assert(expression.IsValue())
' Dig through parenthesized.
If Not expression.IsNothingLiteral Then
expression = expression.GetMostEnclosedParenthesizedExpression()
End If
Dim expressionKind As BoundKind = expression.Kind
Dim expressionType As TypeSymbol = expression.Type
If expressionKind = BoundKind.UnboundLambda Then
expressionType = DirectCast(expression, UnboundLambda).InferredAnonymousDelegate.Key
typeList.AddType(expressionType, RequiredConversion.Any, expression)
ElseIf expressionKind = BoundKind.ArrayLiteral Then
Dim arrayLiteral = DirectCast(expression, BoundArrayLiteral)
' Empty array literals {} should not be constraints on the dominant type algorithm.
' Array's without a dominant type should not be constraints on the dominant type algorithm.
If arrayLiteral.IsEmptyArrayLiteral Then
countOfEmptyArrays += 1
anEmptyArray = arrayLiteral
ElseIf arrayLiteral.HasDominantType Then
expressionType = New ArrayLiteralTypeSymbol(arrayLiteral)
typeList.AddType(expressionType, RequiredConversion.Any, expression)
End If
ElseIf expressionType IsNot Nothing AndAlso Not expressionType.IsVoidType() AndAlso
Not (expressionType.IsArrayType() AndAlso DirectCast(expressionType, ArrayTypeSymbol).ElementType.IsVoidType()) Then
typeList.AddType(expressionType, RequiredConversion.Any, expression)
If expressionType.IsRestrictedType() Then
' this element is a restricted type; not convertible to object
allConvertibleToObject = False
End If
Else
' What else?
Debug.Assert(expressionType Is Nothing)
If Not expression.IsNothingLiteral Then
' NOTE: Some expressions without type are still convertible to System.Object, example: Nothing literal
allConvertibleToObject = False
End If
' this will pick up lambdas which couldn't be inferred, and array literals which lacked a dominant type,
' and AddressOf expressions.
End If
Next
' Here we calculate the dominant type.
' Note: if there were no candidate types in the list, this will fail with errorReason = NoneBest.
errorReasons = InferenceErrorReasons.Other
Dim results = ArrayBuilder(Of DominantTypeData).GetInstance()
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
typeList.FindDominantType(results, errorReasons, useSiteDiagnostics)
If diagnostics.Add(syntax, useSiteDiagnostics) Then
' Suppress additional diagnostics
diagnostics = New DiagnosticBag()
End If
Dim dominantType As TypeSymbol
If results.Count = 1 AndAlso errorReasons = InferenceErrorReasons.Other Then
' main case: we succeeded in finding a dominant type
Debug.Assert(Not results(0).ResultType.IsVoidType(), "internal logic error: how could void have won the dominant type algorithm?")
numCandidates = 1
dominantType = results(0).ResultType
ElseIf count = countOfEmptyArrays AndAlso count > 0 Then
' special case: the dominant type of a list of empty arrays is Object(), not Object.
Debug.Assert(anEmptyArray IsNot Nothing, "internal logic error: if we got at least one empty array, then AnEmptyArray should not be null")
numCandidates = 1
' Use the inferred Object() from the array literal. ReclassifyArrayLiteral depends on the array identity for correct error reporting
' of inference errors.
dominantType = anEmptyArray.InferredType
Debug.Assert(dominantType.IsArrayType AndAlso DirectCast(dominantType, ArrayTypeSymbol).Rank = 1 AndAlso DirectCast(dominantType, ArrayTypeSymbol).ElementType.SpecialType = SpecialType.System_Object)
ElseIf allConvertibleToObject AndAlso (errorReasons And InferenceErrorReasons.Ambiguous) <> 0 Then
' special case: there were multiple dominant types, so we fall back to Object
Debug.Assert(results.Count > 1, "internal logic error: if InferenceErrorReasonsAmbiguous, you'd have expected more than 1 candidate")
numCandidates = results.Count
dominantType = GetSpecialType(SpecialType.System_Object, syntax, diagnostics)
ElseIf allConvertibleToObject Then
' fallback case: we didn't find a dominant type, but can fall back to Object
numCandidates = 0
dominantType = GetSpecialType(SpecialType.System_Object, syntax, diagnostics)
Else
numCandidates = 0
dominantType = Nothing
End If
' Ensure that ArrayLiteralType is not returned from the dominant type algorithm
Dim arrayLiteralType = TryCast(dominantType, ArrayLiteralTypeSymbol)
If arrayLiteralType IsNot Nothing Then
dominantType = arrayLiteralType.ArrayLiteral.InferredType
End If
results.Free()
Return dominantType
End Function
Public Function IsInAsyncContext() As Boolean
Return ContainingMember.Kind = SymbolKind.Method AndAlso DirectCast(ContainingMember, MethodSymbol).IsAsync
End Function
Public Function IsInIteratorContext() As Boolean
Return ContainingMember.Kind = SymbolKind.Method AndAlso DirectCast(ContainingMember, MethodSymbol).IsIterator
End Function
Private Function BindAwait(
node As AwaitExpressionSyntax,
diagnostics As DiagnosticBag,
Optional bindAsStatement As Boolean = False
) As BoundExpression
If IsInQuery Then
ReportDiagnostic(diagnostics, node.AwaitKeyword, ERRID.ERR_BadAsyncInQuery)
ElseIf Not IsInAsyncContext() Then
ReportDiagnostic(diagnostics, node.AwaitKeyword, GetAwaitInNonAsyncError())
End If
Dim operand As BoundExpression = BindExpression(node.Expression, diagnostics)
Return BindAwait(node, operand, diagnostics, bindAsStatement)
End Function
Private Function BindAwait(
node As VisualBasicSyntaxNode,
operand As BoundExpression,
diagnostics As DiagnosticBag,
bindAsStatement As Boolean
) As BoundExpression
' If the user tries to do "await f()" or "await expr.f()" where f is an async sub,
' then we'll give a more helpful error message...
If Not operand.HasErrors AndAlso
operand.Type IsNot Nothing AndAlso
operand.Type.IsVoidType() AndAlso
operand.Kind = BoundKind.Call Then
Dim method As MethodSymbol = DirectCast(operand, BoundCall).Method
If method.IsSub AndAlso method.IsAsync Then
ReportDiagnostic(diagnostics, operand.Syntax, ERRID.ERR_CantAwaitAsyncSub1, method.Name)
Return BadExpression(node, operand, ErrorTypeSymbol.UnknownResultType)
End If
End If
operand = MakeRValue(operand, diagnostics)
If operand.IsNothingLiteral() Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_BadAwaitNothing)
Return BadExpression(node, operand, ErrorTypeSymbol.UnknownResultType)
ElseIf operand.Type.IsObjectType() Then
' Late-bound pattern.
If OptionStrict = OptionStrict.On Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_StrictDisallowsLateBinding)
Return BadExpression(node, operand, ErrorTypeSymbol.UnknownResultType)
ElseIf OptionStrict = OptionStrict.Custom Then
ReportDiagnostic(diagnostics, node, ERRID.WRN_LateBindingResolution)
End If
End If
Dim ignoreDiagnostics = DiagnosticBag.GetInstance()
' Will accumulate all ignored diagnostics in case we want to add them
Dim allIgnoreDiagnostics = DiagnosticBag.GetInstance()
If operand.HasErrors Then
' Disable error reporting going forward.
diagnostics = ignoreDiagnostics
End If
Dim awaitableInstancePlaceholder = New BoundRValuePlaceholder(operand.Syntax, operand.Type).MakeCompilerGenerated()
Dim awaiterInstancePlaceholder As BoundLValuePlaceholder = Nothing
Dim getAwaiter As BoundExpression = Nothing
Dim isCompleted As BoundExpression = Nothing
Dim getResult As BoundExpression = Nothing
If operand.Type.IsObjectType Then
' Late-bound pattern.
getAwaiter = BindLateBoundMemberAccess(node, WellKnownMemberNames.GetAwaiter, Nothing, awaitableInstancePlaceholder, operand.Type,
ignoreDiagnostics, suppressLateBindingResolutionDiagnostics:=True).MakeCompilerGenerated()
getAwaiter = DirectCast(getAwaiter, BoundLateMemberAccess).SetAccessKind(LateBoundAccessKind.Get)
Debug.Assert(getAwaiter.Type.IsObjectType())
awaiterInstancePlaceholder = New BoundLValuePlaceholder(operand.Syntax, getAwaiter.Type).MakeCompilerGenerated()
isCompleted = BindLateBoundMemberAccess(node, WellKnownMemberNames.IsCompleted, Nothing, awaiterInstancePlaceholder, awaiterInstancePlaceholder.Type,
ignoreDiagnostics, suppressLateBindingResolutionDiagnostics:=True).MakeCompilerGenerated()
isCompleted = DirectCast(isCompleted, BoundLateMemberAccess).SetAccessKind(LateBoundAccessKind.Get)
Debug.Assert(isCompleted.Type.IsObjectType())
getResult = BindLateBoundMemberAccess(node, WellKnownMemberNames.GetResult, Nothing, awaiterInstancePlaceholder, awaiterInstancePlaceholder.Type,
ignoreDiagnostics, suppressLateBindingResolutionDiagnostics:=True).MakeCompilerGenerated()
Debug.Assert(getResult.Type.IsObjectType())
getResult = DirectCast(getResult, BoundLateMemberAccess).SetAccessKind(If(bindAsStatement, LateBoundAccessKind.Call, LateBoundAccessKind.Get))
Debug.Assert(operand.Type.IsErrorType() OrElse ignoreDiagnostics.IsEmptyWithoutResolution())
Else
Dim lookupResult As LookupResult = LookupResult.GetInstance()
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
' 11.25 Await Operator
'
'1. C contains an accessible instance or extension method named GetAwaiter which has no arguments and which returns some type E;
LookupMember(lookupResult, awaitableInstancePlaceholder.Type, WellKnownMemberNames.GetAwaiter, 0, LookupOptions.AllMethodsOfAnyArity, useSiteDiagnostics)
Dim methodGroup As BoundMethodGroup = Nothing
If lookupResult.Kind = LookupResultKind.Good AndAlso lookupResult.Symbols(0).Kind = SymbolKind.Method Then
methodGroup = CreateBoundMethodGroup(
node,
lookupResult,
LookupOptions.Default,
awaitableInstancePlaceholder,
Nothing,
QualificationKind.QualifiedViaValue).MakeCompilerGenerated()
ignoreDiagnostics.Clear()
getAwaiter = MakeRValue(BindInvocationExpression(node,
operand.Syntax,
TypeCharacter.None,
methodGroup,
ImmutableArray(Of BoundExpression).Empty,
Nothing,
ignoreDiagnostics,
callerInfoOpt:=node).MakeCompilerGenerated(),
ignoreDiagnostics).MakeCompilerGenerated()
' The result we are looking for is:
' 1) a non-latebound call of an instance (extension method is considered instance) method;
' 2) method doesn't have any parameters, optional parameters should be ruled out;
' 3) method is not a Sub;
' 4) result is not Object.
If getAwaiter.HasErrors OrElse
DiagnosticBagHasErrorsOtherThanObsoleteOnes(ignoreDiagnostics) OrElse
getAwaiter.Kind <> BoundKind.Call OrElse
getAwaiter.Type.IsObjectType() Then
getAwaiter = Nothing
Else
allIgnoreDiagnostics.AddRange(ignoreDiagnostics)
Dim method As MethodSymbol = DirectCast(getAwaiter, BoundCall).Method
If method.IsShared OrElse method.ParameterCount <> 0 Then
getAwaiter = Nothing
End If
End If
Debug.Assert(getAwaiter Is Nothing OrElse Not DiagnosticBagHasErrorsOtherThanObsoleteOnes(ignoreDiagnostics))
End If
If getAwaiter IsNot Nothing AndAlso Not getAwaiter.Type.IsErrorType() Then
' 2. E contains a readable instance property named IsCompleted which takes no arguments and has type Boolean;
awaiterInstancePlaceholder = New BoundLValuePlaceholder(operand.Syntax, getAwaiter.Type).MakeCompilerGenerated()
lookupResult.Clear()
LookupMember(lookupResult, awaiterInstancePlaceholder.Type, WellKnownMemberNames.IsCompleted, 0,
LookupOptions.AllMethodsOfAnyArity Or LookupOptions.IgnoreExtensionMethods, useSiteDiagnostics)
If lookupResult.Kind = LookupResultKind.Good AndAlso lookupResult.Symbols(0).Kind = SymbolKind.Property Then
Dim propertyGroup = New BoundPropertyGroup(node,
lookupResult.Symbols.ToDowncastedImmutable(Of PropertySymbol),
lookupResult.Kind,
awaiterInstancePlaceholder,
QualificationKind.QualifiedViaValue).MakeCompilerGenerated()
ignoreDiagnostics.Clear()
isCompleted = MakeRValue(BindInvocationExpression(node,
operand.Syntax,
TypeCharacter.None,
propertyGroup,
ImmutableArray(Of BoundExpression).Empty,
Nothing,
ignoreDiagnostics,
callerInfoOpt:=node).MakeCompilerGenerated(),
ignoreDiagnostics).MakeCompilerGenerated()
' The result we are looking for is:
' 1) a non-latebound get of an instance property;
' 2) property doesn't have any parameters, optional parameters should be ruled out;
' 3) result is Boolean.
If isCompleted.HasErrors OrElse
DiagnosticBagHasErrorsOtherThanObsoleteOnes(ignoreDiagnostics) OrElse
isCompleted.Kind <> BoundKind.PropertyAccess OrElse
Not isCompleted.Type.IsBooleanType() Then
isCompleted = Nothing
Else
allIgnoreDiagnostics.AddRange(ignoreDiagnostics)
Debug.Assert(DirectCast(isCompleted, BoundPropertyAccess).AccessKind = PropertyAccessKind.Get)
Dim prop As PropertySymbol = DirectCast(isCompleted, BoundPropertyAccess).PropertySymbol
If prop.IsShared OrElse prop.ParameterCount <> 0 Then
isCompleted = Nothing
End If
End If
Debug.Assert(isCompleted Is Nothing OrElse Not DiagnosticBagHasErrorsOtherThanObsoleteOnes(ignoreDiagnostics))
End If
' 3. E contains an accessible instance method named GetResult which takes no arguments;
lookupResult.Clear()
LookupMember(lookupResult, awaiterInstancePlaceholder.Type, WellKnownMemberNames.GetResult, 0,
LookupOptions.AllMethodsOfAnyArity Or LookupOptions.IgnoreExtensionMethods, useSiteDiagnostics)
If lookupResult.Kind = LookupResultKind.Good AndAlso lookupResult.Symbols(0).Kind = SymbolKind.Method Then
methodGroup = CreateBoundMethodGroup(
node,
lookupResult,
LookupOptions.Default,
awaiterInstancePlaceholder,
Nothing,
QualificationKind.QualifiedViaValue).MakeCompilerGenerated()
ignoreDiagnostics.Clear()
getResult = BindInvocationExpression(node,
operand.Syntax,
TypeCharacter.None,
methodGroup,
ImmutableArray(Of BoundExpression).Empty,
Nothing,
ignoreDiagnostics,
callerInfoOpt:=node).MakeCompilerGenerated()
' The result we are looking for is:
' 1) a non-latebound call of an instance (extension methods ignored) method;
' 2) method doesn't have any parameters, optional parameters should be ruled out;
If getResult.HasErrors OrElse
DiagnosticBagHasErrorsOtherThanObsoleteOnes(ignoreDiagnostics) OrElse
getResult.Kind <> BoundKind.Call Then
getResult = Nothing
Else
allIgnoreDiagnostics.AddRange(ignoreDiagnostics)
Dim method As MethodSymbol = DirectCast(getResult, BoundCall).Method
Debug.Assert(Not method.IsReducedExtensionMethod)
If method.IsShared OrElse method.ParameterCount <> 0 OrElse
(method.IsSub AndAlso method.IsConditional) Then
getResult = Nothing
End If
End If
Debug.Assert(getResult Is Nothing OrElse Not DiagnosticBagHasErrorsOtherThanObsoleteOnes(ignoreDiagnostics))
End If
' 4. E implements either System.Runtime.CompilerServices.INotifyCompletion or ICriticalNotifyCompletion.
Dim notifyCompletion As NamedTypeSymbol = GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_INotifyCompletion, node, diagnostics)
' ICriticalNotifyCompletion inherits from INotifyCompletion, so a check for INotifyCompletion is sufficient.
If Not notifyCompletion.IsErrorType() AndAlso
Not Conversions.IsWideningConversion(Conversions.ClassifyDirectCastConversion(getAwaiter.Type, notifyCompletion, useSiteDiagnostics)) Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_DoesntImplementAwaitInterface2, getAwaiter.Type, notifyCompletion)
End If
End If
diagnostics.Add(node, useSiteDiagnostics)
lookupResult.Free()
End If
Dim hasErrors As Boolean = False
If getAwaiter Is Nothing Then
hasErrors = True
ReportDiagnostic(diagnostics, node, ERRID.ERR_BadGetAwaiterMethod1, operand.Type)
Debug.Assert(isCompleted Is Nothing AndAlso getResult Is Nothing)
getAwaiter = BadExpression(node, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
ElseIf getAwaiter.Type.IsErrorType() Then
hasErrors = True
ElseIf isCompleted Is Nothing OrElse getResult Is Nothing Then
hasErrors = True
ReportDiagnostic(diagnostics, node, ERRID.ERR_BadIsCompletedOnCompletedGetResult2, getAwaiter.Type, operand.Type)
End If
If awaiterInstancePlaceholder Is Nothing Then
Debug.Assert(hasErrors)
awaiterInstancePlaceholder = New BoundLValuePlaceholder(node, getAwaiter.Type).MakeCompilerGenerated()
End If
If isCompleted Is Nothing Then
isCompleted = BadExpression(node, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
End If
If getResult Is Nothing Then
getResult = BadExpression(node, ErrorTypeSymbol.UnknownResultType).MakeCompilerGenerated()
End If
Dim resultType As TypeSymbol
If bindAsStatement Then
resultType = GetSpecialType(SpecialType.System_Void, node, diagnostics)
Else
resultType = getResult.Type
End If
If Not hasErrors Then
diagnostics.AddRange(allIgnoreDiagnostics)
End If
allIgnoreDiagnostics.Free()
ignoreDiagnostics.Free()
Return New BoundAwaitOperator(node, operand,
awaitableInstancePlaceholder, getAwaiter,
awaiterInstancePlaceholder, isCompleted, getResult,
resultType, hasErrors)
End Function
Private Shared Function DiagnosticBagHasErrorsOtherThanObsoleteOnes(bag As DiagnosticBag) As Boolean
If bag.IsEmptyWithoutResolution Then
Return False
End If
For Each diag In bag.AsEnumerable()
If diag.Severity = DiagnosticSeverity.Error Then
Select Case diag.Code
Case ERRID.ERR_UseOfObsoletePropertyAccessor2,
ERRID.ERR_UseOfObsoletePropertyAccessor3,
ERRID.ERR_UseOfObsoleteSymbolNoMessage1,
ERRID.ERR_UseOfObsoleteSymbol2
' ignore
Case Else
Return True
End Select
End If
Next
Return False
End Function
Private Function GetAwaitInNonAsyncError() As DiagnosticInfo
If Me.IsInLambda Then
Return ErrorFactory.ErrorInfo(ERRID.ERR_BadAwaitInNonAsyncLambda)
ElseIf ContainingMember.Kind = SymbolKind.Method Then
Dim method = DirectCast(ContainingMember, MethodSymbol)
If method.IsSub Then
Return ErrorFactory.ErrorInfo(ERRID.ERR_BadAwaitInNonAsyncVoidMethod)
Else
Return ErrorFactory.ErrorInfo(ERRID.ERR_BadAwaitInNonAsyncMethod, method.ReturnType)
End If
End If
Return ErrorFactory.ErrorInfo(ERRID.ERR_BadAwaitNotInAsyncMethodOrLambda)
End Function
End Class
End Namespace
|
paladique/roslyn
|
src/Compilers/VisualBasic/Portable/Binding/Binder_Expressions.vb
|
Visual Basic
|
apache-2.0
| 244,053
|
' 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.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic
Public Class CodeVariableTests
Inherits AbstractCodeVariableTests
#Region "GetStartPoint() tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetStartPoint1()
Dim code =
<Code>
Class C
Dim i$$ As Integer
End Class
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=2, lineOffset:=9, absoluteOffset:=17, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)))
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetStartPoint_Attribute()
Dim code =
<Code>
Class C
<System.CLSCompliant(True)>
Dim i$$ As Integer
End Class
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=9, absoluteOffset:=49, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31)))
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetStartPoint_EnumMember()
Dim code =
<Code>
Enum E
A$$
End Enum
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)))
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetStartPoint_EnumMember_Attribute()
Dim code =
<Code>
Enum E
<System.CLSCompliant(True)>
A$$
End Enum
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31)))
End Sub
#End Region
#Region "GetEndPoint() tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetEndPoint1()
Dim code =
<Code>
Class C
Dim i$$ As Integer
End Class
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=2, lineOffset:=10, absoluteOffset:=18, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)))
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetEndPoint_Attribute()
Dim code =
<Code>
Class C
<System.CLSCompliant(True)>
Dim i$$ As Integer
End Class
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
TextPoint(line:=2, lineOffset:=32, absoluteOffset:=40, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=32, absoluteOffset:=40, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=10, absoluteOffset:=50, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)))
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetEndPoint_EnumMember()
Dim code =
<Code>
Enum E
A$$
End Enum
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)))
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetEndPoint_EnumMember_Attribute()
Dim code =
<Code>
Enum E
<System.CLSCompliant(True)>
A$$
End Enum
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
TextPoint(line:=2, lineOffset:=32, absoluteOffset:=39, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=32, absoluteOffset:=39, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)))
End Sub
#End Region
#Region "Access tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestAccess1()
Dim code =
<Code>
Class C
Dim $$x as Integer
End Class
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestAccess2()
Dim code =
<Code>
Class C
Private $$x as Integer
End Class
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestAccess3()
Dim code =
<Code>
Class C
Protected $$x as Integer
End Class
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProtected)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestAccess4()
Dim code =
<Code>
Class C
Protected Friend $$x as Integer
End Class
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestAccess5()
Dim code =
<Code>
Class C
Friend $$x as Integer
End Class
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestAccess6()
Dim code =
<Code>
Class C
Public $$x as Integer
End Class
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestAccess7()
Dim code =
<Code>
Enum E
$$Goo
End Enum
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Sub
#End Region
#Region "Comment tests"
<WorkItem(638909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638909")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestComment1()
Dim code =
<Code>
Class C
' Goo
Dim $$i As Integer
End Class
</Code>
Dim result = " Goo"
TestComment(code, result)
End Sub
#End Region
#Region "ConstKind tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestConstKind1()
Dim code =
<Code>
Enum E
$$Goo
End Enum
</Code>
TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestConstKind2()
Dim code =
<Code>
Class C
Dim $$x As Integer
End Class
</Code>
TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindNone)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestConstKind3()
Dim code =
<Code>
Class C
Const $$x As Integer
End Class
</Code>
TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestConstKind4()
Dim code =
<Code>
Class C
ReadOnly $$x As Integer
End Class
</Code>
TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestConstKind5()
Dim code =
<Code>
Class C
ReadOnly Const $$x As Integer
End Class
</Code>
TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst)
End Sub
#End Region
#Region "InitExpression tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestInitExpression1()
Dim code =
<Code>
Class C
Dim i$$ As Integer = 42
End Class
</Code>
TestInitExpression(code, "42")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestInitExpression2()
Dim code =
<Code>
Class C
Const $$i As Integer = 19 + 23
End Class
</Code>
TestInitExpression(code, "19 + 23")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestInitExpression3()
Dim code =
<Code>
Enum E
$$i = 19 + 23
End Enum
</Code>
TestInitExpression(code, "19 + 23")
End Sub
#End Region
#Region "IsConstant tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestIsConstant1()
Dim code =
<Code>
Enum E
$$Goo
End Enum
</Code>
TestIsConstant(code, True)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestIsConstant2()
Dim code =
<Code>
Class C
Dim $$x As Integer
End Class
</Code>
TestIsConstant(code, False)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestIsConstant3()
Dim code =
<Code>
Class C
Const $$x As Integer = 0
End Class
</Code>
TestIsConstant(code, True)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestIsConstant4()
Dim code =
<Code>
Class C
ReadOnly $$x As Integer = 0
End Class
</Code>
TestIsConstant(code, True)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestIsConstant5()
Dim code =
<Code>
Class C
WithEvents $$x As Integer
End Class
</Code>
TestIsConstant(code, False)
End Sub
#End Region
#Region "IsShared tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestIsShared1()
Dim code =
<Code>
Class C
Dim $$x As Integer
End Class
</Code>
TestIsShared(code, False)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestIsShared2()
Dim code =
<Code>
Class C
Shared $$x As Integer
End Class
</Code>
TestIsShared(code, True)
End Sub
#End Region
#Region "Name tests"
<WorkItem(638224, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638224")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestName_EnumMember()
Dim code =
<Code>
Enum SomeEnum
A$$
End Enum
</Code>
TestName(code, "A")
End Sub
#End Region
#Region "Prototype tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPrototype_UniqueSignature()
Dim code =
<Code>
Namespace N
Class C
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeUniqueSignature, "F:N.C.x")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPrototype_ClassName1()
Dim code =
<Code>
Namespace N
Class C
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "Private C.x")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPrototype_ClassName2()
Dim code =
<Code>
Namespace N
Class C(Of T)
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "Private C(Of T).x")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPrototype_ClassName3()
Dim code =
<Code>
Namespace N
Class C
Public ReadOnly $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "Public C.x")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPrototype_ClassName_InitExpression()
Dim code =
<Code>
Namespace N
Class C
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "Private C.x = 42")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPrototype_FullName1()
Dim code =
<Code>
Namespace N
Class C
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "Private N.C.x")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPrototype_FullName2()
Dim code =
<Code>
Namespace N
Class C(Of T)
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "Private N.C(Of T).x")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPrototype_FullName_InitExpression()
Dim code =
<Code>
Namespace N
Class C
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "Private N.C.x = 42")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPrototype_NoName()
Dim code =
<Code>
Namespace N
Class C
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeNoName, "Private ")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPrototype_NoName_InitExpression()
Dim code =
<Code>
Namespace N
Class C
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeNoName Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "Private = 42")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPrototype_NoName_InitExpression_Type()
Dim code =
<Code>
Namespace N
Class C
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeNoName Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType, "Private As Integer = 42")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPrototype_InitExpression_Type_ForAsNew()
' Amusingly, this will *crash* Dev10.
Dim code =
<Code>
Namespace N
Class C
Dim $$x As New System.Text.StringBuilder
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType, "Private x As System.Text.StringBuilder")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPrototype_Type()
Dim code =
<Code>
Namespace N
Class C
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeType, "Private x As Integer")
End Sub
#End Region
#Region "Type tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestType1()
Dim code =
<Code>
Class C
Dim $$a As Integer
End Class
</Code>
TestTypeProp(code,
New CodeTypeRefData With {
.AsString = "Integer",
.AsFullName = "System.Int32",
.CodeTypeFullName = "System.Int32",
.TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefInt
})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestType2()
Dim code =
<Code>
Class C
WithEvents $$a As Object
End Class
</Code>
TestTypeProp(code,
New CodeTypeRefData With {
.AsString = "Object",
.AsFullName = "System.Object",
.CodeTypeFullName = "System.Object",
.TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefObject
})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestType3()
Dim code =
<Code>
Class C
Private $$a As New Object
End Class
</Code>
TestTypeProp(code,
New CodeTypeRefData With {
.AsString = "Object",
.AsFullName = "System.Object",
.CodeTypeFullName = "System.Object",
.TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefObject
})
End Sub
#End Region
#Region "AddAttribute tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute1() As Task
Dim code =
<Code>
Imports System
Class C
Dim $$goo As Integer
End Class
</Code>
Dim expected =
<Code><![CDATA[
Imports System
Class C
<Serializable()>
Dim goo As Integer
End Class
]]></Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WorkItem(1087167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087167")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute2() As Task
Dim code =
<Code><![CDATA[
Imports System
Class C
<Serializable>
Dim $$goo As Integer
End Class
]]></Code>
Dim expected =
<Code><![CDATA[
Imports System
Class C
<Serializable>
<CLSCompliant(True)>
Dim goo As Integer
End Class
]]></Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True", .Position = 1})
End Function
<WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_BelowDocComment() As Task
Dim code =
<Code><![CDATA[
Imports System
Class C
''' <summary></summary>
Dim $$goo As Integer
End Class
]]></Code>
Dim expected =
<Code><![CDATA[
Imports System
Class C
''' <summary></summary>
<CLSCompliant(True)>
Dim goo As Integer
End Class
]]></Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True"})
End Function
#End Region
#Region "Set Access tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetEnumAccess1() As Task
Dim code =
<Code>
Enum E
$$Goo
End Enum
</Code>
Dim expected =
<Code>
Enum E
Goo
End Enum
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetEnumAccess2() As Task
Dim code =
<Code>
Enum E
$$Goo
End Enum
</Code>
Dim expected =
<Code>
Enum E
Goo
End Enum
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetEnumAccess3() As Task
Dim code =
<Code>
Enum E
$$Goo
End Enum
</Code>
Dim expected =
<Code>
Enum E
Goo
End Enum
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate, ThrowsArgumentException(Of EnvDTE.vsCMAccess)())
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess1() As Task
Dim code =
<Code>
Class C
Dim $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Public i As Integer
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess2() As Task
Dim code =
<Code>
Class C
Public $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim i As Integer
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess3() As Task
Dim code =
<Code>
Class C
Private $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim i As Integer
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess4() As Task
Dim code =
<Code>
Class C
Dim $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim i As Integer
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess5() As Task
Dim code =
<Code>
Class C
Public $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Protected Friend i As Integer
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess6() As Task
Dim code =
<Code>
Class C
#Region "Goo"
Dim x As Integer
#End Region
Dim $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
#Region "Goo"
Dim x As Integer
#End Region
Public i As Integer
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess7() As Task
Dim code =
<Code>
Class C
#Region "Goo"
Dim x As Integer
#End Region
Public $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
#Region "Goo"
Dim x As Integer
#End Region
Protected Friend i As Integer
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess8() As Task
Dim code =
<Code>
Class C
#Region "Goo"
Dim x As Integer
#End Region
Public $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
#Region "Goo"
Dim x As Integer
#End Region
Dim i As Integer
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess9() As Task
Dim code =
<Code>
Class C
#Region "Goo"
Dim $$x As Integer
#End Region
End Class
</Code>
Dim expected =
<Code>
Class C
#Region "Goo"
Public x As Integer
#End Region
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess10() As Task
Dim code =
<Code>
Class C
#Region "Goo"
Public $$x As Integer
#End Region
End Class
</Code>
Dim expected =
<Code>
Class C
#Region "Goo"
Dim x As Integer
#End Region
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess11() As Task
Dim code =
<Code>
Class C
#Region "Goo"
Public $$x As Integer
#End Region
End Class
</Code>
Dim expected =
<Code>
Class C
#Region "Goo"
Protected Friend x As Integer
#End Region
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess12() As Task
Dim code =
<Code><![CDATA[
Class C
#Region "Goo"
<Bar>
Public $$x As Integer
#End Region
End Class
]]></Code>
Dim expected =
<Code><![CDATA[
Class C
#Region "Goo"
<Bar>
Protected Friend x As Integer
#End Region
End Class
]]></Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess13() As Task
Dim code =
<Code>
Class C
#Region "Goo"
' Comment comment comment
Public $$x As Integer
#End Region
End Class
</Code>
Dim expected =
<Code>
Class C
#Region "Goo"
' Comment comment comment
Protected Friend x As Integer
#End Region
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess14() As Task
Dim code =
<Code><![CDATA[
Class C
#Region "Goo"
''' <summary>
''' Comment comment comment
''' </summary>
Public $$x As Integer
#End Region
End Class
]]></Code>
Dim expected =
<Code><![CDATA[
Class C
#Region "Goo"
''' <summary>
''' Comment comment comment
''' </summary>
Protected Friend x As Integer
#End Region
End Class
]]></Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess15() As Task
Dim code =
<Code>
Class C
Dim $$x As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Private WithEvents x As Integer
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate Or EnvDTE.vsCMAccess.vsCMAccessWithEvents)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess16() As Task
Dim code =
<Code>
Class C
Private WithEvents $$x As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim x As Integer
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault)
End Function
#End Region
#Region "Set ConstKind tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetConstKind1() As Task
Dim code =
<Code>
Enum
$$Goo
End Enum
</Code>
Dim expected =
<Code>
Enum
Goo
End Enum
</Code>
Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone, ThrowsNotImplementedException(Of EnvDTE80.vsCMConstKind))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetConstKind2() As Task
Dim code =
<Code>
Enum
$$Goo
End Enum
</Code>
Dim expected =
<Code>
Enum
Goo
End Enum
</Code>
Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly, ThrowsNotImplementedException(Of EnvDTE80.vsCMConstKind))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetConstKind3() As Task
Dim code =
<Code>
Enum
$$Goo
End Enum
</Code>
Dim expected =
<Code>
Enum
Goo
End Enum
</Code>
Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst, ThrowsNotImplementedException(Of EnvDTE80.vsCMConstKind))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetConstKind4() As Task
Dim code =
<Code>
Class C
Dim $$x As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim x As Integer
End Class
</Code>
Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetConstKind5() As Task
Dim code =
<Code>
Class C
Shared $$x As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Shared x As Integer
End Class
</Code>
Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetConstKind6() As Task
Dim code =
<Code>
Class C
Dim $$x As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Const x As Integer
End Class
</Code>
Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetConstKind7() As Task
Dim code =
<Code>
Class C
Const $$x As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim x As Integer
End Class
</Code>
Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetConstKind8() As Task
Dim code =
<Code>
Class C
Dim $$x As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
ReadOnly x As Integer
End Class
</Code>
Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetConstKind9() As Task
Dim code =
<Code>
Class C
ReadOnly $$x As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim x As Integer
End Class
</Code>
Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone)
End Function
#End Region
#Region "Set InitExpression tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetInitExpression1() As Task
Dim code =
<Code>
Class C
Dim $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim i As Integer = 42
End Class
</Code>
Await TestSetInitExpression(code, expected, "42")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetInitExpression2() As Task
Dim code =
<Code>
Class C
Dim $$i As Integer, j As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim i As Integer = 42, j As Integer
End Class
</Code>
Await TestSetInitExpression(code, expected, "42")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetInitExpression3() As Task
Dim code =
<Code>
Class C
Dim i As Integer, $$j As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim i As Integer, j As Integer = 42
End Class
</Code>
Await TestSetInitExpression(code, expected, "42")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetInitExpression4() As Task
' The result below is a bit silly, but that's what the legacy Code Model does.
Dim code =
<Code>
Class C
Dim $$o As New Object
End Class
</Code>
Dim expected =
<Code>
Class C
Dim o As New Object = 42
End Class
</Code>
Await TestSetInitExpression(code, expected, "42")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetInitExpression5() As Task
Dim code =
<Code>
Class C
Const $$i As Integer = 0
End Class
</Code>
Dim expected =
<Code>
Class C
Const i As Integer = 19 + 23
End Class
</Code>
Await TestSetInitExpression(code, expected, "19 + 23")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetInitExpression6() As Task
Dim code =
<Code>
Class C
Const $$i As Integer = 0
End Class
</Code>
Dim expected =
<Code>
Class C
Const i As Integer
End Class
</Code>
Await TestSetInitExpression(code, expected, "")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetInitExpression7() As Task
Dim code =
<Code>
Enum E
$$Goo
End Enum
</Code>
Dim expected =
<Code>
Enum E
Goo = 42
End Enum
</Code>
Await TestSetInitExpression(code, expected, "42")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetInitExpression8() As Task
Dim code =
<Code>
Enum E
$$Goo = 0
End Enum
</Code>
Dim expected =
<Code>
Enum E
Goo = 42
End Enum
</Code>
Await TestSetInitExpression(code, expected, "42")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetInitExpression9() As Task
Dim code =
<Code>
Enum E
$$Goo = 0
End Enum
</Code>
Dim expected =
<Code>
Enum E
Goo
End Enum
</Code>
Await TestSetInitExpression(code, expected, Nothing)
End Function
#End Region
#Region "Set IsConstant tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetIsConstant1() As Task
Dim code =
<Code>
Class C
Dim $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Const i As Integer
End Class
</Code>
Await TestSetIsConstant(code, expected, True)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetIsConstant2() As Task
Dim code =
<Code>
Class C
Const $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim i As Integer
End Class
</Code>
Await TestSetIsConstant(code, expected, False)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetIsConstant3() As Task
Dim code =
<Code>
Class C
ReadOnly $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Const i As Integer
End Class
</Code>
Await TestSetIsConstant(code, expected, True)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetIsConstant4() As Task
Dim code =
<Code>
Class C
ReadOnly $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim i As Integer
End Class
</Code>
Await TestSetIsConstant(code, expected, False)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetIsConstant5() As Task
Dim code =
<Code>
Module C
Dim $$i As Integer
End Module
</Code>
Dim expected =
<Code>
Module C
Const i As Integer
End Module
</Code>
Await TestSetIsConstant(code, expected, True)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetIsConstant6() As Task
Dim code =
<Code>
Enum E
$$Goo
End Enum
</Code>
Dim expected =
<Code>
Enum E
Goo
End Enum
</Code>
Await TestSetIsConstant(code, expected, True, ThrowsNotImplementedException(Of Boolean))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetIsConstant7() As Task
Dim code =
<Code>
Enum E
$$Goo
End Enum
</Code>
Dim expected =
<Code>
Enum E
Goo
End Enum
</Code>
Await TestSetIsConstant(code, expected, False, ThrowsNotImplementedException(Of Boolean))
End Function
#End Region
#Region "Set IsShared tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetIsShared1() As Task
Dim code =
<Code>
Class C
Dim $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Shared i As Integer
End Class
</Code>
Await TestSetIsShared(code, expected, True)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetIsShared2() As Task
Dim code =
<Code>
Class C
Shared $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim i As Integer
End Class
</Code>
Await TestSetIsShared(code, expected, False)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetIsShared3() As Task
Dim code =
<Code>
Class C
Private $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Private Shared i As Integer
End Class
</Code>
Await TestSetIsShared(code, expected, True)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetIsShared4() As Task
Dim code =
<Code>
Class C
Private Shared $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Private i As Integer
End Class
</Code>
Await TestSetIsShared(code, expected, False)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetIsShared5() As Task
Dim code =
<Code>
Module C
Dim $$i As Integer
End Module
</Code>
Dim expected =
<Code>
Module C
Dim i As Integer
End Module
</Code>
Await TestSetIsShared(code, expected, True, ThrowsNotImplementedException(Of Boolean))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetIsShared6() As Task
Dim code =
<Code>
Enum E
$$Goo
End Enum
</Code>
Dim expected =
<Code>
Enum E
Goo
End Enum
</Code>
Await TestSetIsShared(code, expected, True, ThrowsNotImplementedException(Of Boolean))
End Function
#End Region
#Region "Set Name tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetName1() As Task
Dim code =
<Code>
Class C
Dim $$Goo As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim Bar As Integer
End Class
</Code>
Await TestSetName(code, expected, "Bar", NoThrow(Of String)())
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetName2() As Task
Dim code =
<Code>
Class C
#Region "Goo"
Dim $$Goo As Integer
#End Region
End Class
</Code>
Dim expected =
<Code>
Class C
#Region "Goo"
Dim Bar As Integer
#End Region
End Class
</Code>
Await TestSetName(code, expected, "Bar", NoThrow(Of String)())
End Function
#End Region
#Region "Set Type tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetType1() As Task
Dim code =
<Code>
Class C
Dim $$a As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim a As Double
End Class
</Code>
Await TestSetTypeProp(code, expected, "double")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetType2() As Task
Dim code =
<Code>
Class C
Dim $$a, b As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim a, b As Double
End Class
</Code>
Await TestSetTypeProp(code, expected, "double")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetType3() As Task
Dim code =
<Code>
Class C
Private $$a As New Object
End Class
</Code>
Dim expected =
<Code>
Class C
Private a As New String
End Class
</Code>
Await TestSetTypeProp(code, expected, "String")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetType4() As Task
Dim code =
<Code>
Class C
Private $$a As New Object, x As Integer = 0
End Class
</Code>
Dim expected =
<Code>
Class C
Private a As New String, x As Integer = 0
End Class
</Code>
Await TestSetTypeProp(code, expected, "String")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetType5() As Task
Dim code =
<Code>
Class C
Private a As New Object, x$$ As Integer = 0
End Class
</Code>
Dim expected =
<Code>
Class C
Private a As New Object, x As String = 0
End Class
</Code>
Await TestSetTypeProp(code, expected, "String")
End Function
#End Region
Protected Overrides ReadOnly Property LanguageName As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
End Class
End Namespace
|
physhi/roslyn
|
src/VisualStudio/Core/Test/CodeModel/VisualBasic/CodeVariableTests.vb
|
Visual Basic
|
apache-2.0
| 53,633
|
'*********************************************************
'
' 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 Windows.UI.Xaml
Imports Windows.UI.Xaml.Controls
Imports Windows.UI.Xaml.Navigation
Imports System
Namespace Global.SDKTemplate
Public NotInheritable Partial Class Scenario3_Replace
Inherits Page
Private rootPage As MainPage = MainPage.Current
Public Sub New()
Me.InitializeComponent()
End Sub
''' <summary>
''' Replace an appointment on the user's calendar using the default appointments provider app.
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Async Sub Replace_Click(sender As Object, e As RoutedEventArgs)
' The appointment id argument for ReplaceAppointmentAsync is typically retrieved from AddAppointmentAsync and stored in app data.
Dim appointmentIdOfAppointmentToReplace As String = AppointmentIdTextBox.Text
If String.IsNullOrEmpty(appointmentIdOfAppointmentToReplace) Then
rootPage.NotifyUser("The appointment id cannot be empty", NotifyType.ErrorMessage)
Else
' The Appointment argument for ReplaceAppointmentAsync should contain all of the Appointment's properties including those that may have changed.
Dim appointment = New Windows.ApplicationModel.Appointments.Appointment()
' Get the selection rect of the button pressed to replace this appointment
Dim rect = MainPage.GetElementRect(TryCast(sender, FrameworkElement))
' ReplaceAppointmentAsync returns an updated appointment id when the appointment was successfully replaced.
' The updated id may or may not be the same as the original one retrieved from AddAppointmentAsync.
' An optional instance start time can be provided to indicate that a specific instance on that date should be replaced
' in the case of a recurring appointment.
' If the appointment id returned is an empty string, that indicates that the appointment was not replaced.
Dim updatedAppointmentId As String
If InstanceStartDateCheckBox.IsChecked.Value Then
' Replace a specific instance starting on the date provided.
Dim instanceStartDate = InstanceStartDateDatePicker.Date
updatedAppointmentId = Await Windows.ApplicationModel.Appointments.AppointmentManager.ShowReplaceAppointmentAsync(appointmentIdOfAppointmentToReplace, appointment, rect, Windows.UI.Popups.Placement.Default, instanceStartDate)
Else
updatedAppointmentId = Await Windows.ApplicationModel.Appointments.AppointmentManager.ShowReplaceAppointmentAsync(appointmentIdOfAppointmentToReplace, appointment, rect, Windows.UI.Popups.Placement.Default)
End If
If updatedAppointmentId <> String.Empty Then
rootPage.NotifyUser("Updated Appointment Id: " & updatedAppointmentId, NotifyType.StatusMessage)
Else
rootPage.NotifyUser("Appointment not replaced.", NotifyType.ErrorMessage)
End If
End If
End Sub
End Class
End Namespace
|
oldnewthing/Windows-universal-samples
|
Samples/Appointments/vb/Scenario3_Replace.xaml.vb
|
Visual Basic
|
mit
| 3,670
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeStyle
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SimplifyTypeNames
Public Class SimplifyTypeNamesTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
<Fact>
<Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)>
<Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)>
Public Async Function TestFixAllInDocument() As Task
Dim input = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document><![CDATA[
Imports System
Class Program
Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32
Dim i1 As {|FixAllInDocument:System.Int32|} = 0
Dim s1 As System.Int16 = 0
Dim i2 As System.Int32 = 0
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
<Document><![CDATA[
Imports System
Class Program
Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32
Dim i1 As System.Int32 = 0
Dim s1 As System.Int16 = 0
Dim i2 As System.Int32 = 0
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<ProjectReference>Assembly1</ProjectReference>
<Document><![CDATA[
Imports System
Class Program
Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32
Dim i1 As System.Int32 = 0
Dim s1 As System.Int16 = 0
Dim i2 As System.Int32 = 0
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
</Project>
</Workspace>.ToString()
Dim expected = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document><![CDATA[
Imports System
Class Program
Private Shared Function F(x As Integer, y As Short) As Integer
Dim i1 As Integer = 0
Dim s1 As Short = 0
Dim i2 As Integer = 0
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
<Document><![CDATA[
Imports System
Class Program
Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32
Dim i1 As System.Int32 = 0
Dim s1 As System.Int16 = 0
Dim i2 As System.Int32 = 0
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<ProjectReference>Assembly1</ProjectReference>
<Document><![CDATA[
Imports System
Class Program
Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32
Dim i1 As System.Int32 = 0
Dim s1 As System.Int16 = 0
Dim i2 As System.Int32 = 0
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
</Project>
</Workspace>.ToString()
Await TestInRegularAndScriptAsync(input, expected, options:=PreferIntrinsicPredefinedTypeEverywhere())
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)>
<Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)>
Public Async Function TestFixAllInProject() As Task
Dim input = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document><![CDATA[
Imports System
Class Program
Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32
Dim i1 As {|FixAllInProject:System.Int32|} = 0
Dim s1 As System.Int16 = 0
Dim i2 As System.Int32 = 0
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
<Document><![CDATA[
Imports System
Class Program
Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32
Dim i1 As System.Int32 = 0
Dim s1 As System.Int16 = 0
Dim i2 As System.Int32 = 0
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<ProjectReference>Assembly1</ProjectReference>
<Document><![CDATA[
Imports System
Class Program
Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32
Dim i1 As System.Int32 = 0
Dim s1 As System.Int16 = 0
Dim i2 As System.Int32 = 0
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
</Project>
</Workspace>.ToString()
Dim expected = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document><![CDATA[
Imports System
Class Program
Private Shared Function F(x As Integer, y As Short) As Integer
Dim i1 As Integer = 0
Dim s1 As Short = 0
Dim i2 As Integer = 0
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
<Document><![CDATA[
Imports System
Class Program
Private Shared Function F(x As Integer, y As Short) As Integer
Dim i1 As Integer = 0
Dim s1 As Short = 0
Dim i2 As Integer = 0
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<ProjectReference>Assembly1</ProjectReference>
<Document><![CDATA[
Imports System
Class Program
Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32
Dim i1 As System.Int32 = 0
Dim s1 As System.Int16 = 0
Dim i2 As System.Int32 = 0
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
</Project>
</Workspace>.ToString()
Await TestInRegularAndScriptAsync(input, expected, options:=PreferIntrinsicPredefinedTypeEverywhere())
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)>
<Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)>
Public Async Function TestFixAllInSolution() As Task
Dim input = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document><![CDATA[
Imports System
Class Program
Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32
Dim i1 As {|FixAllInSolution:System.Int32|} = 0
Dim s1 As System.Int16 = 0
Dim i2 As System.Int32 = 0
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
<Document><![CDATA[
Imports System
Class Program
Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32
Dim i1 As System.Int32 = 0
Dim s1 As System.Int16 = 0
Dim i2 As System.Int32 = 0
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<ProjectReference>Assembly1</ProjectReference>
<Document><![CDATA[
Imports System
Class Program
Private Shared Function F(x As System.Int32, y As System.Int16) As System.Int32
Dim i1 As System.Int32 = 0
Dim s1 As System.Int16 = 0
Dim i2 As System.Int32 = 0
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
</Project>
</Workspace>.ToString()
Dim expected = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document><![CDATA[
Imports System
Class Program
Private Shared Function F(x As Integer, y As Short) As Integer
Dim i1 As Integer = 0
Dim s1 As Short = 0
Dim i2 As Integer = 0
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
<Document><![CDATA[
Imports System
Class Program
Private Shared Function F(x As Integer, y As Short) As Integer
Dim i1 As Integer = 0
Dim s1 As Short = 0
Dim i2 As Integer = 0
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<ProjectReference>Assembly1</ProjectReference>
<Document><![CDATA[
Imports System
Class Program
Private Shared Function F(x As Integer, y As Short) As Integer
Dim i1 As Integer = 0
Dim s1 As Short = 0
Dim i2 As Integer = 0
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
</Project>
</Workspace>.ToString()
Await TestInRegularAndScriptAsync(input, expected, options:=PreferIntrinsicPredefinedTypeEverywhere())
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)>
<Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)>
Public Async Function TestFixAllInSolution_SimplifyMemberAccess() As Task
Dim input = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document><![CDATA[
Imports System
Class ProgramA
Dim x As Integer = 0
Dim y As Integer = 0
Dim z As Integer = 0
Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32
Dim i1 As System.Int32 = Me.x
Dim s1 As System.Int16 = Me.y
Dim i2 As System.Int32 = Me.z
{|FixAllInSolution:System.Console.Write|}(i1 + s1 + i2)
System.Console.WriteLine(i1 + s1 + i2)
Dim ex As System.Exception = Nothing
Return i1 + s1 + i2
End Function
End Class
Class ProgramB
Dim x2 As Integer = 0
Dim y2 As Integer = 0
Dim z2 As Integer = 0
Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32
Dim i1 As System.Int32 = Me.x2
Dim s1 As System.Int16 = Me.y2
Dim i2 As System.Int32 = Me.z2
System.Console.Write(i1 + s1 + i2)
System.Console.WriteLine(i1 + s1 + i2)
Dim ex As System.Exception = Nothing
Return i1 + s1 + i2
End Function
End Class
]]>
</Document>
<Document><![CDATA[
Imports System
Class ProgramA2
Dim x As Integer = 0
Dim y As Integer = 0
Dim z As Integer = 0
Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32
Dim i1 As System.Int32 = Me.x
Dim s1 As System.Int16 = Me.y
Dim i2 As System.Int32 = Me.z
System.Console.Write(i1 + s1 + i2)
System.Console.WriteLine(i1 + s1 + i2)
Dim ex As System.Exception = Nothing
Return i1 + s1 + i2
End Function
End Class
Class ProgramB2
Dim x2 As Integer = 0
Dim y2 As Integer = 0
Dim z2 As Integer = 0
Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32
Dim i1 As System.Int32 = Me.x2
Dim s1 As System.Int16 = Me.y2
Dim i2 As System.Int32 = Me.z2
System.Console.Write(i1 + s1 + i2)
System.Console.WriteLine(i1 + s1 + i2)
Dim ex As System.Exception = Nothing
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<ProjectReference>Assembly1</ProjectReference>
<Document><![CDATA[
Imports System
Class ProgramA3
Dim x As Integer = 0
Dim y As Integer = 0
Dim z As Integer = 0
Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32
Dim i1 As System.Int32 = Me.x
Dim s1 As System.Int16 = Me.y
Dim i2 As System.Int32 = Me.z
System.Console.Write(i1 + s1 + i2)
System.Console.WriteLine(i1 + s1 + i2)
Dim ex As System.Exception = Nothing
Return i1 + s1 + i2
End Function
End Class
Class ProgramB3
Dim x2 As Integer = 0
Dim y2 As Integer = 0
Dim z2 As Integer = 0
Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32
Dim i1 As System.Int32 = Me.x2
Dim s1 As System.Int16 = Me.y2
Dim i2 As System.Int32 = Me.z2
System.Console.Write(i1 + s1 + i2)
System.Console.WriteLine(i1 + s1 + i2)
Dim ex As System.Exception = Nothing
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
</Project>
</Workspace>.ToString()
Dim expected = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document><![CDATA[
Imports System
Class ProgramA
Dim x As Integer = 0
Dim y As Integer = 0
Dim z As Integer = 0
Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32
Dim i1 As System.Int32 = Me.x
Dim s1 As System.Int16 = Me.y
Dim i2 As System.Int32 = Me.z
Console.Write(i1 + s1 + i2)
Console.WriteLine(i1 + s1 + i2)
Dim ex As System.Exception = Nothing
Return i1 + s1 + i2
End Function
End Class
Class ProgramB
Dim x2 As Integer = 0
Dim y2 As Integer = 0
Dim z2 As Integer = 0
Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32
Dim i1 As System.Int32 = Me.x2
Dim s1 As System.Int16 = Me.y2
Dim i2 As System.Int32 = Me.z2
Console.Write(i1 + s1 + i2)
Console.WriteLine(i1 + s1 + i2)
Dim ex As System.Exception = Nothing
Return i1 + s1 + i2
End Function
End Class
]]>
</Document>
<Document><![CDATA[
Imports System
Class ProgramA2
Dim x As Integer = 0
Dim y As Integer = 0
Dim z As Integer = 0
Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32
Dim i1 As System.Int32 = Me.x
Dim s1 As System.Int16 = Me.y
Dim i2 As System.Int32 = Me.z
Console.Write(i1 + s1 + i2)
Console.WriteLine(i1 + s1 + i2)
Dim ex As System.Exception = Nothing
Return i1 + s1 + i2
End Function
End Class
Class ProgramB2
Dim x2 As Integer = 0
Dim y2 As Integer = 0
Dim z2 As Integer = 0
Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32
Dim i1 As System.Int32 = Me.x2
Dim s1 As System.Int16 = Me.y2
Dim i2 As System.Int32 = Me.z2
Console.Write(i1 + s1 + i2)
Console.WriteLine(i1 + s1 + i2)
Dim ex As System.Exception = Nothing
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<ProjectReference>Assembly1</ProjectReference>
<Document><![CDATA[
Imports System
Class ProgramA3
Dim x As Integer = 0
Dim y As Integer = 0
Dim z As Integer = 0
Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32
Dim i1 As System.Int32 = Me.x
Dim s1 As System.Int16 = Me.y
Dim i2 As System.Int32 = Me.z
Console.Write(i1 + s1 + i2)
Console.WriteLine(i1 + s1 + i2)
Dim ex As System.Exception = Nothing
Return i1 + s1 + i2
End Function
End Class
Class ProgramB3
Dim x2 As Integer = 0
Dim y2 As Integer = 0
Dim z2 As Integer = 0
Private Function F(p1 As System.Int32, p2 As System.Int16) As System.Int32
Dim i1 As System.Int32 = Me.x2
Dim s1 As System.Int16 = Me.y2
Dim i2 As System.Int32 = Me.z2
Console.Write(i1 + s1 + i2)
Console.WriteLine(i1 + s1 + i2)
Dim ex As System.Exception = Nothing
Return i1 + s1 + i2
End Function
End Class]]>
</Document>
</Project>
</Workspace>.ToString()
Await TestInRegularAndScriptAsync(input, expected)
End Function
End Class
End Namespace
|
diryboy/roslyn
|
src/EditorFeatures/VisualBasicTest/SimplifyTypeNames/SimplifyTypeNamesTests_FixAllTests.vb
|
Visual Basic
|
mit
| 18,771
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
'-----------------------------------------------------------------------------
' Contains the definition of the ExecutableStatementContext. The base class
' for all blocks that contain statements.
'-----------------------------------------------------------------------------
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Friend MustInherit Class ExecutableStatementContext
Inherits DeclarationContext
Friend Sub New(contextKind As SyntaxKind, statement As StatementSyntax, prevContext As BlockContext)
MyBase.New(contextKind, statement, prevContext)
End Sub
Friend NotOverridable Overrides Function Parse() As StatementSyntax
Return Parser.ParseStatementInMethodBody()
End Function
Friend Overrides Function ProcessSyntax(node As VisualBasicSyntaxNode) As BlockContext
If Parser.IsDeclarationStatement(node.Kind) Then
' VS 314714
' When we have specifiers or attributes preceding an invalid method declaration,
' we want an error of ERRID_InvInsideEndsProc reported, so that this file is decompiled
' to no state. This will remove the task list error (no state) added in FindEndProc.
' Without this fix, an invalid identifier error will be reported, and the file will
' not decompile far enough. The task list error will incorrectly stay around.
'
' Note: This bug addresses the requirement that this method (ParseStatementInMethodBody)
' should report ERRID_InvInsideEndsProc in exactly the same cases that FindEndProc
' does
'End the current block and add the block to the context above
'This must end not only the current block but the current method.
Dim declarationContext = FindNearest(Function(s) SyntaxFacts.IsMethodBlock(s) OrElse
s = SyntaxKind.ConstructorBlock OrElse
s = SyntaxKind.OperatorBlock OrElse
SyntaxFacts.IsAccessorBlock(s))
If declarationContext IsNot Nothing Then
Dim context = declarationContext.PrevBlock
RecoverFromMissingEnd(context)
'Let the outer context process this statement
Return context.ProcessSyntax(Parser.ReportSyntaxError(node, ERRID.ERR_InvInsideEndsProc))
Else
' we are in a block in a top-level code:
node = Parser.ReportSyntaxError(node, ERRID.ERR_InvInsideBlock, SyntaxFacts.GetBlockName(BlockKind))
Return MyBase.ProcessSyntax(node)
End If
Else
Select Case node.Kind
Case _
SyntaxKind.InheritsStatement,
SyntaxKind.ImplementsStatement,
SyntaxKind.OptionStatement,
SyntaxKind.ImportsStatement
Dim declarationContext = FindNearest(Function(s) SyntaxFacts.IsMethodBlock(s) OrElse
s = SyntaxKind.ConstructorBlock OrElse
s = SyntaxKind.OperatorBlock OrElse
SyntaxFacts.IsAccessorBlock(s) OrElse
SyntaxFacts.IsMultiLineLambdaExpression(s) OrElse
SyntaxFacts.IsSingleLineLambdaExpression(s))
If declarationContext IsNot Nothing Then
' in a method or multiline lambda expression:
node = Parser.ReportSyntaxError(node, ERRID.ERR_InvInsideProc)
Else
' we are in a block or in top-level code:
node = Parser.ReportSyntaxError(node, ERRID.ERR_InvInsideBlock, SyntaxFacts.GetBlockName(BlockKind))
End If
Add(node)
Return Me
Case Else
Dim newContext = TryProcessExecutableStatement(node)
Return If(newContext, MyBase.ProcessSyntax(node))
End Select
End If
End Function
Friend Overrides Function TryLinkSyntax(node As VisualBasicSyntaxNode, ByRef newContext As BlockContext) As LinkResult
newContext = Nothing
Select Case node.Kind
' these are errors, but ParseStatementInMethodBody accepts them for error recovery
Case _
SyntaxKind.OptionStatement,
SyntaxKind.ImportsStatement,
SyntaxKind.InheritsStatement,
SyntaxKind.ImplementsStatement,
SyntaxKind.NamespaceStatement
Return UseSyntax(node, newContext)
Case _
SyntaxKind.ClassStatement,
SyntaxKind.StructureStatement,
SyntaxKind.ModuleStatement,
SyntaxKind.InterfaceStatement
' Reuse as long as the statement does not have modifiers.
' These statements parse differently when they appear at the top level and when they appear within a method body.
' Within a method body, if the statement begins with a modifier then the statement is parsed as a variable declaration (with an error).
If Not DirectCast(node, TypeStatementSyntax).Modifiers.Any() Then
Return UseSyntax(node, newContext)
Else
newContext = Me
Return LinkResult.NotUsed
End If
Case SyntaxKind.EnumStatement
' Reuse as long as the statement does not have modifiers
' These statements parse differently when they appear at the top level and when they appear within a method body.
' Within a method body, if the statement begins with a modifier then the statement is parsed as a variable declaration (with an error).
If Not DirectCast(node, EnumStatementSyntax).Modifiers.Any() Then
Return UseSyntax(node, newContext)
Else
newContext = Me
Return LinkResult.NotUsed
End If
Case _
SyntaxKind.SubNewStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
' Reuse as long as the statement does not have modifiers
' These statements parse differently when they appear at the top level and when they appear within a method body.
' Within a method body, if the statement begins with a dim/const then the statement is parsed as a variable declaration (with an error).
If Not DirectCast(node, MethodBaseSyntax).Modifiers.Any() Then
Return UseSyntax(node, newContext)
Else
newContext = Me
Return LinkResult.NotUsed
End If
Case _
SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.PropertyStatement,
SyntaxKind.EventStatement
' Reuse as long as the statement does not have dim or const
If Not DirectCast(node, MethodBaseSyntax).Modifiers.Any(SyntaxKind.DimKeyword, SyntaxKind.ConstKeyword) Then
Return UseSyntax(node, newContext)
Else
newContext = Me
Return LinkResult.NotUsed
End If
' these blocks cannot happen in current context so we should crumble them
' on next pass we will give error on the first statement
Case _
SyntaxKind.SubBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.PropertyBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.EventBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock,
SyntaxKind.NamespaceBlock,
SyntaxKind.ClassBlock,
SyntaxKind.StructureBlock,
SyntaxKind.EnumBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.CaseBlock,
SyntaxKind.CaseElseBlock,
SyntaxKind.CatchBlock,
SyntaxKind.FinallyBlock,
SyntaxKind.ElseBlock,
SyntaxKind.ElseIfBlock,
SyntaxKind.SingleLineElseClause,
SyntaxKind.AttributeList,
SyntaxKind.ConstructorBlock,
SyntaxKind.FieldDeclaration
newContext = Me
Return LinkResult.Crumble
Case _
SyntaxKind.SetAccessorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
' Don't reuse a set statement. Set/Get are parsed differently in declarations and executable contexts
newContext = Me
Return LinkResult.NotUsed
Case Else
Return TryLinkStatement(node, newContext)
End Select
End Function
Friend Overrides Function ProcessStatementTerminator(lambdaContext As BlockContext) As BlockContext
Dim kind = Parser.CurrentToken.Kind
Dim singleLine = IsSingleLine
If singleLine Then
Select Case kind
Case SyntaxKind.StatementTerminatorToken, SyntaxKind.EndOfFileToken
' A single-line statement is terminated at the end of the line.
Dim context = EndBlock(Nothing)
Return context.ProcessStatementTerminator(lambdaContext)
End Select
End If
Dim allowLeadingMultiline = False
Select Case kind
Case SyntaxKind.StatementTerminatorToken
allowLeadingMultiline = True
Case SyntaxKind.ColonToken
allowLeadingMultiline = Not IsSingleLine
End Select
If lambdaContext Is Nothing OrElse
Parser.IsNextStatementInsideLambda(Me, lambdaContext, allowLeadingMultiline) Then
' More statements within the block so the statement
' terminator can be consumed.
Parser.ConsumeStatementTerminator(colonAsSeparator:=singleLine)
Return Me
Else
' The following statement is considered outside the enclosing lambda, so the lambda
' should be terminated but the statement terminator should not be consumed
' since it represents the end of a containing expression statement.
Return EndLambda()
End If
End Function
Friend Overrides ReadOnly Property IsSingleLine As Boolean
Get
Return PrevBlock.IsSingleLine
End Get
End Property
End Class
End Namespace
|
AmadeusW/roslyn
|
src/Compilers/VisualBasic/Portable/Parser/BlockContexts/ExecutableStatementContext.vb
|
Visual Basic
|
apache-2.0
| 12,815
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Represents a <see cref="VisualBasicSyntaxVisitor"/> which descends an entire <see cref="SyntaxNode"/> graph and
''' may replace or remove visited SyntaxNodes in depth-first order.
''' </summary>
Partial Public Class VisualBasicSyntaxRewriter
Inherits VisualBasicSyntaxVisitor(Of SyntaxNode)
Private ReadOnly _visitIntoStructuredTrivia As Boolean
Public Sub New(Optional visitIntoStructuredTrivia As Boolean = False)
Me._visitIntoStructuredTrivia = visitIntoStructuredTrivia
End Sub
Public Overridable ReadOnly Property VisitIntoStructuredTrivia As Boolean
Get
Return Me._visitIntoStructuredTrivia
End Get
End Property
Private _recursionDepth As Integer
Public Overrides Function Visit(node As SyntaxNode) As SyntaxNode
If node IsNot Nothing Then
_recursionDepth += 1
StackGuard.EnsureSufficientExecutionStack(_recursionDepth)
Dim result = DirectCast(node, VisualBasicSyntaxNode).Accept(Me)
_recursionDepth -= 1
Return result
Else
Return node
End If
End Function
Public Overridable Function VisitToken(token As SyntaxToken) As SyntaxToken
Dim leading = Me.VisitList(token.LeadingTrivia)
Dim trailing = Me.VisitList(token.TrailingTrivia)
If leading <> token.LeadingTrivia OrElse trailing <> token.TrailingTrivia Then
If leading <> token.LeadingTrivia Then
token = token.WithLeadingTrivia(leading)
End If
If trailing <> token.TrailingTrivia Then
token = token.WithTrailingTrivia(trailing)
End If
End If
Return token
End Function
Public Overridable Function VisitTrivia(trivia As SyntaxTrivia) As SyntaxTrivia
If Me.VisitIntoStructuredTrivia AndAlso trivia.HasStructure Then
Dim [structure] = DirectCast(trivia.GetStructure(), VisualBasicSyntaxNode)
Dim newStructure = DirectCast(Me.Visit([structure]), StructuredTriviaSyntax)
If newStructure IsNot [structure] Then
If newStructure IsNot Nothing Then
Return SyntaxFactory.Trivia(newStructure)
Else
Return Nothing
End If
End If
End If
Return trivia
End Function
Public Overridable Function VisitList(Of TNode As SyntaxNode)(list As SyntaxList(Of TNode)) As SyntaxList(Of TNode)
Dim alternate As SyntaxListBuilder = Nothing
Dim i = 0, n = list.Count
While i < n
Dim item = list(i)
Dim visited = Me.VisitListElement(item)
If item IsNot visited AndAlso alternate Is Nothing Then
alternate = New SyntaxListBuilder(n)
alternate.AddRange(list, 0, i)
End If
If alternate IsNot Nothing AndAlso visited IsNot Nothing AndAlso visited.Kind <> SyntaxKind.None Then
alternate.Add(visited)
End If
i = i + 1
End While
If alternate IsNot Nothing Then
Return alternate.ToList(Of TNode)()
End If
Return list
End Function
Public Overridable Function VisitListElement(Of TNode As SyntaxNode)(node As TNode) As TNode
Return DirectCast(Me.Visit(node), TNode)
End Function
Public Overridable Function VisitList(list As SyntaxTokenList) As SyntaxTokenList
Dim alternate As SyntaxTokenListBuilder = Nothing
Dim i = -1, n = list.Count
For Each item In list
i = i + 1
Dim visited = Me.VisitListElement(item)
If item <> visited AndAlso alternate Is Nothing Then
alternate = New SyntaxTokenListBuilder(n)
alternate.Add(list, 0, i)
End If
If alternate IsNot Nothing AndAlso visited.Kind <> SyntaxKind.None Then ' skip the null check since SyntaxToken is a value type
alternate.Add(visited)
End If
Next
If alternate IsNot Nothing Then
Return alternate.ToList()
End If
Return list
End Function
Public Overridable Function VisitListElement(token As SyntaxToken) As SyntaxToken
Return Me.VisitToken(token)
End Function
Public Overridable Function VisitList(Of TNode As SyntaxNode)(list As SeparatedSyntaxList(Of TNode)) As SeparatedSyntaxList(Of TNode)
Dim count As Integer = list.Count
Dim sepCount As Integer = list.SeparatorCount
Dim alternate As SeparatedSyntaxListBuilder(Of TNode) = Nothing
Dim i As Integer = 0
While i < sepCount
Dim node As TNode = list(i)
Dim visitedNode As TNode = Me.VisitListElement(Of TNode)(node)
Dim separator As SyntaxToken = list.GetSeparator(i)
Dim visitedSeparator As SyntaxToken = Me.VisitListSeparator(separator)
If alternate.IsNull Then
If node IsNot visitedNode OrElse separator <> visitedSeparator Then
alternate = New SeparatedSyntaxListBuilder(Of TNode)(count)
alternate.AddRange(list, i)
End If
End If
If Not alternate.IsNull Then
If visitedNode IsNot Nothing Then
alternate.Add(visitedNode)
If visitedSeparator.RawKind = 0 Then
Throw New InvalidOperationException("separator is expected")
End If
alternate.AddSeparator(visitedSeparator)
Else
If visitedNode Is Nothing Then
Throw New InvalidOperationException("element is expected")
End If
End If
End If
i += 1
End While
If i < count Then
Dim node As TNode = list(i)
Dim visitedNode As TNode = Me.VisitListElement(Of TNode)(node)
If alternate.IsNull Then
If node IsNot visitedNode Then
alternate = New SeparatedSyntaxListBuilder(Of TNode)(count)
alternate.AddRange(list, i)
End If
End If
If Not alternate.IsNull AndAlso visitedNode IsNot Nothing Then
alternate.Add(visitedNode)
End If
End If
If Not alternate.IsNull Then
Return alternate.ToList()
End If
Return list
End Function
Public Overridable Function VisitListSeparator(token As SyntaxToken) As SyntaxToken
Return Me.VisitToken(token)
End Function
Public Overridable Function VisitList(list As SyntaxTriviaList) As SyntaxTriviaList
Dim count = list.Count
If count <> 0 Then
Dim alternate As SyntaxTriviaListBuilder = Nothing
Dim index = -1
For Each item In list
index += 1
Dim visited = Me.VisitListElement(item)
'skip the null check since SyntaxTrivia Is a value type
If visited <> item AndAlso alternate Is Nothing Then
alternate = New SyntaxTriviaListBuilder(count)
alternate.Add(list, 0, index)
End If
If alternate IsNot Nothing AndAlso visited.Kind() <> SyntaxKind.None Then
alternate.Add(visited)
End If
Next
If alternate IsNot Nothing Then
Return alternate.ToList()
End If
End If
Return list
End Function
Public Overridable Function VisitListElement(element As SyntaxTrivia) As SyntaxTrivia
Return Me.VisitTrivia(element)
End Function
End Class
End Namespace
|
MatthieuMEZIL/roslyn
|
src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxRewriter.vb
|
Visual Basic
|
apache-2.0
| 9,054
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports System.Threading
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Extensions
Public Class StatementSyntaxExtensionTests
Private Sub TestStatementDeclarationWithPublicModifier(Of T As StatementSyntax)(node As T)
Dim modifierList = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
Dim newNode = DirectCast(node.WithModifiers(modifierList), T)
Dim actual = newNode.GetModifiers().First().ToString()
Assert.Equal("Public", actual)
End Sub
Private Sub VerifyTokenName(Of T As DeclarationStatementSyntax)(code As String, expectedName As String)
Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of T).First()
Dim actualNameToken = node.GetNameToken()
Assert.Equal(expectedName, actualNameToken.ToString())
End Sub
<Fact>
Public Sub MethodReturnType()
Dim methodDeclaration = SyntaxFactory.FunctionStatement(attributeLists:=Nothing,
modifiers:=Nothing,
identifier:=SyntaxFactory.Identifier("F1"),
typeParameterList:=Nothing,
parameterList:=Nothing,
asClause:=SyntaxFactory.SimpleAsClause(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntegerKeyword))),
handlesClause:=Nothing,
implementsClause:=Nothing)
Assert.True(methodDeclaration.HasReturnType())
Dim result = methodDeclaration.GetReturnType()
Dim returnTypeName = result.ToString()
Assert.Equal("Integer", returnTypeName)
End Sub
<Fact>
Public Sub PropertyReturnType()
Dim propertyDeclaration = SyntaxFactory.PropertyStatement(attributeLists:=Nothing,
modifiers:=Nothing,
identifier:=SyntaxFactory.Identifier("P1"),
parameterList:=Nothing,
asClause:=SyntaxFactory.SimpleAsClause(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ByteKeyword))),
initializer:=Nothing,
implementsClause:=Nothing)
Assert.True(propertyDeclaration.HasReturnType())
Dim result = propertyDeclaration.GetReturnType()
Dim returnTypeName = result.ToString()
Assert.Equal("Byte", returnTypeName)
End Sub
Private Sub TestTypeBlockWithPublicModifier(Of T As TypeBlockSyntax)(code As String)
Dim node = SyntaxFactory.ParseCompilationUnit(code).Members.First()
Dim modifierList = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
Dim newNode = DirectCast(node.WithModifiers(modifierList), T)
Dim actual = newNode.GetModifiers().First().ToString()
Assert.Equal("Public", actual)
End Sub
<Fact>
Public Sub GetClassStatementModifiers()
Dim code = <String>Public Class C</String>.Value
Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of ClassStatementSyntax).First()
Dim actualModifierName = node.Modifiers().First().ToString()
Assert.Equal("Public", actualModifierName)
End Sub
<Fact>
Public Sub GetEnumStatementModifiers()
Dim code = <String>Public Enum E</String>.Value
Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of EnumStatementSyntax).First()
Dim actualModifierName = node.Modifiers().First().ToString()
Assert.Equal("Public", actualModifierName)
End Sub
<Fact>
Public Sub InterfaceBlockWithPublicModifier()
Dim code = <String>Interface I
End Interface</String>.Value
TestTypeBlockWithPublicModifier(Of InterfaceBlockSyntax)(code)
End Sub
<Fact>
Public Sub ModuleBlockWithPublicModifier()
Dim code = <String>Module M
End Module</String>.Value
TestTypeBlockWithPublicModifier(Of ModuleBlockSyntax)(code)
End Sub
<Fact>
Public Sub StructureBlockWithPublicModifier()
Dim code = <string>Structure S
End Structure</string>.Value
TestTypeBlockWithPublicModifier(Of StructureBlockSyntax)(code)
End Sub
<Fact>
Public Sub EnumBlockWithPublicModifier()
Dim code = <String>Enum E
End Enum</String>.Value
Dim node = DirectCast(SyntaxFactory.ParseCompilationUnit(code).Members.First(), EnumBlockSyntax)
TestStatementDeclarationWithPublicModifier(node)
End Sub
<Fact>
Public Sub ClassStatementWithPublicModifier()
Dim node = SyntaxFactory.ClassStatement(SyntaxFactory.Identifier("C"))
TestStatementDeclarationWithPublicModifier(node)
End Sub
<Fact>
Public Sub EnumStatementWithPublicModifier()
Dim node = SyntaxFactory.EnumStatement(SyntaxFactory.Identifier("E"))
TestStatementDeclarationWithPublicModifier(node)
End Sub
<Fact>
Public Sub FieldDeclarationWithPublicModifier()
Dim code = <String>Class C
dim _field as Integer = 1
End Class</String>.Value
Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of FieldDeclarationSyntax).First()
TestStatementDeclarationWithPublicModifier(node)
End Sub
<Fact>
Public Sub EventBlockWithPublicModifier()
Dim code = <String>Custom Event E As EventHandler
End Event</String>.Value
Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of EventBlockSyntax).First()
TestStatementDeclarationWithPublicModifier(node)
End Sub
<Fact>
Public Sub EventStatementWithPublicModifier()
Dim node = SyntaxFactory.EventStatement(SyntaxFactory.Identifier("E"))
TestStatementDeclarationWithPublicModifier(node)
End Sub
<Fact>
Public Sub PropertyBlockWithPublicModifier()
Dim code = <String>Property P as Integer
End Property</String>.Value
Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of PropertyBlockSyntax).First()
TestStatementDeclarationWithPublicModifier(node)
End Sub
<Fact>
Public Sub SubBlockWithPublicModifier()
Dim code = <String>Sub Foo
End Sub</String>.Value
Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of MethodBlockSyntax).First()
TestStatementDeclarationWithPublicModifier(node)
End Sub
<Fact>
Public Sub VerifyClassNameToken()
Dim code = <String>Class C
End Class</String>.Value
VerifyTokenName(Of ClassBlockSyntax)(code, "C")
End Sub
<Fact>
Public Sub VerifyInterfaceNameToken()
Dim code = <String>Interface I
End Interface</String>.Value
VerifyTokenName(Of InterfaceBlockSyntax)(code, "I")
End Sub
<Fact>
Public Sub VerifyStructureNameToken()
Dim code = <String>Structure S
End Structure</String>.Value
VerifyTokenName(Of StructureBlockSyntax)(code, "S")
End Sub
<Fact>
Public Sub VerifyModuleNameToken()
Dim code = <String>Module M
End Module</String>.Value
VerifyTokenName(Of ModuleBlockSyntax)(code, "M")
End Sub
<Fact>
Public Sub VerifyStructureStatementNameToken()
Dim code = <String>Structure SS
</String>.Value
VerifyTokenName(Of StructureStatementSyntax)(code, "SS")
End Sub
<Fact>
Public Sub VerifyConstructorNameTokenIsNothing()
Dim code = <String>Class C
Sub New()
End Class</String>.Value
VerifyTokenName(Of SubNewStatementSyntax)(code, "")
End Sub
<Fact, WorkItem(552823, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552823")>
Public Sub TestIsInStatementBlockOfKindForBrokenCode()
Dim code = <String>End Sub
End Module
End Namespace
d</String>.Value
Dim tree = SyntaxFactory.ParseSyntaxTree(code)
Dim token = tree.GetRoot() _
.DescendantTokens() _
.Where(Function(t) t.Kind = SyntaxKind.NamespaceKeyword) _
.First()
For position = token.SpanStart To token.Span.End
Dim targetToken = tree.GetTargetToken(position, CancellationToken.None)
tree.IsInStatementBlockOfKind(position, targetToken, CancellationToken.None)
Next
End Sub
End Class
End Namespace
|
bbarry/roslyn
|
src/EditorFeatures/VisualBasicTest/Extensions/StatementSyntaxExtensionTests.vb
|
Visual Basic
|
apache-2.0
| 9,772
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings.EncapsulateField
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.EncapsulateField
Public Class EncapsulateFieldTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace) As Object
Return New EncapsulateFieldRefactoringProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Public Sub EncapsulatePrivateFieldAndUpdateReferences()
Dim text = <File>
Class C
Private ReadOnly x[||] As Integer
Public Sub New()
x = 3
End Sub
Sub foo()
Dim z = x
End Sub
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Private ReadOnly x As Integer
Public Sub New()
x = 3
End Sub
Public ReadOnly Property X1 As Integer
Get
Return x
End Get
End Property
Sub foo()
Dim z = X1
End Sub
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False, index:=0)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Public Sub EncapsulateDimField()
Dim text = <File>
Class C
Dim x[||] As Integer
Sub foo()
Dim z = x
End Sub
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Dim x As Integer
Public Property X1 As Integer
Get
Return x
End Get
Set(value As Integer)
x = value
End Set
End Property
Sub foo()
Dim z = X1
End Sub
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Public Sub EncapsulateGenericField()
Dim text = <File>
Class C(Of T)
Dim x[||] As T
Sub foo()
Dim z = x
End Sub
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C(Of T)
Dim x As T
Public Property X1 As T
Get
Return x
End Get
Set(value As T)
x = value
End Set
End Property
Sub foo()
Dim z = X1
End Sub
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Public Sub EncapsulatePublicFieldIgnoringReferences()
Dim text = <File>
Class C
Public [|x|] As Integer
Sub foo()
x = 3
End Sub
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Private _x As Integer
Public Property X As Integer
Get
Return _x
End Get
Set(value As Integer)
_x = value
End Set
End Property
Sub foo()
x = 3
End Sub
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False, index:=1)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Public Sub EncapsulatePublicFieldUpdatingReferences()
Dim text = <File>
Class C
Public [|x|] As Integer
Sub foo()
x = 3
End Sub
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Private _x As Integer
Public Property X As Integer
Get
Return _x
End Get
Set(value As Integer)
_x = value
End Set
End Property
Sub foo()
X = 3
End Sub
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False, index:=0)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Public Sub EncapsulateMultiplePrivateFieldsWithReferences()
Dim text = <File>
Class C
Private [|x, y|] As Integer
Sub foo()
x = 3
y = 4
End Sub
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Private x, y As Integer
Public Property X1 As Integer
Get
Return x
End Get
Set(value As Integer)
x = value
End Set
End Property
Public Property Y1 As Integer
Get
Return y
End Get
Set(value As Integer)
y = value
End Set
End Property
Sub foo()
X1 = 3
Y1 = 4
End Sub
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False, index:=0)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Public Sub EncapsulateMultiplePublicFieldsWithReferences()
Dim text = <File>
Class C
[|Public x As String
Public y As Integer|]
Sub foo()
x = "foo"
y = 4
End Sub
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Private _x As String
Private _y As Integer
Public Property X As String
Get
Return _x
End Get
Set(value As String)
_x = value
End Set
End Property
Public Property Y As Integer
Get
Return _y
End Get
Set(value As Integer)
_y = value
End Set
End Property
Sub foo()
x = "foo"
y = 4
End Sub
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False, index:=1)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Public Sub NoSetterForConstField()
Dim text = <File>
Class Program
Private Const [|foo|] As Integer = 3
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class Program
Private Const foo As Integer = 3
Public Shared ReadOnly Property Foo1 As Integer
Get
Return foo
End Get
End Property
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False, index:=0)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Public Sub EncapsulateEscapedIdentifier()
Dim text = <File>
Class C
Private [|[Class]|] As String
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Private [Class] As String
Public Property Class1 As String
Get
Return [Class]
End Get
Set(value As String)
Me.Class = value
End Set
End Property
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False, index:=0)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Public Sub EncapsulateFieldNamedValue()
Dim text = <File>
Class C
Private [|value|] As Integer = 3
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Private value As Integer = 3
Public Property Value1 As Integer
Get
Return value
End Get
Set(value As Integer)
Me.value = value
End Set
End Property
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False, index:=0)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Public Sub EncapsulateFieldName__()
Dim text = <File>
Class D
Public [|__|] As Integer
End Class
</File>.ConvertTestSourceTag()
Dim expected = <File>
Class D
Private ___ As Integer
Public Property __ As Integer
Get
Return ___
End Get
Set(value As Integer)
___ = value
End Set
End Property
End Class
</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False)
End Sub
<WorkItem(694262)>
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Public Sub PreserveTrivia()
Dim text = <File>
Class AA
Private name As String : Public [|dsds|] As Integer
End Class
</File>.ConvertTestSourceTag()
Dim expected = <File>
Class AA
Private name As String : Private _dsds As Integer
Public Property Dsds As Integer
Get
Return _dsds
End Get
Set(value As Integer)
_dsds = value
End Set
End Property
End Class
</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False)
End Sub
<WorkItem(694241)>
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Public Sub NewPropertyNameIsUnique()
Dim text = <File>
Class AA
Private [|name|] As String
Property Name1 As String
Get
End Get
Set(value As String)
End Set
End Property
End Class
</File>.ConvertTestSourceTag()
Dim expected = <File>
Class AA
Private name As String
Property Name1 As String
Get
End Get
Set(value As String)
End Set
End Property
Public Property Name2 As String
Get
Return name
End Get
Set(value As String)
name = value
End Set
End Property
End Class
</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False)
End Sub
<WorkItem(695046)>
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Public Sub AvailableNotJustOnVariableName()
Dim text = <File>
Class C
Private [||] ReadOnly x As Integer
End Class</File>.ConvertTestSourceTag()
TestActionCount(text, 2)
End Sub
<WorkItem(705898)>
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Public Sub CopyAccessibility()
Dim text = <File>
Class C
Protected [|x|] As Integer
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Private _x As Integer
Protected Property X As Integer
Get
Return _x
End Get
Set(value As Integer)
_x = value
End Set
End Property
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False)
End Sub
<WorkItem(707080)>
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Public Sub BackingFieldStartsWithUnderscore()
Dim text = <File>
Public Class Class1
Public [|Name|] As String
Sub foo()
name = ""
End Sub
End Class
</File>.ConvertTestSourceTag()
Dim expected = <File>
Public Class Class1
Private _name As String
Public Property Name As String
Get
Return _name
End Get
Set(value As String)
_name = value
End Set
End Property
Sub foo()
Name = ""
End Sub
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Public Sub EncapsulateShadowingField()
Dim text = <File>
Class C
Protected _foo As Integer
Public Property Foo As Integer
Get
End Get
Set(value As Integer)
End Set
End Property
End Class
Class D
Inherits C
Protected Shadows [|_foo|] As Integer
End Class</File>.ConvertTestSourceTag()
Dim expected = <File>
Class C
Protected _foo As Integer
Public Property Foo As Integer
Get
End Get
Set(value As Integer)
End Set
End Property
End Class
Class D
Inherits C
Private Shadows _foo As Integer
Protected Property Foo1 As Integer
Get
Return _foo
End Get
Set(value As Integer)
_foo = value
End Set
End Property
End Class</File>.ConvertTestSourceTag()
Test(text, expected, compareTokens:=False)
End Sub
<WorkItem(1096007, "https://github.com/dotnet/roslyn/issues/282")>
<Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)>
Public Sub DoNotEncapsulateOutsideTypeDeclaration()
Dim globalField = <File>
Dim [|x|] = 1
</File>.ConvertTestSourceTag()
TestMissing(globalField)
Dim namespaceField = <File>
Namespace N
Dim [|x|] = 1
End Namespace
</File>.ConvertTestSourceTag()
TestMissing(namespaceField)
Dim enumField = <File>
Enum E
[|x|] = 1
End Enum
</File>.ConvertTestSourceTag()
TestMissing(enumField)
End Sub
End Class
End Namespace
|
droyad/roslyn
|
src/EditorFeatures/VisualBasicTest/CodeActions/EncapsulateField/EncapsulateFieldTests.vb
|
Visual Basic
|
apache-2.0
| 13,103
|
Imports MPD
Partial Class DesktopModules_AgapeConnect_mpdCalc_controls_mpdAdmin
Inherits Entities.Modules.PortalModuleBase
Private _mpdDefId As Integer
Public Property MpdDefId() As Integer
Get
Return _mpdDefId
End Get
Set(ByVal v As Integer)
_mpdDefId = v
hfMpdDefId.Value = v
If v > 0 Then
Dim PS = CType(HttpContext.Current.Items("PortalSettings"), PortalSettings)
Dim d As New MPDDataContext
Dim thisForm = From c In d.AP_mpdCalc_Definitions Where c.PortalId = PS.PortalId And c.mpdDefId = v
If thisForm.Count > 0 Then
Dim ds As New StaffBroker.StaffBrokerDataContext
Dim staffTypes = From c In ds.AP_StaffBroker_StaffTypes Where c.PortalId = PS.PortalId Select c.Name, Value = c.StaffTypeId
cblStaffTypes.Items.Clear()
cblStaffTypes.DataSource = staffTypes
cblStaffTypes.DataTextField = "Name"
cblStaffTypes.DataValueField = "Value"
cblStaffTypes.DataBind()
ddlAccount.DataSource = From c In ds.AP_StaffBroker_AccountCodes Where c.PortalId = PS.PortalId Order By c.AccountCode Select c.AccountCode, Name = c.AccountCode & "-" & c.AccountCodeName
ddlAccount.DataTextField = "Name"
ddlAccount.DataValueField = "AccountCode"
ddlAccount.DataBind()
pnlAccountCode.Visible = Not StaffBrokerFunctions.GetSetting("NonDynamics", PS.PortalId) = "True"
Dim staff = From c In ds.Users Where c.AP_StaffBroker_Staffs.PortalId = PS.PortalId Select c.UserID, Name = c.LastName & ", " & c.FirstName Order By Name
ddlAuthUser.DataSource = staff
ddlAuthUser.DataTextField = "Name"
ddlAuthUser.DataValueField = "UserID"
ddlAuthUser.DataBind()
If Not thisForm.First.AuthUser Is Nothing Then
ddlAuthUser.SelectedValue = thisForm.First.AuthUser
End If
ddlAuthAuthUser.DataSource = staff
ddlAuthAuthUser.DataTextField = "Name"
ddlAuthAuthUser.DataValueField = "UserID"
ddlAuthAuthUser.DataBind()
If Not thisForm.First.AuthAuthUser Is Nothing Then
ddlAuthAuthUser.SelectedValue = thisForm.First.AuthAuthUser
End If
If Not String.IsNullOrEmpty(thisForm.First.StaffTypes) Then
Dim selectedTypes = thisForm.First.StaffTypes.Split(";")
For Each row As ListItem In cblStaffTypes.Items
If selectedTypes.Contains(row.Value) Then
row.Selected = True
End If
Next
End If
tbComplience.Text = thisForm.First.Complience
If Not String.IsNullOrEmpty(thisForm.First.Compensation) Then
If thisForm.First.Compensation.StartsWith("%") Then
tbCompensation.Text = thisForm.First.Compensation.Trim("%")
ddlCompensationType.SelectedValue = "Percentage"
Else
tbCompensation.Text = thisForm.First.Compensation
ddlCompensationType.SelectedValue = "Formula"
End If
End If
If Not String.IsNullOrEmpty(thisForm.First.Assessment) Then
If thisForm.First.Assessment.StartsWith("%") Then
tbAssessment.Text = thisForm.First.Assessment.Trim("%")
ddlAssessmentType.SelectedValue = "Percentage"
Else
tbAssessment.Text = thisForm.First.Assessment
ddlAssessmentType.SelectedValue = "Formula"
End If
End If
tbDataserverURL.Text = StaffBrokerFunctions.GetSetting("DataserverURL", PS.PortalId)
'Dim ds As New StaffBroker.StaffBrokerDataContext
If Not ddlAccount.Items.FindByValue(thisForm.First.DefaultAccount) Is Nothing Then
ddlAccount.SelectedValue = thisForm.First.DefaultAccount
End If
End If
End If
End Set
End Property
Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
Dim FileName As String = System.IO.Path.GetFileNameWithoutExtension(Me.AppRelativeVirtualPath)
If Not (Me.ID Is Nothing) Then
'this will fix it when its placed as a ChildUserControl
Me.LocalResourceFile = Me.LocalResourceFile.Replace(Me.ID, FileName)
Else
' this will fix it when its dynamically loaded using LoadControl method
Me.LocalResourceFile = Me.LocalResourceFile & FileName & ".ascx.resx"
Dim Locale = System.Threading.Thread.CurrentThread.CurrentCulture.Name
Dim AppLocRes As New System.IO.DirectoryInfo(Me.LocalResourceFile.Replace(FileName & ".ascx.resx", ""))
If Locale = PortalSettings.CultureCode Then
'look for portal varient
If AppLocRes.GetFiles(FileName & ".ascx.Portal-" & PortalId & ".resx").Count > 0 Then
Me.LocalResourceFile = Me.LocalResourceFile.Replace("resx", "Portal-" & PortalId & ".resx")
End If
Else
If AppLocRes.GetFiles(FileName & ".ascx." & Locale & ".Portal-" & PortalId & ".resx").Count > 0 Then
'lookFor a CulturePortalVarient
Me.LocalResourceFile = Me.LocalResourceFile.Replace("resx", Locale & ".Portal-" & PortalId & ".resx")
ElseIf AppLocRes.GetFiles(FileName & ".ascx." & Locale & ".resx").Count > 0 Then
'look for a CultureVarient
Me.LocalResourceFile = Me.LocalResourceFile.Replace("resx", Locale & ".resx")
ElseIf AppLocRes.GetFiles(FileName & ".ascx.Portal-" & PortalId & ".resx").Count > 0 Then
'lookFor a PortalVarient
Me.LocalResourceFile = Me.LocalResourceFile.Replace("resx", "Portal-" & PortalId & ".resx")
End If
End If
End If
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Protected Sub btnUpdateConfig_Click(sender As Object, e As EventArgs) Handles btnUpdateConfig.Click
Dim PS = CType(HttpContext.Current.Items("PortalSettings"), PortalSettings)
Dim d As New MPDDataContext()
Dim theForm = From c In d.AP_mpdCalc_Definitions Where c.PortalId = PS.PortalId And c.mpdDefId = hfMpdDefId.Value
If theForm.Count > 0 Then
Dim st = ""
For Each row As ListItem In cblStaffTypes.Items
If row.Selected Then
st &= row.Value & ";"
End If
Next
theForm.First.StaffTypes = st
If ddlAssessmentType.SelectedValue = "Percentage" Then
theForm.First.Assessment = "%" & tbAssessment.Text.Trim("%")
Else
theForm.First.Assessment = tbAssessment.Text
End If
If ddlCompensationType.SelectedValue = "Percentage" Then
theForm.First.Compensation = "%" & tbCompensation.Text.Trim("%")
Else
theForm.First.Compensation = tbCompensation.Text
End If
theForm.First.Complience = tbComplience.Text
theForm.First.ShowComplience = tbComplience.Text.Trim(" ").Length > 0
If Not StaffBrokerFunctions.GetSetting("NonDynamics", PS.PortalId) = "True" Then
theForm.First.DefaultAccount = ddlAccount.SelectedValue
End If
theForm.First.AuthUser = ddlAuthUser.SelectedValue
theForm.First.AuthAuthUser = ddlAuthAuthUser.SelectedValue
d.SubmitChanges()
TrimDataserverString()
StaffBrokerFunctions.SetSetting("DataserverURL", tbDataserverURL.Text, PS.PortalId)
Response.Redirect(Request.Url.ToString())
End If
End Sub
Private Sub TrimDataserverString()
tbDataserverURL.Text = tbDataserverURL.Text.ToLower()
If Not tbDataserverURL.Text.StartsWith("http") Then
tbDataserverURL.Text = "https://" & tbDataserverURL.Text
End If
Dim r = tbDataserverURL.Text.IndexOf("dataserver/")
If r > 0 Then
r += 11
Dim o = tbDataserverURL.Text.Substring(r).IndexOf("/")
If o > 0 Then
tbDataserverURL.Text = tbDataserverURL.Text.Substring(0, r + o + 1)
End If
End If
End Sub
Protected Sub btnTestDataserver_Click(sender As Object, e As EventArgs) Handles btnTestDataserver.Click
TrimDataserverString()
Dim resp = tntWebUsers.TestDataserverConnection(tbDataserverURL.Text)
imgOK.Visible = False
imgWarning.Visible = False
pnlWarning.Visible = False
If resp.connectionSuccess And resp.hasTrustedUser Then
imgOK.Visible = True
Else
imgWarning.Visible = True
pnlWarning.Visible = True
If resp.connectionSuccess Then
lblWarning.Text = "The URL appears to be correct. However the trusted user, allowing this site to access your dataserver, has not been setup. You will need to setup ""trusteduser@agapeconnect.me"" in tntDataserver. For help, please contact ThadHoskins@agapeeurope.org. "
Else
lblWarning.Text = resp.ErrorMessage
End If
End If
End Sub
End Class
|
GlobalTechnology/OpsInABox
|
DesktopModules/AgapeConnect/mpdCalc/controls/mpdAdmin.ascx.vb
|
Visual Basic
|
mit
| 10,134
|
Imports System.Web.Optimization
Public Class Global_asax
Inherits HttpApplication
Sub Application_Start(sender As Object, e As EventArgs)
' Fires when the application is started
RouteConfig.RegisterRoutes(RouteTable.Routes)
End Sub
End Class
|
maria-shahid-aspose/Aspose.Cells-for-.NET
|
Examples.GridWeb/VisualBasic/Global.asax.vb
|
Visual Basic
|
mit
| 280
|
Public Class Horario
Public Property IdHorario As System.Nullable(Of Int32)
Public Property ciclo As String
Public Property Descripcion As String
Public Property IdJornadaDeTrabajo As System.Nullable(Of Int32)
Public Property DiaIniDescanso As System.Nullable(Of Int32)
Public Property TipoTurno As String
Public Property ListaTurnosRegulares As List(Of TurnosRegulares)
Private Property DescTurnos As String = ""
Public ReadOnly Property DescripcionCompleta As String
Get
For Each turno As TurnosRegulares In ListaTurnosRegulares
DescTurnos = DescTurnos & turno.HoraInicio & "-" & turno.HoraFin
Next
Return Descripcion & " - " & DescTurnos
End Get
End Property
Public ReadOnly Property ClavesPrimarias As String
Get
Return IdHorario & "/" & IdJornadaDeTrabajo
End Get
End Property
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.BussinessEntities/Horario.vb
|
Visual Basic
|
mit
| 943
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'<summary>
' A strongly-typed resource class, for looking up localized strings, etc.
'</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'<summary>
' Returns the cached ResourceManager instance used by this class.
'</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("_01.TreeView.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'<summary>
' Overrides the current thread's CurrentUICulture property for all
' resource lookups using this strongly typed resource class.
'</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set(ByVal value As Global.System.Globalization.CultureInfo)
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
VanyaD/CSS
|
CSSLayoutHomework/01. TreeView/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,701
|
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("DTIMapControlTester")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("DTIMapControlTester")>
<Assembly: AssemblyCopyright("Copyright © 2009")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("334e9cee-0d47-4d70-924b-b5098a3432cb")>
' 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")>
|
Micmaz/DTIControls
|
DTIMapControl/DTIMapControlTester/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,155
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Text
Imports System.Windows
Imports Microsoft.CodeAnalysis.Editor.CommandHandlers
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.VisualStudio.InteractiveWindow
Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands
Imports Microsoft.VisualStudio.Text.Operations
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.InteractivePaste
<[UseExportProvider]>
Public Class InteractivePasteCommandhandlerTests
Const ClipboardLineBasedCutCopyTag As String = "VisualStudioEditorOperationsLineCutCopyClipboardTag"
Const BoxSelectionCutCopyTag As String = "MSDEVColumnSelect"
Private Function CreateCommandHandler(workspace As TestWorkspace) As InteractivePasteCommandHandler
Dim handler = New InteractivePasteCommandHandler(workspace.GetService(Of IEditorOperationsFactoryService),
workspace.GetService(Of ITextUndoHistoryRegistry))
handler.RoslynClipboard = New MockClipboard()
Return handler
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Interactive)>
Public Sub PasteCommandWithInteractiveFormat()
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document/>
</Project>
</Workspace>)
Dim textView = workspace.Documents.Single().GetTextView()
Dim handler = CreateCommandHandler(workspace)
Dim clipboard = DirectCast(handler.RoslynClipboard, MockClipboard)
Dim json = "
[
{""content"":""a\u000d\u000abc"",""kind"":1},
{""content"":""> "",""kind"":0},
{""content"":""< "",""kind"":0},
{""content"":""12"",""kind"":2},
{""content"":""3"",""kind"":3},
]"
Dim text = $"a{vbCrLf}bc123"
CopyToClipboard(clipboard, text, json, includeRepl:=True, isLineCopy:=False, isBoxCopy:=False)
Assert.True(handler.ExecuteCommand(New PasteCommandArgs(textView, textView.TextBuffer), TestCommandExecutionContext.Create()))
Assert.Equal("a" & vbCrLf & "bc123", textView.TextBuffer.CurrentSnapshot.GetText())
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Interactive)>
Public Sub PasteCommandWithOutInteractiveFormat()
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document/>
</Project>
</Workspace>)
Dim textView = workspace.Documents.Single().GetTextView()
Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(textView)
Dim handler = CreateCommandHandler(workspace)
Dim clipboard = DirectCast(handler.RoslynClipboard, MockClipboard)
Dim json = "
[
{""content"":""a\u000d\u000abc"",""kind"":1},
{""content"":""> "",""kind"":0},
{""content"":""< "",""kind"":0},
{""content"":""12"",""kind"":2},
{""content"":""3"",""kind"":3}]
]"
Dim text = $"a{vbCrLf}bc123"
CopyToClipboard(clipboard, text, json, includeRepl:=False, isLineCopy:=False, isBoxCopy:=False)
If Not handler.ExecuteCommand(New PasteCommandArgs(textView, textView.TextBuffer), TestCommandExecutionContext.Create()) Then
editorOperations.InsertText("p")
End If
Assert.Equal("p", textView.TextBuffer.CurrentSnapshot.GetText())
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Interactive)>
Public Sub PasteCommandWithInteractiveFormatAsLineCopy()
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document/>
</Project>
</Workspace>)
Dim textView = workspace.Documents.Single().GetTextView()
Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(textView)
editorOperations.InsertText("line1")
editorOperations.InsertNewLine()
editorOperations.InsertText("line2")
Assert.Equal("line1" & vbCrLf & " line2", textView.TextBuffer.CurrentSnapshot.GetText())
Dim handler = CreateCommandHandler(workspace)
Dim clipboard = DirectCast(handler.RoslynClipboard, MockClipboard)
Dim json = "
[
{""content"":""> "",""kind"":0},
{""content"":""InsertedLine"",""kind"":2},
{""content"":""\u000d\u000a"",""kind"":4}]
]"
Dim text = $"InsertedLine{vbCrLf}"
CopyToClipboard(clipboard, text, json, includeRepl:=True, isLineCopy:=True, isBoxCopy:=False)
Assert.True(handler.ExecuteCommand(New PasteCommandArgs(textView, textView.TextBuffer), TestCommandExecutionContext.Create()))
Assert.Equal("line1" & vbCrLf & "InsertedLine" & vbCrLf & " line2", textView.TextBuffer.CurrentSnapshot.GetText())
End Using
End Sub
<WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/24749")>
<Trait(Traits.Feature, Traits.Features.Interactive)>
Public Sub PasteCommandWithInteractiveFormatAsBoxCopy()
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document/>
</Project>
</Workspace>)
Dim textView = workspace.Documents.Single().GetTextView()
Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(textView)
editorOperations.InsertText("line1")
editorOperations.InsertNewLine()
editorOperations.InsertText("line2")
editorOperations.MoveLineUp(False)
editorOperations.MoveToPreviousCharacter(False)
Assert.Equal("line1" & vbCrLf & " line2", textView.TextBuffer.CurrentSnapshot.GetText())
Dim handler = CreateCommandHandler(workspace)
Dim clipboard = DirectCast(handler.RoslynClipboard, MockClipboard)
Dim json = "
[
{""content"":""> "",""kind"":0},
{""content"":""BoxLine1"",""kind"":2},
{""content"":""\u000d\u000a"",""kind"":4},
{""content"":""> "",""kind"":0},
{""content"":""BoxLine2"",""kind"":2},
{""content"":""\u000d\u000a"",""kind"":4}]
]"
Dim text = $"BoxLine1{vbCrLf}BoxLine2{vbCrLf}"
CopyToClipboard(clipboard, text, json, includeRepl:=True, isLineCopy:=False, isBoxCopy:=True)
Assert.True(handler.ExecuteCommand(New PasteCommandArgs(textView, textView.TextBuffer), TestCommandExecutionContext.Create()))
Assert.Equal("lineBoxLine11" & vbCrLf & " BoxLine2line2", textView.TextBuffer.CurrentSnapshot.GetText())
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Interactive)>
Public Sub PasteCommandWithInteractiveFormatAsBoxCopyOnBlankLine()
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document/>
</Project>
</Workspace>)
Dim textView = workspace.Documents.Single().GetTextView()
Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(textView)
editorOperations.InsertNewLine()
editorOperations.InsertText("line1")
editorOperations.InsertNewLine()
editorOperations.InsertText("line2")
editorOperations.MoveLineUp(False)
editorOperations.MoveLineUp(False)
Assert.Equal(vbCrLf & "line1" & vbCrLf & " line2", textView.TextBuffer.CurrentSnapshot.GetText())
Dim handler = CreateCommandHandler(workspace)
Dim clipboard = DirectCast(handler.RoslynClipboard, MockClipboard)
Dim json = "
[
{""content"":""> "",""kind"":0},
{""content"":""BoxLine1"",""kind"":2},
{""content"":""\u000d\u000a"",""kind"":4},
{""content"":""> "",""kind"":0},
{""content"":""BoxLine2"",""kind"":2},
{""content"":""\u000d\u000a"",""kind"":4}
]"
Dim text = $"> BoxLine1{vbCrLf}> BoxLine2{vbCrLf}"
CopyToClipboard(clipboard, text, json, includeRepl:=True, isLineCopy:=False, isBoxCopy:=True)
Assert.True(handler.ExecuteCommand(New PasteCommandArgs(textView, textView.TextBuffer), TestCommandExecutionContext.Create()))
Assert.Equal("BoxLine1" & vbCrLf & "BoxLine2" & vbCrLf & "line1" & vbCrLf & " line2", textView.TextBuffer.CurrentSnapshot.GetText())
End Using
End Sub
Private Sub CopyToClipboard(clipboard As MockClipboard, text As String, json As String, includeRepl As Boolean, isLineCopy As Boolean, isBoxCopy As Boolean)
clipboard.Clear()
Dim data = New DataObject()
Dim builder = New StringBuilder()
data.SetData(DataFormats.UnicodeText, text)
data.SetData(DataFormats.StringFormat, text)
If includeRepl Then
data.SetData(InteractiveClipboardFormat.Tag, json)
End If
If isLineCopy Then
data.SetData(ClipboardLineBasedCutCopyTag, True)
End If
If isBoxCopy Then
data.SetData(BoxSelectionCutCopyTag, True)
End If
clipboard.SetDataObject(data)
End Sub
Private Class MockClipboard
Implements InteractivePasteCommandHandler.IRoslynClipboard
Private _data As DataObject
Friend Sub Clear()
_data = Nothing
End Sub
Friend Sub SetDataObject(data As Object)
_data = DirectCast(data, DataObject)
End Sub
Public Function ContainsData(format As String) As Boolean Implements InteractivePasteCommandHandler.IRoslynClipboard.ContainsData
Return _data IsNot Nothing And _data.GetData(format) IsNot Nothing
End Function
Public Function GetData(format As String) As Object Implements InteractivePasteCommandHandler.IRoslynClipboard.GetData
If _data Is Nothing Then
Return Nothing
Else
Return _data.GetData(format)
End If
End Function
Public Function GetDataObject() As IDataObject Implements InteractivePasteCommandHandler.IRoslynClipboard.GetDataObject
Return _data
End Function
End Class
End Class
End Namespace
|
davkean/roslyn
|
src/EditorFeatures/Test2/InteractivePaste/InteractivePasteCommandHandlerTests.vb
|
Visual Basic
|
apache-2.0
| 11,958
|
Public Class frmStandard
Private Function Answers()
Dim Ans As Double
If txtOperator.Text = "+" Then
Ans = CDbl(txtPreAns.Text) + CDbl(lblAnswer.Text)
txtAns.Text = Ans
lblAnswer.Text = txtAns.Text
Else
If txtOperator.Text = "*" Then
Ans = CDbl(txtPreAns.Text) * CDbl(lblAnswer.Text)
txtAns.Text = Ans
lblAnswer.Text = txtAns.Text
Else
If txtOperator.Text = "-" Then
Ans = CDbl(txtPreAns.Text) - CDbl(lblAnswer.Text)
txtAns.Text = Ans
lblAnswer.Text = txtAns.Text
Else
If txtOperator.Text = "/" Then
Ans = CDbl(txtPreAns.Text) / CDbl(lblAnswer.Text)
txtAns.Text = Ans
lblAnswer.Text = txtAns.Text
End If
End If
End If
End If
End Function
Private Sub cboMode_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboMode.SelectedIndexChanged
End Sub
Private Sub cmdSeven_Click(sender As Object, e As EventArgs) Handles cmdSeven.Click
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "s" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "y" Then
lblAnswer.Text = "7"
lblScreen.Text = "7"
Else
If Microsoft.VisualBasic.Left(lblAnswer.Text, 1) = "-" And Len(lblAnswer.Text) < 2 Then
lblAnswer.Text = lblAnswer.Text & "7"
lblScreen.Text = lblScreen.Text & "7"
Else
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "+" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "-" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "/" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "*" Then
lblAnswer.Text = "7"
lblScreen.Text = lblScreen.Text & "7"
Else
lblAnswer.Text = lblAnswer.Text & "7"
lblScreen.Text = lblScreen.Text & "7"
End If
End If
End If
End Sub
Private Sub cmdEight_Click(sender As Object, e As EventArgs) Handles cmdEight.Click
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "s" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "y" Then
lblAnswer.Text = "8"
lblScreen.Text = "8"
Else
If Microsoft.VisualBasic.Left(lblAnswer.Text, 1) = "-" And Len(lblAnswer.Text) < 2 Then
lblAnswer.Text = lblAnswer.Text & "8"
lblScreen.Text = lblScreen.Text & "8"
Else
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "+" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "-" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "/" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "*" Then
lblAnswer.Text = "8"
lblScreen.Text = lblScreen.Text & "8"
Else
lblAnswer.Text = lblAnswer.Text & "8"
lblScreen.Text = lblScreen.Text & "8"
End If
End If
End If
End Sub
Private Sub cmdNine_Click(sender As Object, e As EventArgs) Handles cmdNine.Click
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "s" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "y" Then
lblAnswer.Text = "9"
lblScreen.Text = "9"
Else
If Microsoft.VisualBasic.Left(lblAnswer.Text, 1) = "-" And Len(lblAnswer.Text) < 2 Then
lblAnswer.Text = lblAnswer.Text & "9"
lblScreen.Text = lblScreen.Text & "9"
Else
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "+" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "-" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "/" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "*" Then
lblAnswer.Text = "9"
lblScreen.Text = lblScreen.Text & "9"
Else
lblAnswer.Text = lblAnswer.Text & "9"
lblScreen.Text = lblScreen.Text & "9"
End If
End If
End If
End Sub
Private Sub cmdFour_Click(sender As Object, e As EventArgs) Handles cmdFour.Click
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "s" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "y" Then
lblAnswer.Text = "4"
lblScreen.Text = "4"
Else
If Microsoft.VisualBasic.Left(lblAnswer.Text, 1) = "-" And Len(lblAnswer.Text) < 2 Then
lblAnswer.Text = lblAnswer.Text & "4"
lblScreen.Text = lblScreen.Text & "4"
Else
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "+" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "-" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "/" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "*" Then
lblAnswer.Text = "4"
lblScreen.Text = lblScreen.Text & "4"
Else
lblAnswer.Text = lblAnswer.Text & "4"
lblScreen.Text = lblScreen.Text & "4"
End If
End If
End If
End Sub
Private Sub cmdFive_Click(sender As Object, e As EventArgs) Handles cmdFive.Click
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "s" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "y" Then
lblAnswer.Text = "5"
lblScreen.Text = "5"
Else
If Microsoft.VisualBasic.Left(lblAnswer.Text, 1) = "-" And Len(lblAnswer.Text) < 2 Then
lblAnswer.Text = lblAnswer.Text & "5"
lblScreen.Text = lblScreen.Text & "5"
Else
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "+" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "-" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "/" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "*" Then
lblAnswer.Text = "5"
lblScreen.Text = lblScreen.Text & "5"
Else
lblAnswer.Text = lblAnswer.Text & "5"
lblScreen.Text = lblScreen.Text & "5"
End If
End If
End If
End Sub
Private Sub cmdSix_Click(sender As Object, e As EventArgs) Handles cmdSix.Click
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "s" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "y" Then
lblAnswer.Text = "6"
lblScreen.Text = "6"
Else
If Microsoft.VisualBasic.Left(lblAnswer.Text, 1) = "-" And Len(lblAnswer.Text) < 2 Then
lblAnswer.Text = lblAnswer.Text & "6"
lblScreen.Text = lblScreen.Text & "6"
Else
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "+" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "-" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "/" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "*" Then
lblAnswer.Text = "6"
lblScreen.Text = lblScreen.Text & "6"
Else
lblAnswer.Text = lblAnswer.Text & "6"
lblScreen.Text = lblScreen.Text & "6"
End If
End If
End If
End Sub
Private Sub cmdOne_Click(sender As Object, e As EventArgs) Handles cmdOne.Click
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "s" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "y" Then
lblAnswer.Text = "1"
lblScreen.Text = "1"
Else
If Microsoft.VisualBasic.Left(lblAnswer.Text, 1) = "-" And Len(lblAnswer.Text) < 2 Then
lblAnswer.Text = lblAnswer.Text & "1"
lblScreen.Text = lblScreen.Text & "1"
Else
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "+" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "-" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "/" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "*" Then
lblAnswer.Text = "1"
lblScreen.Text = lblScreen.Text & "1"
Else
lblAnswer.Text = lblAnswer.Text & "1"
lblScreen.Text = lblScreen.Text & "1"
End If
End If
End If
End Sub
Private Sub cmdTwo_Click(sender As Object, e As EventArgs) Handles cmdTwo.Click
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "s" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "y" Then
lblAnswer.Text = "2"
lblScreen.Text = "2"
Else
If Microsoft.VisualBasic.Left(lblAnswer.Text, 1) = "-" And Len(lblAnswer.Text) < 2 Then
lblAnswer.Text = lblAnswer.Text & "2"
lblScreen.Text = lblScreen.Text & "2"
Else
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "+" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "-" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "/" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "*" Then
lblAnswer.Text = "2"
lblScreen.Text = lblScreen.Text & "2"
Else
lblAnswer.Text = lblAnswer.Text & "2"
lblScreen.Text = lblScreen.Text & "2"
End If
End If
End If
End Sub
Private Sub cmdThree_Click(sender As Object, e As EventArgs) Handles cmdThree.Click
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "s" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "y" Then
lblAnswer.Text = "3"
lblScreen.Text = "3"
Else
If Microsoft.VisualBasic.Left(lblAnswer.Text, 1) = "-" And Len(lblAnswer.Text) < 2 Then
lblAnswer.Text = lblAnswer.Text & "3"
lblScreen.Text = lblScreen.Text & "3"
Else
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "+" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "-" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "/" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "*" Then
lblAnswer.Text = "3"
lblScreen.Text = lblScreen.Text & "3"
Else
lblAnswer.Text = lblAnswer.Text & "3"
lblScreen.Text = lblScreen.Text & "3"
End If
End If
End If
End Sub
Private Sub cmdZero_Click(sender As Object, e As EventArgs) Handles cmdZero.Click
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "s" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "y" Then
lblAnswer.Text = "0"
lblScreen.Text = "0"
Else
If Microsoft.VisualBasic.Left(lblAnswer.Text, 1) = "-" And Len(lblAnswer.Text) < 2 Then
lblAnswer.Text = lblAnswer.Text & "0"
lblScreen.Text = lblScreen.Text & "0"
Else
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "+" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "-" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "/" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "*" Then
lblAnswer.Text = "0"
lblScreen.Text = lblScreen.Text & "0"
Else
lblAnswer.Text = lblAnswer.Text & "0"
lblScreen.Text = lblScreen.Text & "0"
End If
End If
End If
End Sub
Private Sub cmdDecimal_Click(sender As Object, e As EventArgs) Handles cmdDecimal.Click
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "s" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "y" Then
lblAnswer.Text = "."
lblScreen.Text = "."
Else
If Microsoft.VisualBasic.Left(lblAnswer.Text, 1) = "-" And Len(lblAnswer.Text) < 2 Then
lblAnswer.Text = lblAnswer.Text & "."
lblScreen.Text = lblScreen.Text & "."
Else
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "+" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "-" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "/" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "*" Then
lblAnswer.Text = "."
lblScreen.Text = lblScreen.Text & "."
Else
lblAnswer.Text = lblAnswer.Text & "."
lblScreen.Text = lblScreen.Text & "."
End If
End If
End If
End Sub
Private Sub cmdDivide_Click(sender As Object, e As EventArgs) Handles cmdDivide.Click
Dim PreAns As Double
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Then
lblScreen.Text = "Ans"
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
Else
If InStr(1, lblScreen.Text, "+") > 0 Or InStr(1, lblScreen.Text, "-") Or InStr(1, lblScreen.Text, "*") Or InStr(1, lblScreen.Text, "/") Then
Call Answers()
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
Else
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
End If
End If
lblScreen.Text = lblScreen.Text & "/"
txtOperator.Text = "/"
End Sub
Private Sub cmdMultiply_Click(sender As Object, e As EventArgs) Handles cmdMultiply.Click
Dim PreAns As Double
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Then
lblScreen.Text = "Ans"
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
Else
If InStr(1, lblScreen.Text, "+") > 0 Or InStr(1, lblScreen.Text, "-") Or InStr(1, lblScreen.Text, "*") Or InStr(1, lblScreen.Text, "/") Then
Call Answers()
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
Else
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
End If
End If
lblScreen.Text = lblScreen.Text & "*"
txtOperator.Text = "*"
End Sub
Private Sub CmdMinus_Click(sender As Object, e As EventArgs) Handles CmdMinus.Click
Dim PreAns As Double
If lblScreen.Text = "" And lblAnswer.Text = "" Then
lblAnswer.Text = "-"
Else
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "/" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "+" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "*" Then
lblAnswer.Text = "-"
Else
If Microsoft.VisualBasic.Left(lblScreen.Text, 1) = "-" And Len(lblScreen.Text) < 2 Then
lblAnswer.Text = "-"
Else
If Microsoft.VisualBasic.Left(lblScreen.Text, 2) = "-" And Len(lblScreen.Text) < 2 Then
lblAnswer.Text = ""
Else
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Then
lblScreen.Text = "Ans"
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
Else
If InStr(1, lblScreen.Text, "+") > 0 Or InStr(1, lblScreen.Text, "-") > 0 Or InStr(1, lblScreen.Text, "*") > 0 Or InStr(1, lblScreen.Text, "/") > 0 Then
Call Answers()
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
Else
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
End If
End If
End If
End If
End If
End If
lblScreen.Text = lblScreen.Text & "-"
If Microsoft.VisualBasic.Left(lblAnswer.Text, 1) = "-" Then
lblAnswer.Text = lblAnswer.Text
Else
txtOperator.Text = "-"
End If
End Sub
Private Sub cmdAdd_Click(sender As Object, e As EventArgs) Handles cmdAdd.Click
Dim PreAns As Double
If Microsoft.VisualBasic.Right(lblScreen.text, 1) = "=" Then
lblScreen.text = "Ans"
PreAns = CDbl(lblanswer.text)
txtPreAns.Text = PreAns
Else
If InStr(1, lblScreen.text, "+") > 0 Or InStr(1, lblScreen.text, "-") Or InStr(1, lblScreen.text, "*") Or InStr(1, lblScreen.text, "/") Then
Call Answers()
PreAns = CDbl(lblanswer.text)
txtPreAns.Text = PreAns
Else
PreAns = CDbl(lblanswer.text)
txtPreAns.Text = PreAns
End If
End If
lblScreen.text = lblScreen.text & "+"
txtOperator.Text = "+"
End Sub
Private Sub cmdAnswer_Click(sender As Object, e As EventArgs) Handles cmdAnswer.Click
If lblAnswer.Text = "" Then
MsgBox("Please type in a number first")
lblScreen.Text = "Ans"
lblAnswer.Text = txtAns.Text
Else
txtAns.Text = CDbl(lblAnswer.Text)
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or lblScreen.Text = "Ans" Then
txtAns.Text = CDbl(lblAnswer.Text)
lblAnswer.Text = txtAns.Text
Else
If InStr(1, lblScreen.Text, "+") > 0 Or InStr(1, lblScreen.Text, "-") Or InStr(1, lblScreen.Text, "*") Or InStr(1, lblScreen.Text, "/") Then
Dim Ans As Double
If txtOperator.Text = "+" Then
Ans = CDbl(txtPreAns.Text) + CDbl(lblAnswer.Text)
txtAns.Text = Ans
lblAnswer.Text = txtAns.Text
Else
If txtOperator.Text = "-" Then
Ans = CDbl(txtPreAns.Text) - CDbl(lblAnswer.Text)
txtAns.Text = Ans
lblAnswer.Text = txtAns.Text
Else
If txtOperator.Text = "*" Then
Ans = CDbl(txtPreAns.Text) * CDbl(lblAnswer.Text)
txtAns.Text = Ans
lblAnswer.Text = txtAns.Text
Else
If txtOperator.Text = "/" Then
Ans = CDbl(txtPreAns.Text) / CDbl(lblAnswer.Text)
txtAns.Text = Ans
lblAnswer.Text = txtAns.Text
Else
txtAns.Text = CDbl(lblAnswer.Text)
lblAnswer.Text = txtAns.Text
End If
End If
End If
End If
End If
End If
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Then
lblScreen.Text = lblScreen.Text & ""
Else
Dim OneKey As String
OneKey = lblScreen.Text
lblScreen.Text = OneKey & "="
End If
End If
End Sub
Private Sub cmdAns_Click(sender As Object, e As EventArgs) Handles cmdAns.Click
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Then
lblAnswer.Text = CDbl(txtAns.Text)
lblScreen.Text = "Ans"
Else
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "+" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "-" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "/" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "*" Then
lblAnswer.Text = CDbl(txtAns.Text)
lblScreen.Text = lblScreen.Text & "Ans"
Else
lblScreen.Text = "Ans"
lblAnswer.Text = CDbl(txtAns.Text)
End If
End If
End Sub
Private Sub cmdMemoryPlus_Click(sender As Object, e As EventArgs) Handles cmdMemoryPlus.Click
If lblAnswer.Text = "" Then
MsgBox("Please type in a number first")
lblScreen.Text = "Ans"
lblAnswer.Text = txtAns.Text
Else
Dim PreAns As Double
Dim Memory As Double
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or lblScreen.Text = "Ans" Then
PreAns = CDbl(lblAnswer.Text)
Memory = CDbl(txtMemory.Text)
txtMemory.Text = PreAns + Memory
Else
If InStr(1, lblScreen.Text, "+") > 0 Or InStr(1, lblScreen.Text, "-") Or InStr(1, lblScreen.Text, "*") Or InStr(1, lblScreen.Text, "/") Then
Call Answers()
PreAns = CDbl(lblAnswer.Text)
Memory = CDbl(txtMemory.Text)
txtMemory.Text = PreAns + Memory
Else
PreAns = CDbl(lblAnswer.Text)
Memory = CDbl(txtMemory.Text)
txtMemory.Text = PreAns + Memory
End If
End If
If txtMemory.Text = "0" Then
lblMemory.Visible = False
Else
lblMemory.Visible = True
End If
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Then
lblScreen.Text = lblScreen.Text & ""
Else
lblScreen.Text = lblScreen.Text & "="
End If
End If
End Sub
Private Sub cmdMemoryRecall_Click(sender As Object, e As EventArgs) Handles cmdMemoryRecall.Click
Dim OneKey As String
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Then
lblAnswer.Text = CDbl(txtMemory.Text)
lblScreen.Text = "Memory"
Else
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "+" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "-" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "/" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "*" Then
lblAnswer.Text = CDbl(txtMemory.Text)
lblScreen.Text = lblScreen.Text & "Memory"
Else
OneKey = lblScreen.Text
lblScreen.Text = OneKey & ""
lblAnswer.Text = lblAnswer.Text & ""
End If
End If
txtAns.Text = lblAnswer.Text
End Sub
Private Sub cmdSqrt_Click(sender As Object, e As EventArgs) Handles cmdSqrt.Click
If lblAnswer.Text = "" Then
MsgBox("Please type in a number first")
lblScreen.Text = "Ans"
lblAnswer.Text = txtAns.Text
Else
Dim Multiply As Double
Dim PreAns As Double
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or lblScreen.Text = "Ans" Then
lblScreen.Text = "Ans"
If Microsoft.VisualBasic.Left(lblAnswer.Text, 1) = "-" Then
Console.WriteLine("Cannot find the square root of negative numbers")
MsgBox("Cannot find the square root of negative numbers")
Else
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
lblScreen.Text = "sqrt(" & lblAnswer.Text & ")="
Multiply = Math.Sqrt(CDbl(lblAnswer.Text))
txtAns.Text = Multiply
lblAnswer.Text = txtAns.Text
End If
Else
Call Answers()
If Microsoft.VisualBasic.Left(lblAnswer.Text, 1) = "-" Then
lblScreen.Text = "Ans"
MsgBox("Cannot find the square root of negative numbers")
Else
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
lblScreen.Text = "sqrt(" & lblAnswer.Text & ")="
Multiply = Math.Sqrt(CDbl(lblAnswer.Text))
txtAns.Text = Multiply
lblAnswer.Text = txtAns.Text
End If
End If
End If
End Sub
Private Sub cmdPi_Click(sender As Object, e As EventArgs) Handles cmdPi.Click
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Then
lblAnswer.Text = CDbl(4 * Math.Atan(1))
lblScreen.Text = "π"
Else
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "+" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "-" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "/" Or Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "*" Then
lblAnswer.Text = CDbl(4 * Math.Atan(1))
lblScreen.Text = lblScreen.Text & "π"
Else
lblScreen.Text = "π"
lblAnswer.Text = CDbl(4 * Math.Atan(1))
End If
End If
End Sub
Private Sub cmdLogBase10_Click(sender As Object, e As EventArgs) Handles cmdLogBase10.Click
If lblAnswer.Text = "" Then
MsgBox("Please type in a number first")
lblScreen.Text = "Ans"
lblAnswer.Text = txtAns.Text
Else
Dim Multiply As Double
Dim PreAns As Double
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or lblScreen.Text = "Ans" Then
lblScreen.Text = "Ans"
If Microsoft.VisualBasic.Left(lblAnswer.Text, 1) = "-" Then
MsgBox("Cannot find the logarithm of a negative number")
Else
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
lblScreen.Text = "log(" & lblAnswer.Text & ")="
Multiply = Math.Round(Math.Log(CDbl(lblAnswer.Text)) / Math.Log(10), 15)
txtAns.Text = Multiply
lblAnswer.Text = txtAns.Text
End If
Else
Call Answers()
If Microsoft.VisualBasic.Left(lblAnswer.Text, 1) = "-" Then
lblScreen.Text = "Ans"
MsgBox("Cannot find the logarithm of a negative number")
Else
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
lblScreen.Text = "log(" & lblAnswer.Text & ")="
Multiply = Math.Round(Math.Log(CDbl(lblAnswer.Text)) / Math.Log(10), 15)
txtAns.Text = Multiply
lblAnswer.Text = txtAns.Text
End If
End If
End If
End Sub
Private Sub cmdReciprocal_Click(sender As Object, e As EventArgs) Handles cmdReciprocal.Click
If lblAnswer.Text = "" Then
MsgBox("Please type in a number first")
lblScreen.Text = "Ans"
lblAnswer.Text = txtAns.Text
Else
Dim Multiply As Double
Dim PreAns As Double
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or lblScreen.Text = "Ans" Then
lblScreen.Text = "Ans"
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
lblScreen.Text = "reciprocal(" & lblAnswer.Text & ")="
Multiply = Math.Round(1 / (CDbl(lblAnswer.Text)), 15)
txtAns.Text = Multiply
lblAnswer.Text = txtAns.Text
Else
Call Answers()
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
lblScreen.Text = "reciprocal(" & lblAnswer.Text & ")="
Multiply = Math.Round(1 / (CDbl(lblAnswer.Text)), 15)
txtAns.Text = Multiply
lblAnswer.Text = txtAns.Text
End If
End If
End Sub
Private Sub cmdMemoryMinus_Click(sender As Object, e As EventArgs) Handles cmdMemoryMinus.Click
If lblAnswer.Text = "" Then
MsgBox("Please type in a number first")
lblScreen.Text = "Ans"
lblAnswer.Text = txtAns.Text
Else
Dim PreAns As Double
Dim Memory As Double
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or lblScreen.Text = "Ans" Then
PreAns = CDbl(lblAnswer.Text)
Memory = CDbl(txtMemory.Text)
txtMemory.Text = Memory - PreAns
Else
If InStr(1, lblScreen.Text, "+") > 0 Or InStr(1, lblScreen.Text, "-") Or InStr(1, lblScreen.Text, "*") Or InStr(1, lblScreen.Text, "/") Then
Call Answers()
PreAns = CDbl(lblAnswer.Text)
Memory = CDbl(txtMemory.Text)
txtMemory.Text = Memory - PreAns
Else
PreAns = CDbl(lblAnswer.Text)
Memory = CDbl(txtMemory.Text)
txtMemory.Text = Memory - PreAns
End If
End If
If txtMemory.Text = "0" Then
lblMemory.Visible = False
Else
lblMemory.Visible = True
End If
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Then
lblScreen.Text = lblScreen.Text & ""
Else
lblScreen.Text = lblScreen.Text & "="
End If
End If
End Sub
Private Sub cmdSine_Click(sender As Object, e As EventArgs) Handles cmdSine.Click
If lblAnswer.Text = "" Then
MsgBox("Please type in a number first")
lblScreen.Text = "Ans"
lblAnswer.Text = txtAns.Text
Else
Dim Multiply As Double
Dim PreAns As Double
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or lblScreen.Text = "Ans" Then
lblScreen.Text = "Ans"
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
lblScreen.Text = "sin(" & lblAnswer.Text & ")="
Multiply = Math.Round(CDbl(Math.Sin(lblAnswer.Text * 4 * Math.Atan(1) / 180)), 15)
txtAns.Text = Multiply
lblAnswer.Text = txtAns.Text
Else
Call Answers()
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
lblScreen.Text = "sin(" & lblAnswer.Text & ")="
Multiply = Math.Round(CDbl(Math.Sin(lblAnswer.Text * 4 * Math.Atan(1) / 180)), 15)
txtAns.Text = Multiply
lblAnswer.Text = txtAns.Text
End If
End If
End Sub
Private Sub cmdCosine_Click(sender As Object, e As EventArgs) Handles cmdCosine.Click
If lblAnswer.Text = "" Then
MsgBox("Please type in a number first")
lblScreen.Text = "Ans"
lblAnswer.Text = txtAns.Text
Else
Dim Multiply As Double
Dim PreAns As Double
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or lblScreen.Text = "Ans" Then
lblScreen.Text = "Ans"
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
lblScreen.Text = "cos(" & lblAnswer.Text & ")="
Multiply = Math.Round(CDbl(Math.Cos(lblAnswer.Text * 4 * Math.Atan(1) / 180)), 15)
txtAns.Text = Multiply
lblAnswer.Text = txtAns.Text
Else
Call Answers()
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
lblScreen.Text = "cos(" & lblAnswer.Text & ")="
Multiply = Math.Round(CDbl(Math.Cos(lblAnswer.Text * 4 * Math.Atan(1) / 180)), 15)
txtAns.Text = Multiply
lblAnswer.Text = txtAns.Text
End If
End If
End Sub
Private Sub cmdTan_Click(sender As Object, e As EventArgs) Handles cmdTan.Click
If lblAnswer.Text = "" Then
MsgBox("Please type in a number first")
lblScreen.Text = "Ans"
lblAnswer.Text = txtAns.Text
Else
Dim Multiply As Double
Dim PreAns As Double
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or lblScreen.Text = "Ans" Then
lblScreen.Text = "Ans"
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
lblScreen.Text = "tan(" & lblAnswer.Text & ")="
Multiply = Math.Round(CDbl(Math.Tan(lblAnswer.Text * 4 * Math.Atan(1) / 180)), 15)
txtAns.Text = Multiply
lblAnswer.Text = txtAns.Text
Else
Call Answers()
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
lblScreen.Text = "tan(" & lblAnswer.Text & ")="
Multiply = Math.Round(CDbl(Math.Tan(lblAnswer.Text * 4 * Math.Atan(1) / 180)), 15)
txtAns.Text = Multiply
lblAnswer.Text = txtAns.Text
End If
End If
End Sub
Private Sub cmdClear_Click(sender As Object, e As EventArgs) Handles cmdClear.Click
If lblAnswer.Text = "" Then
lblAnswer.Text = lblAnswer.Text & ""
Else
lblAnswer.Text = Microsoft.VisualBasic.Left(lblAnswer.Text, Len(lblAnswer.Text) - 1)
End If
If lblScreen.Text = "" Then
lblScreen.Text = lblScreen.Text & ""
Else
lblScreen.Text = Microsoft.VisualBasic.Left(lblScreen.Text, Len(lblScreen.Text) - 1)
End If
End Sub
Private Sub cmdClearAll_Click(sender As Object, e As EventArgs) Handles cmdClearAll.Click
lblScreen.Text = ""
lblAnswer.Text = ""
txtPreAns.Text = "0"
txtOperator.Text = ""
End Sub
Private Sub cmdSquare_Click(sender As Object, e As EventArgs) Handles cmdSquare.Click
If lblAnswer.Text = "" Then
MsgBox("Please type in a number first")
lblScreen.Text = "Ans"
lblAnswer.Text = txtAns.Text
Else
Dim Multiply As Double
Dim PreAns As Double
If Microsoft.VisualBasic.Right(lblScreen.Text, 1) = "=" Or lblScreen.Text = "Ans" Then
lblScreen.Text = "Ans"
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
lblScreen.Text = lblAnswer.Text & "^2="
Multiply = lblAnswer.Text ^ 2
txtAns.Text = Multiply
lblAnswer.Text = txtAns.Text
Else
Call Answers()
PreAns = CDbl(lblAnswer.Text)
txtPreAns.Text = PreAns
lblScreen.Text = lblAnswer.Text & "^2="
Multiply = lblAnswer.Text ^ 2
txtAns.Text = Multiply
lblAnswer.Text = txtAns.Text
End If
End If
End Sub
Private Sub frmStandard_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cboMode.SelectedIndex = 0
End Sub
End Class
|
OKOLI1463/Visual-Studio-All-Pupose-Scientific-Calculator
|
OKOLI Lotanna Uche Calculator Project/Form1.vb
|
Visual Basic
|
mit
| 37,132
|
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("DataAdapter_MultiValue")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("DataAdapter_MultiValue")>
<Assembly: AssemblyCopyright("Copyright © 2012")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("e3e52293-aa61-489a-9ebd-b646d3860a3c")>
' 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")>
|
nkesic/multivalue-lab
|
U2/Demos/U2-Toolkit/.NET Samples/samples/VB.NET/UniData/DataAdapter_MultiValue/My Project/AssemblyInfo.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.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Statements
Public Class WhenKeywordRecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function WhenAfterCatchBlockTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>
Try
Catch x As Exception |
End Try</MethodBody>, "When")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function WhenAfterCatchBlockWithoutAsTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>
Dim x
Try
Catch x |
End Try</MethodBody>, "When")
End Function
<WorkItem(542803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542803")>
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function NoWhenAfterDimStatementTest() As Task
Await VerifyRecommendationsMissingAsync(<MethodBody>Dim ex As Exception |</MethodBody>, "When")
End Function
<WorkItem(542803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542803")>
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function NoWhenAfterLambdaInExceptionFilterTest() As Task
Await VerifyRecommendationsMissingAsync(
<MethodBody>
Try
Catch ex As Exception When (Function(e As Exception) As Boolean |
Return False
End Function).Invoke(ex)
End Try
</MethodBody>,
"When")
End Function
<WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function NotAfterEolTest() As Task
Await VerifyRecommendationsMissingAsync(
<MethodBody>
Try
Catch x As Exception
|
End Try</MethodBody>, "When")
End Function
<WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AfterExplicitLineContinuationTest() As Task
Await VerifyRecommendationsContainAsync(
<MethodBody>
Try
Catch x As Exception _
|
End Try</MethodBody>, "When")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function AfterExplicitLineContinuationTestCommentsAfterLineContinuation() As Task
Await VerifyRecommendationsContainAsync(
<MethodBody>
Try
Catch x As Exception _ ' Test
|
End Try</MethodBody>, "When")
End Function
End Class
End Namespace
|
aelij/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/Statements/WhenKeywordRecommenderTests.vb
|
Visual Basic
|
apache-2.0
| 2,913
|
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Queries
Public Class SelectKeywordRecommenderTests
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub SelectInQueryTest()
VerifyRecommendationsContain(<MethodBody>Dim x = From y In z |</MethodBody>, "Select")
End Sub
<WorkItem(543173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543173")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub SelectAfterMultiLineFunctionLambdaExprTest()
VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By Function()
Return 5
End Function |</MethodBody>, "Select")
End Sub
<WorkItem(543174, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543174")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub SelectAnonymousObjectCreationExprTest()
VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By New With {.Key = 10} |</MethodBody>, "Select")
End Sub
<WorkItem(543219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543219")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub SelectAfterIntoClauseTest()
VerifyRecommendationsContain(<MethodBody>Dim q1 = From i1 In arr Group By i1 Into Count |</MethodBody>, "Select")
End Sub
<WorkItem(543232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543232")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub SelectAfterNestedAggregateFromClauseTest()
VerifyRecommendationsContain(<MethodBody>Dim q1 = Aggregate i1 In arr From i4 In arr |</MethodBody>, "Select")
End Sub
End Class
End Namespace
|
shyamnamboodiripad/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/Queries/SelectKeywordRecommenderTests.vb
|
Visual Basic
|
apache-2.0
| 2,171
|
' 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.Immutable
Imports System.Reflection
Imports System.Reflection.Metadata
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports CommonAssemblyWellKnownAttributeData = Microsoft.CodeAnalysis.CommonAssemblyWellKnownAttributeData(Of Microsoft.CodeAnalysis.VisualBasic.Symbols.NamedTypeSymbol)
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents an assembly built by compiler.
''' </summary>
''' <remarks></remarks>
Partial Friend NotInheritable Class SourceAssemblySymbol
Inherits MetadataOrSourceAssemblySymbol
Implements ISourceAssemblySymbolInternal, IAttributeTargetSymbol
''' <summary>
''' A Compilation the assembly is created for.
''' </summary>
''' <remarks></remarks>
Private ReadOnly _compilation As VisualBasicCompilation
Private _lazyStrongNameKeys As StrongNameKeys
''' <summary>
''' Assembly's identity.
''' </summary>
''' <remarks></remarks>
Friend m_lazyIdentity As AssemblyIdentity
''' <summary>
''' A list of modules the assembly consists of.
''' The first (index=0) module is a SourceModuleSymbol, which is a primary module, the rest are net-modules.
''' </summary>
Private ReadOnly _modules As ImmutableArray(Of ModuleSymbol)
Private _lazySourceAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData)
Private _lazyNetModuleAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData)
''' <summary>
''' Indices of duplicate assembly attributes, i.e. attributes that bind to the same constructor and have identical arguments, that must not be emitted.
''' </summary>
''' <remarks>
''' These indices correspond to the merged assembly attributes from source and added net modules, i.e. attributes returned by <see cref="GetAttributes"/> method.
''' </remarks>
Private _lazyDuplicateAttributeIndices As HashSet(Of Integer)
Private _lazyEmitExtensionAttribute As Byte = ThreeState.Unknown
Private _lazyIsVbRuntime As ThreeState = ThreeState.Unknown
Private _lazyAssemblyLevelDeclarationErrors As ImmutableArray(Of Diagnostic)
Private ReadOnly _assemblySimpleName As String
'This maps from assembly name to a set of public keys. It uses concurrent dictionaries because it is built,
'one attribute at a time, in the callback that validates an attribute's application to a symbol. It is assumed
'to be complete after a call to GetAttributes(). The second dictionary is acting like a set. The value element is
'only used when the key is empty in which case it stores the location and value of the attribute string which
'may be used to construct a diagnostic if the assembly being compiled is found to be strong named.
Private _lazyInternalsVisibleToMap As ConcurrentDictionary(Of String, ConcurrentDictionary(Of ImmutableArray(Of Byte), Tuple(Of Location, String)))
Friend Sub New(compilation As VisualBasicCompilation,
assemblySimpleName As String,
moduleName As String,
netModules As ImmutableArray(Of PEModule))
Debug.Assert(compilation IsNot Nothing)
Debug.Assert(assemblySimpleName IsNot Nothing)
Debug.Assert(Not String.IsNullOrWhiteSpace(moduleName))
Debug.Assert(Not netModules.IsDefault)
_compilation = compilation
_assemblySimpleName = assemblySimpleName
Dim moduleBuilder As New ArrayBuilder(Of ModuleSymbol)(1 + netModules.Length)
moduleBuilder.Add(New SourceModuleSymbol(Me, compilation.Declarations, compilation.Options, moduleName))
Dim importOptions = If(compilation.Options.MetadataImportOptions = MetadataImportOptions.All,
MetadataImportOptions.All,
MetadataImportOptions.Internal)
For Each netModule As PEModule In netModules
moduleBuilder.Add(New PEModuleSymbol(Me, netModule, importOptions, moduleBuilder.Count))
' SetReferences will be called later by the ReferenceManager (in CreateSourceAssemblyFullBind for
' a fresh manager, in CreateSourceAssemblyReuseData for a reused one).
Next
_modules = moduleBuilder.ToImmutableAndFree()
If Not compilation.Options.CryptoPublicKey.IsEmpty Then
_lazyStrongNameKeys = StrongNameKeys.Create(compilation.Options.CryptoPublicKey, MessageProvider.Instance)
End If
End Sub
''' <summary>
''' This override is essential - it's a base case of the recursive definition.
''' </summary>
Friend Overrides ReadOnly Property DeclaringCompilation As VisualBasicCompilation
Get
Return _compilation
End Get
End Property
Public Overrides ReadOnly Property IsInteractive As Boolean
Get
Return _compilation.IsSubmission
End Get
End Property
Friend Function MightContainNoPiaLocalTypes() As Boolean
For i As Integer = 1 To _modules.Length - 1
Dim peModuleSymbol = DirectCast(_modules(i), Symbols.Metadata.PE.PEModuleSymbol)
If peModuleSymbol.[Module].ContainsNoPiaLocalTypes() Then
Return True
End If
Next
Return SourceModule.MightContainNoPiaLocalTypes()
End Function
Public Overrides ReadOnly Property Identity As AssemblyIdentity
Get
If m_lazyIdentity Is Nothing Then
Interlocked.CompareExchange(m_lazyIdentity, ComputeIdentity(), Nothing)
End If
Return m_lazyIdentity
End Get
End Property
Friend Overrides Function GetSpecialTypeMember(member As SpecialMember) As Symbol
If _compilation.IsMemberMissing(member) Then
Return Nothing
End If
Return MyBase.GetSpecialTypeMember(member)
End Function
Public Overrides ReadOnly Property Name As String
Get
Return _assemblySimpleName
End Get
End Property
Private Function IsKnownAssemblyAttribute(attribute As VisualBasicAttributeData) As Boolean
' TODO: This list used to include AssemblyOperatingSystemAttribute and AssemblyProcessorAttribute,
' but it doesn't look like they are defined, cannot find them on MSDN.
If attribute.IsTargetAttribute(Me, AttributeDescription.AssemblyTitleAttribute) OrElse
attribute.IsTargetAttribute(Me, AttributeDescription.AssemblyDescriptionAttribute) OrElse
attribute.IsTargetAttribute(Me, AttributeDescription.AssemblyConfigurationAttribute) OrElse
attribute.IsTargetAttribute(Me, AttributeDescription.AssemblyCultureAttribute) OrElse
attribute.IsTargetAttribute(Me, AttributeDescription.AssemblyVersionAttribute) OrElse
attribute.IsTargetAttribute(Me, AttributeDescription.AssemblyCompanyAttribute) OrElse
attribute.IsTargetAttribute(Me, AttributeDescription.AssemblyProductAttribute) OrElse
attribute.IsTargetAttribute(Me, AttributeDescription.AssemblyInformationalVersionAttribute) OrElse
attribute.IsTargetAttribute(Me, AttributeDescription.AssemblyCopyrightAttribute) OrElse
attribute.IsTargetAttribute(Me, AttributeDescription.AssemblyTrademarkAttribute) OrElse
attribute.IsTargetAttribute(Me, AttributeDescription.AssemblyKeyFileAttribute) OrElse
attribute.IsTargetAttribute(Me, AttributeDescription.AssemblyKeyNameAttribute) OrElse
attribute.IsTargetAttribute(Me, AttributeDescription.AssemblyAlgorithmIdAttribute) OrElse
attribute.IsTargetAttribute(Me, AttributeDescription.AssemblyFlagsAttribute) OrElse
attribute.IsTargetAttribute(Me, AttributeDescription.AssemblyDelaySignAttribute) OrElse
attribute.IsTargetAttribute(Me, AttributeDescription.AssemblyFileVersionAttribute) OrElse
attribute.IsTargetAttribute(Me, AttributeDescription.SatelliteContractVersionAttribute) OrElse
attribute.IsTargetAttribute(Me, AttributeDescription.AssemblySignatureKeyAttribute) Then
Return True
End If
Return False
End Function
''' <summary>
''' Gets unique source assembly attributes that should be emitted,
''' i.e. filters out attributes with errors and duplicate attributes.
''' </summary>
Private Function GetUniqueSourceAssemblyAttributes(<Out> ByRef attributeIndicesToSkip As HashSet(Of Integer)) As HashSet(Of VisualBasicAttributeData)
Dim appliedSourceAttributes As ImmutableArray(Of VisualBasicAttributeData) = Me.GetSourceAttributesBag().Attributes
Dim uniqueAttributes As HashSet(Of VisualBasicAttributeData) = Nothing
attributeIndicesToSkip = Nothing
For i As Integer = 0 To appliedSourceAttributes.Length - 1
Dim attribute As VisualBasicAttributeData = appliedSourceAttributes(i)
If Not attribute.HasErrors Then
If Not AddUniqueAssemblyAttribute(attribute, uniqueAttributes) Then
If attributeIndicesToSkip Is Nothing Then
attributeIndicesToSkip = New HashSet(Of Integer)
End If
attributeIndicesToSkip.Add(i)
End If
End If
Next
Return uniqueAttributes
End Function
Private Shared Function AddUniqueAssemblyAttribute(attribute As VisualBasicAttributeData, ByRef uniqueAttributes As HashSet(Of VisualBasicAttributeData)) As Boolean
Debug.Assert(Not attribute.HasErrors)
If uniqueAttributes Is Nothing Then
uniqueAttributes = New HashSet(Of VisualBasicAttributeData)(comparer:=CommonAttributeDataComparer.Instance)
End If
Return uniqueAttributes.Add(attribute)
End Function
Private Function ValidateAttributeUsageForNetModuleAttribute(attribute As VisualBasicAttributeData, netModuleName As String, diagnostics As DiagnosticBag, ByRef uniqueAttributes As HashSet(Of VisualBasicAttributeData)) As Boolean
Debug.Assert(Not attribute.HasErrors)
Dim attributeClass = attribute.AttributeClass
If attributeClass.GetAttributeUsageInfo().AllowMultiple Then
' Duplicate attributes are allowed, but native compiler doesn't emit duplicate attributes, i.e. attributes with same constructor and arguments.
Return AddUniqueAssemblyAttribute(attribute, uniqueAttributes)
Else
' Duplicate attributes with same attribute type are not allowed.
' Check if there is an existing assembly attribute with same attribute type.
If uniqueAttributes Is Nothing OrElse Not uniqueAttributes.Contains(Function(a) a.AttributeClass = attributeClass) Then
' Attribute with unique attribute type, not a duplicate.
Dim success As Boolean = AddUniqueAssemblyAttribute(attribute, uniqueAttributes)
Debug.Assert(success)
Return True
Else
' Duplicate attribute with same attribute type, we should report an error.
' Native compiler suppresses the error for
' (a) Duplicate well-known assembly attributes and
' (b) Identical duplicates, i.e. attributes with same constructor and arguments.
' For (a), native compiler picks the last of these duplicate well-known netmodule attributes, but these can vary based on the ordering of referenced netmodules.
If IsKnownAssemblyAttribute(attribute) Then
If Not uniqueAttributes.Contains(attribute) Then
' This attribute application will be ignored.
diagnostics.Add(ERRID.WRN_AssemblyAttributeFromModuleIsOverridden, NoLocation.Singleton, attribute.AttributeClass, netModuleName)
End If
ElseIf AddUniqueAssemblyAttribute(attribute, uniqueAttributes) Then
' Error
diagnostics.Add(ERRID.ERR_InvalidMultipleAttributeUsageInNetModule2, NoLocation.Singleton, attribute.AttributeClass.Name, netModuleName)
End If
Return False
End If
End If
' CONSIDER Handling badly targetted assembly attributes from netmodules
'If (attributeUsage.ValidTargets And AttributeTargets.Assembly) = 0 Then
' If Not attribute.HasErrors Then
' 'Error and skip
' diagnostics.Add(ERRID.ERR_InvalidAssemblyAttributeInNetModule2, NoLocation.Singleton, attribute.AttributeClass.Name, netModuleName, attributeUsage.GetValidTargetsString())
' End If
'End If
End Function
Private Function GetNetModuleAttributes(<Out> ByRef netModuleNames As ImmutableArray(Of String)) As ImmutableArray(Of VisualBasicAttributeData)
Dim netModuleNamesBuilder As ArrayBuilder(Of String) = Nothing
Dim moduleAssemblyAttributesBuilder As ArrayBuilder(Of VisualBasicAttributeData) = Nothing
For i As Integer = 1 To _modules.Length - 1
Dim peModuleSymbol = DirectCast(_modules(i), Symbols.Metadata.PE.PEModuleSymbol)
Dim netModuleName As String = peModuleSymbol.Name
For Each attributeData In peModuleSymbol.GetAssemblyAttributes()
If netModuleNamesBuilder Is Nothing Then
netModuleNamesBuilder = ArrayBuilder(Of String).GetInstance()
moduleAssemblyAttributesBuilder = ArrayBuilder(Of VisualBasicAttributeData).GetInstance()
End If
netModuleNamesBuilder.Add(netModuleName)
moduleAssemblyAttributesBuilder.Add(attributeData)
Next
Next
If netModuleNamesBuilder Is Nothing Then
netModuleNames = ImmutableArray(Of String).Empty
Return ImmutableArray(Of VisualBasicAttributeData).Empty
End If
netModuleNames = netModuleNamesBuilder.ToImmutableAndFree()
Return moduleAssemblyAttributesBuilder.ToImmutableAndFree()
End Function
Private Function ValidateAttributeUsageAndDecodeWellKnownNetModuleAttributes(
attributesFromNetModules As ImmutableArray(Of VisualBasicAttributeData),
netModuleNames As ImmutableArray(Of String),
diagnostics As DiagnosticBag,
<Out> ByRef attributeIndicesToSkip As HashSet(Of Integer)) As WellKnownAttributeData
Debug.Assert(attributesFromNetModules.Any())
Debug.Assert(netModuleNames.Any())
Debug.Assert(attributesFromNetModules.Length = netModuleNames.Length)
Dim tree = VisualBasicSyntaxTree.Dummy
Dim node = tree.GetRoot()
Dim binder As Binder = BinderBuilder.CreateSourceModuleBinder(Me.SourceModule)
Dim netModuleAttributesCount As Integer = attributesFromNetModules.Length
Dim sourceAttributesCount As Integer = Me.GetSourceAttributesBag().Attributes.Length
' Get unique source assembly attributes.
Dim uniqueAttributes As HashSet(Of VisualBasicAttributeData) = GetUniqueSourceAssemblyAttributes(attributeIndicesToSkip)
Dim arguments = New DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)()
arguments.AttributesCount = netModuleAttributesCount
arguments.Diagnostics = diagnostics
arguments.SymbolPart = AttributeLocation.None
' Attributes from the second added module should override attributes from the first added module, etc.
' Attributes from source should override attributes from added modules.
' That is why we are iterating attributes backwards.
For i As Integer = netModuleAttributesCount - 1 To 0 Step -1
Dim attribute As VisualBasicAttributeData = attributesFromNetModules(i)
If Not attribute.HasErrors AndAlso ValidateAttributeUsageForNetModuleAttribute(attribute, netModuleNames(i), diagnostics, uniqueAttributes) Then
arguments.Attribute = attribute
arguments.Index = i
' CONSIDER Provide usable AttributeSyntax node for diagnostics of malformed netmodule assembly attributes
arguments.AttributeSyntaxOpt = Nothing
Me.DecodeWellKnownAttribute(arguments)
Else
If attributeIndicesToSkip Is Nothing Then
attributeIndicesToSkip = New HashSet(Of Integer)
End If
attributeIndicesToSkip.Add(i + sourceAttributesCount)
End If
Next
Return If(arguments.HasDecodedData, arguments.DecodedData, Nothing)
End Function
Private Sub LoadAndValidateNetModuleAttributes(ByRef lazyNetModuleAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData))
' Indices of duplicate assembly attributes, i.e. attributes that bind to the same constructor and have identical arguments, that must not be emitted.
Dim attributeIndicesToSkip As HashSet(Of Integer) = Nothing
If _compilation.Options.OutputKind.IsNetModule() Then
' Compute duplicate source assembly attributes, i.e. attributes with same constructor and arguments, that must not be emitted.
Dim unused = GetUniqueSourceAssemblyAttributes(attributeIndicesToSkip)
Interlocked.CompareExchange(lazyNetModuleAttributesBag, CustomAttributesBag(Of VisualBasicAttributeData).Empty, Nothing)
Else
Dim diagnostics = DiagnosticBag.GetInstance()
Dim netModuleNames As ImmutableArray(Of String) = Nothing
Dim attributesFromNetModules As ImmutableArray(Of VisualBasicAttributeData) = GetNetModuleAttributes(netModuleNames)
Dim wellKnownData As WellKnownAttributeData = Nothing
If attributesFromNetModules.Any() Then
wellKnownData = ValidateAttributeUsageAndDecodeWellKnownNetModuleAttributes(attributesFromNetModules, netModuleNames, diagnostics, attributeIndicesToSkip)
Else
' Compute duplicate source assembly attributes, i.e. attributes with same constructor and arguments, that must not be emitted.
Dim unused = GetUniqueSourceAssemblyAttributes(attributeIndicesToSkip)
End If
' Load type forwarders from modules
Dim forwardedTypes As HashSet(Of NamedTypeSymbol) = Nothing
' Similar to attributes, type forwarders from the second added module should override type forwarders from the first added module, etc.
' This affects only diagnostics.
For i As Integer = _modules.Length - 1 To 1 Step -1
Dim peModuleSymbol = DirectCast(_modules(i), PEModuleSymbol)
For Each forwarded As NamedTypeSymbol In peModuleSymbol.GetForwardedTypes()
If forwardedTypes Is Nothing Then
If wellKnownData Is Nothing Then
wellKnownData = New CommonAssemblyWellKnownAttributeData()
End If
forwardedTypes = DirectCast(wellKnownData, CommonAssemblyWellKnownAttributeData).ForwardedTypes
If forwardedTypes Is Nothing Then
forwardedTypes = New HashSet(Of NamedTypeSymbol)()
DirectCast(wellKnownData, CommonAssemblyWellKnownAttributeData).ForwardedTypes = forwardedTypes
End If
End If
If forwardedTypes.Add(forwarded) Then
If forwarded.IsErrorType() Then
Dim info As DiagnosticInfo = If(forwarded.GetUseSiteErrorInfo(), DirectCast(forwarded, ErrorTypeSymbol).ErrorInfo)
If info IsNot Nothing Then
diagnostics.Add(info, NoLocation.Singleton)
End If
End If
End If
Next
Next
Dim netModuleAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData)
If wellKnownData IsNot Nothing OrElse attributesFromNetModules.Any() Then
netModuleAttributesBag = New CustomAttributesBag(Of VisualBasicAttributeData)()
netModuleAttributesBag.SetEarlyDecodedWellKnownAttributeData(Nothing)
netModuleAttributesBag.SetDecodedWellKnownAttributeData(wellKnownData)
netModuleAttributesBag.SetAttributes(attributesFromNetModules)
Else
netModuleAttributesBag = CustomAttributesBag(Of VisualBasicAttributeData).Empty
End If
' Check if we have any duplicate assembly attribute that must not be emitted,
' unless we are emitting a net module.
If attributeIndicesToSkip IsNot Nothing Then
Debug.Assert(attributeIndicesToSkip.Any())
Interlocked.CompareExchange(_lazyDuplicateAttributeIndices, attributeIndicesToSkip, Nothing)
End If
SourceModule.AtomicStoreReferenceAndDiagnostics(lazyNetModuleAttributesBag, netModuleAttributesBag, diagnostics, CompilationStage.Declare)
diagnostics.Free()
Debug.Assert(attributeIndicesToSkip Is Nothing OrElse
Not attributeIndicesToSkip.Any(Function(index) index < 0 OrElse index >= Me.GetAttributes().Length))
End If
Debug.Assert(lazyNetModuleAttributesBag.IsSealed)
End Sub
Private Sub EnsureNetModuleAttributesAreBound()
If _lazyNetModuleAttributesBag Is Nothing Then
LoadAndValidateNetModuleAttributes(_lazyNetModuleAttributesBag)
End If
End Sub
''' <summary>
''' Returns true if the assembly attribute at the given index is a duplicate assembly attribute that must not be emitted.
''' Duplicate assembly attributes are attributes that bind to the same constructor and have identical arguments.
''' </summary>
''' <remarks>
''' This method must be invoked only after all the assembly attributes have been bound.
''' </remarks>
Friend Function IsIndexOfDuplicateAssemblyAttribute(index As Integer) As Boolean
Debug.Assert(Me._lazySourceAttributesBag.IsSealed)
Debug.Assert(Me._lazyNetModuleAttributesBag.IsSealed)
Debug.Assert(index >= 0)
Debug.Assert(index < Me.GetAttributes().Length)
Debug.Assert(Me._lazyDuplicateAttributeIndices Is Nothing OrElse
Not Me.DeclaringCompilation.Options.OutputKind.IsNetModule())
Return Me._lazyDuplicateAttributeIndices IsNot Nothing AndAlso Me._lazyDuplicateAttributeIndices.Contains(index)
End Function
Public ReadOnly Property DefaultAttributeLocation As AttributeLocation Implements IAttributeTargetSymbol.DefaultAttributeLocation
Get
Return AttributeLocation.Assembly
End Get
End Property
Friend Function GetAttributeDeclarations() As ImmutableArray(Of SyntaxList(Of AttributeListSyntax))
Dim attributeBlocks = ArrayBuilder(Of SyntaxList(Of AttributeListSyntax)).GetInstance()
Dim declarations = DeclaringCompilation.MergedRootDeclaration.Declarations
For Each rootNs As RootSingleNamespaceDeclaration In declarations
If rootNs.HasAssemblyAttributes Then
Dim compilationUnitSyntax = DirectCast(rootNs.Location.SourceTree.GetRoot(), CompilationUnitSyntax)
Dim attributeStatements = compilationUnitSyntax.Attributes
If attributeStatements.Any Then
For Each statement In attributeStatements
'For Each block In statement.AttributeLists
'attributeBlocks.Add(block)
'Next
attributeBlocks.Add(statement.AttributeLists)
Next
End If
End If
Next
Return attributeBlocks.ToImmutableAndFree()
End Function
''' <summary>
''' Returns a bag of netmodule assembly attributes and data decoded from well-known attributes. Returns null if there are no attributes applied on the symbol.
''' </summary>
''' <remarks>
''' Forces binding and decoding of attributes.
''' </remarks>
Friend Function GetNetModuleAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData)
EnsureNetModuleAttributesAreBound()
Return _lazyNetModuleAttributesBag
End Function
Private Function GetNetModuleAttributes() As ImmutableArray(Of VisualBasicAttributeData)
Dim attributesBag = Me.GetNetModuleAttributesBag()
Debug.Assert(attributesBag.IsSealed)
Return attributesBag.Attributes
End Function
Friend Function GetNetModuleDecodedWellKnownAttributeData() As CommonAssemblyWellKnownAttributeData
Dim attributesBag = Me.GetNetModuleAttributesBag()
Debug.Assert(attributesBag.IsSealed)
Return DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonAssemblyWellKnownAttributeData)
End Function
''' <summary>
''' Gets the attributes applied on this symbol.
''' Returns an empty array if there are no attributes.
''' </summary>
''' <remarks>
''' NOTE: This method should always be kept as a NotOverridable method.
''' If you want to override attribute binding logic for a sub-class, then override <see cref="GetSourceAttributesBag"/> method.
''' </remarks>
Public Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData)
Dim attributes = Me.GetSourceAttributesBag().Attributes
Dim netmoduleAttributes = Me.GetNetModuleAttributesBag().Attributes
Debug.Assert(Not attributes.IsDefault)
Debug.Assert(Not netmoduleAttributes.IsDefault)
If attributes.Length > 0 Then
If netmoduleAttributes.Length > 0 Then
attributes = attributes.Concat(netmoduleAttributes)
End If
Else
attributes = netmoduleAttributes
End If
Debug.Assert(Not attributes.IsDefault)
Return attributes
End Function
Friend Function GetSourceAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData)
EnsureAttributesAreBound()
Return Me._lazySourceAttributesBag
End Function
''' <summary>
''' Returns data decoded from source assembly attributes or null if there are none.
''' </summary>
''' <returns>
''' Forces binding and decoding of attributes.
''' TODO: We should replace methods GetSourceDecodedWellKnownAttributeData and GetNetModuleDecodedWellKnownAttributeData with
''' a single method GetDecodedWellKnownAttributeData, which merges DecodedWellKnownAttributeData from source and netmodule attributes.
''' </returns>
''' <remarks></remarks>
Friend Function GetSourceDecodedWellKnownAttributeData() As CommonAssemblyWellKnownAttributeData
Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me._lazySourceAttributesBag
If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then
attributesBag = Me.GetSourceAttributesBag()
End If
Return DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonAssemblyWellKnownAttributeData)
End Function
Private Function GetWellKnownAttributeDataStringField(fieldGetter As Func(Of CommonAssemblyWellKnownAttributeData, String), Optional missingValue As String = Nothing) As String
Dim defaultValue As String = missingValue
Dim fieldValue = defaultValue
Dim data = GetSourceDecodedWellKnownAttributeData()
If data IsNot Nothing Then
fieldValue = fieldGetter(data)
End If
If fieldValue Is missingValue Then
data = GetNetModuleDecodedWellKnownAttributeData()
If data IsNot Nothing Then
fieldValue = fieldGetter(data)
End If
End If
Return fieldValue
End Function
Friend Function GetSecurityAttributes() As IEnumerable(Of Cci.SecurityAttribute)
Dim sourceSecurityAttributes As IEnumerable(Of Cci.SecurityAttribute) = Nothing
Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me.GetSourceAttributesBag()
Dim wellKnownAttributeData = DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonAssemblyWellKnownAttributeData(Of NamedTypeSymbol))
If wellKnownAttributeData IsNot Nothing Then
Dim securityData As SecurityWellKnownAttributeData = wellKnownAttributeData.SecurityInformation
If securityData IsNot Nothing Then
sourceSecurityAttributes = securityData.GetSecurityAttributes(attributesBag.Attributes)
End If
End If
Dim netmoduleSecurityAttributes As IEnumerable(Of Cci.SecurityAttribute) = Nothing
attributesBag = Me.GetNetModuleAttributesBag()
wellKnownAttributeData = DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonAssemblyWellKnownAttributeData(Of NamedTypeSymbol))
If wellKnownAttributeData IsNot Nothing Then
Dim securityData As SecurityWellKnownAttributeData = wellKnownAttributeData.SecurityInformation
If securityData IsNot Nothing Then
netmoduleSecurityAttributes = securityData.GetSecurityAttributes(attributesBag.Attributes)
End If
End If
Dim securityAttributes As IEnumerable(Of Cci.SecurityAttribute) = Nothing
If sourceSecurityAttributes IsNot Nothing Then
If netmoduleSecurityAttributes IsNot Nothing Then
securityAttributes = sourceSecurityAttributes.Concat(netmoduleSecurityAttributes)
Else
securityAttributes = sourceSecurityAttributes
End If
Else
If netmoduleSecurityAttributes IsNot Nothing Then
securityAttributes = netmoduleSecurityAttributes
Else
securityAttributes = SpecializedCollections.EmptyEnumerable(Of Cci.SecurityAttribute)()
End If
End If
Debug.Assert(securityAttributes IsNot Nothing)
Return securityAttributes
End Function
Friend ReadOnly Property FileVersion As String
Get
Return GetWellKnownAttributeDataStringField(Function(data) data.AssemblyFileVersionAttributeSetting)
End Get
End Property
Friend ReadOnly Property Title As String
Get
Return GetWellKnownAttributeDataStringField(Function(data) data.AssemblyTitleAttributeSetting)
End Get
End Property
Friend ReadOnly Property Description As String
Get
Return GetWellKnownAttributeDataStringField(Function(data) data.AssemblyDescriptionAttributeSetting)
End Get
End Property
Friend ReadOnly Property Company As String
Get
Return GetWellKnownAttributeDataStringField(Function(data) data.AssemblyCompanyAttributeSetting)
End Get
End Property
Friend ReadOnly Property Product As String
Get
Return GetWellKnownAttributeDataStringField(Function(data) data.AssemblyProductAttributeSetting)
End Get
End Property
Friend ReadOnly Property InformationalVersion As String
Get
Return GetWellKnownAttributeDataStringField(Function(data) data.AssemblyInformationalVersionAttributeSetting)
End Get
End Property
Friend ReadOnly Property Copyright As String
Get
Return GetWellKnownAttributeDataStringField(Function(data) data.AssemblyCopyrightAttributeSetting)
End Get
End Property
Friend ReadOnly Property Trademark As String
Get
Return GetWellKnownAttributeDataStringField(Function(data) data.AssemblyTrademarkAttributeSetting)
End Get
End Property
''' <summary>
''' This represents what the user claimed in source through the AssemblyFlagsAttribute.
''' It may be modified as emitted due to presence or absence of the public key.
''' </summary>
Public ReadOnly Property AssemblyFlags As AssemblyFlags Implements ISourceAssemblySymbolInternal.AssemblyFlags
Get
Dim fieldValue As AssemblyFlags = Nothing
Dim data = GetSourceDecodedWellKnownAttributeData()
If data IsNot Nothing Then
fieldValue = data.AssemblyFlagsAttributeSetting
End If
data = GetNetModuleDecodedWellKnownAttributeData()
If data IsNot Nothing Then
fieldValue = fieldValue Or data.AssemblyFlagsAttributeSetting
End If
Return fieldValue
End Get
End Property
Private ReadOnly Property DelaySignAttributeSetting As Boolean
Get
Dim defaultValue = False
Dim fieldValue = defaultValue
Dim data = GetSourceDecodedWellKnownAttributeData()
If data IsNot Nothing Then
fieldValue = (data.AssemblyDelaySignAttributeSetting = ThreeState.True)
End If
If fieldValue = defaultValue Then
data = GetNetModuleDecodedWellKnownAttributeData()
If data IsNot Nothing Then
fieldValue = (data.AssemblyDelaySignAttributeSetting = ThreeState.True)
End If
End If
Return fieldValue
End Get
End Property
Public ReadOnly Property SignatureKey As String Implements ISourceAssemblySymbolInternal.SignatureKey
Get
Return GetWellKnownAttributeDataStringField(Function(data) data.AssemblySignatureKeyAttributeSetting)
End Get
End Property
Private ReadOnly Property AssemblyKeyContainerAttributeSetting As String
Get
Return GetWellKnownAttributeDataStringField(Function(data) data.AssemblyKeyContainerAttributeSetting, CommonAssemblyWellKnownAttributeData.StringMissingValue)
End Get
End Property
Private ReadOnly Property AssemblyKeyFileAttributeSetting As String
Get
Return GetWellKnownAttributeDataStringField(Function(data) data.AssemblyKeyFileAttributeSetting, CommonAssemblyWellKnownAttributeData.StringMissingValue)
End Get
End Property
Private ReadOnly Property AssemblyCultureAttributeSetting As String
Get
Return GetWellKnownAttributeDataStringField(Function(data) data.AssemblyCultureAttributeSetting)
End Get
End Property
Private ReadOnly Property AssemblyVersionAttributeSetting As Version
Get
Dim defaultValue As Version = Nothing
Dim fieldValue = defaultValue
Dim data = GetSourceDecodedWellKnownAttributeData()
If data IsNot Nothing Then
fieldValue = data.AssemblyVersionAttributeSetting
End If
If fieldValue Is defaultValue Then
data = GetNetModuleDecodedWellKnownAttributeData()
If data IsNot Nothing Then
fieldValue = data.AssemblyVersionAttributeSetting
End If
End If
Return fieldValue
End Get
End Property
Public Overrides ReadOnly Property AssemblyVersionPattern As Version Implements ISourceAssemblySymbolInternal.AssemblyVersionPattern
Get
Dim attributeValue = AssemblyVersionAttributeSetting
Return If(attributeValue Is Nothing OrElse (attributeValue.Build <> UShort.MaxValue AndAlso attributeValue.Revision <> UShort.MaxValue), Nothing, attributeValue)
End Get
End Property
Public ReadOnly Property HashAlgorithm As AssemblyHashAlgorithm Implements ISourceAssemblySymbolInternal.HashAlgorithm
Get
Return If(AssemblyAlgorithmIdAttributeSetting, AssemblyHashAlgorithm.Sha1)
End Get
End Property
Friend ReadOnly Property AssemblyAlgorithmIdAttributeSetting As AssemblyHashAlgorithm?
Get
Dim fieldValue As AssemblyHashAlgorithm? = Nothing
Dim data = GetSourceDecodedWellKnownAttributeData()
If data IsNot Nothing Then
fieldValue = data.AssemblyAlgorithmIdAttributeSetting
End If
If fieldValue Is Nothing Then
data = GetNetModuleDecodedWellKnownAttributeData()
If data IsNot Nothing Then
fieldValue = data.AssemblyAlgorithmIdAttributeSetting
End If
End If
Return fieldValue
End Get
End Property
Private Sub EnsureAttributesAreBound()
If _lazySourceAttributesBag Is Nothing OrElse Not _lazySourceAttributesBag.IsSealed Then
LoadAndValidateAttributes(OneOrMany.Create(GetAttributeDeclarations()), _lazySourceAttributesBag)
End If
End Sub
' TODO: cache
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return Me.Modules.SelectMany(Function(m) m.Locations).AsImmutable()
End Get
End Property
Public Overrides ReadOnly Property Modules As ImmutableArray(Of ModuleSymbol)
Get
Return _modules
End Get
End Property
Friend Overrides Function GetNoPiaResolutionAssemblies() As ImmutableArray(Of AssemblySymbol)
Return SourceModule.GetReferencedAssemblySymbols()
End Function
Friend Overrides Sub SetNoPiaResolutionAssemblies(assemblies As ImmutableArray(Of AssemblySymbol))
Throw ExceptionUtilities.Unreachable
End Sub
Friend Overrides Function GetLinkedReferencedAssemblies() As ImmutableArray(Of AssemblySymbol)
' SourceAssemblySymbol is never used directly as a reference
' when it is or any of its references is linked.
Return Nothing
End Function
Friend Overrides Sub SetLinkedReferencedAssemblies(assemblies As ImmutableArray(Of AssemblySymbol))
' SourceAssemblySymbol is never used directly as a reference
' when it is or any of its references is linked.
Throw ExceptionUtilities.Unreachable
End Sub
Friend Overrides ReadOnly Property IsLinked As Boolean
Get
Return False
End Get
End Property
' Computing the identity requires computing the public key. Computing the public key
' can require binding attributes that contain version or strong name information.
' Attribute binding will check type visibility which will possibly
' check IVT relationships. To correctly determine the IVT relationship requires the public key.
' To avoid infinite recursion, this type notes, per thread, the assembly for which the thread
' is actively computing the public key (s_AssemblyForWhichCurrentThreadIsComputingKeys). Should a request to determine IVT
' relationship occur on the thread that is computing the public key, access is optimistically
' granted provided the simple assembly names match. When such access is granted
' the assembly to which we have been granted access is noted (m_optimisticallyGrantedInternalsAccess).
' After the public key has been computed, the set of optimistic grants is reexamined
' to ensure that full identities match. This may produce diagnostics.
' EDMAURER please don't use thread local storage widely. This is hoped to be a one-off usage.
<ThreadStatic()>
Private Shared s_AssemblyForWhichCurrentThreadIsComputingKeys As AssemblySymbol
' A collection of assemblies to which we were granted internals access by only checking matches for assembly name
' and ignoring public key. This just acts as a set. The Boolean is ignored.
Private _optimisticallyGrantedInternalsAccess As ConcurrentDictionary(Of AssemblySymbol, Boolean)
' Once the computation of the AssemblyIdentity is complete, check whether
' any of the IVT access grants that were optimistically made during AssemblyIdentity computation
' are in fact invalid now that the full identity is known.
Private Sub CheckOptimisticIVTAccessGrants(bag As DiagnosticBag)
Dim haveGrantedAssemblies As ConcurrentDictionary(Of AssemblySymbol, Boolean) = _optimisticallyGrantedInternalsAccess
If haveGrantedAssemblies IsNot Nothing Then
For Each otherAssembly In haveGrantedAssemblies.Keys
Dim conclusion As IVTConclusion = MakeFinalIVTDetermination(otherAssembly)
Debug.Assert(conclusion <> IVTConclusion.NoRelationshipClaimed)
If conclusion = IVTConclusion.PublicKeyDoesntMatch Then
bag.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_FriendRefNotEqualToThis,
otherAssembly.Identity,
Me.Identity),
NoLocation.Singleton))
ElseIf conclusion = IVTConclusion.OneSignedOneNot Then
bag.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_FriendRefSigningMismatch,
otherAssembly.Identity,
Me.Identity),
NoLocation.Singleton))
End If
Next
End If
End Sub
Friend Overrides Function GetInternalsVisibleToPublicKeys(simpleName As String) As IEnumerable(Of ImmutableArray(Of Byte))
'EDMAURER assume that if EnsureAttributesAreBound() returns, then the internals visible to map has been populated.
'Do not optimize by checking if m_lazyInternalsVisibleToMap is Nothing. It may be non-null yet still
'incomplete because another thread is in the process of building it.
EnsureAttributesAreBound()
If _lazyInternalsVisibleToMap Is Nothing Then
Return SpecializedCollections.EmptyEnumerable(Of ImmutableArray(Of Byte))()
End If
Dim result As ConcurrentDictionary(Of ImmutableArray(Of Byte), Tuple(Of Location, String)) = Nothing
_lazyInternalsVisibleToMap.TryGetValue(simpleName, result)
Return If(result IsNot Nothing, result.Keys, SpecializedCollections.EmptyEnumerable(Of ImmutableArray(Of Byte))())
End Function
Friend ReadOnly Property DeclaresTheObjectClass As Boolean
Get
If Me.CorLibrary IsNot Me Then
Return False
End If
Dim obj = GetSpecialType(SpecialType.System_Object)
Return Not obj.IsErrorType() AndAlso obj.DeclaredAccessibility = Accessibility.Public
End Get
End Property
Friend ReadOnly Property SourceModule As SourceModuleSymbol
Get
Return DirectCast(_modules(0), SourceModuleSymbol)
End Get
End Property
Public Overrides ReadOnly Property MightContainExtensionMethods As Boolean
Get
' Only primary module of an assembly marked with an Extension attribute
' can contain extension methods recognized by the language (Dev10 behavior).
Return SourceModule.MightContainExtensionMethods
End Get
End Property
Private Function ProcessOneInternalsVisibleToAttribute(nodeOpt As AttributeSyntax, attrData As VisualBasicAttributeData, diagnostics As DiagnosticBag) As Boolean
'assume that this code won't be called unless we bound a well-formed, semantically
'correct ctor call.
Dim displayName As String = TryCast(attrData.CommonConstructorArguments(0).Value, String)
If displayName Is Nothing Then
diagnostics.Add(ERRID.ERR_FriendAssemblyNameInvalid, If(nodeOpt IsNot Nothing, nodeOpt.GetLocation(), NoLocation.Singleton), displayName)
Return False
End If
Dim identity As AssemblyIdentity = Nothing
Dim parts As AssemblyIdentityParts = Nothing
If Not AssemblyIdentity.TryParseDisplayName(displayName, identity, parts) Then
diagnostics.Add(ERRID.ERR_FriendAssemblyNameInvalid, If(nodeOpt IsNot Nothing, nodeOpt.GetLocation(), NoLocation.Singleton), displayName)
Return False
End If
' Allow public key token due to compatibility reasons, but we are not going to use its value.
Const allowedParts = AssemblyIdentityParts.Name Or AssemblyIdentityParts.PublicKey Or AssemblyIdentityParts.PublicKeyToken
If (parts And Not allowedParts) <> 0 Then
diagnostics.Add(ERRID.ERR_FriendAssemblyBadArguments, If(nodeOpt IsNot Nothing, nodeOpt.GetLocation(), NoLocation.Singleton), displayName)
Return False
End If
If _lazyInternalsVisibleToMap Is Nothing Then
Interlocked.CompareExchange(_lazyInternalsVisibleToMap,
New ConcurrentDictionary(Of String, ConcurrentDictionary(Of ImmutableArray(Of Byte), Tuple(Of Location, String)))(StringComparer.OrdinalIgnoreCase), Nothing)
End If
'later, once the identity is established we confirm that if the assembly being
'compiled is signed all of the IVT attributes specify a key. Stash the location for that
' in the event that a diagnostic needs to be produced.
Dim locationAndValue As Tuple(Of Location, String) = Nothing
' only need to store anything when there is no public key. The only reason to store
' this stuff is for production of errors when the assembly is signed but the IVT attrib
' doesn't contain a public key.
If identity.PublicKey.IsEmpty Then
locationAndValue = New Tuple(Of Location, String)(If(nodeOpt IsNot Nothing, nodeOpt.GetLocation(), NoLocation.Singleton), displayName)
End If
'when two threads are attempting to update the internalsVisibleToMap one of these TryAdd()
'calls can fail. We assume that the 'other' thread in that case will successfully add the same
'contents eventually.
Dim keys As ConcurrentDictionary(Of ImmutableArray(Of Byte), Tuple(Of Location, String)) = Nothing
If _lazyInternalsVisibleToMap.TryGetValue(identity.Name, keys) Then
keys.TryAdd(identity.PublicKey, locationAndValue)
Else
keys = New ConcurrentDictionary(Of ImmutableArray(Of Byte), Tuple(Of Location, String))
keys.TryAdd(identity.PublicKey, locationAndValue)
_lazyInternalsVisibleToMap.TryAdd(identity.Name, keys)
End If
Return True
End Function
Friend Overrides Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation))
Dim attrData = arguments.Attribute
Debug.Assert(Not attrData.HasErrors)
Debug.Assert(arguments.SymbolPart = AttributeLocation.None)
If attrData.IsTargetAttribute(Me, AttributeDescription.CaseInsensitiveExtensionAttribute) Then
' Already have an attribute, no need to add another one.
Debug.Assert(_lazyEmitExtensionAttribute <> ThreeState.True)
_lazyEmitExtensionAttribute = ThreeState.False
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.InternalsVisibleToAttribute) Then
ProcessOneInternalsVisibleToAttribute(arguments.AttributeSyntaxOpt, attrData, arguments.Diagnostics)
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.AssemblySignatureKeyAttribute) Then
Dim signatureKey = DirectCast(attrData.CommonConstructorArguments(0).Value, String)
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().AssemblySignatureKeyAttributeSetting = signatureKey
If Not StrongNameKeys.IsValidPublicKeyString(signatureKey) Then
arguments.Diagnostics.Add(ERRID.ERR_InvalidSignaturePublicKey, GetAssemblyAttributeFirstArgumentLocation(arguments.AttributeSyntaxOpt))
End If
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.AssemblyKeyFileAttribute) Then
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().AssemblyKeyFileAttributeSetting = DirectCast(attrData.CommonConstructorArguments(0).Value, String)
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.AssemblyKeyNameAttribute) Then
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().AssemblyKeyContainerAttributeSetting = DirectCast(attrData.CommonConstructorArguments(0).Value, String)
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.AssemblyDelaySignAttribute) Then
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().AssemblyDelaySignAttributeSetting = If(DirectCast(attrData.CommonConstructorArguments(0).Value, Boolean), ThreeState.True, ThreeState.False)
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.AssemblyVersionAttribute) Then
Dim verString = DirectCast(attrData.CommonConstructorArguments(0).Value, String)
Dim version As Version = Nothing
If Not VersionHelper.TryParseAssemblyVersion(verString, allowWildcard:=Not _compilation.IsEmitDeterministic, version:=version) Then
arguments.Diagnostics.Add(ERRID.ERR_InvalidVersionFormat, GetAssemblyAttributeFirstArgumentLocation(arguments.AttributeSyntaxOpt))
End If
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().AssemblyVersionAttributeSetting = version
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.AssemblyFileVersionAttribute) Then
Dim dummy As Version = Nothing
Dim verString = DirectCast(attrData.CommonConstructorArguments(0).Value, String)
If Not VersionHelper.TryParse(verString, version:=dummy) Then
arguments.Diagnostics.Add(ERRID.WRN_InvalidVersionFormat, GetAssemblyAttributeFirstArgumentLocation(arguments.AttributeSyntaxOpt))
End If
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().AssemblyFileVersionAttributeSetting = verString
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.AssemblyInformationalVersionAttribute) Then
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().AssemblyInformationalVersionAttributeSetting = DirectCast(attrData.CommonConstructorArguments(0).Value, String)
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.AssemblyTitleAttribute) Then
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().AssemblyTitleAttributeSetting = DirectCast(attrData.CommonConstructorArguments(0).Value, String)
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.AssemblyDescriptionAttribute) Then
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().AssemblyDescriptionAttributeSetting = DirectCast(attrData.CommonConstructorArguments(0).Value, String)
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.AssemblyCultureAttribute) Then
Dim cultureString = DirectCast(attrData.CommonConstructorArguments(0).Value, String)
If Not String.IsNullOrEmpty(cultureString) Then
If Me.DeclaringCompilation.Options.OutputKind.IsApplication() Then
arguments.Diagnostics.Add(ERRID.ERR_InvalidAssemblyCultureForExe, GetAssemblyAttributeFirstArgumentLocation(arguments.AttributeSyntaxOpt))
ElseIf Not AssemblyIdentity.IsValidCultureName(cultureString) Then
arguments.Diagnostics.Add(ERRID.ERR_InvalidAssemblyCulture, GetAssemblyAttributeFirstArgumentLocation(arguments.AttributeSyntaxOpt))
cultureString = Nothing
End If
End If
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().AssemblyCultureAttributeSetting = cultureString
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.AssemblyCompanyAttribute) Then
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().AssemblyCompanyAttributeSetting = DirectCast(attrData.CommonConstructorArguments(0).Value, String)
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.AssemblyProductAttribute) Then
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().AssemblyProductAttributeSetting = DirectCast(attrData.CommonConstructorArguments(0).Value, String)
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.AssemblyInformationalVersionAttribute) Then
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().AssemblyInformationalVersionAttributeSetting = DirectCast(attrData.CommonConstructorArguments(0).Value, String)
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SatelliteContractVersionAttribute) Then
'just check the format of this one, don't do anything else with it.
Dim dummy As Version = Nothing
Dim verString = DirectCast(attrData.CommonConstructorArguments(0).Value, String)
If Not VersionHelper.TryParseAssemblyVersion(verString, allowWildcard:=False, version:=dummy) Then
arguments.Diagnostics.Add(ERRID.ERR_InvalidVersionFormat2, GetAssemblyAttributeFirstArgumentLocation(arguments.AttributeSyntaxOpt))
End If
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.AssemblyCopyrightAttribute) Then
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().AssemblyCopyrightAttributeSetting = DirectCast(attrData.CommonConstructorArguments(0).Value, String)
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.AssemblyTrademarkAttribute) Then
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().AssemblyTrademarkAttributeSetting = DirectCast(attrData.CommonConstructorArguments(0).Value, String)
ElseIf attrData.IsSecurityAttribute(Me.DeclaringCompilation) Then
attrData.DecodeSecurityAttribute(Of CommonAssemblyWellKnownAttributeData)(Me, Me.DeclaringCompilation, arguments)
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.ClassInterfaceAttribute) Then
attrData.DecodeClassInterfaceAttribute(arguments.AttributeSyntaxOpt, arguments.Diagnostics)
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.TypeLibVersionAttribute) Then
ValidateIntegralAttributeNonNegativeArguments(attrData, arguments.AttributeSyntaxOpt, arguments.Diagnostics)
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.ComCompatibleVersionAttribute) Then
ValidateIntegralAttributeNonNegativeArguments(attrData, arguments.AttributeSyntaxOpt, arguments.Diagnostics)
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.GuidAttribute) Then
attrData.DecodeGuidAttribute(arguments.AttributeSyntaxOpt, arguments.Diagnostics)
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.CompilationRelaxationsAttribute) Then
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().HasCompilationRelaxationsAttribute = True
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.ReferenceAssemblyAttribute) Then
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().HasReferenceAssemblyAttribute = True
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.RuntimeCompatibilityAttribute) Then
' VB doesn't need to decode argument values
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().RuntimeCompatibilityWrapNonExceptionThrows = True
ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.DebuggableAttribute) Then
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().HasDebuggableAttribute = True
Else
Dim signature As Integer = attrData.GetTargetAttributeSignatureIndex(Me, AttributeDescription.AssemblyAlgorithmIdAttribute)
If signature <> -1 Then
Dim value As Object = attrData.CommonConstructorArguments(0).Value
Dim algorithmId As AssemblyHashAlgorithm
If signature = 0 Then
algorithmId = CType(value, AssemblyHashAlgorithm)
Else
algorithmId = CType(CUInt(value), AssemblyHashAlgorithm)
End If
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().AssemblyAlgorithmIdAttributeSetting = algorithmId
Else
signature = attrData.GetTargetAttributeSignatureIndex(Me, AttributeDescription.AssemblyFlagsAttribute)
If signature <> -1 Then
Dim value As Object = attrData.CommonConstructorArguments(0).Value
Dim nameFlags As AssemblyFlags
If signature = 0 OrElse signature = 1 Then
nameFlags = CType(CType(value, AssemblyNameFlags), AssemblyFlags)
Else
nameFlags = CType(CUInt(value), AssemblyFlags)
End If
arguments.GetOrCreateData(Of CommonAssemblyWellKnownAttributeData)().AssemblyFlagsAttributeSetting = nameFlags
End If
End If
End If
MyBase.DecodeWellKnownAttribute(arguments)
End Sub
Private Shared Function GetAssemblyAttributeFirstArgumentLocation(attributeSyntaxOpt As AttributeSyntax) As Location
If attributeSyntaxOpt Is Nothing Then
Return NoLocation.Singleton
End If
Return attributeSyntaxOpt.ArgumentList.Arguments.First().GetLocation()
End Function
' Checks that the integral arguments for the given well-known attribute are non-negative.
Private Sub ValidateIntegralAttributeNonNegativeArguments(attrData As VisualBasicAttributeData, nodeOpt As AttributeSyntax, diagnostics As DiagnosticBag)
Debug.Assert(Not attrData.HasErrors)
Dim argCount As Integer = attrData.CommonConstructorArguments.Length
For i = 0 To argCount - 1
Dim arg As Integer = attrData.GetConstructorArgument(Of Integer)(i, SpecialType.System_Int32)
If arg < 0 Then
diagnostics.Add(ERRID.ERR_BadAttribute1, If(nodeOpt IsNot Nothing, nodeOpt.ArgumentList.Arguments(i).GetLocation(), NoLocation.Singleton), attrData.AttributeClass)
End If
Next
End Sub
Friend Sub AnErrorHasBeenReportedAboutExtensionAttribute()
' Note, we are storing false because, even though we might be required to emit the attribute,
' we can't do that due to the error that we just reported.
Debug.Assert(_lazyEmitExtensionAttribute <> ThreeState.True)
_lazyEmitExtensionAttribute = ThreeState.False
End Sub
Friend Function GetAllDeclarationErrors(Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic)
Dim hasExtensionMethods As Boolean = False
Dim moduleErrors = SourceModule.GetAllDeclarationErrors(cancellationToken, hasExtensionMethods)
Return moduleErrors.Concat(GetAssemblyLevelDeclarationErrors(hasExtensionMethods))
End Function
''' <summary>
''' Get assembly level declaration errors.
''' </summary>
Private Function GetAssemblyLevelDeclarationErrors(
haveExtensionMethodsInSource As Boolean) As ImmutableArray(Of Diagnostic)
If _lazyAssemblyLevelDeclarationErrors.IsDefault Then
Dim diagnostics = DiagnosticBag.GetInstance()
Dim emitExtensionAttribute As ThreeState = CType(_lazyEmitExtensionAttribute, ThreeState)
If emitExtensionAttribute = ThreeState.Unknown Then
Dim needAttribute As Boolean = haveExtensionMethodsInSource
If Not needAttribute Then
emitExtensionAttribute = ThreeState.False
Else
' We need to emit an Extension attribute on the assembly.
' Can we locate it?
Dim useSiteError As DiagnosticInfo = Nothing
_compilation.GetExtensionAttributeConstructor(useSiteError:=useSiteError)
If useSiteError IsNot Nothing Then
' Note, we are storing false because, even though we should emit the attribute,
' we can't do that due to the use site error.
' The diagnostic itself was already reported at the location where the attribute was applied to.
' Reporting it also on a place where it's implicitly used would not be expected by developers.
emitExtensionAttribute = ThreeState.False
Else
emitExtensionAttribute = ThreeState.True
End If
End If
End If
Debug.Assert(_lazyEmitExtensionAttribute = ThreeState.Unknown OrElse
_lazyEmitExtensionAttribute = emitExtensionAttribute)
_lazyEmitExtensionAttribute = emitExtensionAttribute
'strong name key settings are not validated when building netmodules.
'They are validated when the netmodule is added to an assembly.
If StrongNameKeys.DiagnosticOpt IsNot Nothing AndAlso Not DeclaringCompilation.Options.OutputKind.IsNetModule() Then
diagnostics.Add(StrongNameKeys.DiagnosticOpt)
End If
ValidateIVTPublicKeys(diagnostics)
CheckOptimisticIVTAccessGrants(diagnostics)
DetectAttributeAndOptionConflicts(diagnostics)
If IsDelaySigned AndAlso Not Identity.HasPublicKey Then
diagnostics.Add(ERRID.WRN_DelaySignButNoKey, NoLocation.Singleton)
End If
If DeclaringCompilation.Options.PublicSign Then
If DeclaringCompilation.Options.OutputKind.IsNetModule() Then
diagnostics.Add(ERRID.ERR_PublicSignNetModule, NoLocation.Singleton)
ElseIf Not Identity.HasPublicKey Then
diagnostics.Add(ERRID.ERR_PublicSignNoKey, NoLocation.Singleton)
End If
End If
' If the options and attributes applied on the compilation imply real signing,
' but we have no private key to sign it with report an error.
' Note that if public key is set and delay sign is off we do OSS signing, which doesn't require private key.
' Consider: should we allow to OSS sign if the key file only contains public key?
If DeclaringCompilation.Options.OutputKind <> OutputKind.NetModule AndAlso
DeclaringCompilation.Options.CryptoPublicKey.IsEmpty AndAlso
Identity.HasPublicKey AndAlso
Not IsDelaySigned AndAlso
Not DeclaringCompilation.Options.PublicSign AndAlso
Not StrongNameKeys.CanSign Then
' Since the container always contains both keys, the problem is that the key file didn't contain private key.
diagnostics.Add(ERRID.ERR_SignButNoPrivateKey, NoLocation.Singleton, StrongNameKeys.KeyFilePath)
End If
ReportDiagnosticsForSynthesizedAttributes(DeclaringCompilation, diagnostics)
ReportDiagnosticsForAddedModules(diagnostics)
ImmutableInterlocked.InterlockedInitialize(_lazyAssemblyLevelDeclarationErrors, diagnostics.ToReadOnlyAndFree(Of Diagnostic)())
End If
Return _lazyAssemblyLevelDeclarationErrors
End Function
Private Sub DetectAttributeAndOptionConflicts(diagnostics As DiagnosticBag)
EnsureAttributesAreBound()
If _compilation.Options.PublicSign AndAlso DelaySignAttributeSetting Then
diagnostics.Add(ERRID.ERR_CmdOptionConflictsSource, NoLocation.Singleton,
AttributeDescription.AssemblyDelaySignAttribute.FullName,
NameOf(_compilation.Options.PublicSign))
End If
If _compilation.Options.OutputKind = OutputKind.NetModule Then
If Not String.IsNullOrEmpty(_compilation.Options.CryptoKeyContainer) Then
Dim assemblyKeyContainerAttributeSetting As String = Me.AssemblyKeyContainerAttributeSetting
If assemblyKeyContainerAttributeSetting Is CommonAssemblyWellKnownAttributeData.StringMissingValue Then
' We need to synthesize this attribute for .NET module,
' touch the constructor in order to generate proper use-site diagnostics
Binder.ReportUseSiteErrorForSynthesizedAttribute(
WellKnownMember.System_Reflection_AssemblyKeyNameAttribute__ctor,
_compilation,
NoLocation.Singleton,
diagnostics)
ElseIf String.Compare(_compilation.Options.CryptoKeyContainer, assemblyKeyContainerAttributeSetting, StringComparison.OrdinalIgnoreCase) <> 0 Then
' If we are building a .NET module, things get more complicated. In particular, we don't sign the module, we emit an attribute with the key
' information, which will be used to sign an assembly once the module is linked into it. If there is already an attribute like that in source,
' native compiler emits both of them, synthetic attribute is emitted after the one from source. Incidentally, ALink picks the last attribute
' for signing and things seem to work out. However, relying on the order of attributes feels fragile, especially given that Roslyn emits
' synthetic attributes before attributes from source. The behavior we settled on for .NET modules is that, if the attribute in source has the
' same value as the one in compilation options, we won't emit the synthetic attribute. If the value doesn't match, we report an error, which
' is a breaking change. Bottom line, we will never produce a module or an assembly with two attributes, regardless whether values are the same
' or not.
diagnostics.Add(ERRID.ERR_CmdOptionConflictsSource, NoLocation.Singleton, AttributeDescription.AssemblyKeyNameAttribute.FullName, "CryptoKeyContainer")
End If
End If
If Not String.IsNullOrEmpty(_compilation.Options.CryptoKeyFile) Then
Dim assemblyKeyFileAttributeSetting As String = Me.AssemblyKeyFileAttributeSetting
If assemblyKeyFileAttributeSetting Is CommonAssemblyWellKnownAttributeData.StringMissingValue Then
' We need to synthesize this attribute for .NET module,
' touch the constructor in order to generate proper use-site diagnostics
Binder.ReportUseSiteErrorForSynthesizedAttribute(
WellKnownMember.System_Reflection_AssemblyKeyFileAttribute__ctor,
_compilation,
NoLocation.Singleton,
diagnostics)
ElseIf String.Compare(_compilation.Options.CryptoKeyFile, assemblyKeyFileAttributeSetting, StringComparison.OrdinalIgnoreCase) <> 0 Then
' Comment in similar section for CryptoKeyContainer is applicable here as well.
diagnostics.Add(ERRID.ERR_CmdOptionConflictsSource, NoLocation.Singleton, AttributeDescription.AssemblyKeyFileAttribute.FullName, "CryptoKeyFile")
End If
End If
ElseIf _compilation.Options.PublicSign Then
If Me.AssemblyKeyContainerAttributeSetting IsNot CommonAssemblyWellKnownAttributeData.StringMissingValue Then
diagnostics.Add(ERRID.WRN_AttributeIgnoredWhenPublicSigning, NoLocation.Singleton, AttributeDescription.AssemblyKeyNameAttribute.FullName)
End If
If Me.AssemblyKeyFileAttributeSetting IsNot CommonAssemblyWellKnownAttributeData.StringMissingValue Then
diagnostics.Add(ERRID.WRN_AttributeIgnoredWhenPublicSigning, NoLocation.Singleton, AttributeDescription.AssemblyKeyFileAttribute.FullName)
End If
End If
End Sub
Private Sub ReportDiagnosticsForAddedModules(diagnostics As DiagnosticBag)
For Each pair In _compilation.GetBoundReferenceManager().ReferencedModuleIndexMap
Dim fileRef = TryCast(pair.Key, PortableExecutableReference)
If fileRef IsNot Nothing AndAlso fileRef.FilePath IsNot Nothing Then
Dim fileName As String = FileNameUtilities.GetFileName(fileRef.FilePath)
Dim moduleName As String = _modules(pair.Value).Name
If Not String.Equals(fileName, moduleName, StringComparison.OrdinalIgnoreCase) Then
' Used to be ERR_UnableToEmitAssembly
diagnostics.Add(ERRID.ERR_NetModuleNameMismatch, NoLocation.Singleton, moduleName, fileName)
End If
End If
Next
' Alink performed these checks only when emitting an assembly.
If _modules.Length > 1 AndAlso Not _compilation.Options.OutputKind.IsNetModule() Then
Dim assemblyMachine = Me.Machine
Dim isPlatformAgnostic As Boolean = (assemblyMachine = PortableExecutable.Machine.I386 AndAlso Not Me.Bit32Required)
Dim knownModuleNames As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase)
For i As Integer = 1 To Modules.Length - 1
Dim m As ModuleSymbol = Modules(i)
If Not knownModuleNames.Add(m.Name) Then
diagnostics.Add(ERRID.ERR_NetModuleNameMustBeUnique, NoLocation.Singleton, m.Name)
End If
If Not DirectCast(m, PEModuleSymbol).Module.IsCOFFOnly Then
Dim moduleMachine = m.Machine
If moduleMachine = PortableExecutable.Machine.I386 AndAlso Not m.Bit32Required Then
' Other module is agnostic, this is always safe
ElseIf isPlatformAgnostic Then
diagnostics.Add(ERRID.ERR_AgnosticToMachineModule, NoLocation.Singleton, m)
ElseIf assemblyMachine <> moduleMachine Then
' Different machine types, and neither is agnostic
' So it is a conflict
diagnostics.Add(ERRID.ERR_ConflictingMachineModule, NoLocation.Singleton, m)
End If
End If
Next
' Assembly main module must explicitly reference all the modules referenced by other assembly
' modules, i.e. all modules from transitive closure must be referenced explicitly here
For i As Integer = 1 To Modules.Length - 1
Dim m = DirectCast(Modules(i), PEModuleSymbol)
Try
For Each referencedModuleName In m.Module.GetReferencedManagedModulesOrThrow()
' Do not report error for this module twice
If knownModuleNames.Add(referencedModuleName) Then
diagnostics.Add(ERRID.ERR_MissingNetModuleReference, NoLocation.Singleton, referencedModuleName)
End If
Next
Catch mrEx As BadImageFormatException
diagnostics.Add(ERRID.ERR_UnsupportedModule1, NoLocation.Singleton, m)
End Try
Next
End If
End Sub
Friend ReadOnly Property IsDelaySigned As Boolean
Get
EnsureAttributesAreBound()
'TODO need to figure out the right behavior when command line and
'attribute value conflict. Does command line setting need to be three-valued?
If (DeclaringCompilation.Options.DelaySign.HasValue) Then
Return DeclaringCompilation.Options.DelaySign.Value
End If
Return DelaySignAttributeSetting
End Get
End Property
Protected Sub ValidateIVTPublicKeys(diagnostics As DiagnosticBag)
EnsureAttributesAreBound()
If Not Me.Identity.IsStrongName Then
Return
End If
If _lazyInternalsVisibleToMap IsNot Nothing Then
For Each keys In _lazyInternalsVisibleToMap.Values
For Each oneKey In keys
If oneKey.Key.IsDefaultOrEmpty Then
diagnostics.Add(ERRID.ERR_FriendAssemblyStrongNameRequired, oneKey.Value.Item1, oneKey.Value.Item2)
End If
Next
Next
End If
End Sub
''' <summary>
''' True if internals are exposed at all.
''' </summary>
''' <remarks>
''' Forces binding and decoding of attributes.
''' This property shouldn't be accessed during binding as it can lead to attribute binding cycle.
''' </remarks>
Public ReadOnly Property InternalsAreVisible As Boolean Implements ISourceAssemblySymbolInternal.InternalsAreVisible
Get
EnsureAttributesAreBound()
Return _lazyInternalsVisibleToMap IsNot Nothing
End Get
End Property
''' <summary>
''' We may synthesize some well-known attributes for this assembly symbol. However, at synthesis time, it is
''' too late to report diagnostics or cancel the emit. Instead, we check for use site errors on the types and members
''' we know we'll need at synthesis time.
''' </summary>
Private Shared Sub ReportDiagnosticsForSynthesizedAttributes(compilation As VisualBasicCompilation, diagnostics As DiagnosticBag)
' May need to synthesize CompilationRelaxationsAttribute and/or RuntimeCompatibilityAttribute if we are not building a net-module.
' NOTE: Native compiler skips synthesizing these attributes if the respective well-known attribute types aren't available, we do the same.
Dim compilationOptions As VisualBasicCompilationOptions = compilation.Options
If Not compilationOptions.OutputKind.IsNetModule() Then
Dim compilationRelaxationsAttributeType = compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_CompilationRelaxationsAttribute)
If TryCast(compilationRelaxationsAttributeType, MissingMetadataTypeSymbol) Is Nothing Then
Binder.ReportUseSiteErrorForSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilationRelaxationsAttribute__ctorInt32, compilation, NoLocation.Singleton, diagnostics)
End If
Dim runtimeCompatibilityAttributeType = compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute)
If TryCast(runtimeCompatibilityAttributeType, MissingMetadataTypeSymbol) Is Nothing Then
Binder.ReportUseSiteErrorForSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__ctor, compilation, NoLocation.Singleton, diagnostics)
Binder.ReportUseSiteErrorForSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__WrapNonExceptionThrows, compilation, NoLocation.Singleton, diagnostics)
End If
End If
End Sub
Private ReadOnly Property HasAssemblyOrModuleDebuggableAttribute As Boolean
Get
Dim assemblyData As CommonAssemblyWellKnownAttributeData = Me.GetSourceDecodedWellKnownAttributeData()
If assemblyData IsNot Nothing AndAlso assemblyData.HasDebuggableAttribute Then
Return True
End If
Dim moduleData As CommonModuleWellKnownAttributeData = Me.SourceModule.GetDecodedWellKnownAttributeData()
If moduleData IsNot Nothing AndAlso moduleData.HasDebuggableAttribute Then
Return True
End If
Return False
End Get
End Property
Private ReadOnly Property HasReferenceAssemblyAttribute As Boolean
Get
Dim assemblyData As CommonAssemblyWellKnownAttributeData = Me.GetSourceDecodedWellKnownAttributeData()
Return assemblyData IsNot Nothing AndAlso assemblyData.HasReferenceAssemblyAttribute
End Get
End Property
Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))
MyBase.AddSynthesizedAttributes(compilationState, attributes)
Debug.Assert(_lazyEmitExtensionAttribute <> ThreeState.Unknown)
Debug.Assert(_lazySourceAttributesBag.IsSealed)
Dim options As VisualBasicCompilationOptions = Me.DeclaringCompilation.Options
Dim isBuildingNetModule As Boolean = options.OutputKind.IsNetModule()
Dim emitExtensionAttribute As Boolean = _lazyEmitExtensionAttribute = ThreeState.True
If emitExtensionAttribute Then
AddSynthesizedAttribute(attributes, _compilation.SynthesizeExtensionAttribute())
End If
' Note that manager's collection of referenced symbols may not be sealed
' yet in case this and previous emits didn't emit IL, but only metadata
Dim emitEmbeddedAttribute As Boolean = Me.DeclaringCompilation.EmbeddedSymbolManager.IsAnySymbolReferenced
If emitEmbeddedAttribute Then
AddSynthesizedAttribute(attributes, DeclaringCompilation.TrySynthesizeAttribute(WellKnownMember.Microsoft_VisualBasic_Embedded__ctor))
End If
' Synthesize CompilationRelaxationsAttribute only if all the following requirements are met:
' (a) We are not building a netmodule.
' (b) There is no applied CompilationRelaxationsAttribute assembly attribute in source.
' (c) There is no applied CompilationRelaxationsAttribute assembly attribute for any of the added PE modules.
' Above requirements also hold for synthesizing RuntimeCompatibilityAttribute attribute.
Dim emitCompilationRelaxationsAttribute As Boolean = Not isBuildingNetModule AndAlso Not Me.Modules.Any(Function(m) m.HasAssemblyCompilationRelaxationsAttribute)
If emitCompilationRelaxationsAttribute Then
' Synthesize attribute: <CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning)>
' NOTE: Native compiler skips synthesizing these attributes if the respective well-known attribute types aren't available, we do the same.
Dim compilationRelaxationsAttributeType = DeclaringCompilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_CompilationRelaxationsAttribute)
If TryCast(compilationRelaxationsAttributeType, MissingMetadataTypeSymbol) Is Nothing Then
Dim int32Type = Me.DeclaringCompilation.GetSpecialType(SpecialType.System_Int32)
Debug.Assert(int32Type.GetUseSiteErrorInfo() Is Nothing, "Use site errors should have been checked ahead of time (type int).")
Dim typedConstantNoStringInterning = New TypedConstant(int32Type, TypedConstantKind.Primitive, Cci.Constants.CompilationRelaxations_NoStringInterning)
AddSynthesizedAttribute(attributes, DeclaringCompilation.TrySynthesizeAttribute(
WellKnownMember.System_Runtime_CompilerServices_CompilationRelaxationsAttribute__ctorInt32,
ImmutableArray.Create(typedConstantNoStringInterning)))
End If
End If
Dim emitRuntimeCompatibilityAttribute As Boolean = Not isBuildingNetModule AndAlso Not Me.Modules.Any(Function(m) m.HasAssemblyRuntimeCompatibilityAttribute)
If emitRuntimeCompatibilityAttribute Then
' Synthesize attribute: <RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)>
' NOTE: Native compiler skips synthesizing these attributes if the respective well-known attribute types aren't available, we do the same.
Dim runtimeCompatibilityAttributeType = DeclaringCompilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute)
If TryCast(runtimeCompatibilityAttributeType, MissingMetadataTypeSymbol) Is Nothing Then
Dim boolType = Me.DeclaringCompilation.GetSpecialType(SpecialType.System_Boolean)
Debug.Assert(boolType.GetUseSiteErrorInfo() Is Nothing, "Use site errors should have been checked ahead of time (type bool).")
Dim typedConstantTrue = New TypedConstant(boolType, TypedConstantKind.Primitive, True)
AddSynthesizedAttribute(attributes, DeclaringCompilation.TrySynthesizeAttribute(
WellKnownMember.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__ctor,
ImmutableArray(Of TypedConstant).Empty,
ImmutableArray.Create(New KeyValuePair(Of WellKnownMember, TypedConstant)(
WellKnownMember.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__WrapNonExceptionThrows, typedConstantTrue))))
End If
End If
' Synthesize DebuggableAttribute only if all the following requirements are met:
' (a) We are not building a netmodule.
' (b) We are emitting debug information (full or pdbonly).
' (c) There is no applied DebuggableAttribute assembly attribute in source.
' (d) There is no applied DebuggableAttribute module attribute in source (NOTE: Native C# compiler and Roslyn C# compiler doesn't check this).
If Not isBuildingNetModule AndAlso Not Me.HasAssemblyOrModuleDebuggableAttribute Then
' Synthesize attribute: <DebuggableAttribute(DebuggableAttribute.DebuggingMode.<Value>)>
Dim int32Type = Me.DeclaringCompilation.GetSpecialType(SpecialType.System_Int32)
If int32Type.GetUseSiteErrorInfo() Is Nothing Then
Dim debuggingMode = DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints
' Since .NET 2.0 the combinations of None, Default And DisableOptimizations have the following effect
'
' None JIT optimizations enabled
' Default JIT optimizations enabled
' DisableOptimizations JIT optimizations enabled
' Default | DisableOptimizations JIT optimizations disabled
If options.OptimizationLevel = OptimizationLevel.Debug Then
debuggingMode = debuggingMode Or DebuggableAttribute.DebuggingModes.Default Or
DebuggableAttribute.DebuggingModes.DisableOptimizations
End If
If options.EnableEditAndContinue Then
debuggingMode = debuggingMode Or DebuggableAttribute.DebuggingModes.EnableEditAndContinue
End If
Dim typedConstantDebugMode = New TypedConstant(int32Type, TypedConstantKind.Enum, CInt(debuggingMode))
AddSynthesizedAttribute(attributes, DeclaringCompilation.TrySynthesizeAttribute(
WellKnownMember.System_Diagnostics_DebuggableAttribute__ctorDebuggingModes,
ImmutableArray.Create(typedConstantDebugMode)))
End If
End If
If _compilation.Options.OutputKind = OutputKind.NetModule Then
' If the attribute is applied in source, do not add synthetic one.
' If its value is different from the supplied through options, an error should have been reported by now.
If Not String.IsNullOrEmpty(_compilation.Options.CryptoKeyContainer) AndAlso
AssemblyKeyContainerAttributeSetting Is CommonAssemblyWellKnownAttributeData.StringMissingValue Then
Dim stringType = _compilation.GetSpecialType(SpecialType.System_String)
Debug.Assert(stringType.GetUseSiteErrorInfo Is Nothing, "Use site errors should have been checked ahead of time (type string).")
Dim typedConstant = New TypedConstant(stringType, TypedConstantKind.Primitive, _compilation.Options.CryptoKeyContainer)
AddSynthesizedAttribute(attributes, _compilation.TrySynthesizeAttribute(WellKnownMember.System_Reflection_AssemblyKeyNameAttribute__ctor, ImmutableArray.Create(typedConstant)))
End If
If Not String.IsNullOrEmpty(_compilation.Options.CryptoKeyFile) AndAlso
AssemblyKeyFileAttributeSetting Is CommonAssemblyWellKnownAttributeData.StringMissingValue Then
Dim stringType = _compilation.GetSpecialType(SpecialType.System_String)
Debug.Assert(stringType.GetUseSiteErrorInfo Is Nothing, "Use site errors should have been checked ahead of time (type string).")
Dim typedConstant = New TypedConstant(stringType, TypedConstantKind.Primitive, _compilation.Options.CryptoKeyFile)
AddSynthesizedAttribute(attributes, _compilation.TrySynthesizeAttribute(WellKnownMember.System_Reflection_AssemblyKeyFileAttribute__ctor, ImmutableArray.Create(typedConstant)))
End If
End If
End Sub
Friend Overrides ReadOnly Property PublicKey As ImmutableArray(Of Byte)
Get
Return StrongNameKeys.PublicKey
End Get
End Property
Friend Overrides Function AreInternalsVisibleToThisAssembly(potentialGiverOfAccess As AssemblySymbol) As Boolean
' Ensure that optimistic IVT access is only granted to requests that originated on the thread
' that is trying to compute the assembly identity. This gives us deterministic behavior when
' two threads are checking IVT access but only one of them is in the process of computing identity.
'as an optimization confirm that the identity has not yet been computed to avoid testing TLS
If _lazyStrongNameKeys Is Nothing Then
Dim assemblyWhoseKeysAreBeingComputed = s_AssemblyForWhichCurrentThreadIsComputingKeys
If assemblyWhoseKeysAreBeingComputed IsNot Nothing Then
Debug.Assert(assemblyWhoseKeysAreBeingComputed Is Me)
If Not potentialGiverOfAccess.GetInternalsVisibleToPublicKeys(Me.Name).IsEmpty() Then
If _optimisticallyGrantedInternalsAccess Is Nothing Then
Interlocked.CompareExchange(_optimisticallyGrantedInternalsAccess, New ConcurrentDictionary(Of AssemblySymbol, Boolean), Nothing)
End If
_optimisticallyGrantedInternalsAccess.TryAdd(potentialGiverOfAccess, True)
Return True
Else
Return False
End If
End If
End If
Return MakeFinalIVTDetermination(potentialGiverOfAccess) = IVTConclusion.Match
End Function
Friend ReadOnly Property StrongNameKeys As StrongNameKeys
Get
If _lazyStrongNameKeys Is Nothing Then
Try
Debug.Assert(s_AssemblyForWhichCurrentThreadIsComputingKeys Is Nothing)
s_AssemblyForWhichCurrentThreadIsComputingKeys = Me
ComputeAndSetStrongNameKeys()
Finally
s_AssemblyForWhichCurrentThreadIsComputingKeys = Nothing
End Try
End If
Return _lazyStrongNameKeys
End Get
End Property
Private Sub ComputeAndSetStrongNameKeys()
' TODO
' In order to allow users to escape problems that we create with our provisional granting of IVT access,
' consider not binding the attributes if the command line options were specified, then later bind them
' and report warnings if both were used.
' make sure keycontainer and keyfile attribute contents fields will be set
EnsureAttributesAreBound()
' Creating strong names is a potentially expensive operation, so we will check
' if keys could have been created and published already.
If _lazyStrongNameKeys IsNot Nothing Then
Return
End If
Dim keys As StrongNameKeys
Dim keyFile As String = _compilation.Options.CryptoKeyFile
' Public sign requires a keyfile
If DeclaringCompilation.Options.PublicSign Then
If Not String.IsNullOrEmpty(keyFile) AndAlso Not PathUtilities.IsAbsolute(keyFile) Then
' If keyFile has a relative path then there should be a diagnostic
' about it
Debug.Assert(Not DeclaringCompilation.Options.Errors.IsEmpty)
keys = StrongNameKeys.None
Else
keys = StrongNameKeys.Create(keyFile, MessageProvider.Instance)
End If
' Public signing doesn't require a strong name provider to be used.
Interlocked.CompareExchange(_lazyStrongNameKeys, keys, Nothing)
Return
End If
' when both attributes and command-line options specified, cmd line wins.
If String.IsNullOrEmpty(keyFile) Then
keyFile = Me.AssemblyKeyFileAttributeSetting
If keyFile Is CommonAssemblyWellKnownAttributeData.StringMissingValue Then
keyFile = Nothing
End If
End If
Dim keyContainer As String = _compilation.Options.CryptoKeyContainer
If String.IsNullOrEmpty(keyContainer) Then
keyContainer = Me.AssemblyKeyContainerAttributeSetting
If keyContainer Is CommonAssemblyWellKnownAttributeData.StringMissingValue Then
keyContainer = Nothing
End If
End If
keys = StrongNameKeys.Create(DeclaringCompilation.Options.StrongNameProvider, keyFile, keyContainer, MessageProvider.Instance)
Interlocked.CompareExchange(_lazyStrongNameKeys, keys, Nothing)
End Sub
Private Function ComputeIdentity() As AssemblyIdentity
EnsureAttributesAreBound()
Return New AssemblyIdentity(_assemblySimpleName,
VersionHelper.GenerateVersionFromPatternAndCurrentTime(_compilation.Options.CurrentLocalTime, AssemblyVersionAttributeSetting),
Me.AssemblyCultureAttributeSetting,
StrongNameKeys.PublicKey,
hasPublicKey:=Not StrongNameKeys.PublicKey.IsDefault)
End Function
Friend ReadOnly Property IsVbRuntime As Boolean
Get
If Me._lazyIsVbRuntime = ThreeState.Unknown Then
Me._lazyIsVbRuntime = CheckForRuntime().ToThreeState
End If
Return Me._lazyIsVbRuntime = ThreeState.True
End Get
End Property
Private Function CheckForRuntime() As Boolean
Dim stdmodule = Me.DeclaringCompilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute)
Return Not stdmodule.IsErrorType AndAlso
Not stdmodule.IsEmbedded AndAlso
stdmodule.ContainingAssembly Is Me
End Function
Friend Overrides Function TryLookupForwardedMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), ignoreCase As Boolean) As NamedTypeSymbol
If Not _compilation.Options.OutputKind.IsNetModule() Then
' See if any of added modules forward the type.
Dim matchedName As String = Nothing
' Similar to attributes, type forwarders from the second added module should override type forwarders from the first added module, etc.
For i As Integer = _modules.Length - 1 To 1 Step -1
Dim peModuleSymbol = DirectCast(_modules(i), PEModuleSymbol)
Dim forwardedToAssemblies = peModuleSymbol.GetAssembliesForForwardedType(emittedName, ignoreCase, matchedName)
If forwardedToAssemblies.FirstSymbol IsNot Nothing Then
If forwardedToAssemblies.SecondSymbol IsNot Nothing Then
Return CreateMultipleForwardingErrorTypeSymbol(emittedName, peModuleSymbol, forwardedToAssemblies.FirstSymbol, forwardedToAssemblies.SecondSymbol)
End If
' Don't bother to check the forwarded-to assembly if we've already seen it.
If visitedAssemblies IsNot Nothing AndAlso visitedAssemblies.Contains(forwardedToAssemblies.FirstSymbol) Then
Return CreateCycleInTypeForwarderErrorTypeSymbol(emittedName)
Else
visitedAssemblies = New ConsList(Of AssemblySymbol)(Me, If(visitedAssemblies, ConsList(Of AssemblySymbol).Empty))
If ignoreCase AndAlso Not String.Equals(emittedName.FullName, matchedName, StringComparison.Ordinal) Then
emittedName = MetadataTypeName.FromFullName(matchedName, emittedName.UseCLSCompliantNameArityEncoding, emittedName.ForcedArity)
End If
Return forwardedToAssemblies.FirstSymbol.LookupTopLevelMetadataTypeWithCycleDetection(emittedName, visitedAssemblies, digThroughForwardedTypes:=True)
End If
End If
Next
End If
Return Nothing
End Function
Public Overrides Function GetMetadata() As AssemblyMetadata
Return Nothing
End Function
Private ReadOnly Property ISourceAssemblySymbol_Compilation As Compilation Implements ISourceAssemblySymbol.Compilation
Get
Return _compilation
End Get
End Property
End Class
End Namespace
|
jkotas/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/Source/SourceAssemblySymbol.vb
|
Visual Basic
|
apache-2.0
| 100,422
|
' 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.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
Partial Friend Class Binder
#Region "Bind select case statement"
Private Function BindSelectBlock(node As SelectBlockSyntax, diagnostics As BindingDiagnosticBag) As BoundStatement
Debug.Assert(node IsNot Nothing)
' Bind select expression
Dim selectExprStatementSyntax = node.SelectStatement
Dim expression = BindSelectExpression(selectExprStatementSyntax.Expression, diagnostics)
If expression.HasErrors Then
diagnostics = BindingDiagnosticBag.Discarded
End If
Dim exprPlaceHolder = New BoundRValuePlaceholder(selectExprStatementSyntax.Expression, expression.Type)
exprPlaceHolder.SetWasCompilerGenerated()
Dim expressionStmt = New BoundExpressionStatement(selectExprStatementSyntax, expression)
' Get the binder for the select block. This defines the exit label.
Dim selectBinder = GetBinder(DirectCast(node, VisualBasicSyntaxNode))
' Flag to determine if we need to generate switch table based code or If list based code.
' See OptimizeSelectStatement method for more details.
Dim recommendSwitchTable = False
' Bind case blocks.
Dim caseBlocks As ImmutableArray(Of BoundCaseBlock) = selectBinder.BindCaseBlocks(
node.CaseBlocks,
exprPlaceHolder,
convertCaseElements:=expression.Type.IsIntrinsicOrEnumType(),
recommendSwitchTable:=recommendSwitchTable,
diagnostics:=diagnostics)
' Create the bound node.
Return New BoundSelectStatement(node, expressionStmt, exprPlaceHolder, caseBlocks, recommendSwitchTable,
exitLabel:=selectBinder.GetExitLabel(SyntaxKind.ExitSelectStatement))
End Function
Private Function BindSelectExpression(node As ExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
' SPEC: A Select Case statement executes statements based on the value of an expression.
' SPEC: The expression must be classified as a value.
' We want to generate select case specific diagnostics if select expression is
' AddressOf expression or Lambda expression.
' For remaining expression kinds, bind the select expression as value.
' We also need to handle SyntaxKind.ParenthesizedExpression here.
' We might have a AddressOf expression or Lambda expression within a parenthesized expression.
' We want to generate ERRID.ERR_AddressOfInSelectCaseExpr/ERRID.ERR_LambdaInSelectCaseExpr for this case.
' See test BindingErrorTests.BC36635ERR_LambdaInSelectCaseExpr.
Dim errorId As ERRID = Nothing
Select Case node.Kind
Case SyntaxKind.ParenthesizedExpression
Dim parenthesizedExpr = DirectCast(node, ParenthesizedExpressionSyntax)
Dim boundExpression = BindSelectExpression(parenthesizedExpr.Expression, diagnostics)
Return New BoundParenthesized(node, boundExpression, boundExpression.Type)
Case SyntaxKind.AddressOfExpression
errorId = ERRID.ERR_AddressOfInSelectCaseExpr
Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression
errorId = ERRID.ERR_LambdaInSelectCaseExpr
End Select
Dim boundExpr = BindExpression(node, diagnostics)
If boundExpr.HasErrors() Then
boundExpr = MakeRValue(boundExpr, diagnostics)
ElseIf errorId <> Nothing Then
ReportDiagnostic(diagnostics, node, errorId)
boundExpr = MakeRValueAndIgnoreDiagnostics(boundExpr)
Else
boundExpr = MakeRValue(boundExpr, diagnostics)
End If
Return boundExpr
End Function
Private Function BindCaseBlocks(
caseBlocks As SyntaxList(Of CaseBlockSyntax),
selectExpression As BoundRValuePlaceholder,
convertCaseElements As Boolean,
ByRef recommendSwitchTable As Boolean,
diagnostics As BindingDiagnosticBag
) As ImmutableArray(Of BoundCaseBlock)
If Not caseBlocks.IsEmpty() Then
Dim caseBlocksBuilder = ArrayBuilder(Of BoundCaseBlock).GetInstance()
' Bind case blocks.
For Each caseBlock In caseBlocks
caseBlocksBuilder.Add(BindCaseBlock(caseBlock, selectExpression, convertCaseElements, diagnostics))
Next
Return OptimizeSelectStatement(selectExpression, caseBlocksBuilder, recommendSwitchTable, diagnostics)
End If
Return ImmutableArray(Of BoundCaseBlock).Empty
End Function
Private Function BindCaseBlock(
node As CaseBlockSyntax,
selectExpression As BoundRValuePlaceholder,
convertCaseElements As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundCaseBlock
Dim caseStatement As BoundCaseStatement = BindCaseStatement(node.CaseStatement, selectExpression, convertCaseElements, diagnostics)
Dim statementsSyntax As SyntaxList(Of StatementSyntax) = node.Statements
Dim bodyBinder = GetBinder(statementsSyntax)
Dim body As BoundBlock = bodyBinder.BindBlock(node, statementsSyntax, diagnostics).MakeCompilerGenerated()
Return New BoundCaseBlock(node, caseStatement, body)
End Function
Private Function BindCaseStatement(
node As CaseStatementSyntax,
selectExpressionOpt As BoundRValuePlaceholder,
convertCaseElements As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundCaseStatement
Dim caseClauses As ImmutableArray(Of BoundCaseClause)
If node.Kind = SyntaxKind.CaseStatement Then
Dim caseClauseBuilder = ArrayBuilder(Of BoundCaseClause).GetInstance()
' Bind case clauses.
For Each caseClause In node.Cases
caseClauseBuilder.Add(BindCaseClause(caseClause, selectExpressionOpt, convertCaseElements, diagnostics))
Next
caseClauses = caseClauseBuilder.ToImmutableAndFree()
Else
Debug.Assert(node.Kind = SyntaxKind.CaseElseStatement)
caseClauses = ImmutableArray(Of BoundCaseClause).Empty
End If
Return New BoundCaseStatement(node, caseClauses, conditionOpt:=Nothing)
End Function
Private Function BindCaseClause(
node As CaseClauseSyntax,
selectExpressionOpt As BoundRValuePlaceholder,
convertCaseElements As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundCaseClause
Select Case node.Kind
Case SyntaxKind.CaseEqualsClause, SyntaxKind.CaseNotEqualsClause,
SyntaxKind.CaseGreaterThanClause, SyntaxKind.CaseGreaterThanOrEqualClause,
SyntaxKind.CaseLessThanClause, SyntaxKind.CaseLessThanOrEqualClause
Return BindRelationalCaseClause(DirectCast(node, RelationalCaseClauseSyntax), selectExpressionOpt, convertCaseElements, diagnostics)
Case SyntaxKind.SimpleCaseClause
Return BindSimpleCaseClause(DirectCast(node, SimpleCaseClauseSyntax), selectExpressionOpt, convertCaseElements, diagnostics)
Case SyntaxKind.RangeCaseClause
Return BindRangeCaseClause(DirectCast(node, RangeCaseClauseSyntax), selectExpressionOpt, convertCaseElements, diagnostics)
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
End Select
End Function
Private Function BindRelationalCaseClause(
node As RelationalCaseClauseSyntax,
selectExpressionOpt As BoundRValuePlaceholder,
convertCaseElements As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundCaseClause
' SPEC: A Case clause may take two forms.
' SPEC: One form is an optional Is keyword, a comparison operator, and an expression.
' SPEC: The expression is converted to the type of the Select expression;
' SPEC: if the expression is not implicitly convertible to the type of
' SPEC: the Select expression, a compile-time error occurs.
' SPEC: If the Select expression is E, the comparison operator is Op,
' SPEC: and the Case expression is E1, the case is evaluated as E OP E1.
' SPEC: The operator must be valid for the types of the two expressions;
' SPEC: otherwise a compile-time error occurs.
' Bind relational case clause as binary operator: E OP E1.
' BindBinaryOperator will generate the appropriate diagnostics.
Debug.Assert(SyntaxFacts.IsRelationalOperator(node.OperatorToken.Kind) OrElse node.ContainsDiagnostics)
Dim operatorKind As BinaryOperatorKind
Select Case node.Kind
Case SyntaxKind.CaseEqualsClause : operatorKind = BinaryOperatorKind.Equals
Case SyntaxKind.CaseNotEqualsClause : operatorKind = BinaryOperatorKind.NotEquals
Case SyntaxKind.CaseLessThanOrEqualClause : operatorKind = BinaryOperatorKind.LessThanOrEqual
Case SyntaxKind.CaseGreaterThanOrEqualClause : operatorKind = BinaryOperatorKind.GreaterThanOrEqual
Case SyntaxKind.CaseLessThanClause : operatorKind = BinaryOperatorKind.LessThan
Case SyntaxKind.CaseGreaterThanClause : operatorKind = BinaryOperatorKind.GreaterThan
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
End Select
Dim conditionOpt As BoundExpression = Nothing
Dim operandE1 As BoundExpression = BindCaseClauseExpression(
expressionSyntax:=node.Value,
caseClauseSyntax:=node,
selectExpressionOpt:=selectExpressionOpt,
operatorTokenKind:=node.OperatorToken.Kind,
operatorKind:=operatorKind,
convertCaseElements:=convertCaseElements,
conditionOpt:=conditionOpt,
diagnostics:=diagnostics)
Return New BoundRelationalCaseClause(node, operatorKind, operandE1, conditionOpt)
End Function
Private Function BindSimpleCaseClause(
node As SimpleCaseClauseSyntax,
selectExpressionOpt As BoundRValuePlaceholder,
convertCaseElements As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundCaseClause
' SPEC: The other form is an expression optionally followed by the keyword To and
' SPEC: a second expression. Both expressions are converted to the type of the
' SPEC: Select expression; if either expression is not implicitly convertible to
' SPEC: the type of the Select expression, a compile-time error occurs.
' SPEC: If the Select expression is E, the first Case expression is E1,
' SPEC: and the second Case expression is E2, the Case is evaluated either
' SPEC: as E = E1 (if no E2 is specified) or (E >= E1) And (E <= E2).
' SPEC: The operators must be valid for the types of the two expressions;
' SPEC: otherwise a compile-time error occurs.
Dim conditionOpt As BoundExpression = Nothing
' Bind the Case clause as E = E1 (no E2 is specified)
Dim value As BoundExpression = BindCaseClauseExpression(
expressionSyntax:=node.Value,
caseClauseSyntax:=node,
selectExpressionOpt:=selectExpressionOpt,
operatorTokenKind:=SyntaxKind.EqualsToken,
operatorKind:=BinaryOperatorKind.Equals,
convertCaseElements:=convertCaseElements,
conditionOpt:=conditionOpt,
diagnostics:=diagnostics)
Return New BoundSimpleCaseClause(node, value, conditionOpt)
End Function
Private Function BindRangeCaseClause(
node As RangeCaseClauseSyntax,
selectExpressionOpt As BoundRValuePlaceholder,
convertCaseElements As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundCaseClause
' SPEC: The other form is an expression optionally followed by the keyword To and
' SPEC: a second expression. Both expressions are converted to the type of the
' SPEC: Select expression; if either expression is not implicitly convertible to
' SPEC: the type of the Select expression, a compile-time error occurs.
' SPEC: If the Select expression is E, the first Case expression is E1,
' SPEC: and the second Case expression is E2, the Case is evaluated either
' SPEC: as E = E1 (if no E2 is specified) or (E >= E1) And (E <= E2).
' SPEC: The operators must be valid for the types of the two expressions;
' SPEC: otherwise a compile-time error occurs.
Dim lowerBoundConditionOpt As BoundExpression = Nothing
' Bind case clause lower bound value (E >= E1)
Dim lowerBound As BoundExpression = BindCaseClauseExpression(
expressionSyntax:=node.LowerBound,
caseClauseSyntax:=node,
selectExpressionOpt:=selectExpressionOpt,
operatorTokenKind:=SyntaxKind.GreaterThanEqualsToken,
operatorKind:=BinaryOperatorKind.GreaterThanOrEqual,
convertCaseElements:=convertCaseElements,
conditionOpt:=lowerBoundConditionOpt,
diagnostics:=diagnostics)
' Bind case clause upper bound value (E <= E2)
Dim upperBoundConditionOpt As BoundExpression = Nothing
Dim upperBound As BoundExpression = BindCaseClauseExpression(
expressionSyntax:=node.UpperBound,
caseClauseSyntax:=node,
selectExpressionOpt:=selectExpressionOpt,
operatorTokenKind:=SyntaxKind.LessThanEqualsToken,
operatorKind:=BinaryOperatorKind.LessThanOrEqual,
convertCaseElements:=convertCaseElements,
conditionOpt:=upperBoundConditionOpt,
diagnostics:=diagnostics)
Return New BoundRangeCaseClause(node, lowerBound, upperBound, lowerBoundConditionOpt, upperBoundConditionOpt)
End Function
Private Function BindCaseClauseExpression(
expressionSyntax As ExpressionSyntax,
caseClauseSyntax As CaseClauseSyntax,
selectExpressionOpt As BoundRValuePlaceholder,
operatorTokenKind As SyntaxKind,
operatorKind As BinaryOperatorKind,
convertCaseElements As Boolean,
ByRef conditionOpt As BoundExpression,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Dim caseExpr As BoundExpression = BindValue(expressionSyntax, diagnostics)
If selectExpressionOpt Is Nothing Then
' In error scenarios, such as a Case statement outside of a
' Select statement, the Select expression may be Nothing.
conditionOpt = Nothing
Return MakeRValue(caseExpr, diagnostics)
End If
If convertCaseElements AndAlso caseExpr.Type.IsIntrinsicOrEnumType() Then
' SPEC: The expression is converted to the type of the Select expression;
' SPEC: if the expression is not implicitly convertible to the type of the Select expression, a compile-time error occurs.
Debug.Assert(selectExpressionOpt.Type IsNot Nothing)
Return ApplyImplicitConversion(expressionSyntax, selectExpressionOpt.Type, caseExpr, diagnostics)
Else
' SPEC: If the Select expression is E, the comparison operator is Op,
' SPEC: and the Case expression is E1, the case is evaluated as E OP E1.
' Bind binary operator "selectExpression OP caseExpr" to generate necessary diagnostics.
conditionOpt = BindBinaryOperator(
node:=caseClauseSyntax,
left:=selectExpressionOpt,
right:=caseExpr,
operatorTokenKind:=operatorTokenKind,
preliminaryOperatorKind:=operatorKind,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated()
Return Nothing
End If
End Function
#Region "Helper methods for Binding Select case statement"
' This function is identical to the Semantics::OptimizeSelectStatement in native compiler.
' It performs two primary tasks:
' 1) Determines what kind of byte codes will be used for select: Switch Table or If List.
' Ideally we would like to delay these kind of optimizations till rewriting/emit phase.
' However, the computation of the case statement conditional would be redundant if
' we are eventually going to emit Switch table based byte code. Hence we match the
' native compiler behavior and check RecommendSwitchTable() here and store this
' value in the BoundSelectStatement node to be reused in the rewriter.
' 2) If we are going to generate If list based byte code, this function computes the
' conditional expression for case statements and stores it in the BoundCaseStatement nodes.
' Condition for each case statement "Case clause1, clause2, ..., clauseN"
' is computed as "clause1 OrElse clause2 OrElse ... OrElse clauseN" expression.
Private Function OptimizeSelectStatement(
selectExpression As BoundRValuePlaceholder,
caseBlockBuilder As ArrayBuilder(Of BoundCaseBlock),
ByRef generateSwitchTable As Boolean,
diagnostics As BindingDiagnosticBag
) As ImmutableArray(Of BoundCaseBlock)
Debug.Assert(Not selectExpression.HasErrors)
generateSwitchTable = RecommendSwitchTable(selectExpression, caseBlockBuilder, diagnostics)
' CONSIDER: Do we need to compute the case statement conditional expression
' CONSIDER: even for generateSwitchTable case? We might want to do so to
' CONSIDER: maintain consistency of bound nodes coming out of the binder.
' CONSIDER: With the current design, value of BoundCaseStatement.ConditionOpt field
' CONSIDER: is dependent on the value of generateSwitchTable.
If Not generateSwitchTable AndAlso caseBlockBuilder.Any() Then
Dim booleanType = GetSpecialType(SpecialType.System_Boolean, selectExpression.Syntax, diagnostics)
Dim caseClauseBuilder = ArrayBuilder(Of BoundCaseClause).GetInstance()
For index = 0 To caseBlockBuilder.Count - 1
Dim caseBlock = caseBlockBuilder(index)
If caseBlock.Syntax.Kind <> SyntaxKind.CaseElseBlock AndAlso
Not caseBlock.CaseStatement.Syntax.IsMissing Then
Dim caseStatement = caseBlock.CaseStatement
Dim caseStatementSyntax = caseStatement.Syntax
Dim caseStatementCondition As BoundExpression = Nothing
Debug.Assert(caseStatement.CaseClauses.Any())
Dim clausesChanged = False
' Compute conditional expression for case statement
For Each caseClause In caseStatement.CaseClauses
Dim clauseCondition As BoundExpression = Nothing
' Compute conditional expression for case clause, if not already computed.
Dim newCaseClause = ComputeCaseClauseCondition(caseClause, clauseCondition, selectExpression, diagnostics)
caseClauseBuilder.Add(newCaseClause)
clausesChanged = clausesChanged OrElse Not newCaseClause.Equals(caseClause)
Debug.Assert(clauseCondition IsNot Nothing)
If caseStatementCondition Is Nothing Then
caseStatementCondition = clauseCondition
Else
' caseStatementCondition = caseStatementCondition OrElse clauseCondition
caseStatementCondition = BindBinaryOperator(
node:=caseStatementSyntax,
left:=caseStatementCondition,
right:=clauseCondition,
operatorTokenKind:=SyntaxKind.OrElseKeyword,
preliminaryOperatorKind:=BinaryOperatorKind.OrElse,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated()
End If
Next
Dim newCaseClauses As ImmutableArray(Of BoundCaseClause)
If clausesChanged Then
newCaseClauses = caseClauseBuilder.ToImmutable()
Else
newCaseClauses = caseStatement.CaseClauses
End If
caseClauseBuilder.Clear()
caseStatementCondition = ApplyImplicitConversion(caseStatementCondition.Syntax, booleanType, caseStatementCondition, diagnostics:=diagnostics, isOperandOfConditionalBranch:=True)
caseStatement = caseStatement.Update(newCaseClauses, caseStatementCondition)
caseBlockBuilder(index) = caseBlock.Update(caseStatement, caseBlock.Body)
End If
Next
caseClauseBuilder.Free()
End If
Return caseBlockBuilder.ToImmutableAndFree()
End Function
Private Function ComputeCaseClauseCondition(caseClause As BoundCaseClause, <Out()> ByRef conditionOpt As BoundExpression, selectExpression As BoundRValuePlaceholder, diagnostics As BindingDiagnosticBag) As BoundCaseClause
Select Case caseClause.Kind
Case BoundKind.RelationalCaseClause
Return ComputeRelationalCaseClauseCondition(DirectCast(caseClause, BoundRelationalCaseClause), conditionOpt, selectExpression, diagnostics)
Case BoundKind.SimpleCaseClause
Return ComputeSimpleCaseClauseCondition(DirectCast(caseClause, BoundSimpleCaseClause), conditionOpt, selectExpression, diagnostics)
Case BoundKind.RangeCaseClause
Return ComputeRangeCaseClauseCondition(DirectCast(caseClause, BoundRangeCaseClause), conditionOpt, selectExpression, diagnostics)
Case Else
Throw ExceptionUtilities.UnexpectedValue(caseClause.Kind)
End Select
End Function
Private Function ComputeRelationalCaseClauseCondition(boundClause As BoundRelationalCaseClause, <Out()> ByRef conditionOpt As BoundExpression, selectExpression As BoundRValuePlaceholder, diagnostics As BindingDiagnosticBag) As BoundCaseClause
Dim syntax = DirectCast(boundClause.Syntax, RelationalCaseClauseSyntax)
' Exactly one of the operand or condition must be non-null
Debug.Assert(boundClause.ConditionOpt IsNot Nothing Xor boundClause.ValueOpt IsNot Nothing)
conditionOpt = If(boundClause.ConditionOpt, BindBinaryOperator(node:=syntax,
left:=selectExpression,
right:=boundClause.ValueOpt,
operatorTokenKind:=syntax.OperatorToken.Kind,
preliminaryOperatorKind:=boundClause.OperatorKind,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated())
Return boundClause.Update(boundClause.OperatorKind, valueOpt:=Nothing, conditionOpt:=conditionOpt)
End Function
Private Function ComputeSimpleCaseClauseCondition(boundClause As BoundSimpleCaseClause, <Out()> ByRef conditionOpt As BoundExpression, selectExpression As BoundRValuePlaceholder, diagnostics As BindingDiagnosticBag) As BoundCaseClause
' Exactly one of the value or condition must be non-null
Debug.Assert(boundClause.ConditionOpt IsNot Nothing Xor boundClause.ValueOpt IsNot Nothing)
conditionOpt = If(boundClause.ConditionOpt, BindBinaryOperator(node:=boundClause.Syntax,
left:=selectExpression,
right:=boundClause.ValueOpt,
operatorTokenKind:=SyntaxKind.EqualsToken,
preliminaryOperatorKind:=BinaryOperatorKind.Equals,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated())
Return boundClause.Update(valueOpt:=Nothing, conditionOpt:=conditionOpt)
End Function
Private Function ComputeRangeCaseClauseCondition(boundClause As BoundRangeCaseClause, <Out()> ByRef conditionOpt As BoundExpression, selectExpression As BoundRValuePlaceholder, diagnostics As BindingDiagnosticBag) As BoundCaseClause
Dim syntax = boundClause.Syntax
' Exactly one of the LowerBoundOpt or LowerBoundConditionOpt must be non-null
Debug.Assert(boundClause.LowerBoundOpt IsNot Nothing Xor boundClause.LowerBoundConditionOpt IsNot Nothing)
Dim lowerBoundConditionOpt = boundClause.LowerBoundConditionOpt
If lowerBoundConditionOpt Is Nothing Then
lowerBoundConditionOpt = BindBinaryOperator(
node:=boundClause.Syntax,
left:=selectExpression,
right:=boundClause.LowerBoundOpt,
operatorTokenKind:=SyntaxKind.GreaterThanEqualsToken,
preliminaryOperatorKind:=BinaryOperatorKind.GreaterThanOrEqual,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated()
End If
' Exactly one of the UpperBoundOpt or UpperBoundConditionOpt must be non-null
Debug.Assert(boundClause.UpperBoundOpt IsNot Nothing Xor boundClause.UpperBoundConditionOpt IsNot Nothing)
Dim upperBoundConditionOpt = boundClause.UpperBoundConditionOpt
If upperBoundConditionOpt Is Nothing Then
upperBoundConditionOpt = BindBinaryOperator(
node:=syntax,
left:=selectExpression,
right:=boundClause.UpperBoundOpt,
operatorTokenKind:=SyntaxKind.LessThanEqualsToken,
preliminaryOperatorKind:=BinaryOperatorKind.LessThanOrEqual,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated()
End If
conditionOpt = BindBinaryOperator(
node:=syntax,
left:=lowerBoundConditionOpt,
right:=upperBoundConditionOpt,
operatorTokenKind:=SyntaxKind.AndAlsoKeyword,
preliminaryOperatorKind:=BinaryOperatorKind.AndAlso,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated()
Return boundClause.Update(lowerBoundOpt:=Nothing, upperBoundOpt:=Nothing, lowerBoundConditionOpt:=lowerBoundConditionOpt, upperBoundConditionOpt:=upperBoundConditionOpt)
End Function
' Helper method to determine if we must rewrite the select case statement as an IF list or a SWITCH table
Private Function RecommendSwitchTable(selectExpr As BoundRValuePlaceholder, caseBlocks As ArrayBuilder(Of BoundCaseBlock), diagnostics As BindingDiagnosticBag) As Boolean
' We can rewrite select case statement as an IF list or a SWITCH table
' This function determines which method to use.
' The conditions for choosing the SWITCH table are:
' select case expression type must be integral/boolean/string (see TypeSymbolExtensions.IsValidTypeForSwitchTable())
' no "Is <relop>" cases, except for <relop> = BinaryOperatorKind.Equals
' no "<lb> To <ub>" cases for string type
' for integral/boolean type, case values must be (or expand to, as in ranges) integer constants
' for string type, all case values must be string constants and OptionCompareText must be False.
' beneficial over IF lists (as per a threshold on size ratio)
' ranges must have lower bound first
' We also generate warnings for Invalid range clauses in this function.
' Ideally we would like to generate them in BindRangeCaseClause.
' However, Dev10 doesn't do this check individually for each CaseClause.
' It is performed only if bounds for all clauses in the Select are integer constants and
' all clauses are either range clauses or equality clause.
' Doing this differently will produce warnings in more scenarios - breaking change.
If Not caseBlocks.Any() OrElse Not selectExpr.Type.IsValidTypeForSwitchTable() Then
Return False
End If
Dim isSelectExprStringType = selectExpr.Type.IsStringType
If isSelectExprStringType AndAlso OptionCompareText Then
Return False
End If
Dim recommendSwitch = True
For Each caseBlock In caseBlocks
For Each caseClause In caseBlock.CaseStatement.CaseClauses
Select Case caseClause.Kind
Case BoundKind.RelationalCaseClause
Dim relationalClause = DirectCast(caseClause, BoundRelationalCaseClause)
' Exactly one of the operand or condition must be non-null
Debug.Assert(relationalClause.ValueOpt IsNot Nothing Xor relationalClause.ConditionOpt IsNot Nothing)
Dim operand = relationalClause.ValueOpt
If operand Is Nothing OrElse
relationalClause.OperatorKind <> BinaryOperatorKind.Equals OrElse
operand.ConstantValueOpt Is Nothing OrElse
Not SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(operand.ConstantValueOpt) Then
Return False
End If
Case BoundKind.RangeCaseClause
' TODO: RecommendSwitchTable for Range clause.
' TODO: If we decide to implement it we will need to
' TODO: add heuristic to determine when the range is
' TODO: big enough to prefer IF lists over SWITCH table.
' TODO: We will also need to add logic in the emitter
' TODO: to iterate through ConstantValues in a range.
' For now we use IF lists if we encounter BoundRangeCaseClause
Dim rangeCaseClause = DirectCast(caseClause, BoundRangeCaseClause)
' Exactly one of the LowerBoundOpt or LowerBoundConditionOpt must be non-null
Debug.Assert(rangeCaseClause.LowerBoundOpt IsNot Nothing Xor rangeCaseClause.LowerBoundConditionOpt IsNot Nothing)
' Exactly one of the UpperBoundOpt or UpperBoundConditionOpt must be non-null
Debug.Assert(rangeCaseClause.UpperBoundOpt IsNot Nothing Xor rangeCaseClause.UpperBoundConditionOpt IsNot Nothing)
Dim lowerBound = rangeCaseClause.LowerBoundOpt
Dim upperBound = rangeCaseClause.UpperBoundOpt
If lowerBound Is Nothing OrElse
upperBound Is Nothing OrElse
lowerBound.ConstantValueOpt Is Nothing OrElse
upperBound.ConstantValueOpt Is Nothing OrElse
Not SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(lowerBound.ConstantValueOpt) OrElse
Not SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(upperBound.ConstantValueOpt) Then
Return False
End If
recommendSwitch = False
Case Else
Dim simpleCaseClause = DirectCast(caseClause, BoundSimpleCaseClause)
' Exactly one of the value or condition must be non-null
Debug.Assert(simpleCaseClause.ValueOpt IsNot Nothing Xor simpleCaseClause.ConditionOpt IsNot Nothing)
Dim value = simpleCaseClause.ValueOpt
If value Is Nothing OrElse
value.ConstantValueOpt Is Nothing OrElse
Not SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(value.ConstantValueOpt) Then
Return False
End If
End Select
Next
Next
' TODO: beneficial over IF lists (as per a threshold on size ratio)
Return Not ReportInvalidSelectCaseRange(caseBlocks, diagnostics) AndAlso recommendSwitch
End Function
' Function reports WRN_SelectCaseInvalidRange for any invalid select case range.
' Returns True if an invalid range was found, False otherwise.
Private Function ReportInvalidSelectCaseRange(caseBlocks As ArrayBuilder(Of BoundCaseBlock), diagnostics As BindingDiagnosticBag) As Boolean
For Each caseBlock In caseBlocks
For Each caseClause In caseBlock.CaseStatement.CaseClauses
Select Case caseClause.Kind
Case BoundKind.RangeCaseClause
Dim rangeCaseClause = DirectCast(caseClause, BoundRangeCaseClause)
Dim lowerBound = rangeCaseClause.LowerBoundOpt
Dim upperBound = rangeCaseClause.UpperBoundOpt
Debug.Assert(lowerBound IsNot Nothing)
Debug.Assert(lowerBound.ConstantValueOpt IsNot Nothing)
Debug.Assert(upperBound IsNot Nothing)
Debug.Assert(upperBound.ConstantValueOpt IsNot Nothing)
Debug.Assert(rangeCaseClause.LowerBoundConditionOpt Is Nothing)
Debug.Assert(rangeCaseClause.UpperBoundConditionOpt Is Nothing)
If IsInvalidSelectCaseRange(lowerBound.ConstantValueOpt, upperBound.ConstantValueOpt) Then
ReportDiagnostic(diagnostics, rangeCaseClause.Syntax, ERRID.WRN_SelectCaseInvalidRange)
Return True
End If
End Select
Next
Next
Return False
End Function
Private Shared Function IsInvalidSelectCaseRange(lbConstantValue As ConstantValue, ubConstantValue As ConstantValue) As Boolean
Debug.Assert(lbConstantValue IsNot Nothing)
Debug.Assert(ubConstantValue IsNot Nothing)
Debug.Assert(lbConstantValue.SpecialType = ubConstantValue.SpecialType)
Select Case lbConstantValue.SpecialType
Case SpecialType.System_Boolean,
SpecialType.System_Byte,
SpecialType.System_UInt16,
SpecialType.System_UInt32,
SpecialType.System_UInt64
Return lbConstantValue.UInt64Value > ubConstantValue.UInt64Value
Case SpecialType.System_SByte,
SpecialType.System_Int16,
SpecialType.System_Int32,
SpecialType.System_Int64,
SpecialType.System_Char
Return lbConstantValue.Int64Value > ubConstantValue.Int64Value
Case SpecialType.System_Single,
SpecialType.System_Double
Return lbConstantValue.DoubleValue > ubConstantValue.DoubleValue
Case SpecialType.System_Decimal
Return lbConstantValue.DecimalValue > ubConstantValue.DecimalValue
Case Else
Return False
End Select
End Function
#End Region
#End Region
End Class
End Namespace
|
physhi/roslyn
|
src/Compilers/VisualBasic/Portable/Binding/Binder_SelectCase.vb
|
Visual Basic
|
apache-2.0
| 39,837
|
' 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.UnitTests.ChangeSignature
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature
Imports Microsoft.VisualStudio.Text.Operations
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature
Partial Public Class ChangeSignatureTests
Inherits AbstractChangeSignatureTests
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestReorderParameters_AcrossLanguages_InvokeFromDeclaration() As Task
Dim workspace = <Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="VBDocument">
Public Class Test
Public Sub $$Goo(x as Integer, y as Integer)
End Sub
End Class</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly" CommonReferences="true">
<ProjectReference>VBAssembly</ProjectReference>
<Document FilePath="CSharpDocument">
class C
{
void M()
{
new Test().Goo(1, 2);
}
}</Document>
</Project>
</Workspace>
Dim permutation = {New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(0)}
Dim expectedVBCode = <Text><![CDATA[
Public Class Test
Public Sub Goo(y as Integer, x as Integer)
End Sub
End Class]]></Text>.NormalizedValue()
Dim expectedCSharpCode = <Text><![CDATA[
class C
{
void M()
{
new Test().Goo(2, 1);
}
}]]></Text>.NormalizedValue()
Using testState = ChangeSignatureTestState.Create(workspace)
Dim history = testState.Workspace.GetService(Of ITextUndoHistoryRegistry)().RegisterHistory(testState.Workspace.Documents.First().GetTextBuffer())
testState.TestChangeSignatureOptionsService.UpdatedSignature = permutation
Dim result = Await testState.ChangeSignatureAsync().ConfigureAwait(False)
Dim vbdoc = result.UpdatedSolution.Projects.Single(Function(p) p.AssemblyName = "VBAssembly").Documents.Single()
Dim csdoc = result.UpdatedSolution.Projects.Single(Function(p) p.AssemblyName = "CSAssembly").Documents.Single()
Assert.Equal(expectedCSharpCode, (Await csdoc.GetTextAsync()).ToString())
Assert.Equal(expectedVBCode, (Await vbdoc.GetTextAsync()).ToString())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestReorderParameters_AcrossLanguages_InvokeFromReference() As Task
Dim workspace = <Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document FilePath="VBDocument">
Public Class Test
Public Sub Goo(x as Integer, y as Integer)
End Sub
End Class</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly" CommonReferences="true">
<ProjectReference>VBAssembly</ProjectReference>
<Document FilePath="CSharpDocument">
class C
{
void M()
{
new Test().Goo$$(1, 2);
}
}</Document>
</Project>
</Workspace>
Dim permutation = {New AddedParameterOrExistingIndex(1), New AddedParameterOrExistingIndex(0)}
Dim expectedVBCode = <Text><![CDATA[
Public Class Test
Public Sub Goo(y as Integer, x as Integer)
End Sub
End Class]]></Text>.NormalizedValue()
Dim expectedCSharpCode = <Text><![CDATA[
class C
{
void M()
{
new Test().Goo(2, 1);
}
}]]></Text>.NormalizedValue()
Using testState = ChangeSignatureTestState.Create(workspace)
Dim history = testState.Workspace.GetService(Of ITextUndoHistoryRegistry)().RegisterHistory(testState.Workspace.Documents.First().GetTextBuffer())
testState.TestChangeSignatureOptionsService.UpdatedSignature = permutation
Dim result = Await testState.ChangeSignatureAsync().ConfigureAwait(False)
Dim vbdoc = result.UpdatedSolution.Projects.Single(Function(p) p.AssemblyName = "VBAssembly").Documents.Single()
Dim csdoc = result.UpdatedSolution.Projects.Single(Function(p) p.AssemblyName = "CSAssembly").Documents.Single()
Assert.Equal(expectedCSharpCode, (Await csdoc.GetTextAsync()).ToString())
Assert.Equal(expectedVBCode, (Await vbdoc.GetTextAsync()).ToString())
End Using
End Function
End Class
End Namespace
|
physhi/roslyn
|
src/EditorFeatures/VisualBasicTest/ChangeSignature/ReorderParameters.MultiFile.vb
|
Visual Basic
|
apache-2.0
| 5,207
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.